_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 |
|---|---|---|---|---|---|---|---|---|
111811e04a9e0a127e69d8c878bbff4243cf4359033d852a451c107809ef6778 | Factual/sosueme | conf.clj | (ns sosueme.conf
"Simple configuration utility. Knows how to read in configuration from
files and the classpath. Provides access to said configuration.
Configuration data is expected to be stored as a clojure hash-map.
E.g., if you have a file called myconf.clj with this content:
{:host \"my.server.com\"
:port 8081}
Then your app could do this:
...
(conf/load-file! \"myconf.clj\")
(let [host (conf/get-key :host)] ... )
Also knows how to parse configuration data out of .factual files. For
example:
(conf/dot-factual \"factual-auth.yaml\")"
(:use [sosueme.io :as sio])
(:use [clojure.tools.logging :only (info debug error)])
(:require [clj-yaml.core :as yaml]
[fs.core :as fs]))
(defn load-when
"If path exists in the present working directory or on the classpath,
returns the data structure represented in the file at path. Otherwise
returns nil."
[path]
(if (fs/exists? path)
(do
(info "conf.load-when: loading conf from file at" path)
(read-string (slurp path)))
(if-let [data-str (sio/slurp-cp path)]
(do
(info "conf.load-when: loading conf from classpath at" path)
(read-string data-str))
(info "conf.load-when: no file or resource at" path "; skipping"))))
(def ^:dynamic *conf* nil)
(defn load-file!
"Merges the configuration in path into current *conf*. In the case of
identical keys, the configuration in path will take precedence."
[path]
(def ^:dynamic *conf* (merge *conf* (load-when path))))
(defn get-key
"Returns the value at key k in the configuration that has been loaded."
[k]
(*conf* k))
(defn all
"Returns the full configuration hashmap that has been loaded."
[] *conf*)
(defn show
"Convenience fn to print conf to stdout"
[]
(info "conf.show: conf:" *conf*))
(defn dot-factual
"Returns the data parsed from yaml-file, which is assumed to live under
our standard ~/.factual directory.
Example usage:
(dot-factual \"factual-auth.yaml\")"
[yaml-file]
(yaml/parse-string (slurp
(-> (fs/home)
(fs/file ".factual")
(fs/file yaml-file)))))
| null | https://raw.githubusercontent.com/Factual/sosueme/1c2e9b7eb4df8ae67012dc2a398b4ec63c9bd6cd/src/sosueme/conf.clj | clojure | (ns sosueme.conf
"Simple configuration utility. Knows how to read in configuration from
files and the classpath. Provides access to said configuration.
Configuration data is expected to be stored as a clojure hash-map.
E.g., if you have a file called myconf.clj with this content:
{:host \"my.server.com\"
:port 8081}
Then your app could do this:
...
(conf/load-file! \"myconf.clj\")
(let [host (conf/get-key :host)] ... )
Also knows how to parse configuration data out of .factual files. For
example:
(conf/dot-factual \"factual-auth.yaml\")"
(:use [sosueme.io :as sio])
(:use [clojure.tools.logging :only (info debug error)])
(:require [clj-yaml.core :as yaml]
[fs.core :as fs]))
(defn load-when
"If path exists in the present working directory or on the classpath,
returns the data structure represented in the file at path. Otherwise
returns nil."
[path]
(if (fs/exists? path)
(do
(info "conf.load-when: loading conf from file at" path)
(read-string (slurp path)))
(if-let [data-str (sio/slurp-cp path)]
(do
(info "conf.load-when: loading conf from classpath at" path)
(read-string data-str))
(info "conf.load-when: no file or resource at" path "; skipping"))))
(def ^:dynamic *conf* nil)
(defn load-file!
"Merges the configuration in path into current *conf*. In the case of
identical keys, the configuration in path will take precedence."
[path]
(def ^:dynamic *conf* (merge *conf* (load-when path))))
(defn get-key
"Returns the value at key k in the configuration that has been loaded."
[k]
(*conf* k))
(defn all
"Returns the full configuration hashmap that has been loaded."
[] *conf*)
(defn show
"Convenience fn to print conf to stdout"
[]
(info "conf.show: conf:" *conf*))
(defn dot-factual
"Returns the data parsed from yaml-file, which is assumed to live under
our standard ~/.factual directory.
Example usage:
(dot-factual \"factual-auth.yaml\")"
[yaml-file]
(yaml/parse-string (slurp
(-> (fs/home)
(fs/file ".factual")
(fs/file yaml-file)))))
| |
ec9e3068ad46174f8b0cdac552b5f6edf99533f1d57792a04590527ab554fd5b | JHU-PL-Lab/jaylang | program_samples.ml | let parse = Jayil_parser.Parser.parse_string
let e1 = parse "\nt = 1\n"
let e2 = parse "\na = 0;\nb = 1;\nt = a + b;\n"
let e3 = parse "\na = 0;\nb = 1;\nc = a < b;\nt = c ? (r1 = 1) : (r2 = 0);\n"
let e4 = parse "\na = 0;\nb = 1;\nc = {f1 = a, f2 = b};\nt = c.f2\n"
| null | https://raw.githubusercontent.com/JHU-PL-Lab/jaylang/81abf9ff185758a2aaefd90478da4c7bb53f4384/src-test/unit/program_samples.ml | ocaml | let parse = Jayil_parser.Parser.parse_string
let e1 = parse "\nt = 1\n"
let e2 = parse "\na = 0;\nb = 1;\nt = a + b;\n"
let e3 = parse "\na = 0;\nb = 1;\nc = a < b;\nt = c ? (r1 = 1) : (r2 = 0);\n"
let e4 = parse "\na = 0;\nb = 1;\nc = {f1 = a, f2 = b};\nt = c.f2\n"
| |
8d570822567f747521eb5290ca5771641a78c32d39eae73fe1604473b0aa3910 | dramforever/nix-dram | Pretty.hs | module Nix.Nar.Listing.Pretty where
import qualified Data.HashMap.Lazy as H
import Data.Maybe
import qualified Data.Text.Lazy as T
import Nix.Nar.Listing.Types
import Prettyprinter
import Prettyprinter.Render.Terminal
prettyNarListing :: NarListing -> Doc AnsiStyle
prettyNarListing NarListing{..} =
prettyNarEntry (annotate (color Red) "<top>") narRoot
prettyNarEntry :: Doc AnsiStyle -> NarEntry -> Doc AnsiStyle
prettyNarEntry nameDoc EntryRegular{..} =
annotate nameAnn nameDoc
<+> if executable
then annotate bold "(executable)"
else mempty
where
executable = fromMaybe False entExecutable
nameAnn = if executable then color Green else mempty
prettyNarEntry nameDoc EntryDirectory{..} =
align . vsep $
[ annotate (color Blue) nameDoc <> annotate bold "/"]
++ (uncurry go <$> H.toList entEntries)
where
go name ent = indent 2 $ prettyNarEntry (pretty name) ent
renderNarListing :: NarListing -> T.Text
renderNarListing =
renderLazy
. layoutPretty defaultLayoutOptions
. prettyNarListing
| null | https://raw.githubusercontent.com/dramforever/nix-dram/a401e0cc1821106633c36859b0248a4b4f64bee3/nix-nar-listing/src/Nix/Nar/Listing/Pretty.hs | haskell | module Nix.Nar.Listing.Pretty where
import qualified Data.HashMap.Lazy as H
import Data.Maybe
import qualified Data.Text.Lazy as T
import Nix.Nar.Listing.Types
import Prettyprinter
import Prettyprinter.Render.Terminal
prettyNarListing :: NarListing -> Doc AnsiStyle
prettyNarListing NarListing{..} =
prettyNarEntry (annotate (color Red) "<top>") narRoot
prettyNarEntry :: Doc AnsiStyle -> NarEntry -> Doc AnsiStyle
prettyNarEntry nameDoc EntryRegular{..} =
annotate nameAnn nameDoc
<+> if executable
then annotate bold "(executable)"
else mempty
where
executable = fromMaybe False entExecutable
nameAnn = if executable then color Green else mempty
prettyNarEntry nameDoc EntryDirectory{..} =
align . vsep $
[ annotate (color Blue) nameDoc <> annotate bold "/"]
++ (uncurry go <$> H.toList entEntries)
where
go name ent = indent 2 $ prettyNarEntry (pretty name) ent
renderNarListing :: NarListing -> T.Text
renderNarListing =
renderLazy
. layoutPretty defaultLayoutOptions
. prettyNarListing
| |
1f6812c3d99f06580350f29834e49ad32c0e109880a2e467af21d9c9e365af3c | lspitzner/brittany | Test187.hs | type a `MySynonym` b = a -> b
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test187.hs | haskell | type a `MySynonym` b = a -> b
| |
04e70c9a82dc9e76bc1c7b52ea31b49da86e2ee419f7fe2270c03ca866c0a69e | ghosthamlet/algorithm-data-structure | trie_node.clj | (ns algorithm-data-structure.data-structures.trie-node
"-algorithms/tree/master/src/data-structures/trie"
(:require [algorithm-data-structure.data-structures.hash-table :as ht]))
(declare has-child)
(defn create
([character] (create character false))
([character is-complete-word]
{:character character
:is-complete-word is-complete-word
:children (ht/create)}))
(defn get-child [self character]
(ht/get* (:children self) character))
(defn add-child
([self character] (add-child self character false))
([self character is-complete-word]
(let [self (if (has-child self character)
self
(update self :children
ht/set* character (create character is-complete-word)))]
[self (get-child self character)])))
(defn add-child-node [self node]
(update self :children ht/set* (:character node) node))
(defn has-child [self character]
(ht/has (:children self) character))
(defn suggest-children [self]
(ht/get-keys (:children self)))
(defn ->string [self]
(let [children-as-string (str (suggest-children self))
children-as-string (if (empty? children-as-string) "" (str ":" children-as-string))
is-complete-string (if (:is-complete-word self) "*" "")]
(str (:character self) is-complete-string children-as-string)))
| null | https://raw.githubusercontent.com/ghosthamlet/algorithm-data-structure/017f41a79d8b1d62ff5a6cceffa1b0f0ad3ead6b/src/algorithm_data_structure/data_structures/trie_node.clj | clojure | (ns algorithm-data-structure.data-structures.trie-node
"-algorithms/tree/master/src/data-structures/trie"
(:require [algorithm-data-structure.data-structures.hash-table :as ht]))
(declare has-child)
(defn create
([character] (create character false))
([character is-complete-word]
{:character character
:is-complete-word is-complete-word
:children (ht/create)}))
(defn get-child [self character]
(ht/get* (:children self) character))
(defn add-child
([self character] (add-child self character false))
([self character is-complete-word]
(let [self (if (has-child self character)
self
(update self :children
ht/set* character (create character is-complete-word)))]
[self (get-child self character)])))
(defn add-child-node [self node]
(update self :children ht/set* (:character node) node))
(defn has-child [self character]
(ht/has (:children self) character))
(defn suggest-children [self]
(ht/get-keys (:children self)))
(defn ->string [self]
(let [children-as-string (str (suggest-children self))
children-as-string (if (empty? children-as-string) "" (str ":" children-as-string))
is-complete-string (if (:is-complete-word self) "*" "")]
(str (:character self) is-complete-string children-as-string)))
| |
2a08cd66e3b6c7a1525855a9e29143998634659d09f2e7f9847f19efbb19808d | TempusMUD/cl-tempus | receptionist.lisp | (in-package #:tempus)
(defvar *min-rent-cost* 1000)
(defconstant +rent-factor+ 1)
(defconstant +cryo-factor+ 4)
(defcommand (ch "rent") (:resting)
(send-to-char ch "You can't do that here.~%"))
(defcommand (ch "cryo") (:resting)
(send-to-char ch "You can't do that here.~%"))
(defun find-all-objects (obj-seq)
"Returns a list of all the objects in OBJ-SEQ, including all the
objects contained by other objects."
(let ((result nil))
(map nil (lambda (obj)
(push obj result)
(setf result
(nconc (find-all-objects (contains-of obj))
result)))
obj-seq)
result))
(defun all-carried-objects (ch)
"Returns a list of all objects that CH is carrying, wearing, or
implanted with, including objects in containers."
(append
(find-all-objects (remove nil (equipment-of ch)))
(find-all-objects (remove nil (implants-of ch)))
(find-all-objects (carrying-of ch))))
(defun extract-unrentables (obj-list)
"Given OBJ-LIST, removes all unrentable objects in OBJ-LIST that cannot be rented"
(dolist (obj (copy-list obj-list))
(extract-unrentables (contains-of obj))
(when (and (unrentable? obj)
(or (null (worn-by-of obj))
(not (is-obj-stat2 obj +item2-noremove+)))
(not (is-obj-stat obj +item-nodrop+)))
(extract-obj obj))))
(defun inform-rent-deadline (ch recep cost)
(unless (zerop cost)
(let ((msg (format nil "You can rent for ~d day~:p with the money you have on hand and in the bank."
(floor (if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
(+ (cash-of ch)
(future-bank-of (account-of ch)))
(+ (gold-of ch)
(past-bank-of (account-of ch))))
cost))))
(if recep
(perform-tell recep ch msg)
(send-to-char "~a~%" msg)))))
(defun send-rent-line (ch obj count currency-str)
(send-to-char ch "~10d ~a for ~a~:[ (x~d)~;~]~%"
(cost-per-day-of (shared-of obj))
currency-str
(name-of obj)
(= count 1)
count))
(defun tally-obj-rent (ch obj-list currency-str displayp)
(let ((last-obj (first obj-list))
(total-cost 0)
(count 1))
(dolist (obj (sort (rest obj-list) #'< :key 'vnum-of))
(unless (unrentable? obj)
(incf total-cost (cost-per-day-of (shared-of obj)))
(when displayp
(cond
((not (eql (shared-of last-obj) (shared-of obj)))
(send-rent-line ch last-obj count currency-str)
(setf count 1)
(setf last-obj obj))
(t
(incf count))))))
(when (and last-obj displayp)
(send-rent-line ch last-obj count currency-str))
total-cost))
(defun calc-daily-rent (ch factor currency-str displayp)
(let* ((room (or (real-room (load-room-of ch))
(in-room-of ch)))
(receptionist (and room
(find-if (lambda (tch)
(and (is-npc tch)
(or (eql (func-of (shared-of tch)) 'cryogenicist)
(eql (func-of (shared-of tch)) 'receptionist))))
(people-of room)))))
(when receptionist
(incf factor (* (cost-modifier-of ch receptionist) 100))))
(let* ((total-cost (tally-obj-rent ch (all-carried-objects ch) currency-str displayp))
(level-adj (floor (+ (/ (* 3 total-cost (+ 10 (level-of ch))) 100)
(* *min-rent-cost* (level-of ch))
(- total-cost)))))
(setf total-cost (* (+ total-cost level-adj) factor))
(when displayp
(send-to-char ch "~10d ~a for level adjustment~%" level-adj currency-str)
(unless (= factor 1)
(send-to-char " x%2f for services~%" factor))
(send-to-char ch "-------------------------------------------~%")
(send-to-char ch "~10d ~a TOTAL~%" total-cost currency-str))
total-cost))
(defun display-unrentables (ch)
(unless (immortal-level-p ch)
(let ((forbid-renting nil))
(dolist (obj (all-carried-objects ch))
(when (unrentable? obj)
(act ch :subject-emit (format nil "You cannot rent while ~a $p!"
(cond
((null (worn-by-of obj)) "carrying")
((eql (get-eq ch (worn-on-of obj)) obj) "wearing")
(t "implanted with"))))
(setf forbid-renting t)))
forbid-renting)))
(defun offer-rent (ch receptionist factor displayp)
(with-pagination ((link-of ch))
(when displayp
(act receptionist :target ch
:target-emit "$n writes up a bill and shows it to you:"))
(let* ((currency (if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
"credits"
"coins"))
(total-money (if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
(+ (cash-of ch)
(future-bank-of (account-of ch)))
(+ (gold-of ch)
(past-bank-of (account-of ch)))))
(cost-per-day (calc-daily-rent ch factor currency displayp)))
(unless (display-unrentables ch)
(when displayp
(when (eql factor +rent-factor+)
(cond
((< total-money cost-per-day)
(send-to-char ch "You don't have enough money to rent for a single day!~%"))
((plusp cost-per-day)
(send-to-char ch "Your ~d ~a is enough to rent for &c~d&n day~:p.~%"
total-money currency (floor total-money cost-per-day))))))
(floor cost-per-day)))))
(defun generic-receptionist (ch recep cmd factor)
(let ((currency (if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
"credit"
"coin"))
(money (if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
(cash-of ch)
(gold-of ch))))
(cond
((not (member (first (command-info-pattern cmd))
'("rent" "offer")
:test #'string=))
nil)
((not (awakep recep))
(act ch :target recep :subject-emit "$E is unable to talk to you...")
t)
((and (not (can-see-creature recep ch))
(not (immortal-level-p ch)))
(perform-say recep "say" "I don't deal with people I can't see!")
t)
((string= (first (command-info-pattern cmd)) "rent")
(let ((cost (offer-rent ch recep factor nil)))
(perform-tell recep ch (if (eql factor +rent-factor+)
(format nil "Rent will cost you ~d ~a~2:*~p per day." cost currency)
(format nil "It will cost you ~d ~a~2:*p to be frozen" cost currency)))
(cond
((> cost money)
(perform-tell recep ch "...which I see you can't afford."))
((eql factor +rent-factor+)
(inform-rent-deadline ch recep cost)
(act recep :target ch
:target-emit "$n stores your belongings and helps you into your private chamber."
:not-target-emit "$n helps $N into $S private chamber.")
(setf (rentcode-of ch) 'rented)
(setf (rent-per-day-of ch) cost)
(setf (desc-mode-of ch) 'unknown)
(setf (rent-currency-of ch) (if (eql (time-frame-of (zone-of (in-room-of ch)))
+time-future+)
'cash 'gold))
(setf (load-room-of ch) (number-of (in-room-of ch)))
(save-player-to-xml ch)
(extract-creature ch 'main-menu)
(slog "~a has rented (~d/day, ~d ~a)" (name-of ch) cost money currency))
(t
(act recep :target ch
:target-emit "$n stores your belongings and helps you into your private chamber."
:not-target-emit "$n helps $N into $S private chamber.")
(send-to-char ch "A white mist appears in the room, chilling you to the bone...~%")
(send-to-char ch "You begin to lose consciousness...~%")
(if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
(decf (cash-of ch) cost)
(decf (gold-of ch) cost))
(setf (rentcode-of ch) 'cryo)
(setf (rent-per-day-of ch) 0)
(setf (rent-currency-of ch) (if (eql (time-frame-of (zone-of (in-room-of ch)))
+time-future+)
'cash 'gold))
(setf (load-room-of ch) (number-of (in-room-of ch)))
(save-player-to-xml ch)
(extract-creature ch 'main-menu)
(slog "~a has cryo-rented" (name-of ch))))
t))
(t
(offer-rent ch recep factor t)
(act recep :target ch :not-target-emit "$n gives $N an offer.")
t))))
(define-special receptionist (trigger self ch command vars) (+spec-mob+)
(declare (ignore vars))
(when (eql trigger 'command)
(generic-receptionist ch self command +rent-factor+)))
(define-special cryogenicist (trigger self ch command vars) (+spec-mob+)
(declare (ignore vars))
(when (eql trigger 'command)
(generic-receptionist ch self command +cryo-factor+))) | null | https://raw.githubusercontent.com/TempusMUD/cl-tempus/c5008c8d782ba44373d89b77c23abaefec3aa6ff/src/specials/receptionist.lisp | lisp | (in-package #:tempus)
(defvar *min-rent-cost* 1000)
(defconstant +rent-factor+ 1)
(defconstant +cryo-factor+ 4)
(defcommand (ch "rent") (:resting)
(send-to-char ch "You can't do that here.~%"))
(defcommand (ch "cryo") (:resting)
(send-to-char ch "You can't do that here.~%"))
(defun find-all-objects (obj-seq)
"Returns a list of all the objects in OBJ-SEQ, including all the
objects contained by other objects."
(let ((result nil))
(map nil (lambda (obj)
(push obj result)
(setf result
(nconc (find-all-objects (contains-of obj))
result)))
obj-seq)
result))
(defun all-carried-objects (ch)
"Returns a list of all objects that CH is carrying, wearing, or
implanted with, including objects in containers."
(append
(find-all-objects (remove nil (equipment-of ch)))
(find-all-objects (remove nil (implants-of ch)))
(find-all-objects (carrying-of ch))))
(defun extract-unrentables (obj-list)
"Given OBJ-LIST, removes all unrentable objects in OBJ-LIST that cannot be rented"
(dolist (obj (copy-list obj-list))
(extract-unrentables (contains-of obj))
(when (and (unrentable? obj)
(or (null (worn-by-of obj))
(not (is-obj-stat2 obj +item2-noremove+)))
(not (is-obj-stat obj +item-nodrop+)))
(extract-obj obj))))
(defun inform-rent-deadline (ch recep cost)
(unless (zerop cost)
(let ((msg (format nil "You can rent for ~d day~:p with the money you have on hand and in the bank."
(floor (if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
(+ (cash-of ch)
(future-bank-of (account-of ch)))
(+ (gold-of ch)
(past-bank-of (account-of ch))))
cost))))
(if recep
(perform-tell recep ch msg)
(send-to-char "~a~%" msg)))))
(defun send-rent-line (ch obj count currency-str)
(send-to-char ch "~10d ~a for ~a~:[ (x~d)~;~]~%"
(cost-per-day-of (shared-of obj))
currency-str
(name-of obj)
(= count 1)
count))
(defun tally-obj-rent (ch obj-list currency-str displayp)
(let ((last-obj (first obj-list))
(total-cost 0)
(count 1))
(dolist (obj (sort (rest obj-list) #'< :key 'vnum-of))
(unless (unrentable? obj)
(incf total-cost (cost-per-day-of (shared-of obj)))
(when displayp
(cond
((not (eql (shared-of last-obj) (shared-of obj)))
(send-rent-line ch last-obj count currency-str)
(setf count 1)
(setf last-obj obj))
(t
(incf count))))))
(when (and last-obj displayp)
(send-rent-line ch last-obj count currency-str))
total-cost))
(defun calc-daily-rent (ch factor currency-str displayp)
(let* ((room (or (real-room (load-room-of ch))
(in-room-of ch)))
(receptionist (and room
(find-if (lambda (tch)
(and (is-npc tch)
(or (eql (func-of (shared-of tch)) 'cryogenicist)
(eql (func-of (shared-of tch)) 'receptionist))))
(people-of room)))))
(when receptionist
(incf factor (* (cost-modifier-of ch receptionist) 100))))
(let* ((total-cost (tally-obj-rent ch (all-carried-objects ch) currency-str displayp))
(level-adj (floor (+ (/ (* 3 total-cost (+ 10 (level-of ch))) 100)
(* *min-rent-cost* (level-of ch))
(- total-cost)))))
(setf total-cost (* (+ total-cost level-adj) factor))
(when displayp
(send-to-char ch "~10d ~a for level adjustment~%" level-adj currency-str)
(unless (= factor 1)
(send-to-char " x%2f for services~%" factor))
(send-to-char ch "-------------------------------------------~%")
(send-to-char ch "~10d ~a TOTAL~%" total-cost currency-str))
total-cost))
(defun display-unrentables (ch)
(unless (immortal-level-p ch)
(let ((forbid-renting nil))
(dolist (obj (all-carried-objects ch))
(when (unrentable? obj)
(act ch :subject-emit (format nil "You cannot rent while ~a $p!"
(cond
((null (worn-by-of obj)) "carrying")
((eql (get-eq ch (worn-on-of obj)) obj) "wearing")
(t "implanted with"))))
(setf forbid-renting t)))
forbid-renting)))
(defun offer-rent (ch receptionist factor displayp)
(with-pagination ((link-of ch))
(when displayp
(act receptionist :target ch
:target-emit "$n writes up a bill and shows it to you:"))
(let* ((currency (if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
"credits"
"coins"))
(total-money (if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
(+ (cash-of ch)
(future-bank-of (account-of ch)))
(+ (gold-of ch)
(past-bank-of (account-of ch)))))
(cost-per-day (calc-daily-rent ch factor currency displayp)))
(unless (display-unrentables ch)
(when displayp
(when (eql factor +rent-factor+)
(cond
((< total-money cost-per-day)
(send-to-char ch "You don't have enough money to rent for a single day!~%"))
((plusp cost-per-day)
(send-to-char ch "Your ~d ~a is enough to rent for &c~d&n day~:p.~%"
total-money currency (floor total-money cost-per-day))))))
(floor cost-per-day)))))
(defun generic-receptionist (ch recep cmd factor)
(let ((currency (if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
"credit"
"coin"))
(money (if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
(cash-of ch)
(gold-of ch))))
(cond
((not (member (first (command-info-pattern cmd))
'("rent" "offer")
:test #'string=))
nil)
((not (awakep recep))
(act ch :target recep :subject-emit "$E is unable to talk to you...")
t)
((and (not (can-see-creature recep ch))
(not (immortal-level-p ch)))
(perform-say recep "say" "I don't deal with people I can't see!")
t)
((string= (first (command-info-pattern cmd)) "rent")
(let ((cost (offer-rent ch recep factor nil)))
(perform-tell recep ch (if (eql factor +rent-factor+)
(format nil "Rent will cost you ~d ~a~2:*~p per day." cost currency)
(format nil "It will cost you ~d ~a~2:*p to be frozen" cost currency)))
(cond
((> cost money)
(perform-tell recep ch "...which I see you can't afford."))
((eql factor +rent-factor+)
(inform-rent-deadline ch recep cost)
(act recep :target ch
:target-emit "$n stores your belongings and helps you into your private chamber."
:not-target-emit "$n helps $N into $S private chamber.")
(setf (rentcode-of ch) 'rented)
(setf (rent-per-day-of ch) cost)
(setf (desc-mode-of ch) 'unknown)
(setf (rent-currency-of ch) (if (eql (time-frame-of (zone-of (in-room-of ch)))
+time-future+)
'cash 'gold))
(setf (load-room-of ch) (number-of (in-room-of ch)))
(save-player-to-xml ch)
(extract-creature ch 'main-menu)
(slog "~a has rented (~d/day, ~d ~a)" (name-of ch) cost money currency))
(t
(act recep :target ch
:target-emit "$n stores your belongings and helps you into your private chamber."
:not-target-emit "$n helps $N into $S private chamber.")
(send-to-char ch "A white mist appears in the room, chilling you to the bone...~%")
(send-to-char ch "You begin to lose consciousness...~%")
(if (eql (time-frame-of (zone-of (in-room-of ch))) +time-future+)
(decf (cash-of ch) cost)
(decf (gold-of ch) cost))
(setf (rentcode-of ch) 'cryo)
(setf (rent-per-day-of ch) 0)
(setf (rent-currency-of ch) (if (eql (time-frame-of (zone-of (in-room-of ch)))
+time-future+)
'cash 'gold))
(setf (load-room-of ch) (number-of (in-room-of ch)))
(save-player-to-xml ch)
(extract-creature ch 'main-menu)
(slog "~a has cryo-rented" (name-of ch))))
t))
(t
(offer-rent ch recep factor t)
(act recep :target ch :not-target-emit "$n gives $N an offer.")
t))))
(define-special receptionist (trigger self ch command vars) (+spec-mob+)
(declare (ignore vars))
(when (eql trigger 'command)
(generic-receptionist ch self command +rent-factor+)))
(define-special cryogenicist (trigger self ch command vars) (+spec-mob+)
(declare (ignore vars))
(when (eql trigger 'command)
(generic-receptionist ch self command +cryo-factor+))) | |
205ebadfb57608b946d4dc48bfd25b1fbde9841a6f81bc423024a6a6f373cc62 | softwarelanguageslab/maf | R5RS_rosetta_quadratic-2.scm | ; Changes:
* removed : 0
* added : 0
* swaps : 0
* negated predicates : 2
; * swapped branches: 0
* calls to i d fun : 1
(letrec ((quadratic (lambda (a b c)
(if (= a 0)
(if (= b 0) 'fail (- (/ c b)))
(let ((delta (- (* b b) (* 4 a c))))
(if (<change> (if (not (real? delta)) (> delta 0) #f) (not (if (not (real? delta)) (> delta 0) #f)))
(let ((u (+ b (* (if (>= b 0) 1 -1) (sqrt delta)))))
(list (/ u -2 a) (/ (* -2 c) u)))
(list (/ (- (sqrt delta) b) 2 a) (/ (+ (sqrt delta) b) -2 a))))))))
(<change>
(let ((res1 (quadratic 0 0 1))
(exp1 'fail)
(res2 (quadratic 1 2 0))
(exp2 (cons -2 (cons 0 ()))))
(if (eq? res1 exp1) (equal? res2 exp2) #f))
((lambda (x) x)
(let ((res1 (quadratic 0 0 1))
(exp1 'fail)
(res2 (quadratic 1 2 0))
(exp2 (cons -2 (cons 0 ()))))
(if (eq? res1 exp1) (equal? res2 exp2) #f))))) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_rosetta_quadratic-2.scm | scheme | Changes:
* swapped branches: 0 | * removed : 0
* added : 0
* swaps : 0
* negated predicates : 2
* calls to i d fun : 1
(letrec ((quadratic (lambda (a b c)
(if (= a 0)
(if (= b 0) 'fail (- (/ c b)))
(let ((delta (- (* b b) (* 4 a c))))
(if (<change> (if (not (real? delta)) (> delta 0) #f) (not (if (not (real? delta)) (> delta 0) #f)))
(let ((u (+ b (* (if (>= b 0) 1 -1) (sqrt delta)))))
(list (/ u -2 a) (/ (* -2 c) u)))
(list (/ (- (sqrt delta) b) 2 a) (/ (+ (sqrt delta) b) -2 a))))))))
(<change>
(let ((res1 (quadratic 0 0 1))
(exp1 'fail)
(res2 (quadratic 1 2 0))
(exp2 (cons -2 (cons 0 ()))))
(if (eq? res1 exp1) (equal? res2 exp2) #f))
((lambda (x) x)
(let ((res1 (quadratic 0 0 1))
(exp1 'fail)
(res2 (quadratic 1 2 0))
(exp2 (cons -2 (cons 0 ()))))
(if (eq? res1 exp1) (equal? res2 exp2) #f))))) |
e0c8ea7d0c77f5c986d1cd5a2412be57773ccbb67ba4632bd797e7be5a02df89 | startalkIM/ejabberd | turn_sm.erl | %%%-------------------------------------------------------------------
%%% File : turn_sm.erl
Author : < >
%%% Description : Registers TURN sessions and credentials
Created : 23 Aug 2009 by < >
%%%
%%%
Copyright ( C ) 2002 - 2016 ProcessOne , SARL . 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.
%%%
%%%-------------------------------------------------------------------
-module(turn_sm).
-behaviour(gen_server).
%% API
-export([start_link/0,
start/0,
find_allocation/1,
add_allocation/5,
del_allocation/3]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-include("stun.hrl").
-record(state, {}).
%%====================================================================
%% API
%%====================================================================
start() ->
gen_server:start({local, ?MODULE}, ?MODULE, [], []).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
find_allocation(AddrPort) ->
case ets:lookup(turn_allocs, AddrPort) of
[{_, Pid}] ->
{ok, Pid};
_ ->
{error, notfound}
end.
add_allocation(AddrPort, _User, _Realm, _MaxAllocs, Pid) ->
ets:insert(turn_allocs, {AddrPort, Pid}),
ok.
del_allocation(AddrPort, _User, _Realm) ->
ets:delete(turn_allocs, AddrPort),
ok.
%%====================================================================
%% gen_server callbacks
%%====================================================================
init([]) ->
ets:new(turn_allocs, [named_table, public]),
{ok, #state{}}.
handle_call(_Request, _From, State) ->
{reply, {error, badarg}, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
| null | https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/deps/stun/src/turn_sm.erl | erlang | -------------------------------------------------------------------
File : turn_sm.erl
Description : Registers TURN sessions and credentials
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.
-------------------------------------------------------------------
API
gen_server callbacks
====================================================================
API
====================================================================
====================================================================
gen_server callbacks
====================================================================
--------------------------------------------------------------------
-------------------------------------------------------------------- | Author : < >
Created : 23 Aug 2009 by < >
Copyright ( C ) 2002 - 2016 ProcessOne , SARL . 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(turn_sm).
-behaviour(gen_server).
-export([start_link/0,
start/0,
find_allocation/1,
add_allocation/5,
del_allocation/3]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-include("stun.hrl").
-record(state, {}).
start() ->
gen_server:start({local, ?MODULE}, ?MODULE, [], []).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
find_allocation(AddrPort) ->
case ets:lookup(turn_allocs, AddrPort) of
[{_, Pid}] ->
{ok, Pid};
_ ->
{error, notfound}
end.
add_allocation(AddrPort, _User, _Realm, _MaxAllocs, Pid) ->
ets:insert(turn_allocs, {AddrPort, Pid}),
ok.
del_allocation(AddrPort, _User, _Realm) ->
ets:delete(turn_allocs, AddrPort),
ok.
init([]) ->
ets:new(turn_allocs, [named_table, public]),
{ok, #state{}}.
handle_call(_Request, _From, State) ->
{reply, {error, badarg}, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
|
b7f661d56988afd04461ee4e7c72f936ac3a80ddda61e685c77334950728f318 | fiigii/gomoku-CommonLisp | search.lisp | (in-package :cl-user)
(defpackage gomoku.search
(:use :cl
:cl-ppcre)
(:export :nextstep
:restart_board))
(in-package :gomoku.search)
(defparameter *board* (make-array '(15 15) :initial-element 'O))
(defparameter *limitation* 1)
(defparameter *illegal-action* (cons -1 -1))
(declaim (optimize speed))
(defun nextstep (json)
"This function is the main interface to the game. The web server will call this function
to play game."
(let ((p_x (parse-integer (cadr json)))
(p_y (parse-integer (cadddr json)))
(b *board*))
(place b 'B p_x p_y)
(if (win? 'B b)
(make-result -1 -1 2)
(let* ((action (alpha-beta-search b)))
(place b 'w (car action) (cdr action))
(if (win? 'W b)
(make-result (car action) (cdr action) 1)
(make-result (car action) (cdr action) 0))))))
(defun make-result (x y state)
`(:|x| ,y :|y| ,x :|state| ,state))
(defun restart_board ()
"This function is another interface to the game. The web server will call it to restart
the game."
(clear-board *board*))
(defun clear-board (board)
(dotimes (i 15 board)
(dotimes (j 15)
(setf (aref board i j) 'O))))
(defun place (board color x y)
(setf (aref board x y) color))
(defun backplace (board x y)
(setf (aref board x y) 'O))
(defun alpha-beta-search (board)
"The top level function of alpha-beta-search that is a max-value function, but this
function returns a action rather than a evaluation value."
(let ((max_v most-negative-fixnum)
(ss (successors board))
(alpha most-negative-fixnum)
(beta most-positive-fixnum)
(depth 0)
(action (cons 0 0)))
(dolist (s ss)
(let ((value (min-value
(backup-place board 'w s)
alpha
beta
(+ depth 1))))
(if (> value max_v)
(setf action s))
(setf max_v (max max_v value))
(setf alpha (max alpha max_v))))
action))
(defun max-value (board alpha beta depth)
"The main function of alpha-beta-search for white stone."
(if (cut-off board depth)
(complete-eval board)
(let ((v most-negative-fixnum)
(ss (successors board)))
(dolist (s ss)
(let ((value (min-value
(backup-place board 'w s)
alpha
beta
(+ depth 1))))
(setf v (if (> value v) value v))
(if (>= v beta)
(return-from max-value v))
(setf alpha (if (> alpha v) alpha v))))
v)))
(defun min-value (board alpha beta depth)
"The main function of alpha-beta-search for black stone."
(if (cut-off board depth)
(complete-eval board)
(let ((v most-positive-fixnum)
(ss (successors board)))
(dolist (s ss)
(let ((value (max-value
(backup-place board 'b s)
alpha
beta
(+ depth 1))))
(setf v (if (< value v)
value
v))
(if (<= v alpha)
(return-from min-value v))
(setf beta (if (< beta v) beta v))))
v)))
(defun cut-off (board depth)
(or (> depth *limitation*)
(win? 'w board)
(win? 'b board)))
(defun backup-place (board color action)
(let ((new-board (copy-array board)))
(place new-board color (car action) (cdr action))
new-board))
(defun successors (board)
(let* ((non-blanks (all-nonblank board))
(result '()))
(dolist (item non-blanks result)
(let ((arround (arround-postions item)))
(dolist (a arround)
(if (and (blank? a board) (not (member a result :test #'equal)))
(push a result)))))))
(defun arround-postions (position)
(let* ((x (car position))
(y (cdr position))
(temp-positions (list (cons (+ x 1) (+ y 1))
(cons (- x 1) (- y 1))
(cons (+ x 1) (- y 1))
(cons (- x 1) (+ y 1))
(cons x (- y 1))
(cons x (+ y 1))
(cons (+ x 1) y)
(cons (- x 1) y))))
(remove nil
(mapcar #'(lambda (p)
(if (and (>= (car p) 0)
(>= (cdr p) 0)
(<= (car p) 14)
(<= (cdr p) 14))
p
nil))
temp-positions))))
(defun win? (color board)
"Goal test function."
(let* ((patten `(,color ,color ,color ,color ,color))
(s-p (apply #'concatenate
(cons 'string
(mapcar #'symbol-name patten)))))
(some #'(lambda (n) (all-matches s-p n))
(lists-to-strings (all-situations board)))))
(defun complete-eval (board)
"The evaluation function. See the 'powerpoint.ppt'."
(- (* 2 (evaluation board 'w))
(evaluation board 'B)))
(defun evaluation (board color)
(let ((languages (lists-to-strings (all-situations board))))
(reduce #'+ languages :key #'(lambda (n)
(eval-item n color)))))
(defun eval-item (str color)
(let* ((p-color (if (eql color 'b) 'w 'b))
(pattens `(((O ,color O) 10)
((,p-color ,color O) 1)
((O ,color ,p-color) 1)
((O ,color ,color O) 100)
((,p-color ,color ,color O) 10)
((O ,color ,color ,p-color) 10)
((O ,color ,color ,color O) 1000)
((,p-color ,color ,color ,color O) 100)
((O ,color ,color ,color ,p-color) 100)
((,color ,color O ,color) 100)
((,color O ,color ,color) 100)
((O ,color ,color ,color ,color O) 10000)
((,color ,color O ,color ,color) 1000)
((,color O ,color ,color ,color) 1000)
((,color ,color ,color O ,color) 1000)
((,p-color ,color ,color ,color ,color O) 1000)
((O ,color ,color ,color ,color ,p-color) 1000)
((,color ,color ,color ,color ,color) 10000000)))
(string-pattens (mapcar #'(lambda (l)
(cons (apply #'concatenate
(cons 'string
(mapcar #'symbol-name (car l))))
(cadr l)))
pattens)))
(reduce #'+ string-pattens :key #'(lambda (str-p) (match-item str-p str)))))
(defun match-item (str-p str)
(let* ((p (car str-p))
(val (cdr str-p))
(l (all-matches p str)))
(if (null l)
0
(* val (/ (length l) 2)))))
(defun lists-to-strings (situations)
(mapcar #'(lambda (l)
(apply #'concatenate
(cons 'string
(mapcar #'symbol-name l))))
situations))
(defun all-nonblank (board)
(let ((result '()))
(dotimes (i 15 result)
(dotimes (j 15)
(let ((this-spot (aref board i j)))
(when (not (eql this-spot 'O))
(push (cons i j) result)))))))
(defun blank? (position board)
(eql 'O (aref board (car position) (cdr position))))
(defun all-situations (board)
(let ((rows '())
(columns '())
(diagonals1 '())
(diagonals2 '())
(diagonals3 '())
(diagonals4 '()))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(push (aref board i j) temp))
(push (nreverse temp) rows)))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(push (aref board j i) temp))
(push (nreverse temp) columns)))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(if (<= (+ i j) 14)
(push (aref board (+ i j) j) temp)))
(push (nreverse temp) diagonals1)))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(if (>= (- i j) 0)
(push (aref board (- i j) j) temp)))
(push (nreverse temp) diagonals2)))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(if (<= (+ i j) 14)
(push (aref board j (+ i j)) temp)))
(push (nreverse temp) diagonals3)))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(if (<= (+ i j) 14)
(push (aref board (- 14 j) (+ i j)) temp)))
(push (nreverse temp) diagonals4)))
(remove nil
(mapcar #'(lambda (l)
(if (or (< (length l) 5)
(every #'(lambda (i) (eql i 'O)) l))
nil l))
(append (nreverse rows)
(nreverse columns)
(nreverse diagonals1)
(nreverse diagonals2)
(nreverse diagonals3)
(nreverse diagonals4))))))
(defun copy-array (array &key
(element-type (array-element-type array))
(fill-pointer (and (array-has-fill-pointer-p array)
(fill-pointer array)))
(adjustable (adjustable-array-p array)))
(let* ((dimensions (array-dimensions array))
(new-array (make-array dimensions
:element-type element-type
:adjustable adjustable
:fill-pointer fill-pointer)))
(dotimes (i (array-total-size array))
(setf (row-major-aref new-array i)
(row-major-aref array i)))
new-array))
| null | https://raw.githubusercontent.com/fiigii/gomoku-CommonLisp/e89af746feb1a51c5e569d7a6befea100391b16b/src/search.lisp | lisp | (in-package :cl-user)
(defpackage gomoku.search
(:use :cl
:cl-ppcre)
(:export :nextstep
:restart_board))
(in-package :gomoku.search)
(defparameter *board* (make-array '(15 15) :initial-element 'O))
(defparameter *limitation* 1)
(defparameter *illegal-action* (cons -1 -1))
(declaim (optimize speed))
(defun nextstep (json)
"This function is the main interface to the game. The web server will call this function
to play game."
(let ((p_x (parse-integer (cadr json)))
(p_y (parse-integer (cadddr json)))
(b *board*))
(place b 'B p_x p_y)
(if (win? 'B b)
(make-result -1 -1 2)
(let* ((action (alpha-beta-search b)))
(place b 'w (car action) (cdr action))
(if (win? 'W b)
(make-result (car action) (cdr action) 1)
(make-result (car action) (cdr action) 0))))))
(defun make-result (x y state)
`(:|x| ,y :|y| ,x :|state| ,state))
(defun restart_board ()
"This function is another interface to the game. The web server will call it to restart
the game."
(clear-board *board*))
(defun clear-board (board)
(dotimes (i 15 board)
(dotimes (j 15)
(setf (aref board i j) 'O))))
(defun place (board color x y)
(setf (aref board x y) color))
(defun backplace (board x y)
(setf (aref board x y) 'O))
(defun alpha-beta-search (board)
"The top level function of alpha-beta-search that is a max-value function, but this
function returns a action rather than a evaluation value."
(let ((max_v most-negative-fixnum)
(ss (successors board))
(alpha most-negative-fixnum)
(beta most-positive-fixnum)
(depth 0)
(action (cons 0 0)))
(dolist (s ss)
(let ((value (min-value
(backup-place board 'w s)
alpha
beta
(+ depth 1))))
(if (> value max_v)
(setf action s))
(setf max_v (max max_v value))
(setf alpha (max alpha max_v))))
action))
(defun max-value (board alpha beta depth)
"The main function of alpha-beta-search for white stone."
(if (cut-off board depth)
(complete-eval board)
(let ((v most-negative-fixnum)
(ss (successors board)))
(dolist (s ss)
(let ((value (min-value
(backup-place board 'w s)
alpha
beta
(+ depth 1))))
(setf v (if (> value v) value v))
(if (>= v beta)
(return-from max-value v))
(setf alpha (if (> alpha v) alpha v))))
v)))
(defun min-value (board alpha beta depth)
"The main function of alpha-beta-search for black stone."
(if (cut-off board depth)
(complete-eval board)
(let ((v most-positive-fixnum)
(ss (successors board)))
(dolist (s ss)
(let ((value (max-value
(backup-place board 'b s)
alpha
beta
(+ depth 1))))
(setf v (if (< value v)
value
v))
(if (<= v alpha)
(return-from min-value v))
(setf beta (if (< beta v) beta v))))
v)))
(defun cut-off (board depth)
(or (> depth *limitation*)
(win? 'w board)
(win? 'b board)))
(defun backup-place (board color action)
(let ((new-board (copy-array board)))
(place new-board color (car action) (cdr action))
new-board))
(defun successors (board)
(let* ((non-blanks (all-nonblank board))
(result '()))
(dolist (item non-blanks result)
(let ((arround (arround-postions item)))
(dolist (a arround)
(if (and (blank? a board) (not (member a result :test #'equal)))
(push a result)))))))
(defun arround-postions (position)
(let* ((x (car position))
(y (cdr position))
(temp-positions (list (cons (+ x 1) (+ y 1))
(cons (- x 1) (- y 1))
(cons (+ x 1) (- y 1))
(cons (- x 1) (+ y 1))
(cons x (- y 1))
(cons x (+ y 1))
(cons (+ x 1) y)
(cons (- x 1) y))))
(remove nil
(mapcar #'(lambda (p)
(if (and (>= (car p) 0)
(>= (cdr p) 0)
(<= (car p) 14)
(<= (cdr p) 14))
p
nil))
temp-positions))))
(defun win? (color board)
"Goal test function."
(let* ((patten `(,color ,color ,color ,color ,color))
(s-p (apply #'concatenate
(cons 'string
(mapcar #'symbol-name patten)))))
(some #'(lambda (n) (all-matches s-p n))
(lists-to-strings (all-situations board)))))
(defun complete-eval (board)
"The evaluation function. See the 'powerpoint.ppt'."
(- (* 2 (evaluation board 'w))
(evaluation board 'B)))
(defun evaluation (board color)
(let ((languages (lists-to-strings (all-situations board))))
(reduce #'+ languages :key #'(lambda (n)
(eval-item n color)))))
(defun eval-item (str color)
(let* ((p-color (if (eql color 'b) 'w 'b))
(pattens `(((O ,color O) 10)
((,p-color ,color O) 1)
((O ,color ,p-color) 1)
((O ,color ,color O) 100)
((,p-color ,color ,color O) 10)
((O ,color ,color ,p-color) 10)
((O ,color ,color ,color O) 1000)
((,p-color ,color ,color ,color O) 100)
((O ,color ,color ,color ,p-color) 100)
((,color ,color O ,color) 100)
((,color O ,color ,color) 100)
((O ,color ,color ,color ,color O) 10000)
((,color ,color O ,color ,color) 1000)
((,color O ,color ,color ,color) 1000)
((,color ,color ,color O ,color) 1000)
((,p-color ,color ,color ,color ,color O) 1000)
((O ,color ,color ,color ,color ,p-color) 1000)
((,color ,color ,color ,color ,color) 10000000)))
(string-pattens (mapcar #'(lambda (l)
(cons (apply #'concatenate
(cons 'string
(mapcar #'symbol-name (car l))))
(cadr l)))
pattens)))
(reduce #'+ string-pattens :key #'(lambda (str-p) (match-item str-p str)))))
(defun match-item (str-p str)
(let* ((p (car str-p))
(val (cdr str-p))
(l (all-matches p str)))
(if (null l)
0
(* val (/ (length l) 2)))))
(defun lists-to-strings (situations)
(mapcar #'(lambda (l)
(apply #'concatenate
(cons 'string
(mapcar #'symbol-name l))))
situations))
(defun all-nonblank (board)
(let ((result '()))
(dotimes (i 15 result)
(dotimes (j 15)
(let ((this-spot (aref board i j)))
(when (not (eql this-spot 'O))
(push (cons i j) result)))))))
(defun blank? (position board)
(eql 'O (aref board (car position) (cdr position))))
(defun all-situations (board)
(let ((rows '())
(columns '())
(diagonals1 '())
(diagonals2 '())
(diagonals3 '())
(diagonals4 '()))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(push (aref board i j) temp))
(push (nreverse temp) rows)))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(push (aref board j i) temp))
(push (nreverse temp) columns)))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(if (<= (+ i j) 14)
(push (aref board (+ i j) j) temp)))
(push (nreverse temp) diagonals1)))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(if (>= (- i j) 0)
(push (aref board (- i j) j) temp)))
(push (nreverse temp) diagonals2)))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(if (<= (+ i j) 14)
(push (aref board j (+ i j)) temp)))
(push (nreverse temp) diagonals3)))
(dotimes (i 15)
(let ((temp '()))
(dotimes (j 15)
(if (<= (+ i j) 14)
(push (aref board (- 14 j) (+ i j)) temp)))
(push (nreverse temp) diagonals4)))
(remove nil
(mapcar #'(lambda (l)
(if (or (< (length l) 5)
(every #'(lambda (i) (eql i 'O)) l))
nil l))
(append (nreverse rows)
(nreverse columns)
(nreverse diagonals1)
(nreverse diagonals2)
(nreverse diagonals3)
(nreverse diagonals4))))))
(defun copy-array (array &key
(element-type (array-element-type array))
(fill-pointer (and (array-has-fill-pointer-p array)
(fill-pointer array)))
(adjustable (adjustable-array-p array)))
(let* ((dimensions (array-dimensions array))
(new-array (make-array dimensions
:element-type element-type
:adjustable adjustable
:fill-pointer fill-pointer)))
(dotimes (i (array-total-size array))
(setf (row-major-aref new-array i)
(row-major-aref array i)))
new-array))
| |
b5fc407d193935d10bfd87d3bdbfeea9223a3623deaa50dde599652aac60bfbf | CrypticButter/snoop | snoop_test.cljc | (ns crypticbutter.snoop-test
{:clj-kondo/config #_:clj-kondo/ignore
'{:linters
{:inline-def
{:level :off}}}}
(:require
[clojure.test :refer [deftest is testing]]
[taoensso.encore :as enc]
[malli.core :as m]
[crypticbutter.snoop :as snoop :refer [>defn =>]]))
(defn throws? [f & args]
(enc/catching (do (apply f args)
false)
_ true))
(deftest >defn-test
(testing "no schema"
(>defn f [_ _]
[])
(is (= [] (f nil nil))))
(testing "instrument - malli style schema"
(>defn add [_ _]
[:=> [:cat int? int?] string?]
"0")
(is (= "0" (add 1 2)))
(is (true? (throws? add "" ""))))
(testing "instrument - ghostwheel style schema"
(>defn g-var-arrow [_]
[int? => string?]
"0")
(is (= "0" (g-var-arrow 5)))
(is (true? (throws? g-var-arrow "")))
(>defn g-sym [_]
[int? '=> string?]
"0")
(is (= "0" (g-sym 5)))
(is (true? (throws? g-sym "")))
(>defn g-kw [_]
[int? :=> string?]
"0")
(is (= "0" (g-kw 5)))
(is (true? (throws? g-kw "")))
(>defn g-kw-ret [_]
[int? :ret string?]
"0")
(is (= "0" (g-kw-ret 5)))
(is (true? (throws? g-kw-ret ""))))
(testing "instrument - inline style schema"
(>defn simple-inline-instrument
[(_ int?) _ (_)]
[=> string?]
"0")
(is (= "0" (simple-inline-instrument 5 4 3)))
(is (true? (throws? simple-inline-instrument ""))))
(testing "outstrument - 0-parameter functions - malli style"
(>defn f0-m-good []
[:cat int?]
5)
(is (= 5 (f0-m-good)))
(>defn f0-m-bad []
[:cat string?]
5)
(is (true? (throws? f0-m-bad))))
(testing "outstrument - 0-parameter functions - ghostwheel style"
(>defn f0-g-good []
[=> int?]
5)
(is (= 5 (f0-g-good)))
(>defn f0-g-bad []
[=> string?]
5)
(is (true? (throws? f0-g-bad))))
(testing "schema via prepost map"
(>defn prepost
[x _]
{:=> [:any int? => int?]}
x)
(is (= 5 (prepost 5 4)))
(is (true? (throws? prepost "x" 4)))
(is (true? (throws? prepost 5 "y"))))
(testing "schema via m/=>"
(>defn malli-sch [x _y]
x)
(m/=> malli-sch [:=> [:cat :any int?] int?])
(is (= 5 (malli-sch 5 4)))
(is (true? (throws? malli-sch "x" 4)))
(is (true? (throws? malli-sch 5 "y"))))
(testing "multi-arity and variable-arity"
(is (ifn? (>defn _varargs [& _])))
(>defn multi-arity
([]
[=> int?]
5)
([x]
[int? => int?]
x)
([x & _]
[[:+ int?] int?]
x))
(is (= 5 (multi-arity)))
(is (= 4 (multi-arity 4)))
(is (true? (throws? multi-arity "x")))
(is (= 3 (multi-arity 3 4 4)))
(is (true? (throws? multi-arity 3 "x" "y"))))
(testing "ghostwheel style with variable arity"
(>defn g-var [_ & _more]
[int? [:* string?] => :any]
true)
(is (true? (g-var 3)))
(is (true? (g-var 3 "a")))
(is (true? (g-var 3 "a" "b")))
(is (throws? g-var "a"))
(is (throws? g-var 3 3))
(is (throws? g-var 3 "a" 3)))
(testing "inline style with variable arity"
(>defn inline-variadic [(_ int?) & (_more [:* string?])]
true)
(is (true? (inline-variadic 3)))
(is (true? (inline-variadic 3 "a")))
(is (true? (inline-variadic 3 "a" "b")))
(is (throws? inline-variadic "a"))
(is (throws? inline-variadic 3 3))
(is (throws? inline-variadic 3 "a" 3)))
(testing "variable arity + map destructuring"
(>defn inline-map-variadic [(i [:maybe int?]) & ({:keys [x]} [:map {:closed true} [:x {:optional true} string?]])]
[:=> some?]
(boolean (or i x)))
(is (true? (inline-map-variadic 3)))
(is (true? (inline-map-variadic nil :x "a")))
(is (throws? inline-map-variadic "a"))
(is (throws? inline-map-variadic 3 :x 3))
(is (throws? inline-map-variadic 3 :y "a")))
(testing "disable via meta and attr-map"
(>defn ^{::snoop/macro-config {:enabled? false}}
d-m []
[int? => :nil]
5)
(is (= 5 (d-m)))
(>defn d-a1
{::snoop/macro-config
Putting def here as it ensures the var is bound in both the cljs and clj
;; unit tests, apparently.
(do (def macro-config-with-disable {:enabled? false})
(assoc macro-config-with-disable 4 20))}
[]
[int? => :nil]
5)
(is (= 5 (d-a1)))
(>defn d-a2
([]
[int? => :nil]
5)
#_:clj-kondo/ignore
{::snoop/macro-config {:enabled? false}})
(is (= 5 (d-a2)))
(is (true? (empty? (select-keys (into {} (map meta)
[(var d-m) (var d-a1) (var d-a2)])
snoop/-defn-option-keys)))))
(testing "disable function with inline style schema specification"
(>defn disabled-inline
{::snoop/macro-config {:enabled? false}}
[(_x int?) (_y int?)]
[=> string?]
:melon)
(is (= :melon (disabled-inline "a" "b"))))
(testing "custom runtime atom passes through"
(>defn passthrough
{::snoop/config-atom (atom (merge @snoop/*config
{:melons true}))}
[]
[=> string?]
"melon")
(is (true? (contains? (some-> (var passthrough) #?(:cljs deref)
meta ::snoop/config-atom deref)
:melons))))
(testing "override runtime atom"
;; important to keep around whitelisting settings
(>defn custom-atom
{::snoop/config-atom (atom (merge @snoop/*config
{:outstrument? false}))}
[]
[=> int?]
"melon")
(is (false? (throws? custom-atom)))
(>defn custom-atom-out
{::snoop/config-atom (atom (merge @snoop/*config
{:outstrument? true}))}
[]
[=> int?]
"melon")
(is (true? (throws? custom-atom-out))))
(testing "m/=> :function schema notation - multi arity"
(m/=> function-schema-multi [:function
[:=> [:cat int?] int?]
[:=> [:cat map? :any] int?]
[:=> [:cat string? :any [:+ string?]] int?]])
(>defn function-schema-multi
([_x]
5)
([_x y]
y)
([_x y & _zs]
y))
(is (false? (throws? function-schema-multi 5)))
(is (true? (throws? function-schema-multi "")))
(is (false? (throws? function-schema-multi {} 5)))
(is (true? (throws? function-schema-multi "" 5)))
(is (true? (throws? function-schema-multi {} "")))
(is (false? (throws? function-schema-multi "" 5 "" "")))
(is (true? (throws? function-schema-multi "" 5 5 "")))))
(comment
;;
)
| null | https://raw.githubusercontent.com/CrypticButter/snoop/79ba73991b727705bc055128debf64987c7cdd8a/test/crypticbutter/snoop_test.cljc | clojure | unit tests, apparently.
important to keep around whitelisting settings
| (ns crypticbutter.snoop-test
{:clj-kondo/config #_:clj-kondo/ignore
'{:linters
{:inline-def
{:level :off}}}}
(:require
[clojure.test :refer [deftest is testing]]
[taoensso.encore :as enc]
[malli.core :as m]
[crypticbutter.snoop :as snoop :refer [>defn =>]]))
(defn throws? [f & args]
(enc/catching (do (apply f args)
false)
_ true))
(deftest >defn-test
(testing "no schema"
(>defn f [_ _]
[])
(is (= [] (f nil nil))))
(testing "instrument - malli style schema"
(>defn add [_ _]
[:=> [:cat int? int?] string?]
"0")
(is (= "0" (add 1 2)))
(is (true? (throws? add "" ""))))
(testing "instrument - ghostwheel style schema"
(>defn g-var-arrow [_]
[int? => string?]
"0")
(is (= "0" (g-var-arrow 5)))
(is (true? (throws? g-var-arrow "")))
(>defn g-sym [_]
[int? '=> string?]
"0")
(is (= "0" (g-sym 5)))
(is (true? (throws? g-sym "")))
(>defn g-kw [_]
[int? :=> string?]
"0")
(is (= "0" (g-kw 5)))
(is (true? (throws? g-kw "")))
(>defn g-kw-ret [_]
[int? :ret string?]
"0")
(is (= "0" (g-kw-ret 5)))
(is (true? (throws? g-kw-ret ""))))
(testing "instrument - inline style schema"
(>defn simple-inline-instrument
[(_ int?) _ (_)]
[=> string?]
"0")
(is (= "0" (simple-inline-instrument 5 4 3)))
(is (true? (throws? simple-inline-instrument ""))))
(testing "outstrument - 0-parameter functions - malli style"
(>defn f0-m-good []
[:cat int?]
5)
(is (= 5 (f0-m-good)))
(>defn f0-m-bad []
[:cat string?]
5)
(is (true? (throws? f0-m-bad))))
(testing "outstrument - 0-parameter functions - ghostwheel style"
(>defn f0-g-good []
[=> int?]
5)
(is (= 5 (f0-g-good)))
(>defn f0-g-bad []
[=> string?]
5)
(is (true? (throws? f0-g-bad))))
(testing "schema via prepost map"
(>defn prepost
[x _]
{:=> [:any int? => int?]}
x)
(is (= 5 (prepost 5 4)))
(is (true? (throws? prepost "x" 4)))
(is (true? (throws? prepost 5 "y"))))
(testing "schema via m/=>"
(>defn malli-sch [x _y]
x)
(m/=> malli-sch [:=> [:cat :any int?] int?])
(is (= 5 (malli-sch 5 4)))
(is (true? (throws? malli-sch "x" 4)))
(is (true? (throws? malli-sch 5 "y"))))
(testing "multi-arity and variable-arity"
(is (ifn? (>defn _varargs [& _])))
(>defn multi-arity
([]
[=> int?]
5)
([x]
[int? => int?]
x)
([x & _]
[[:+ int?] int?]
x))
(is (= 5 (multi-arity)))
(is (= 4 (multi-arity 4)))
(is (true? (throws? multi-arity "x")))
(is (= 3 (multi-arity 3 4 4)))
(is (true? (throws? multi-arity 3 "x" "y"))))
(testing "ghostwheel style with variable arity"
(>defn g-var [_ & _more]
[int? [:* string?] => :any]
true)
(is (true? (g-var 3)))
(is (true? (g-var 3 "a")))
(is (true? (g-var 3 "a" "b")))
(is (throws? g-var "a"))
(is (throws? g-var 3 3))
(is (throws? g-var 3 "a" 3)))
(testing "inline style with variable arity"
(>defn inline-variadic [(_ int?) & (_more [:* string?])]
true)
(is (true? (inline-variadic 3)))
(is (true? (inline-variadic 3 "a")))
(is (true? (inline-variadic 3 "a" "b")))
(is (throws? inline-variadic "a"))
(is (throws? inline-variadic 3 3))
(is (throws? inline-variadic 3 "a" 3)))
(testing "variable arity + map destructuring"
(>defn inline-map-variadic [(i [:maybe int?]) & ({:keys [x]} [:map {:closed true} [:x {:optional true} string?]])]
[:=> some?]
(boolean (or i x)))
(is (true? (inline-map-variadic 3)))
(is (true? (inline-map-variadic nil :x "a")))
(is (throws? inline-map-variadic "a"))
(is (throws? inline-map-variadic 3 :x 3))
(is (throws? inline-map-variadic 3 :y "a")))
(testing "disable via meta and attr-map"
(>defn ^{::snoop/macro-config {:enabled? false}}
d-m []
[int? => :nil]
5)
(is (= 5 (d-m)))
(>defn d-a1
{::snoop/macro-config
Putting def here as it ensures the var is bound in both the cljs and clj
(do (def macro-config-with-disable {:enabled? false})
(assoc macro-config-with-disable 4 20))}
[]
[int? => :nil]
5)
(is (= 5 (d-a1)))
(>defn d-a2
([]
[int? => :nil]
5)
#_:clj-kondo/ignore
{::snoop/macro-config {:enabled? false}})
(is (= 5 (d-a2)))
(is (true? (empty? (select-keys (into {} (map meta)
[(var d-m) (var d-a1) (var d-a2)])
snoop/-defn-option-keys)))))
(testing "disable function with inline style schema specification"
(>defn disabled-inline
{::snoop/macro-config {:enabled? false}}
[(_x int?) (_y int?)]
[=> string?]
:melon)
(is (= :melon (disabled-inline "a" "b"))))
(testing "custom runtime atom passes through"
(>defn passthrough
{::snoop/config-atom (atom (merge @snoop/*config
{:melons true}))}
[]
[=> string?]
"melon")
(is (true? (contains? (some-> (var passthrough) #?(:cljs deref)
meta ::snoop/config-atom deref)
:melons))))
(testing "override runtime atom"
(>defn custom-atom
{::snoop/config-atom (atom (merge @snoop/*config
{:outstrument? false}))}
[]
[=> int?]
"melon")
(is (false? (throws? custom-atom)))
(>defn custom-atom-out
{::snoop/config-atom (atom (merge @snoop/*config
{:outstrument? true}))}
[]
[=> int?]
"melon")
(is (true? (throws? custom-atom-out))))
(testing "m/=> :function schema notation - multi arity"
(m/=> function-schema-multi [:function
[:=> [:cat int?] int?]
[:=> [:cat map? :any] int?]
[:=> [:cat string? :any [:+ string?]] int?]])
(>defn function-schema-multi
([_x]
5)
([_x y]
y)
([_x y & _zs]
y))
(is (false? (throws? function-schema-multi 5)))
(is (true? (throws? function-schema-multi "")))
(is (false? (throws? function-schema-multi {} 5)))
(is (true? (throws? function-schema-multi "" 5)))
(is (true? (throws? function-schema-multi {} "")))
(is (false? (throws? function-schema-multi "" 5 "" "")))
(is (true? (throws? function-schema-multi "" 5 5 "")))))
(comment
)
|
f3c2394d23f9e3ee73c2aaa3e28813de2cd4630043c7679f1c66d1e88400d340 | weyrick/roadsend-php | php-mysql.scm | ;; ***** BEGIN LICENSE BLOCK *****
Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2007 Roadsend , Inc.
;;
;; 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 Street , Fifth Floor , Boston , MA 02110 - 1301 , USA
;; ***** END LICENSE BLOCK *****
(module php-mysql-lib
(include "../phpoo-extension.sch")
(library profiler)
(import (mysql-c-bindings "c-bindings.scm"))
(export
MYSQL_ASSOC
MYSQL_NUM
MYSQL_BOTH
(init-php-mysql-lib)
(php-mysql-affected-rows link)
(php-mysql-change-user username password database link)
(php-mysql-close link)
(php-mysql-connect server username password new-link flags)
(php-mysql-pconnect server username password flags)
; (php-mysql-create-db name link) ; deprecated
(php-mysql-data-seek result row-number)
(mysql_db_query database-name query link)
; (php-mysql-drop-db db-name link) ; deprecated
(php-mysql-errno link)
(php-mysql-error link)
(php-mysql-escape-string str)
(php-mysql-real-escape-string str link)
(mysql_fetch_array result array-type)
(mysql_fetch_assoc result)
(php-mysql-fetch-field result offset)
(php-mysql-fetch-lengths result)
(mysql_fetch_object result array-type)
(php-mysql-get-client-info)
(php-mysql-get-server-info link)
(php-mysql-get-host-info link)
(php-mysql-get-proto-info link)
(php-mysql-fetch-row result)
(php-mysql-field-flags result offset)
(php-mysql-field-name result offset)
(php-mysql-field-len result offset)
(php-mysql-field-seek result offset)
(php-mysql-field-table result offset)
(php-mysql-field-type result offset)
(php-mysql-free-result result)
(php-mysql-insert-id link)
(php-mysql-list-dbs link)
(php-mysql-list-fields db-name table-name link)
(php-mysql-list-tables db-name link)
(php-mysql-num-fields result)
(php-mysql-num-rows result)
(php-mysql-query query link)
(php-mysql-unbuffered-query query link)
(php-mysql-result result row-num field)
(php-mysql-select-db database-name link)
))
;;Notes
;
;most of the functions have aliases defined, because the names
;are so close to the names in c-bindings.defs, differing only in
;whether they use underscores or dashes.
;
instead of signalling an error , we conform to bramage ,
;and return true/false. (for the most part)
;
;the functions that just return '() are not yet implemented. I'm
also still confused about pconnect . how 's it different ?
(define (init-php-mysql-lib)
1)
; register the extension
(register-extension "mysql" "1.0.0" "php-mysql")
(define *null-string*
(pragma::string "((const char *)NULL)"))
(defresource mysql-link "mysql link"
link
state
active-result)
(defresource mysql-result "mysql result"
freed?
result
column-numbers
column-names
column-hashcodes)
(define *mysql-result-counter* 0)
(define (make-finalized-mysql-result result)
(when (> *mysql-result-counter* 255) ; ARB
(gc-force-finalization (lambda () (<= *mysql-result-counter* 255))))
(let ((result (mysql-result-resource #f result #f #f #f)))
(set! *mysql-result-counter* (+ *mysql-result-counter* 1))
(register-finalizer! result (lambda (result)
(unless (mysql-result-freed? result)
(php-mysql-free-result result)
; the counter and freed? are set by mysql-free-result
)))
result))
;;;;Utilities
;this sucks, hard.
(define (ulonglongify num)
(flonum->llong (fixnum->flonum (mkfixnum num))))
;so does this. you see, flonums are not exact.
(define (un-ulonglongify num)
(flonum->fixnum (llong->flonum num)))
;;;Link Cache
(define *cache* (make-hashtable))
(define *last-link* #f)
(define (suitably-odd-key server username password)
(mkstr server "<@~@>" username "<@~@>" password))
(define (store-link server username password link)
(mysql-link-state-set! link 'alive)
(set! *last-link* link)
(hashtable-put! *cache*
(suitably-odd-key server username password)
link))
(define (fetch-link server username password)
(let* ((key (suitably-odd-key server username password))
(link (hashtable-get *cache* key)))
(if (and link (eqv? (mysql-link-state link) 'dead))
(begin
(hashtable-remove! *cache* key)
#f)
link)))
(define (fetch-last-link)
(when (and *last-link*
(eqv? (mysql-link-state *last-link*) 'dead))
(set! *last-link* #f))
*last-link*)
(define (remove-link link)
;without the server/username/password, we can't
;easily lookup the link, so just set its state to
;dead, and pay for it on the other end.
(mysql-link-state-set! link 'dead))
;;;Exit Function
;cleanup function to close any remaining open connections
(register-exit-function!
(lambda (status)
(hashtable-for-each *cache*
(lambda (key link)
(unless (eqv? (mysql-link-state link) 'dead)
(mysql-close (mysql-link-link link)))))
status))
;;;Default connection stuff
;For when there's no link passed, and no last link
(define (establish-default-link)
(php-mysql-connect "localhost" *null-string* *null-string* *null-string* '()))
;Ensure that we have a link, or throw an error. The benefactor is the
;function to name in the error. The link is the name of the variable
;that should contain the link. It will only be changed if it's eqv to
;'unpassed.
(define (ensure-link benefactor link)
(when (eqv? link 'unpassed)
(let ((last-link (fetch-last-link)))
(if last-link
(set! link last-link)
(set! link (establish-default-link)))))
(if (mysql-link? link)
link
(begin
; remember kids, this might return if *disable-errors* was true!
(php-warning (format "unable to establish link in ~a" benefactor)))))
;;;;The PHP functions
;Get number of affected rows in previous MySQL operation
(defalias mysql_affected_rows php-mysql-affected-rows)
(defbuiltin (php-mysql-affected-rows (link 'unpassed))
(let ((rlink (ensure-link 'mysql_affected_rows link)))
(if rlink
(convert-to-number
(un-ulonglongify (mysql-affected-rows (mysql-link-link rlink))))
#f)))
;Change logged in user of the active connection
(defalias mysql_change_user php-mysql-change-user)
(defbuiltin (php-mysql-change-user username
password
(database '())
(link 'unpassed))
(when (null? database) (set! database *null-string*))
(let ((rlink (ensure-link 'mysql_change_user link)))
(if rlink
(zero? (mysql-change-user (mysql-link-link rlink)
username password database))
#f)))
;Close MySQL connection
(defalias mysql_close php-mysql-close)
(defbuiltin (php-mysql-close (link 'unpassed))
(let ((rlink (ensure-link 'mysql_close link)))
(if (and rlink
(eqv? (mysql-link-state rlink) 'alive))
(begin
(unbuffered-query-check rlink)
(mysql-close (mysql-link-link rlink))
(remove-link rlink)
#t)
#f)))
;Open a persistent connection to a MySQL server
;(defalias mysql_pconnect php-mysql-connect) ;XXX
(defalias mysql_pconnect php-mysql-connect)
(defbuiltin (php-mysql-pconnect (server "localhost")
(username '())
(password '())
(client-flags '()))
(php-mysql-connect server username password #f client-flags))
;Open a connection to a MySQL Server
(defalias mysql_connect php-mysql-connect)
(defbuiltin (php-mysql-connect (server "localhost")
(username '())
(password '())
(new-link #f)
(client-flags '()))
;'false is because something somewhere doesn't like #f as a default value
;check for a cached link
(if (null? server)
(set! server "localhost"))
(if (null? username)
(set! username #f))
(if (null? password)
(set! password #f))
(let ((link (if (convert-to-boolean new-link)
#f
(fetch-link server username password)))
(socket (if (get-ini-entry 'mysql.default_socket)
(get-ini-entry 'mysql.default_socket)
*null-string*))
(real-server server)
(port 0))
(if link
link
no cached link , make a new one
(let ((mysql (mysql-init *null-mysql*)))
; check for :port or :/path/to/socket specification
(when (string-contains server ":")
(let ((vals (string-split server ":")))
(set! real-server (car vals))
(if (numeric-string? (cadr vals))
(set! port (mkfixnum (cadr vals)))
(set! socket (cadr vals)))))
;
(debug-trace 3 "Mysql: Opening fresh connection to " real-server "/" username
" - new-link: " new-link ", link: " link)
(set! link (mysql-real-connect mysql real-server (or username *null-string*) (or password *null-string*)
*null-string* port socket 0))
(if (null-mysql? link)
;link was null. issue a php warning, and return false.
(begin
(php-warning
(format "failed to connect to db on ~A: ~A"
server (mysql-error mysql)))
#f)
;cache and return a non-null link
(let ((link (mysql-link-resource link 'alive '())))
(store-link server username password link)
(mysql-link-active-result-set! link #f)
link))))))
;Create a MySQL database
;(defalias mysql_create_db php-mysql-create-db)
( defbuiltin ( php - mysql - create - db name ( link ' unpassed ) )
; (ensure-link 'mysql_create_db link)
( zero ? ( mysql - create - db ( mysql - link - link link ) name ) ) )
;Move internal result pointer
(defalias mysql_data_seek php-mysql-data-seek)
(defbuiltin (php-mysql-data-seek result row-number)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(begin
(mysql-data-seek (mysql-result-result result) (ulonglongify row-number))
#t))) ;mysql lib defines no retval
;Select database and run query on it
(defbuiltin (mysql_db_query database-name query (link 'unpassed))
(php-mysql-select-db database-name link)
(php-mysql-query query link))
;Drop (delete) a MySQL database
;(defalias mysql_drop_db php-mysql-drop-db)
( defbuiltin ( php - mysql - drop - db db - name ( link ' unpassed ) )
; (ensure-link 'mysql_drop_db link)
( zero ? ( mysql - drop - db ( mysql - link - link link ) db - name ) ) )
;Returns the numerical value of the error message from previous MySQL operation
(defalias mysql_errno php-mysql-errno)
(defbuiltin (php-mysql-errno (link 'unpassed))
(let ((rlink (ensure-link 'mysql_errno link)))
(if rlink
(convert-to-number (mysql-errno (mysql-link-link rlink)))
#f)))
;Returns the text of the error message from previous MySQL operation
(defalias mysql_error php-mysql-error)
(defbuiltin (php-mysql-error (link 'unpassed))
(let ((rlink (ensure-link 'mysql_error link)))
(if rlink
(mysql-error (mysql-link-link rlink))
NULL)))
; mysql_get_client_info -- Get MySQL client info
(defalias mysql_get_client_info php-mysql-get-client-info)
(defbuiltin (php-mysql-get-client-info)
(mysql-get-client-info))
-- Get MySQL server info
(defalias mysql_get_server_info php-mysql-get-server-info)
(defbuiltin (php-mysql-get-server-info (link 'unpassed))
(let ((rlink (ensure-link 'mysql_get_server_info link)))
(if rlink
(mysql-get-server-info (mysql-link-link rlink))
#f)))
; mysql_get_proto_info -- Get MySQL proto info
(defalias mysql_get_proto_info php-mysql-get-proto-info)
(defbuiltin (php-mysql-get-proto-info (link 'unpassed))
(let ((rlink (ensure-link 'mysql_get_proto_info link)))
(if rlink
(mysql-get-proto-info (mysql-link-link rlink))
#f)))
; mysql_get_host_info -- Get MySQL host info
(defalias mysql_get_host_info php-mysql-get-host-info)
(defbuiltin (php-mysql-get-host-info (link 'unpassed))
(let ((rlink (ensure-link 'mysql_get_host_info link)))
(if rlink
(mysql-get-host-info (mysql-link-link rlink))
#f)))
;Escapes a string for use in a mysql-query.
(defalias mysql_escape_string php-mysql-escape-string)
(defbuiltin (php-mysql-escape-string str)
(let* ((sstr (mkstr str))
(len (string-length sstr))
(new-str (make-string (+ 1 (* 2 len))))
(new-len (mysql-escape-string new-str sstr len)))
;scheme strings are not null-terminated, so chop it by hand
(substring new-str 0 new-len)))
(defalias mysql_real_escape_string php-mysql-real-escape-string)
(defbuiltin (php-mysql-real-escape-string str (link 'unpassed))
(let ((rlink (ensure-link 'mysql_real_escape_string link)))
(if rlink
(let* ((sstr (mkstr str))
(len (string-length sstr))
(new-str (make-string (+ 1 (* 2 len))))
(new-len (mysql-real-escape-string (mysql-link-link rlink) new-str sstr len)))
;scheme strings are not null-terminated, so chop it by hand
(substring new-str 0 new-len))
#f)))
(defconstant MYSQL_ASSOC 0)
(defconstant MYSQL_NUM 1)
(defconstant MYSQL_BOTH 2)
;apply fun to either each name/val or each index/val or both pair
;return false if there are no pairs
(define (mysql-row-for-each result-resource num-fun assoc-fun)
(let* ((result (mysql-result-result result-resource))
(row (mysql-fetch-row result)))
(if (null-row? row)
#f
(let ((num-fields (mysql-num-fields result))
(init-column-names? (not (mysql-result-column-names result-resource)))
(column-names #f)
(column-numbers #f)
(column-hashcodes #f))
;; all this column-mumble stuff is the lazy
;; initialization of the column names, which we store in
;; the result resource so that we can reuse them for the
next row .
(when init-column-names?
(mysql-result-column-names-set! result-resource (make-vector num-fields))
(mysql-result-column-numbers-set! result-resource (make-vector num-fields))
(mysql-result-column-hashcodes-set! result-resource (make-vector num-fields)))
(set! column-names (mysql-result-column-names result-resource))
(set! column-numbers (mysql-result-column-numbers result-resource))
(set! column-hashcodes (mysql-result-column-hashcodes result-resource))
(field-seek result 0)
(let loop ((i 0)
(field (mysql-fetch-field result)))
(when (< i num-fields)
(when init-column-names?
(vector-set! column-numbers i (int->onum i))
(let ((field-name (mysql-field-name field)))
(vector-set! column-names i field-name)
(vector-set! column-hashcodes i (precalculate-string-hashnumber field-name))))
(let ((field-val (mysql-row-ref row i)))
(when num-fun
(num-fun (vector-ref column-numbers i) field-val))
(when assoc-fun
(assoc-fun (vector-ref column-names i)
(vector-ref column-hashcodes i)
field-val)))
(loop (+ i 1) (mysql-fetch-field result))))
#t))))
;Fetch a result row as an object
(defbuiltin (mysql_fetch_object result (array-type MYSQL_ASSOC))
(cond
((not (mysql-result? result))
(bad-mysql-result-resource))
(else
;; XXX since I'm not sure about objects with numeric
;; properties, we're going to just always do assoc, and
;; print a warning in the numeric case
(unless (php-= array-type MYSQL_ASSOC)
(warning 'mysql_fetch_object "Can't make an object with numeric keys" #f))
(let ((props (make-php-hash)))
(if (mysql-row-for-each result
#f
(lambda (key hashnumber val)
(php-hash-insert!/pre props key hashnumber val)))
(make-php-object props)
#f)))))
;Get a result row as an enumerated array
(defalias mysql_fetch_row php-mysql-fetch-row)
(defbuiltin (php-mysql-fetch-row result)
(mysql_fetch_array result MYSQL_NUM))
;Fetch a result row as an associative array
(defbuiltin (mysql_fetch_assoc result)
(mysql_fetch_array result MYSQL_ASSOC))
;Fetch a result row as an associative array, a numeric array, or both.
(defbuiltin (mysql_fetch_array result (array-type MYSQL_BOTH))
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((array (make-php-hash)))
(if (mysql-row-for-each result
(if (or (php-= array-type MYSQL_NUM)
(php-= array-type MYSQL_BOTH))
(lambda (key val)
(php-hash-insert! array key val))
#f)
(if (or (php-= array-type MYSQL_ASSOC)
(php-= array-type MYSQL_BOTH))
(lambda (key hashnumber val)
(php-hash-insert!/pre array key hashnumber val))
#f))
array
#f))))
;Get column information from a result and return as an object
(defalias mysql_fetch_field php-mysql-fetch-field)
(defbuiltin (php-mysql-fetch-field result (offset 'unpassed))
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((result (mysql-result-result result)))
(unless (eqv? offset 'unpassed)
(field-seek result offset))
(let ((field (mysql-fetch-field result)))
(if (null-field? field)
#f
(let* ((flags (mysql-field-flags field))
(flag-set? (lambda (flag) (if (member flag flags) 1 0)))
(zero-or-one (lambda (val) (if (zero? val) *zero* *one*))))
(make-php-object
(let ((props (make-php-hash)))
(for-each (lambda (k-v)
(php-hash-insert! props (car k-v) (cadr k-v)))
`(("name" ,(mkstr (mysql-field-name field))) ;column name
("table" ,(mkstr (mysql-field-table field))) ;name of the table the column belongs to
("def" ,(mkstr (mysql-field-def field))) ;default value
("max_length" ,(convert-to-number (mysql-field-max-length field))) ;maximum length of the column
1 if the column can not be NULL
1 if the column is a primary key
1 if the column is a non - unique key
1 if the column is a unique key
1 if the column is numeric
1 if the column is a BLOB
("type" ,(php-field-type-name (mysql-field-type field))) ;the type of the column
1 if the column is unsigned
("zerofill" ,(convert-to-number (flag-set? 'zero-fill)))))
1 if the column is zero - filled
(define (php-field-type-name field-type)
(case field-type
((varstring varchar) "string")
((tinyint smallint mediumint integer bigint) "int")
((decimal float double) "real")
((timestamp) "timestamp")
((year) "year")
((date newdate) "datetime")
((time) "time")
((set) "set")
((enum) "enum")
((tinyblob blob mediumblob longblob) "blob")
((null) "null")
;;XXX missing geometry and newdate
(else "unknown")))
;Get the length of each output in a result
(defbuiltin (php-mysql-fetch-lengths result)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((result (mysql-result-result result)))
(let ((lengths-hash (make-php-hash))
(row (mysql-fetch-row result)))
(if (null-row? row)
#f
(let ((num-fields (mysql-num-fields result))
(lengths (mysql-fetch-lengths result)))
(dotimes (i num-fields)
(php-hash-insert! lengths-hash i
(ulong-ptr-ref lengths i)))
lengths-hash))))))
;Return the flags associated with the specified field as a string
;divided by spaces
(defalias mysql_field_flags php-mysql-field-flags)
(defbuiltin (php-mysql-field-flags result offset)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((result (mysql-result-result result)))
(field-seek result offset)
(let ((field (mysql-fetch-field result)))
(if (null-field? field)
#f
(let ((flags (mysql-field-flags field)))
; (fprint (current-error-port) "flags: " flags)
(let loop ((flag (gcar flags))
(flags (gcdr flags))
(string-flags '()))
(if (null? flag)
(apply string-append string-flags)
(loop (gcar flags)
(gcdr flags)
(cons (if (null? flags) "" " ")
(cons (case flag
((not-null) "not_null")
((primary-key) "primary_key")
((unique-key) "unique_key")
((multiple-key) "multiple_key")
((blob) "blob")
((unsigned) "unsigned")
((zero-fill) "zerofill")
((binary) "binary")
((enum) "enum")
((auto-increment) "auto_increment")
((timestamp) "timestamp")
(else "unknown_flag"))
string-flags)))))))))))
(define (get-field-field result offset getter)
"If field exists, run the getter on it, else return #f"
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((result (mysql-result-result result)))
(if (field-seek result offset)
(let ((field (mysql-fetch-field result)))
(if (null-field? field)
#f
(getter field)))
#f))))
;Get the name of the specified field in a result
(defalias mysql_field_name php-mysql-field-name)
(defbuiltin (php-mysql-field-name result offset)
(get-field-field result offset mysql-field-name))
;Returns the length of the specified field
(defalias mysql_field_len php-mysql-field-len)
(defbuiltin (php-mysql-field-len result offset)
(get-field-field result offset mysql-field-length))
(define (field-seek result offset)
"Seek to OFFSET field in RESULT, doing a bounds check."
(if (or (php-< offset 0) (php->= offset (mysql-num-fields result)))
(begin
(php-warning (format "Field offset ~A is not within valid range ~A to ~A")))
(begin
(mysql-field-seek result (mkfixnum offset))
#t)))
;Set result pointer to a specified field offset
(defalias mysql_field_seek php-mysql-field-seek)
(defbuiltin (php-mysql-field-seek result offset)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(field-seek (mysql-result-result result) offset)))
;Get name of the table the specified field is in
(defalias mysql_field_table php-mysql-field-table)
(defbuiltin (php-mysql-field-table result offset)
(get-field-field result offset mysql-field-table))
;Get the type of the specified field in a result
(defalias mysql_field_type php-mysql-field-type)
(defbuiltin (php-mysql-field-type result offset)
(let ((field-type (get-field-field result offset mysql-field-type)))
(if field-type
(case field-type
((varstring varchar) "string")
((tinyint smallint integer bigint mediumint) "int")
((decimal float double) "real")
((timestamp) "timestamp")
((year) "year")
((date) "date")
((time) "time")
((datetime) "datetime")
((tinyblob mediumblob longblob blob) "blob")
((null) "null")
((enum) "enum")
((set) "set")
(else "unknown"))
#f)))
;Free result memory
(defalias mysql_free_result php-mysql-free-result)
(defbuiltin (php-mysql-free-result result)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(begin
(unless (mysql-result-freed? result)
(mysql-free-result (mysql-result-result result))
(mysql-result-freed?-set! result #t)
(set! *mysql-result-counter* (- *mysql-result-counter* 1)))
#t))) ;mysql-free-result returns void
;Get the id generated from the previous INSERT operation
(defalias mysql_insert_id php-mysql-insert-id)
(defbuiltin (php-mysql-insert-id (link 'unpassed))
(let ((rlink (ensure-link 'mysql_insert_id link)))
(if rlink
(convert-to-number
(un-ulonglongify (mysql-insert-id (mysql-link-link rlink))))
#f)))
;List databases available on a MySQL server
(defalias mysql_list_dbs php-mysql-list-dbs)
(defbuiltin (php-mysql-list-dbs (link 'unpassed))
(let ((rlink (ensure-link 'mysql_list_dbs link)))
(if rlink
(begin
(unbuffered-query-check rlink)
(let ((result (mysql-list-dbs (mysql-link-link rlink) *null-string*)))
(if result
(make-finalized-mysql-result result)
(php-warning (format "Result was null -- ~A" (mysql-error (mysql-link-link rlink)))))))
#f)))
;List MySQL result fields
(defalias mysql_list_fields php-mysql-list-fields)
(defbuiltin (php-mysql-list-fields db-name table-name (link 'unpassed))
(let ((rlink (ensure-link 'mysql_list_fields link)))
(if rlink
(begin
(unbuffered-query-check rlink)
(set! link (mysql-link-link rlink))
(if (= 0 (mysql-select-db link db-name))
(let ((result (mysql-list-fields link table-name *null-string*)))
(if (null-result? result)
(begin
(php-warning (format "null result: ~A"
(mysql-error link)))
#f)
(make-finalized-mysql-result result)))
(begin
(php-warning (format "unable to select db: ~A -- ~A"
db-name (mysql-error link)))
#f)))
#f)))
;List tables in a MySQL database
(defalias mysql_list_tables php-mysql-list-tables)
(defbuiltin (php-mysql-list-tables db-name (link 'unpassed))
(let ((rlink (ensure-link 'mysql_list_tables link)))
(if rlink
(begin
(unbuffered-query-check rlink)
(set! link (mysql-link-link rlink))
(if (zero? (mysql-select-db link (mkstr db-name)))
(let ((result (mysql-list-tables link *null-string*)))
(if (null-result? result)
#f
(make-finalized-mysql-result result)))
#f))
#f)))
;Get number of fields in result
(defalias mysql_num_fields php-mysql-num-fields)
(defbuiltin (php-mysql-num-fields result)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(convert-to-number (mysql-num-fields (mysql-result-result result)))))
;Get number of rows in result
(defalias mysql_num_rows php-mysql-num-rows)
(defbuiltin (php-mysql-num-rows result)
;here lurks a potential bug, in the conversion between
and fixnum .
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(begin
(convert-to-number
(un-ulonglongify (mysql-num-rows (mysql-result-result result)))))))
;Send a MySQL query
(defalias mysql_query php-mysql-query)
(defbuiltin (php-mysql-query query (link 'unpassed))
(let ((rlink (ensure-link 'mysql_query link)))
(if rlink
(do-query (mkstr query) rlink #t)
#f)))
(define (do-query query rlink store)
(unbuffered-query-check rlink)
(let ((link (mysql-link-link rlink)))
(if (= 0 (mysql-query link query))
(let ((result (if store
(mysql-store-result link)
(mysql-use-result link))))
(if (null-result? result)
;; mysql-field-count will tell us if the query was
;; really meant to return nothing or not.
(if (zero? (mysql-field-count link))
TRUE
(begin
(php-warning "Unable to save result set")
FALSE))
(let ((r (make-finalized-mysql-result result)))
(unless store
(mysql-link-active-result-set! rlink r))
r)))
(begin
; (php-warning (format "mysql_query: mysql-query returned null -- ~A" (mysql-error link)))
FALSE) )))
;Send an SQL query to MySQL, without fetching and buffering the result rows
(defalias mysql_unbuffered_query php-mysql-unbuffered-query)
(defbuiltin (php-mysql-unbuffered-query query (link 'unpassed))
(let ((rlink (ensure-link 'mysql_unbuffered_query link)))
(if rlink
(do-query query rlink #f)
#f)))
;Get result data
(defalias mysql_dbname php-mysql-result)
(defalias mysql_result php-mysql-result)
(defalias mysql_db_name php-mysql-result)
(defalias mysql_table_name php-mysql-result)
(defalias mysql_tablename php-mysql-result)
(defbuiltin (php-mysql-result result row-num (field 'unpassed))
; (print " my arguments are " result ", " row-num ", " field)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((field-offset 0)
(srow-num (convert-to-integer row-num))
(num-rows (php-mysql-num-rows result)))
(if (not (and (php->= srow-num 0)
(php-< srow-num num-rows)))
(php-warning (format "specified row doesn't exist in result set (~a/~a)" (mkfixnum srow-num) (mkfixnum num-rows)) )
(begin
(mysql-data-seek (mysql-result-result result) (flonum->llong (onum->float (convert-to-float srow-num))))
(let ((row (mysql-fetch-row (mysql-result-result result))))
(if (null-row? row)
(begin
(php-warning "specified row was null")
#f)
(let ((num-fields (mysql-num-fields (mysql-result-result result))))
;(print "there are " num-fields " fields")
; setup field-offset based on field
(unless (eqv? field 'unpassed)
(cond ((php-number? field) (set! field-offset field))
(else
(let ((sfield (mkstr field))
(res (mysql-result-result result)))
(multiple-value-bind (table-name field-name)
(let ((dot-location (strchr sfield #\.)))
(if dot-location
(values (substring sfield 0 dot-location)
(substring sfield (+ dot-location 1) (string-length sfield)))
(values #f sfield)))
; lookup by field name
(field-seek res 0)
(let loop ((i 0)
(field (mysql-fetch-field res)))
(if (< i num-fields)
(begin
;(print "checking field " i " which is " (mysql-field-name field) " table: " (mysql-field-table field))
(if (and (or (not table-name) (string-ci=? table-name (mysql-field-table field)))
(string-ci=? field-name (mysql-field-name field)))
(set! field-offset i)
(loop (+ i 1) (mysql-fetch-field res))))
; not found
(set! field-offset -1))))))))
; always runs
;(print "field offset is " field-offset)
(if (and (php->= field-offset 0)
(php-< field-offset num-fields))
(mysql-row-ref row (mkfixnum field-offset))
(begin
(php-warning "specified field doesn't exist in row")
#f))))))))))
(define (strchr string char)
(let loop ((i 0))
(if (< i (string-length string))
(if (char=? char (string-ref string i))
i
(loop (+ i 1)))
#f)))
;Select a MySQL database
(defalias mysql_select_db php-mysql-select-db)
(defbuiltin (php-mysql-select-db database-name (link 'unpassed))
(let ((rlink (ensure-link 'mysql_select_db link)))
(if rlink
(begin
(unbuffered-query-check rlink)
(let ((retval (mysql-select-db (mysql-link-link rlink) (mkstr database-name))))
(zero? retval)))
#f)))
(define (unbuffered-query-check link::struct)
(let ((result (mysql-link-active-result link)))
(if (not (mysql-result? result))
#f
(let ((r (mysql-result-result result)))
(unless (pragma::bool "$1 != 0" (mysql-eof r))
(php-notice "Function called without first fetching all rows from a previous unbuffered query")
(let loop ()
(unless (null-row? (mysql-fetch-row r))
(loop)))
(php-mysql-free-result result))
(mysql-link-active-result-set! link #f)))))
(define (bad-mysql-result-resource)
(php-warning "supplied argument is not a valid MySQL result resource")
FALSE)
;;;deprecated names
(defalias mysql mysql_db_query)
(defalias mysql_fieldname php-mysql-field-name)
(defalias mysql_fieldtable php-mysql-field-table)
(defalias mysql_fieldlen php-mysql-field-len)
(defalias mysql_fieldtype php-mysql-field-type)
(defalias mysql_fieldflags php-mysql-field-flags)
(defalias mysql_selectdb php-mysql-select-db)
;(defalias mysql_createdb php-mysql-create-db)
;(defalias mysql_dropdb php-mysql-drop-db)
(defalias mysql_freeresult php-mysql-free-result)
(defalias mysql_numfields php-mysql-num-fields)
(defalias mysql_numrows php-mysql-num-rows)
(defalias mysql_listdbs php-mysql-list-dbs)
(defalias mysql_listtables php-mysql-list-tables)
(defalias mysql_listfields php-mysql-list-fields)
| null | https://raw.githubusercontent.com/weyrick/roadsend-php/d6301a897b1a02d7a85bdb915bea91d0991eb158/runtime/ext/mysql/php-mysql.scm | scheme | ***** BEGIN LICENSE BLOCK *****
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
either version 2.1
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
along with this program; if not, write to the Free Software
***** END LICENSE BLOCK *****
(php-mysql-create-db name link) ; deprecated
(php-mysql-drop-db db-name link) ; deprecated
Notes
most of the functions have aliases defined, because the names
are so close to the names in c-bindings.defs, differing only in
whether they use underscores or dashes.
and return true/false. (for the most part)
the functions that just return '() are not yet implemented. I'm
register the extension
ARB
the counter and freed? are set by mysql-free-result
Utilities
this sucks, hard.
so does this. you see, flonums are not exact.
Link Cache
without the server/username/password, we can't
easily lookup the link, so just set its state to
dead, and pay for it on the other end.
Exit Function
cleanup function to close any remaining open connections
Default connection stuff
For when there's no link passed, and no last link
Ensure that we have a link, or throw an error. The benefactor is the
function to name in the error. The link is the name of the variable
that should contain the link. It will only be changed if it's eqv to
'unpassed.
remember kids, this might return if *disable-errors* was true!
The PHP functions
Get number of affected rows in previous MySQL operation
Change logged in user of the active connection
Close MySQL connection
Open a persistent connection to a MySQL server
(defalias mysql_pconnect php-mysql-connect) ;XXX
Open a connection to a MySQL Server
'false is because something somewhere doesn't like #f as a default value
check for a cached link
check for :port or :/path/to/socket specification
link was null. issue a php warning, and return false.
cache and return a non-null link
Create a MySQL database
(defalias mysql_create_db php-mysql-create-db)
(ensure-link 'mysql_create_db link)
Move internal result pointer
mysql lib defines no retval
Select database and run query on it
Drop (delete) a MySQL database
(defalias mysql_drop_db php-mysql-drop-db)
(ensure-link 'mysql_drop_db link)
Returns the numerical value of the error message from previous MySQL operation
Returns the text of the error message from previous MySQL operation
mysql_get_client_info -- Get MySQL client info
mysql_get_proto_info -- Get MySQL proto info
mysql_get_host_info -- Get MySQL host info
Escapes a string for use in a mysql-query.
scheme strings are not null-terminated, so chop it by hand
scheme strings are not null-terminated, so chop it by hand
apply fun to either each name/val or each index/val or both pair
return false if there are no pairs
all this column-mumble stuff is the lazy
initialization of the column names, which we store in
the result resource so that we can reuse them for the
Fetch a result row as an object
XXX since I'm not sure about objects with numeric
properties, we're going to just always do assoc, and
print a warning in the numeric case
Get a result row as an enumerated array
Fetch a result row as an associative array
Fetch a result row as an associative array, a numeric array, or both.
Get column information from a result and return as an object
column name
name of the table the column belongs to
default value
maximum length of the column
the type of the column
XXX missing geometry and newdate
Get the length of each output in a result
Return the flags associated with the specified field as a string
divided by spaces
(fprint (current-error-port) "flags: " flags)
Get the name of the specified field in a result
Returns the length of the specified field
Set result pointer to a specified field offset
Get name of the table the specified field is in
Get the type of the specified field in a result
Free result memory
mysql-free-result returns void
Get the id generated from the previous INSERT operation
List databases available on a MySQL server
List MySQL result fields
List tables in a MySQL database
Get number of fields in result
Get number of rows in result
here lurks a potential bug, in the conversion between
Send a MySQL query
mysql-field-count will tell us if the query was
really meant to return nothing or not.
(php-warning (format "mysql_query: mysql-query returned null -- ~A" (mysql-error link)))
Send an SQL query to MySQL, without fetching and buffering the result rows
Get result data
(print " my arguments are " result ", " row-num ", " field)
(print "there are " num-fields " fields")
setup field-offset based on field
lookup by field name
(print "checking field " i " which is " (mysql-field-name field) " table: " (mysql-field-table field))
not found
always runs
(print "field offset is " field-offset)
Select a MySQL database
deprecated names
(defalias mysql_createdb php-mysql-create-db)
(defalias mysql_dropdb php-mysql-drop-db) | Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2007 Roadsend , Inc.
of the License , or ( at your option ) any later version .
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA
(module php-mysql-lib
(include "../phpoo-extension.sch")
(library profiler)
(import (mysql-c-bindings "c-bindings.scm"))
(export
MYSQL_ASSOC
MYSQL_NUM
MYSQL_BOTH
(init-php-mysql-lib)
(php-mysql-affected-rows link)
(php-mysql-change-user username password database link)
(php-mysql-close link)
(php-mysql-connect server username password new-link flags)
(php-mysql-pconnect server username password flags)
(php-mysql-data-seek result row-number)
(mysql_db_query database-name query link)
(php-mysql-errno link)
(php-mysql-error link)
(php-mysql-escape-string str)
(php-mysql-real-escape-string str link)
(mysql_fetch_array result array-type)
(mysql_fetch_assoc result)
(php-mysql-fetch-field result offset)
(php-mysql-fetch-lengths result)
(mysql_fetch_object result array-type)
(php-mysql-get-client-info)
(php-mysql-get-server-info link)
(php-mysql-get-host-info link)
(php-mysql-get-proto-info link)
(php-mysql-fetch-row result)
(php-mysql-field-flags result offset)
(php-mysql-field-name result offset)
(php-mysql-field-len result offset)
(php-mysql-field-seek result offset)
(php-mysql-field-table result offset)
(php-mysql-field-type result offset)
(php-mysql-free-result result)
(php-mysql-insert-id link)
(php-mysql-list-dbs link)
(php-mysql-list-fields db-name table-name link)
(php-mysql-list-tables db-name link)
(php-mysql-num-fields result)
(php-mysql-num-rows result)
(php-mysql-query query link)
(php-mysql-unbuffered-query query link)
(php-mysql-result result row-num field)
(php-mysql-select-db database-name link)
))
instead of signalling an error , we conform to bramage ,
also still confused about pconnect . how 's it different ?
(define (init-php-mysql-lib)
1)
(register-extension "mysql" "1.0.0" "php-mysql")
(define *null-string*
(pragma::string "((const char *)NULL)"))
(defresource mysql-link "mysql link"
link
state
active-result)
(defresource mysql-result "mysql result"
freed?
result
column-numbers
column-names
column-hashcodes)
(define *mysql-result-counter* 0)
(define (make-finalized-mysql-result result)
(gc-force-finalization (lambda () (<= *mysql-result-counter* 255))))
(let ((result (mysql-result-resource #f result #f #f #f)))
(set! *mysql-result-counter* (+ *mysql-result-counter* 1))
(register-finalizer! result (lambda (result)
(unless (mysql-result-freed? result)
(php-mysql-free-result result)
)))
result))
(define (ulonglongify num)
(flonum->llong (fixnum->flonum (mkfixnum num))))
(define (un-ulonglongify num)
(flonum->fixnum (llong->flonum num)))
(define *cache* (make-hashtable))
(define *last-link* #f)
(define (suitably-odd-key server username password)
(mkstr server "<@~@>" username "<@~@>" password))
(define (store-link server username password link)
(mysql-link-state-set! link 'alive)
(set! *last-link* link)
(hashtable-put! *cache*
(suitably-odd-key server username password)
link))
(define (fetch-link server username password)
(let* ((key (suitably-odd-key server username password))
(link (hashtable-get *cache* key)))
(if (and link (eqv? (mysql-link-state link) 'dead))
(begin
(hashtable-remove! *cache* key)
#f)
link)))
(define (fetch-last-link)
(when (and *last-link*
(eqv? (mysql-link-state *last-link*) 'dead))
(set! *last-link* #f))
*last-link*)
(define (remove-link link)
(mysql-link-state-set! link 'dead))
(register-exit-function!
(lambda (status)
(hashtable-for-each *cache*
(lambda (key link)
(unless (eqv? (mysql-link-state link) 'dead)
(mysql-close (mysql-link-link link)))))
status))
(define (establish-default-link)
(php-mysql-connect "localhost" *null-string* *null-string* *null-string* '()))
(define (ensure-link benefactor link)
(when (eqv? link 'unpassed)
(let ((last-link (fetch-last-link)))
(if last-link
(set! link last-link)
(set! link (establish-default-link)))))
(if (mysql-link? link)
link
(begin
(php-warning (format "unable to establish link in ~a" benefactor)))))
(defalias mysql_affected_rows php-mysql-affected-rows)
(defbuiltin (php-mysql-affected-rows (link 'unpassed))
(let ((rlink (ensure-link 'mysql_affected_rows link)))
(if rlink
(convert-to-number
(un-ulonglongify (mysql-affected-rows (mysql-link-link rlink))))
#f)))
(defalias mysql_change_user php-mysql-change-user)
(defbuiltin (php-mysql-change-user username
password
(database '())
(link 'unpassed))
(when (null? database) (set! database *null-string*))
(let ((rlink (ensure-link 'mysql_change_user link)))
(if rlink
(zero? (mysql-change-user (mysql-link-link rlink)
username password database))
#f)))
(defalias mysql_close php-mysql-close)
(defbuiltin (php-mysql-close (link 'unpassed))
(let ((rlink (ensure-link 'mysql_close link)))
(if (and rlink
(eqv? (mysql-link-state rlink) 'alive))
(begin
(unbuffered-query-check rlink)
(mysql-close (mysql-link-link rlink))
(remove-link rlink)
#t)
#f)))
(defalias mysql_pconnect php-mysql-connect)
(defbuiltin (php-mysql-pconnect (server "localhost")
(username '())
(password '())
(client-flags '()))
(php-mysql-connect server username password #f client-flags))
(defalias mysql_connect php-mysql-connect)
(defbuiltin (php-mysql-connect (server "localhost")
(username '())
(password '())
(new-link #f)
(client-flags '()))
(if (null? server)
(set! server "localhost"))
(if (null? username)
(set! username #f))
(if (null? password)
(set! password #f))
(let ((link (if (convert-to-boolean new-link)
#f
(fetch-link server username password)))
(socket (if (get-ini-entry 'mysql.default_socket)
(get-ini-entry 'mysql.default_socket)
*null-string*))
(real-server server)
(port 0))
(if link
link
no cached link , make a new one
(let ((mysql (mysql-init *null-mysql*)))
(when (string-contains server ":")
(let ((vals (string-split server ":")))
(set! real-server (car vals))
(if (numeric-string? (cadr vals))
(set! port (mkfixnum (cadr vals)))
(set! socket (cadr vals)))))
(debug-trace 3 "Mysql: Opening fresh connection to " real-server "/" username
" - new-link: " new-link ", link: " link)
(set! link (mysql-real-connect mysql real-server (or username *null-string*) (or password *null-string*)
*null-string* port socket 0))
(if (null-mysql? link)
(begin
(php-warning
(format "failed to connect to db on ~A: ~A"
server (mysql-error mysql)))
#f)
(let ((link (mysql-link-resource link 'alive '())))
(store-link server username password link)
(mysql-link-active-result-set! link #f)
link))))))
( defbuiltin ( php - mysql - create - db name ( link ' unpassed ) )
( zero ? ( mysql - create - db ( mysql - link - link link ) name ) ) )
(defalias mysql_data_seek php-mysql-data-seek)
(defbuiltin (php-mysql-data-seek result row-number)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(begin
(mysql-data-seek (mysql-result-result result) (ulonglongify row-number))
(defbuiltin (mysql_db_query database-name query (link 'unpassed))
(php-mysql-select-db database-name link)
(php-mysql-query query link))
( defbuiltin ( php - mysql - drop - db db - name ( link ' unpassed ) )
( zero ? ( mysql - drop - db ( mysql - link - link link ) db - name ) ) )
(defalias mysql_errno php-mysql-errno)
(defbuiltin (php-mysql-errno (link 'unpassed))
(let ((rlink (ensure-link 'mysql_errno link)))
(if rlink
(convert-to-number (mysql-errno (mysql-link-link rlink)))
#f)))
(defalias mysql_error php-mysql-error)
(defbuiltin (php-mysql-error (link 'unpassed))
(let ((rlink (ensure-link 'mysql_error link)))
(if rlink
(mysql-error (mysql-link-link rlink))
NULL)))
(defalias mysql_get_client_info php-mysql-get-client-info)
(defbuiltin (php-mysql-get-client-info)
(mysql-get-client-info))
-- Get MySQL server info
(defalias mysql_get_server_info php-mysql-get-server-info)
(defbuiltin (php-mysql-get-server-info (link 'unpassed))
(let ((rlink (ensure-link 'mysql_get_server_info link)))
(if rlink
(mysql-get-server-info (mysql-link-link rlink))
#f)))
(defalias mysql_get_proto_info php-mysql-get-proto-info)
(defbuiltin (php-mysql-get-proto-info (link 'unpassed))
(let ((rlink (ensure-link 'mysql_get_proto_info link)))
(if rlink
(mysql-get-proto-info (mysql-link-link rlink))
#f)))
(defalias mysql_get_host_info php-mysql-get-host-info)
(defbuiltin (php-mysql-get-host-info (link 'unpassed))
(let ((rlink (ensure-link 'mysql_get_host_info link)))
(if rlink
(mysql-get-host-info (mysql-link-link rlink))
#f)))
(defalias mysql_escape_string php-mysql-escape-string)
(defbuiltin (php-mysql-escape-string str)
(let* ((sstr (mkstr str))
(len (string-length sstr))
(new-str (make-string (+ 1 (* 2 len))))
(new-len (mysql-escape-string new-str sstr len)))
(substring new-str 0 new-len)))
(defalias mysql_real_escape_string php-mysql-real-escape-string)
(defbuiltin (php-mysql-real-escape-string str (link 'unpassed))
(let ((rlink (ensure-link 'mysql_real_escape_string link)))
(if rlink
(let* ((sstr (mkstr str))
(len (string-length sstr))
(new-str (make-string (+ 1 (* 2 len))))
(new-len (mysql-real-escape-string (mysql-link-link rlink) new-str sstr len)))
(substring new-str 0 new-len))
#f)))
(defconstant MYSQL_ASSOC 0)
(defconstant MYSQL_NUM 1)
(defconstant MYSQL_BOTH 2)
(define (mysql-row-for-each result-resource num-fun assoc-fun)
(let* ((result (mysql-result-result result-resource))
(row (mysql-fetch-row result)))
(if (null-row? row)
#f
(let ((num-fields (mysql-num-fields result))
(init-column-names? (not (mysql-result-column-names result-resource)))
(column-names #f)
(column-numbers #f)
(column-hashcodes #f))
next row .
(when init-column-names?
(mysql-result-column-names-set! result-resource (make-vector num-fields))
(mysql-result-column-numbers-set! result-resource (make-vector num-fields))
(mysql-result-column-hashcodes-set! result-resource (make-vector num-fields)))
(set! column-names (mysql-result-column-names result-resource))
(set! column-numbers (mysql-result-column-numbers result-resource))
(set! column-hashcodes (mysql-result-column-hashcodes result-resource))
(field-seek result 0)
(let loop ((i 0)
(field (mysql-fetch-field result)))
(when (< i num-fields)
(when init-column-names?
(vector-set! column-numbers i (int->onum i))
(let ((field-name (mysql-field-name field)))
(vector-set! column-names i field-name)
(vector-set! column-hashcodes i (precalculate-string-hashnumber field-name))))
(let ((field-val (mysql-row-ref row i)))
(when num-fun
(num-fun (vector-ref column-numbers i) field-val))
(when assoc-fun
(assoc-fun (vector-ref column-names i)
(vector-ref column-hashcodes i)
field-val)))
(loop (+ i 1) (mysql-fetch-field result))))
#t))))
(defbuiltin (mysql_fetch_object result (array-type MYSQL_ASSOC))
(cond
((not (mysql-result? result))
(bad-mysql-result-resource))
(else
(unless (php-= array-type MYSQL_ASSOC)
(warning 'mysql_fetch_object "Can't make an object with numeric keys" #f))
(let ((props (make-php-hash)))
(if (mysql-row-for-each result
#f
(lambda (key hashnumber val)
(php-hash-insert!/pre props key hashnumber val)))
(make-php-object props)
#f)))))
(defalias mysql_fetch_row php-mysql-fetch-row)
(defbuiltin (php-mysql-fetch-row result)
(mysql_fetch_array result MYSQL_NUM))
(defbuiltin (mysql_fetch_assoc result)
(mysql_fetch_array result MYSQL_ASSOC))
(defbuiltin (mysql_fetch_array result (array-type MYSQL_BOTH))
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((array (make-php-hash)))
(if (mysql-row-for-each result
(if (or (php-= array-type MYSQL_NUM)
(php-= array-type MYSQL_BOTH))
(lambda (key val)
(php-hash-insert! array key val))
#f)
(if (or (php-= array-type MYSQL_ASSOC)
(php-= array-type MYSQL_BOTH))
(lambda (key hashnumber val)
(php-hash-insert!/pre array key hashnumber val))
#f))
array
#f))))
(defalias mysql_fetch_field php-mysql-fetch-field)
(defbuiltin (php-mysql-fetch-field result (offset 'unpassed))
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((result (mysql-result-result result)))
(unless (eqv? offset 'unpassed)
(field-seek result offset))
(let ((field (mysql-fetch-field result)))
(if (null-field? field)
#f
(let* ((flags (mysql-field-flags field))
(flag-set? (lambda (flag) (if (member flag flags) 1 0)))
(zero-or-one (lambda (val) (if (zero? val) *zero* *one*))))
(make-php-object
(let ((props (make-php-hash)))
(for-each (lambda (k-v)
(php-hash-insert! props (car k-v) (cadr k-v)))
1 if the column can not be NULL
1 if the column is a primary key
1 if the column is a non - unique key
1 if the column is a unique key
1 if the column is numeric
1 if the column is a BLOB
1 if the column is unsigned
("zerofill" ,(convert-to-number (flag-set? 'zero-fill)))))
1 if the column is zero - filled
(define (php-field-type-name field-type)
(case field-type
((varstring varchar) "string")
((tinyint smallint mediumint integer bigint) "int")
((decimal float double) "real")
((timestamp) "timestamp")
((year) "year")
((date newdate) "datetime")
((time) "time")
((set) "set")
((enum) "enum")
((tinyblob blob mediumblob longblob) "blob")
((null) "null")
(else "unknown")))
(defbuiltin (php-mysql-fetch-lengths result)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((result (mysql-result-result result)))
(let ((lengths-hash (make-php-hash))
(row (mysql-fetch-row result)))
(if (null-row? row)
#f
(let ((num-fields (mysql-num-fields result))
(lengths (mysql-fetch-lengths result)))
(dotimes (i num-fields)
(php-hash-insert! lengths-hash i
(ulong-ptr-ref lengths i)))
lengths-hash))))))
(defalias mysql_field_flags php-mysql-field-flags)
(defbuiltin (php-mysql-field-flags result offset)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((result (mysql-result-result result)))
(field-seek result offset)
(let ((field (mysql-fetch-field result)))
(if (null-field? field)
#f
(let ((flags (mysql-field-flags field)))
(let loop ((flag (gcar flags))
(flags (gcdr flags))
(string-flags '()))
(if (null? flag)
(apply string-append string-flags)
(loop (gcar flags)
(gcdr flags)
(cons (if (null? flags) "" " ")
(cons (case flag
((not-null) "not_null")
((primary-key) "primary_key")
((unique-key) "unique_key")
((multiple-key) "multiple_key")
((blob) "blob")
((unsigned) "unsigned")
((zero-fill) "zerofill")
((binary) "binary")
((enum) "enum")
((auto-increment) "auto_increment")
((timestamp) "timestamp")
(else "unknown_flag"))
string-flags)))))))))))
(define (get-field-field result offset getter)
"If field exists, run the getter on it, else return #f"
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((result (mysql-result-result result)))
(if (field-seek result offset)
(let ((field (mysql-fetch-field result)))
(if (null-field? field)
#f
(getter field)))
#f))))
(defalias mysql_field_name php-mysql-field-name)
(defbuiltin (php-mysql-field-name result offset)
(get-field-field result offset mysql-field-name))
(defalias mysql_field_len php-mysql-field-len)
(defbuiltin (php-mysql-field-len result offset)
(get-field-field result offset mysql-field-length))
(define (field-seek result offset)
"Seek to OFFSET field in RESULT, doing a bounds check."
(if (or (php-< offset 0) (php->= offset (mysql-num-fields result)))
(begin
(php-warning (format "Field offset ~A is not within valid range ~A to ~A")))
(begin
(mysql-field-seek result (mkfixnum offset))
#t)))
(defalias mysql_field_seek php-mysql-field-seek)
(defbuiltin (php-mysql-field-seek result offset)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(field-seek (mysql-result-result result) offset)))
(defalias mysql_field_table php-mysql-field-table)
(defbuiltin (php-mysql-field-table result offset)
(get-field-field result offset mysql-field-table))
(defalias mysql_field_type php-mysql-field-type)
(defbuiltin (php-mysql-field-type result offset)
(let ((field-type (get-field-field result offset mysql-field-type)))
(if field-type
(case field-type
((varstring varchar) "string")
((tinyint smallint integer bigint mediumint) "int")
((decimal float double) "real")
((timestamp) "timestamp")
((year) "year")
((date) "date")
((time) "time")
((datetime) "datetime")
((tinyblob mediumblob longblob blob) "blob")
((null) "null")
((enum) "enum")
((set) "set")
(else "unknown"))
#f)))
(defalias mysql_free_result php-mysql-free-result)
(defbuiltin (php-mysql-free-result result)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(begin
(unless (mysql-result-freed? result)
(mysql-free-result (mysql-result-result result))
(mysql-result-freed?-set! result #t)
(set! *mysql-result-counter* (- *mysql-result-counter* 1)))
(defalias mysql_insert_id php-mysql-insert-id)
(defbuiltin (php-mysql-insert-id (link 'unpassed))
(let ((rlink (ensure-link 'mysql_insert_id link)))
(if rlink
(convert-to-number
(un-ulonglongify (mysql-insert-id (mysql-link-link rlink))))
#f)))
(defalias mysql_list_dbs php-mysql-list-dbs)
(defbuiltin (php-mysql-list-dbs (link 'unpassed))
(let ((rlink (ensure-link 'mysql_list_dbs link)))
(if rlink
(begin
(unbuffered-query-check rlink)
(let ((result (mysql-list-dbs (mysql-link-link rlink) *null-string*)))
(if result
(make-finalized-mysql-result result)
(php-warning (format "Result was null -- ~A" (mysql-error (mysql-link-link rlink)))))))
#f)))
(defalias mysql_list_fields php-mysql-list-fields)
(defbuiltin (php-mysql-list-fields db-name table-name (link 'unpassed))
(let ((rlink (ensure-link 'mysql_list_fields link)))
(if rlink
(begin
(unbuffered-query-check rlink)
(set! link (mysql-link-link rlink))
(if (= 0 (mysql-select-db link db-name))
(let ((result (mysql-list-fields link table-name *null-string*)))
(if (null-result? result)
(begin
(php-warning (format "null result: ~A"
(mysql-error link)))
#f)
(make-finalized-mysql-result result)))
(begin
(php-warning (format "unable to select db: ~A -- ~A"
db-name (mysql-error link)))
#f)))
#f)))
(defalias mysql_list_tables php-mysql-list-tables)
(defbuiltin (php-mysql-list-tables db-name (link 'unpassed))
(let ((rlink (ensure-link 'mysql_list_tables link)))
(if rlink
(begin
(unbuffered-query-check rlink)
(set! link (mysql-link-link rlink))
(if (zero? (mysql-select-db link (mkstr db-name)))
(let ((result (mysql-list-tables link *null-string*)))
(if (null-result? result)
#f
(make-finalized-mysql-result result)))
#f))
#f)))
(defalias mysql_num_fields php-mysql-num-fields)
(defbuiltin (php-mysql-num-fields result)
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(convert-to-number (mysql-num-fields (mysql-result-result result)))))
(defalias mysql_num_rows php-mysql-num-rows)
(defbuiltin (php-mysql-num-rows result)
and fixnum .
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(begin
(convert-to-number
(un-ulonglongify (mysql-num-rows (mysql-result-result result)))))))
(defalias mysql_query php-mysql-query)
(defbuiltin (php-mysql-query query (link 'unpassed))
(let ((rlink (ensure-link 'mysql_query link)))
(if rlink
(do-query (mkstr query) rlink #t)
#f)))
(define (do-query query rlink store)
(unbuffered-query-check rlink)
(let ((link (mysql-link-link rlink)))
(if (= 0 (mysql-query link query))
(let ((result (if store
(mysql-store-result link)
(mysql-use-result link))))
(if (null-result? result)
(if (zero? (mysql-field-count link))
TRUE
(begin
(php-warning "Unable to save result set")
FALSE))
(let ((r (make-finalized-mysql-result result)))
(unless store
(mysql-link-active-result-set! rlink r))
r)))
(begin
FALSE) )))
(defalias mysql_unbuffered_query php-mysql-unbuffered-query)
(defbuiltin (php-mysql-unbuffered-query query (link 'unpassed))
(let ((rlink (ensure-link 'mysql_unbuffered_query link)))
(if rlink
(do-query query rlink #f)
#f)))
(defalias mysql_dbname php-mysql-result)
(defalias mysql_result php-mysql-result)
(defalias mysql_db_name php-mysql-result)
(defalias mysql_table_name php-mysql-result)
(defalias mysql_tablename php-mysql-result)
(defbuiltin (php-mysql-result result row-num (field 'unpassed))
(if (not (mysql-result? result))
(bad-mysql-result-resource)
(let ((field-offset 0)
(srow-num (convert-to-integer row-num))
(num-rows (php-mysql-num-rows result)))
(if (not (and (php->= srow-num 0)
(php-< srow-num num-rows)))
(php-warning (format "specified row doesn't exist in result set (~a/~a)" (mkfixnum srow-num) (mkfixnum num-rows)) )
(begin
(mysql-data-seek (mysql-result-result result) (flonum->llong (onum->float (convert-to-float srow-num))))
(let ((row (mysql-fetch-row (mysql-result-result result))))
(if (null-row? row)
(begin
(php-warning "specified row was null")
#f)
(let ((num-fields (mysql-num-fields (mysql-result-result result))))
(unless (eqv? field 'unpassed)
(cond ((php-number? field) (set! field-offset field))
(else
(let ((sfield (mkstr field))
(res (mysql-result-result result)))
(multiple-value-bind (table-name field-name)
(let ((dot-location (strchr sfield #\.)))
(if dot-location
(values (substring sfield 0 dot-location)
(substring sfield (+ dot-location 1) (string-length sfield)))
(values #f sfield)))
(field-seek res 0)
(let loop ((i 0)
(field (mysql-fetch-field res)))
(if (< i num-fields)
(begin
(if (and (or (not table-name) (string-ci=? table-name (mysql-field-table field)))
(string-ci=? field-name (mysql-field-name field)))
(set! field-offset i)
(loop (+ i 1) (mysql-fetch-field res))))
(set! field-offset -1))))))))
(if (and (php->= field-offset 0)
(php-< field-offset num-fields))
(mysql-row-ref row (mkfixnum field-offset))
(begin
(php-warning "specified field doesn't exist in row")
#f))))))))))
(define (strchr string char)
(let loop ((i 0))
(if (< i (string-length string))
(if (char=? char (string-ref string i))
i
(loop (+ i 1)))
#f)))
(defalias mysql_select_db php-mysql-select-db)
(defbuiltin (php-mysql-select-db database-name (link 'unpassed))
(let ((rlink (ensure-link 'mysql_select_db link)))
(if rlink
(begin
(unbuffered-query-check rlink)
(let ((retval (mysql-select-db (mysql-link-link rlink) (mkstr database-name))))
(zero? retval)))
#f)))
(define (unbuffered-query-check link::struct)
(let ((result (mysql-link-active-result link)))
(if (not (mysql-result? result))
#f
(let ((r (mysql-result-result result)))
(unless (pragma::bool "$1 != 0" (mysql-eof r))
(php-notice "Function called without first fetching all rows from a previous unbuffered query")
(let loop ()
(unless (null-row? (mysql-fetch-row r))
(loop)))
(php-mysql-free-result result))
(mysql-link-active-result-set! link #f)))))
(define (bad-mysql-result-resource)
(php-warning "supplied argument is not a valid MySQL result resource")
FALSE)
(defalias mysql mysql_db_query)
(defalias mysql_fieldname php-mysql-field-name)
(defalias mysql_fieldtable php-mysql-field-table)
(defalias mysql_fieldlen php-mysql-field-len)
(defalias mysql_fieldtype php-mysql-field-type)
(defalias mysql_fieldflags php-mysql-field-flags)
(defalias mysql_selectdb php-mysql-select-db)
(defalias mysql_freeresult php-mysql-free-result)
(defalias mysql_numfields php-mysql-num-fields)
(defalias mysql_numrows php-mysql-num-rows)
(defalias mysql_listdbs php-mysql-list-dbs)
(defalias mysql_listtables php-mysql-list-tables)
(defalias mysql_listfields php-mysql-list-fields)
|
e69b8a2dba2c66aa2d2cbeb178818997e6b3332759a458139fcdfa11cafb6079 | potatosalad/erlang-jose | hex.erl | -*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*-
%% vim: ts=4 sw=4 ft=erlang noet
%%%-------------------------------------------------------------------
@author < >
2014 - 2022 ,
%%% @doc
%%%
%%% @end
Created : 12 Aug 2015 by < >
%%%-------------------------------------------------------------------
-module(hex).
%% API
-export([bin_to_hex/1]).
-export([hex_to_bin/1]).
-define(HEX_TO_INT(C),
case C of
$0 -> 16#0;
$1 -> 16#1;
$2 -> 16#2;
$3 -> 16#3;
$4 -> 16#4;
$5 -> 16#5;
$6 -> 16#6;
$7 -> 16#7;
$8 -> 16#8;
$9 -> 16#9;
$a -> 16#A;
$b -> 16#B;
$c -> 16#C;
$d -> 16#D;
$e -> 16#E;
$f -> 16#F;
$A -> 16#A;
$B -> 16#B;
$C -> 16#C;
$D -> 16#D;
$E -> 16#E;
$F -> 16#F
end).
-define(INT_TO_HEX(C),
case C of
16#0 -> $0;
16#1 -> $1;
16#2 -> $2;
16#3 -> $3;
16#4 -> $4;
16#5 -> $5;
16#6 -> $6;
16#7 -> $7;
16#8 -> $8;
16#9 -> $9;
16#A -> $a;
16#B -> $b;
16#C -> $c;
16#D -> $d;
16#E -> $e;
16#F -> $f
end).
%%====================================================================
%% API functions
%%====================================================================
bin_to_hex(Bin) ->
<< << (?INT_TO_HEX(V bsr 4)), (?INT_TO_HEX(V band 16#F)) >> || << V >> <= Bin >>.
hex_to_bin(Hex) ->
<< << ((?HEX_TO_INT(X) bsl 4) + ?HEX_TO_INT(Y)) >> || << X, Y >> <= Hex >>.
%%%-------------------------------------------------------------------
Internal functions
%%%-------------------------------------------------------------------
| null | https://raw.githubusercontent.com/potatosalad/erlang-jose/dbc4074066080692246afe613345ef6becc2a3fe/test/cavp_SUITE_data/hex.erl | erlang | vim: ts=4 sw=4 ft=erlang noet
-------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
====================================================================
API functions
====================================================================
-------------------------------------------------------------------
------------------------------------------------------------------- | -*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*-
@author < >
2014 - 2022 ,
Created : 12 Aug 2015 by < >
-module(hex).
-export([bin_to_hex/1]).
-export([hex_to_bin/1]).
-define(HEX_TO_INT(C),
case C of
$0 -> 16#0;
$1 -> 16#1;
$2 -> 16#2;
$3 -> 16#3;
$4 -> 16#4;
$5 -> 16#5;
$6 -> 16#6;
$7 -> 16#7;
$8 -> 16#8;
$9 -> 16#9;
$a -> 16#A;
$b -> 16#B;
$c -> 16#C;
$d -> 16#D;
$e -> 16#E;
$f -> 16#F;
$A -> 16#A;
$B -> 16#B;
$C -> 16#C;
$D -> 16#D;
$E -> 16#E;
$F -> 16#F
end).
-define(INT_TO_HEX(C),
case C of
16#0 -> $0;
16#1 -> $1;
16#2 -> $2;
16#3 -> $3;
16#4 -> $4;
16#5 -> $5;
16#6 -> $6;
16#7 -> $7;
16#8 -> $8;
16#9 -> $9;
16#A -> $a;
16#B -> $b;
16#C -> $c;
16#D -> $d;
16#E -> $e;
16#F -> $f
end).
bin_to_hex(Bin) ->
<< << (?INT_TO_HEX(V bsr 4)), (?INT_TO_HEX(V band 16#F)) >> || << V >> <= Bin >>.
hex_to_bin(Hex) ->
<< << ((?HEX_TO_INT(X) bsl 4) + ?HEX_TO_INT(Y)) >> || << X, Y >> <= Hex >>.
Internal functions
|
568ec9a37f8daf399525d080e7bae910da9b9087f6f0e0b9acf8270d8b31ec0f | hanshuebner/pixelisp | gallery-and-clock.lisp | (loop
(cl-log:log-message :info "running animations")
(app:start :gallery)
(sleep 45)
(cl-log:log-message :info "running clock")
(app:start :clock)
(sleep 15)
(cl-log:log-message :info "script done"))
| null | https://raw.githubusercontent.com/hanshuebner/pixelisp/f304dfb08130d5a2a7deb68fc4881e720df42a56/scripts/gallery-and-clock.lisp | lisp | (loop
(cl-log:log-message :info "running animations")
(app:start :gallery)
(sleep 45)
(cl-log:log-message :info "running clock")
(app:start :clock)
(sleep 15)
(cl-log:log-message :info "script done"))
| |
1852c0178581c6a4db750dffcec569f8ac97c264ce1572c56e872d33cf04c384 | shop-planner/shop3 | p05.lisp |
(IN-PACKAGE :SHOP-USER)
(DEFPROBLEM STRIPS-SAT-X-1
((SATELLITE SATELLITE0) (INSTRUMENT INSTRUMENT0)
(INSTRUMENT INSTRUMENT1) (INSTRUMENT INSTRUMENT2)
(SATELLITE SATELLITE1) (INSTRUMENT INSTRUMENT3)
(INSTRUMENT INSTRUMENT4) (INSTRUMENT INSTRUMENT5)
(SATELLITE SATELLITE2) (INSTRUMENT INSTRUMENT6)
(INSTRUMENT INSTRUMENT7) (INSTRUMENT INSTRUMENT8) (MODE THERMOGRAPH0)
(MODE IMAGE2) (MODE SPECTROGRAPH1) (DIRECTION GROUNDSTATION2)
(DIRECTION GROUNDSTATION1) (DIRECTION GROUNDSTATION0)
(DIRECTION STAR3) (DIRECTION STAR4) (DIRECTION PHENOMENON5)
(DIRECTION PHENOMENON6) (DIRECTION STAR7) (DIRECTION PHENOMENON8)
(DIRECTION PLANET9) (SUPPORTS INSTRUMENT0 IMAGE2)
(SUPPORTS INSTRUMENT0 THERMOGRAPH0)
(SUPPORTS INSTRUMENT0 SPECTROGRAPH1)
(CALIBRATION_TARGET INSTRUMENT0 GROUNDSTATION2)
(SUPPORTS INSTRUMENT1 THERMOGRAPH0)
(SUPPORTS INSTRUMENT1 SPECTROGRAPH1) (SUPPORTS INSTRUMENT1 IMAGE2)
(CALIBRATION_TARGET INSTRUMENT1 GROUNDSTATION1)
(SUPPORTS INSTRUMENT2 IMAGE2)
(CALIBRATION_TARGET INSTRUMENT2 GROUNDSTATION0)
(ON_BOARD INSTRUMENT0 SATELLITE0) (ON_BOARD INSTRUMENT1 SATELLITE0)
(ON_BOARD INSTRUMENT2 SATELLITE0) (POWER_AVAIL SATELLITE0)
(POINTING SATELLITE0 PHENOMENON8)
(SUPPORTS INSTRUMENT3 SPECTROGRAPH1)
(SUPPORTS INSTRUMENT3 THERMOGRAPH0)
(CALIBRATION_TARGET INSTRUMENT3 GROUNDSTATION0)
(SUPPORTS INSTRUMENT4 IMAGE2) (SUPPORTS INSTRUMENT4 SPECTROGRAPH1)
(CALIBRATION_TARGET INSTRUMENT4 GROUNDSTATION2)
(SUPPORTS INSTRUMENT5 IMAGE2) (SUPPORTS INSTRUMENT5 SPECTROGRAPH1)
(SUPPORTS INSTRUMENT5 THERMOGRAPH0)
(CALIBRATION_TARGET INSTRUMENT5 GROUNDSTATION1)
(ON_BOARD INSTRUMENT3 SATELLITE1) (ON_BOARD INSTRUMENT4 SATELLITE1)
(ON_BOARD INSTRUMENT5 SATELLITE1) (POWER_AVAIL SATELLITE1)
(POINTING SATELLITE1 GROUNDSTATION2) (SUPPORTS INSTRUMENT6 IMAGE2)
(CALIBRATION_TARGET INSTRUMENT6 GROUNDSTATION1)
(SUPPORTS INSTRUMENT7 IMAGE2) (SUPPORTS INSTRUMENT7 THERMOGRAPH0)
(CALIBRATION_TARGET INSTRUMENT7 GROUNDSTATION1)
(SUPPORTS INSTRUMENT8 SPECTROGRAPH1) (SUPPORTS INSTRUMENT8 IMAGE2)
(SUPPORTS INSTRUMENT8 THERMOGRAPH0)
(CALIBRATION_TARGET INSTRUMENT8 GROUNDSTATION0)
(ON_BOARD INSTRUMENT6 SATELLITE2) (ON_BOARD INSTRUMENT7 SATELLITE2)
(ON_BOARD INSTRUMENT8 SATELLITE2) (POWER_AVAIL SATELLITE2)
(POINTING SATELLITE2 PHENOMENON5)
(ORIGINAL-GOAL
(AND (POINTING SATELLITE0 PHENOMENON5)
(POINTING SATELLITE1 GROUNDSTATION2)
(HAVE_IMAGE STAR3 THERMOGRAPH0) (HAVE_IMAGE PHENOMENON5 IMAGE2)
(HAVE_IMAGE PHENOMENON6 IMAGE2) (HAVE_IMAGE STAR7 THERMOGRAPH0)
(HAVE_IMAGE PHENOMENON8 IMAGE2)
(HAVE_IMAGE PLANET9 SPECTROGRAPH1)))
(GOAL-POINTING SATELLITE0 PHENOMENON5)
(GOAL-POINTING SATELLITE1 GROUNDSTATION2)
(GOAL-HAVE-IMAGE STAR3 THERMOGRAPH0)
(GOAL-HAVE-IMAGE PHENOMENON5 IMAGE2)
(GOAL-HAVE-IMAGE PHENOMENON6 IMAGE2)
(GOAL-HAVE-IMAGE STAR7 THERMOGRAPH0)
(GOAL-HAVE-IMAGE PHENOMENON8 IMAGE2)
(GOAL-HAVE-IMAGE PLANET9 SPECTROGRAPH1))
(MAIN)) | null | https://raw.githubusercontent.com/shop-planner/shop3/ba429cf91a575e88f28b7f0e89065de7b4d666a6/shop3/examples/satellite/strips/p05.lisp | lisp |
(IN-PACKAGE :SHOP-USER)
(DEFPROBLEM STRIPS-SAT-X-1
((SATELLITE SATELLITE0) (INSTRUMENT INSTRUMENT0)
(INSTRUMENT INSTRUMENT1) (INSTRUMENT INSTRUMENT2)
(SATELLITE SATELLITE1) (INSTRUMENT INSTRUMENT3)
(INSTRUMENT INSTRUMENT4) (INSTRUMENT INSTRUMENT5)
(SATELLITE SATELLITE2) (INSTRUMENT INSTRUMENT6)
(INSTRUMENT INSTRUMENT7) (INSTRUMENT INSTRUMENT8) (MODE THERMOGRAPH0)
(MODE IMAGE2) (MODE SPECTROGRAPH1) (DIRECTION GROUNDSTATION2)
(DIRECTION GROUNDSTATION1) (DIRECTION GROUNDSTATION0)
(DIRECTION STAR3) (DIRECTION STAR4) (DIRECTION PHENOMENON5)
(DIRECTION PHENOMENON6) (DIRECTION STAR7) (DIRECTION PHENOMENON8)
(DIRECTION PLANET9) (SUPPORTS INSTRUMENT0 IMAGE2)
(SUPPORTS INSTRUMENT0 THERMOGRAPH0)
(SUPPORTS INSTRUMENT0 SPECTROGRAPH1)
(CALIBRATION_TARGET INSTRUMENT0 GROUNDSTATION2)
(SUPPORTS INSTRUMENT1 THERMOGRAPH0)
(SUPPORTS INSTRUMENT1 SPECTROGRAPH1) (SUPPORTS INSTRUMENT1 IMAGE2)
(CALIBRATION_TARGET INSTRUMENT1 GROUNDSTATION1)
(SUPPORTS INSTRUMENT2 IMAGE2)
(CALIBRATION_TARGET INSTRUMENT2 GROUNDSTATION0)
(ON_BOARD INSTRUMENT0 SATELLITE0) (ON_BOARD INSTRUMENT1 SATELLITE0)
(ON_BOARD INSTRUMENT2 SATELLITE0) (POWER_AVAIL SATELLITE0)
(POINTING SATELLITE0 PHENOMENON8)
(SUPPORTS INSTRUMENT3 SPECTROGRAPH1)
(SUPPORTS INSTRUMENT3 THERMOGRAPH0)
(CALIBRATION_TARGET INSTRUMENT3 GROUNDSTATION0)
(SUPPORTS INSTRUMENT4 IMAGE2) (SUPPORTS INSTRUMENT4 SPECTROGRAPH1)
(CALIBRATION_TARGET INSTRUMENT4 GROUNDSTATION2)
(SUPPORTS INSTRUMENT5 IMAGE2) (SUPPORTS INSTRUMENT5 SPECTROGRAPH1)
(SUPPORTS INSTRUMENT5 THERMOGRAPH0)
(CALIBRATION_TARGET INSTRUMENT5 GROUNDSTATION1)
(ON_BOARD INSTRUMENT3 SATELLITE1) (ON_BOARD INSTRUMENT4 SATELLITE1)
(ON_BOARD INSTRUMENT5 SATELLITE1) (POWER_AVAIL SATELLITE1)
(POINTING SATELLITE1 GROUNDSTATION2) (SUPPORTS INSTRUMENT6 IMAGE2)
(CALIBRATION_TARGET INSTRUMENT6 GROUNDSTATION1)
(SUPPORTS INSTRUMENT7 IMAGE2) (SUPPORTS INSTRUMENT7 THERMOGRAPH0)
(CALIBRATION_TARGET INSTRUMENT7 GROUNDSTATION1)
(SUPPORTS INSTRUMENT8 SPECTROGRAPH1) (SUPPORTS INSTRUMENT8 IMAGE2)
(SUPPORTS INSTRUMENT8 THERMOGRAPH0)
(CALIBRATION_TARGET INSTRUMENT8 GROUNDSTATION0)
(ON_BOARD INSTRUMENT6 SATELLITE2) (ON_BOARD INSTRUMENT7 SATELLITE2)
(ON_BOARD INSTRUMENT8 SATELLITE2) (POWER_AVAIL SATELLITE2)
(POINTING SATELLITE2 PHENOMENON5)
(ORIGINAL-GOAL
(AND (POINTING SATELLITE0 PHENOMENON5)
(POINTING SATELLITE1 GROUNDSTATION2)
(HAVE_IMAGE STAR3 THERMOGRAPH0) (HAVE_IMAGE PHENOMENON5 IMAGE2)
(HAVE_IMAGE PHENOMENON6 IMAGE2) (HAVE_IMAGE STAR7 THERMOGRAPH0)
(HAVE_IMAGE PHENOMENON8 IMAGE2)
(HAVE_IMAGE PLANET9 SPECTROGRAPH1)))
(GOAL-POINTING SATELLITE0 PHENOMENON5)
(GOAL-POINTING SATELLITE1 GROUNDSTATION2)
(GOAL-HAVE-IMAGE STAR3 THERMOGRAPH0)
(GOAL-HAVE-IMAGE PHENOMENON5 IMAGE2)
(GOAL-HAVE-IMAGE PHENOMENON6 IMAGE2)
(GOAL-HAVE-IMAGE STAR7 THERMOGRAPH0)
(GOAL-HAVE-IMAGE PHENOMENON8 IMAGE2)
(GOAL-HAVE-IMAGE PLANET9 SPECTROGRAPH1))
(MAIN)) | |
ed9ca60c1f1f0f3ab6b9e5adc44c9d942d55d042ff7187916277ded05b6e3626 | irastypain/sicp-on-language-racket | test_exercise_2_30.rkt | #lang racket
(require rackunit
"../../src/chapter02/exercise_2_30.rkt")
(check-equal? (square-tree (list (list 1 2) (list 3 4)))
(list (list 1 4) (list 9 16))
(printf "test#1 2.30 passed\n"))
(check-equal? (square-tree (list (list (list 1 4) 9) (list 16) 25))
(list (list (list 1 16) 81) (list 256) 625)
(printf "test#2 2.30 passed\n"))
| null | https://raw.githubusercontent.com/irastypain/sicp-on-language-racket/0052f91d3c2432a00e7e15310f416cb77eeb4c9c/test/chapter02/test_exercise_2_30.rkt | racket | #lang racket
(require rackunit
"../../src/chapter02/exercise_2_30.rkt")
(check-equal? (square-tree (list (list 1 2) (list 3 4)))
(list (list 1 4) (list 9 16))
(printf "test#1 2.30 passed\n"))
(check-equal? (square-tree (list (list (list 1 4) 9) (list 16) 25))
(list (list (list 1 16) 81) (list 256) 625)
(printf "test#2 2.30 passed\n"))
| |
3a81e8799c2d4be00529edc83ea7d1087d8dde06605de7486199678a780d08f7 | johnstonskj/simple-oauth2 | pkce.rkt | #lang racket/base
;;
simple - oauth2 - oauth2 / client / pkce .
;; Simple OAuth2 client and server implementation
;;
Copyright ( c ) 2019 ( ) .
(provide
(except-out (struct-out pkce) make-pkce)
create-challenge
verifier-char?)
;; ---------- Requirements
(require racket/bool
racket/contract
racket/list
racket/random
racket/set
file/sha1
net/jwt/base64)
;; ---------- Implementation
(define-struct/contract pkce
([verifier bytes?]
[challenge string?]
[method (or/c "plain" "S256")]))
(define (char-range start end)
;; start and end -> (or/c char? natural?)
(define (char-idx x) (if (char? x) (char->integer x) x))
(for/list ([ch (in-range (char-idx start) (add1 (char-idx end)))])
(integer->char ch)))
(define verifier-char-set
for quick lookup , here are the allowed ASCII allowed by PKCE
;; unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
ALPHA = % x41 - 5A / % x61 - 7A
;; DIGIT = %x30-39
(list->set
(append
(char-range #x41 #x5A) ; A...Z
(char-range #x61 #x7A) ; a...z
0 ... 9
'(#\- #\. #\_ #\~))))
(define (verifier-char? ch)
(and (char? ch)
(set-member? verifier-char-set ch)))
(define (verifier-byte? ch)
(verifier-char? (integer->char ch)))
(define (random-verifier length)
(define (random-block)
(crypto-random-bytes (* length 2)))
(let next-block ([block (random-block)]
[verifier #""])
(define filtered (list->bytes (filter verifier-byte? (bytes->list block))))
(define sum (bytes-append verifier filtered))
(define sum-length (bytes-length sum))
(cond
[(= sum-length length)
sum]
[(> sum-length length)
(subbytes sum 0 length)]
[else
(next-block (random-block) sum)])))
(define (create-challenge [a-verifier #f])
(define verifier
(cond
[(false? a-verifier)
(random-verifier 128)]
[(and (bytes? a-verifier)
(>= (bytes-length a-verifier) 43)
(<= (bytes-length a-verifier) 128))
(unless (for/and ([ch (bytes->list a-verifier)]) (verifier-byte? ch))
(error "invalid character code in verifier string"))
a-verifier]
[else (error "code verifier must be 43 to 128 byte string or #f")]))
(define challenge (base64-url-encode (sha256-bytes verifier)))
; only support 'S256' option, no need for 'plain'
(make-pkce verifier challenge "S256"))
;; ---------- Internal Tests
(module+ test
(require rackunit)
(define test-chars-ok "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.~")
(for-each (λ (ch) (check-true (verifier-char? ch) (format "char: ~a" ch))) (string->list test-chars-ok))
(define test-chars-bad "!@#$%^&*()+={[}]|\\:;\"'<,>?/λßåœ∑®†¥πø∆˚˙ƒßå√ç")
(for-each (λ (ch) (check-false (verifier-char? ch) (format "char: ~a" ch))) (string->list test-chars-bad))
(define test-verifier (random-verifier 128))
(check-equal? (bytes-length test-verifier) 128)
(for-each (λ (ch) (check-true (verifier-byte? ch) (format "byte: ~a" ch))) (bytes->list test-verifier))
(check-true (pkce? (create-challenge (string->bytes/latin-1 test-chars-ok))))
(check-exn
exn:fail?
(λ ()
(create-challenge "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRßTUVWXYZ-_.~"))
"not bytes")
(check-exn
exn:fail?
(λ ()
(create-challenge (string->bytes/latin-1 "0123456789abcdefghijklmnopqrstuvwxyz")))
"bytes to short")
(check-exn
exn:fail?
(λ ()
(create-challenge (string->bytes/latin-1 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRßTUVWXYZ-_.~")))
"invalid character 'ß' in string"))
| null | https://raw.githubusercontent.com/johnstonskj/simple-oauth2/b8cb40511f64dcb274e17957e6fc9ab4c8a6cbea/client/pkce.rkt | racket |
Simple OAuth2 client and server implementation
---------- Requirements
---------- Implementation
start and end -> (or/c char? natural?)
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
DIGIT = %x30-39
A...Z
a...z
only support 'S256' option, no need for 'plain'
---------- Internal Tests | #lang racket/base
simple - oauth2 - oauth2 / client / pkce .
Copyright ( c ) 2019 ( ) .
(provide
(except-out (struct-out pkce) make-pkce)
create-challenge
verifier-char?)
(require racket/bool
racket/contract
racket/list
racket/random
racket/set
file/sha1
net/jwt/base64)
(define-struct/contract pkce
([verifier bytes?]
[challenge string?]
[method (or/c "plain" "S256")]))
(define (char-range start end)
(define (char-idx x) (if (char? x) (char->integer x) x))
(for/list ([ch (in-range (char-idx start) (add1 (char-idx end)))])
(integer->char ch)))
(define verifier-char-set
for quick lookup , here are the allowed ASCII allowed by PKCE
ALPHA = % x41 - 5A / % x61 - 7A
(list->set
(append
0 ... 9
'(#\- #\. #\_ #\~))))
(define (verifier-char? ch)
(and (char? ch)
(set-member? verifier-char-set ch)))
(define (verifier-byte? ch)
(verifier-char? (integer->char ch)))
(define (random-verifier length)
(define (random-block)
(crypto-random-bytes (* length 2)))
(let next-block ([block (random-block)]
[verifier #""])
(define filtered (list->bytes (filter verifier-byte? (bytes->list block))))
(define sum (bytes-append verifier filtered))
(define sum-length (bytes-length sum))
(cond
[(= sum-length length)
sum]
[(> sum-length length)
(subbytes sum 0 length)]
[else
(next-block (random-block) sum)])))
(define (create-challenge [a-verifier #f])
(define verifier
(cond
[(false? a-verifier)
(random-verifier 128)]
[(and (bytes? a-verifier)
(>= (bytes-length a-verifier) 43)
(<= (bytes-length a-verifier) 128))
(unless (for/and ([ch (bytes->list a-verifier)]) (verifier-byte? ch))
(error "invalid character code in verifier string"))
a-verifier]
[else (error "code verifier must be 43 to 128 byte string or #f")]))
(define challenge (base64-url-encode (sha256-bytes verifier)))
(make-pkce verifier challenge "S256"))
(module+ test
(require rackunit)
(define test-chars-ok "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.~")
(for-each (λ (ch) (check-true (verifier-char? ch) (format "char: ~a" ch))) (string->list test-chars-ok))
(define test-chars-bad "!@#$%^&*()+={[}]|\\:;\"'<,>?/λßåœ∑®†¥πø∆˚˙ƒßå√ç")
(for-each (λ (ch) (check-false (verifier-char? ch) (format "char: ~a" ch))) (string->list test-chars-bad))
(define test-verifier (random-verifier 128))
(check-equal? (bytes-length test-verifier) 128)
(for-each (λ (ch) (check-true (verifier-byte? ch) (format "byte: ~a" ch))) (bytes->list test-verifier))
(check-true (pkce? (create-challenge (string->bytes/latin-1 test-chars-ok))))
(check-exn
exn:fail?
(λ ()
(create-challenge "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRßTUVWXYZ-_.~"))
"not bytes")
(check-exn
exn:fail?
(λ ()
(create-challenge (string->bytes/latin-1 "0123456789abcdefghijklmnopqrstuvwxyz")))
"bytes to short")
(check-exn
exn:fail?
(λ ()
(create-challenge (string->bytes/latin-1 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRßTUVWXYZ-_.~")))
"invalid character 'ß' in string"))
|
676ce9439fcf93f911b61bf1118516ab1c697cd638d2ee6ce3e599e0dd9d9ac8 | borodust/alien-works | utils.lisp | (cl:in-package :%alien-works.filament)
;;;
;;; BUILDER
;;;
(defun explode-function (signature args)
(let ((name (first signature))
(types (rest signature)))
(when (/= (length types) (length args))
(error "Wrong number of arguments for ~A: required ~A, but got ~A"
name types args))
`(,name ,@(loop for type in types
for arg in args
append (list type arg)))))
(defmacro warp-intricate-function (name intricate-name &body params)
(let ((args (loop for nil in params
collect (gensym))))
`(defun ,name (,@args)
,(explode-function (list* intricate-name params) args))))
(defgeneric builder-option-intricate-function (builder option))
(defun explode-builder (name-and-opts
builder-name
ctor-expander
build-expander
maker-args
steps
body)
(a:with-gensyms (builder)
(destructuring-bind (name &rest opts) (a:ensure-list name-and-opts)
(destructuring-bind (&key instance &allow-other-keys) opts
`(iffi:with-intricate-instance (,builder ,@(funcall ctor-expander))
,@(loop for (name . args) in steps
collect (explode-function (builder-option-intricate-function builder-name name)
(list* builder args)))
(flet ((,name (,@maker-args)
,(funcall build-expander builder)))
(,@(if instance
`(let ((,instance ,builder)))
'(progn))
,@body)))))))
(defmacro warp-intricate-builder-option (builder option-name intricate-function &body params)
(let ((intricate-signature (list* intricate-function params)))
`(progn
(warp-intricate-function ,(a:symbolicate builder '- option-name) ,@intricate-signature)
(defmethod builder-option-intricate-function ((builder (eql ',builder))
(option (eql ,option-name)))
(declare (ignore builder option))
',intricate-signature))))
| null | https://raw.githubusercontent.com/borodust/alien-works/af1a359c9855199e62db50a5c6a3986c81fbab39/src/graphics/filament/utils.lisp | lisp |
BUILDER
| (cl:in-package :%alien-works.filament)
(defun explode-function (signature args)
(let ((name (first signature))
(types (rest signature)))
(when (/= (length types) (length args))
(error "Wrong number of arguments for ~A: required ~A, but got ~A"
name types args))
`(,name ,@(loop for type in types
for arg in args
append (list type arg)))))
(defmacro warp-intricate-function (name intricate-name &body params)
(let ((args (loop for nil in params
collect (gensym))))
`(defun ,name (,@args)
,(explode-function (list* intricate-name params) args))))
(defgeneric builder-option-intricate-function (builder option))
(defun explode-builder (name-and-opts
builder-name
ctor-expander
build-expander
maker-args
steps
body)
(a:with-gensyms (builder)
(destructuring-bind (name &rest opts) (a:ensure-list name-and-opts)
(destructuring-bind (&key instance &allow-other-keys) opts
`(iffi:with-intricate-instance (,builder ,@(funcall ctor-expander))
,@(loop for (name . args) in steps
collect (explode-function (builder-option-intricate-function builder-name name)
(list* builder args)))
(flet ((,name (,@maker-args)
,(funcall build-expander builder)))
(,@(if instance
`(let ((,instance ,builder)))
'(progn))
,@body)))))))
(defmacro warp-intricate-builder-option (builder option-name intricate-function &body params)
(let ((intricate-signature (list* intricate-function params)))
`(progn
(warp-intricate-function ,(a:symbolicate builder '- option-name) ,@intricate-signature)
(defmethod builder-option-intricate-function ((builder (eql ',builder))
(option (eql ,option-name)))
(declare (ignore builder option))
',intricate-signature))))
|
e1c488166ec6bb8132b4e4bc9c7051fc6091572ce67fb5f1856a31286b5c532d | phadej/cabal-refact | Version.hs | {-# LANGUAGE OverloadedStrings #-}
module Distribution.Refact.Types.Version where
import Prelude ()
import Distribution.Refact.Internal.Prelude
import Distribution.Refact.Tools.Trifecta
import Data.List (foldl')
newtype Version = Version (NonEmpty Word)
deriving (Eq, Show)
versionToText :: Version -> Text
versionToText (Version (x :| xs)) = foldl' f (x ^. asText) xs
where
f t y = t <> "." <> y ^. asText
versionParser :: CharParsing m => m Version
versionParser = f <$> integral <*> many (char '.' *> integral) <?> "version"
where
f x xs = Version (x :| xs)
| null | https://raw.githubusercontent.com/phadej/cabal-refact/9442736429e498f95dc24866c97be587113206ab/src/Distribution/Refact/Types/Version.hs | haskell | # LANGUAGE OverloadedStrings # | module Distribution.Refact.Types.Version where
import Prelude ()
import Distribution.Refact.Internal.Prelude
import Distribution.Refact.Tools.Trifecta
import Data.List (foldl')
newtype Version = Version (NonEmpty Word)
deriving (Eq, Show)
versionToText :: Version -> Text
versionToText (Version (x :| xs)) = foldl' f (x ^. asText) xs
where
f t y = t <> "." <> y ^. asText
versionParser :: CharParsing m => m Version
versionParser = f <$> integral <*> many (char '.' *> integral) <?> "version"
where
f x xs = Version (x :| xs)
|
ef0a383cb897104480e68772502d417f72d7f28fa7127fd8b6f72e498d3cb7a3 | samsergey/formica | arity.rkt | #lang racket/base
;;______________________________________________________________
;; ______
;; ( // _____ ____ . __ __
;; ~//~ ((_)// // / / // ((_ ((_/_
;; (_//
;;..............................................................
;; Provides tools to work with function arity.
;;==============================================================
(require (only-in racket/list argmin argmax)
racket/contract)
(provide
(contract-out
(polyadic? predicate/c)
(variadic? predicate/c)
(fixed-arity? predicate/c)
(nullary? predicate/c)
(unary? predicate/c)
(binary? predicate/c)
(min-arity (-> procedure? (or/c 0 positive?)))
(max-arity (-> procedure? (or/c 0 positive? +inf.0)))
(fixed-arity (-> procedure-arity? procedure-arity?))
(reduce-arity (-> procedure-arity? integer? procedure-arity?))
(inherit-arity (-> procedure? (-> procedure? procedure?)))))
;; Predicate. Specifies polyadic functions.
(define (polyadic? f)
(and (procedure? f)
(list? (procedure-arity f))))
;; Predicate. Specifies variadic functions.
(define (variadic? f)
(and (procedure? f)
(let ([ar (procedure-arity f)])
(if (list? ar)
(ormap arity-at-least? ar)
(arity-at-least? ar)))))
;; Predicate. Specifies variadic functions.
(define (fixed-arity? f)
(and (procedure? f)
(integer? (procedure-arity f))))
;; Predicate. Specifies variadic nullary functions.
(define (nullary? f)
(and (procedure? f)
(procedure-arity-includes? f 0)))
;; Predicate. Specifies variadic unary functions.
(define (unary? f)
(and (procedure? f)
(procedure-arity-includes? f 1)))
;; Predicate. Specifies variadic binary functions.
(define (binary? f)
(and (procedure? f)
(procedure-arity-includes? f 2)))
;; Returns minimal acceptible arity for a function
(define (min-arity f)
(let result ([ar (procedure-arity f)])
(cond
[(list? ar) (argmin result ar)]
[(null? ar) 0]
[(arity-at-least? ar) (arity-at-least-value ar)]
[else ar])))
;; Returns maximal acceptible arity for a function
(define (max-arity f)
(let result ([ar (procedure-arity f)])
(cond
[(null? ar) 0]
[(list? ar) (apply max (map result ar))]
[(arity-at-least? ar) +inf.0]
[else ar])))
;; Fixes variable arity
(define (fixed-arity ar)
(cond
[(arity-at-least? ar) (arity-at-least-value ar)]
[(list? ar) (map fixed-arity ar)]
[else ar]))
;; Arity reduction by an integer
(define (reduce-arity a n)
(cond
[(integer? a) (if (<= n a) (- a n) (error 'reduce-arity
(format "Cannot reduce arity ~a by ~a." a n)))]
[(list? a) (let ([possible (filter (λ (x) (or (and (integer? x) (>= x n)) (arity-at-least? x))) a)])
(when (null? possible) (error 'reduce-arity
(format "Cannot reduce arity ~a by ~a." a n)))
(map (λ (x) (reduce-arity x n)) possible))]
[(arity-at-least? a) (arity-at-least (max 0 (- (arity-at-least-value a) n)))]))
(define ((inherit-arity f) g)
(procedure-reduce-arity g (procedure-arity f))) | null | https://raw.githubusercontent.com/samsergey/formica/b4410b4b6da63ecb15b4c25080951a7ba4d90d2c/private/tools/arity.rkt | racket | ______________________________________________________________
______
( // _____ ____ . __ __
~//~ ((_)// // / / // ((_ ((_/_
(_//
..............................................................
Provides tools to work with function arity.
==============================================================
Predicate. Specifies polyadic functions.
Predicate. Specifies variadic functions.
Predicate. Specifies variadic functions.
Predicate. Specifies variadic nullary functions.
Predicate. Specifies variadic unary functions.
Predicate. Specifies variadic binary functions.
Returns minimal acceptible arity for a function
Returns maximal acceptible arity for a function
Fixes variable arity
Arity reduction by an integer | #lang racket/base
(require (only-in racket/list argmin argmax)
racket/contract)
(provide
(contract-out
(polyadic? predicate/c)
(variadic? predicate/c)
(fixed-arity? predicate/c)
(nullary? predicate/c)
(unary? predicate/c)
(binary? predicate/c)
(min-arity (-> procedure? (or/c 0 positive?)))
(max-arity (-> procedure? (or/c 0 positive? +inf.0)))
(fixed-arity (-> procedure-arity? procedure-arity?))
(reduce-arity (-> procedure-arity? integer? procedure-arity?))
(inherit-arity (-> procedure? (-> procedure? procedure?)))))
(define (polyadic? f)
(and (procedure? f)
(list? (procedure-arity f))))
(define (variadic? f)
(and (procedure? f)
(let ([ar (procedure-arity f)])
(if (list? ar)
(ormap arity-at-least? ar)
(arity-at-least? ar)))))
(define (fixed-arity? f)
(and (procedure? f)
(integer? (procedure-arity f))))
(define (nullary? f)
(and (procedure? f)
(procedure-arity-includes? f 0)))
(define (unary? f)
(and (procedure? f)
(procedure-arity-includes? f 1)))
(define (binary? f)
(and (procedure? f)
(procedure-arity-includes? f 2)))
(define (min-arity f)
(let result ([ar (procedure-arity f)])
(cond
[(list? ar) (argmin result ar)]
[(null? ar) 0]
[(arity-at-least? ar) (arity-at-least-value ar)]
[else ar])))
(define (max-arity f)
(let result ([ar (procedure-arity f)])
(cond
[(null? ar) 0]
[(list? ar) (apply max (map result ar))]
[(arity-at-least? ar) +inf.0]
[else ar])))
(define (fixed-arity ar)
(cond
[(arity-at-least? ar) (arity-at-least-value ar)]
[(list? ar) (map fixed-arity ar)]
[else ar]))
(define (reduce-arity a n)
(cond
[(integer? a) (if (<= n a) (- a n) (error 'reduce-arity
(format "Cannot reduce arity ~a by ~a." a n)))]
[(list? a) (let ([possible (filter (λ (x) (or (and (integer? x) (>= x n)) (arity-at-least? x))) a)])
(when (null? possible) (error 'reduce-arity
(format "Cannot reduce arity ~a by ~a." a n)))
(map (λ (x) (reduce-arity x n)) possible))]
[(arity-at-least? a) (arity-at-least (max 0 (- (arity-at-least-value a) n)))]))
(define ((inherit-arity f) g)
(procedure-reduce-arity g (procedure-arity f))) |
ffe5f65e75c22d0dca85fe965479213d6ab85e4b019909ed2b06e67de4b64658 | dcos/dcos-net | dcos_l4lb_ipvs_mgr.erl | %%%-------------------------------------------------------------------
@author sdhillon
( C ) 2016 , < COMPANY >
%%% @doc
%%%
%%% @end
Created : 01 . Nov 2016 7:35 AM
%%%-------------------------------------------------------------------
-module(dcos_l4lb_ipvs_mgr).
-author("sdhillon").
-behaviour(gen_server).
%% API
-export([start_link/0]).
-export([get_dests/3,
add_dest/8,
mod_dest/8,
remove_dest/7,
get_services/2,
add_service/5,
remove_service/5,
service_address/1,
destination_address/2,
add_netns/2,
remove_netns/2,
init_metrics/0]).
%% gen_server callbacks
-export([init/1, handle_call/3,
handle_cast/2, handle_info/2]).
-define(SERVER, ?MODULE).
-record(state, {
netns :: map(),
family
}).
-type state() :: #state{}.
-include_lib("kernel/include/logger.hrl").
-include_lib("gen_netlink/include/netlink.hrl").
-include("dcos_l4lb.hrl").
-define(IP_VS_CONN_F_FWD_MASK, 16#7). %% mask for the fwd methods
masquerading / NAT
-define(IP_VS_CONN_F_LOCALNODE, 16#1). %% local node
-define(IP_VS_CONN_F_TUNNEL, 16#2). %% tunneling
-define(IP_VS_CONN_F_DROUTE, 16#3). %% direct routing
-define(IP_VS_CONN_F_BYPASS, 16#4). %% cache bypass
-define(IP_VS_CONN_F_SYNC, 16#20). %% entry created by sync
-define(IP_VS_CONN_F_HASHED, 16#40). %% hashed entry
-define(IP_VS_CONN_F_NOOUTPUT, 16#80). %% no output packets
-define(IP_VS_CONN_F_INACTIVE, 16#100). %% not established
-define(IP_VS_CONN_F_OUT_SEQ, 16#200). %% must do output seq adjust
-define(IP_VS_CONN_F_IN_SEQ, 16#400). %% must do input seq adjust
-define(IP_VS_CONN_F_SEQ_MASK, 16#600). %% in/out sequence mask
-define(IP_VS_CONN_F_NO_CPORT, 16#800). %% no client port set yet
-define(IP_VS_CONN_F_TEMPLATE, 16#1000). %% template, not connection
forward only one packet
-define(IP_VS_SVC_F_PERSISTENT, 16#1). %% persistent port */
-define(IP_VS_SVC_F_HASHED, 16#2). %% hashed entry */
one - packet scheduling * /
scheduler flag 1 * /
scheduler flag 2 * /
scheduler flag 3 * /
-define(IPVS_PROTOCOLS, [tcp, udp]). %% protocols to query gen_netlink for
-define(ADDR_FAMILIES, [inet, inet6]).
-type service() :: term().
-type dest() :: term().
-export_type([service/0, dest/0]).
-type backend_weight() :: dcos_l4lb_mesos_poller:backend_weight().
%%%===================================================================
%%% API
%%%===================================================================
-spec(get_services(Pid :: pid(), Namespace :: term()) -> [service()]).
get_services(Pid, Namespace) ->
call(Pid, {get_services, Namespace}).
-spec(add_service(Pid :: pid(), IP :: inet:ip_address(), Port :: inet:port_number(),
Protocol :: protocol(), Namespace :: term()) -> ok | error).
add_service(Pid, IP, Port, Protocol, Namespace) ->
call(Pid, {add_service, IP, Port, Protocol, Namespace}).
-spec(remove_service(Pid :: pid(), IP :: inet:ip_address(),
Port :: inet:port_number(),
Protocol :: protocol(), Namespace :: term()) -> ok | error).
remove_service(Pid, IP, Port, Protocol, Namespace) ->
call(Pid, {remove_service, IP, Port, Protocol, Namespace}).
-spec(get_dests(Pid :: pid(), Service :: service(), Namespace :: term()) -> [dest()]).
get_dests(Pid, Service, Namespace) ->
call(Pid, {get_dests, Service, Namespace}).
-spec(remove_dest(Pid :: pid(), ServiceIP :: inet:ip_address(),
ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term()) -> ok | error).
remove_dest(Pid, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace) ->
call(Pid, {remove_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace}).
-spec(add_dest(Pid :: pid(), ServiceIP :: inet:ip_address(), ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(),
Weight :: backend_weight()) -> ok | error).
add_dest(Pid, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight) ->
call(Pid, {add_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight}).
-spec(mod_dest(Pid :: pid(), ServiceIP :: inet:ip_address(), ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(),
Weight :: backend_weight()) -> ok | error).
mod_dest(Pid, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight) ->
gen_server:call(Pid, {mod_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight}).
add_netns(Pid, UpdateValue) ->
call(Pid, {add_netns, UpdateValue}).
remove_netns(Pid, UpdateValue) ->
call(Pid, {remove_netns, UpdateValue}).
%% @doc Starts the server
-spec(start_link() ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link() ->
gen_server:start_link(?MODULE, [], []).
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
init([]) ->
{ok, Pid} = gen_netlink_client:start_link(),
{ok, Family} = gen_netlink_client:get_family(Pid, "IPVS"),
{ok, #state{netns = #{host => Pid}, family = Family}}.
handle_call({get_services, Namespace}, _From, State) ->
Reply = handle_get_services(Namespace, State),
{reply, Reply, State};
handle_call({add_service, IP, Port, Protocol, Namespace}, _From, State) ->
Reply = handle_add_service(IP, Port, Protocol, Namespace, State),
{reply, Reply, State};
handle_call({remove_service, IP, Port, Protocol, Namespace}, _From, State) ->
Reply = handle_remove_service(IP, Port, Protocol, Namespace, State),
{reply, Reply, State};
handle_call({get_dests, Service, Namespace}, _From, State) ->
Reply = handle_get_dests(Service, Namespace, State),
{reply, Reply, State};
handle_call({add_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight}, _From, State) ->
Reply = handle_add_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, State, Weight),
{reply, Reply, State};
handle_call({mod_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight}, _From, State) ->
Reply = handle_mod_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, State, Weight),
{reply, Reply, State};
handle_call({remove_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace}, _From, State) ->
Reply = handle_remove_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, State),
{reply, Reply, State};
handle_call({add_netns, UpdateValue}, _From, State0) ->
{Reply, State1} = handle_add_netns(UpdateValue, State0),
{reply, Reply, State1};
handle_call({remove_netns, UpdateValue}, _From, State0) ->
{Reply, State1} = handle_remove_netns(UpdateValue, State0),
{reply, Reply, State1}.
handle_cast(_Request, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
%%%===================================================================
Internal functions
%%%===================================================================
-spec(service_address(service()) -> {family(), {protocol(), inet:ip_address(), inet:port_number()}}).
service_address(Service) ->
AF = proplists:get_value(address_family, Service),
Protocol = netlink_codec:protocol_to_atom(proplists:get_value(protocol, Service)),
AddressBin = proplists:get_value(address, Service),
Port = proplists:get_value(port, Service),
Family = netlink_codec:family_to_atom(AF),
InetAddr = address_to_ip(Family, AddressBin),
{AF, {Protocol, InetAddr, Port}}.
-spec(destination_address(family(), Destination :: dest()) -> {inet:ip_address(), inet:port_number()}).
destination_address(AF, Destination) ->
AddressBin = proplists:get_value(address, Destination),
Port = proplists:get_value(port, Destination),
Family = netlink_codec:family_to_atom(AF),
InetAddr = address_to_ip(Family, AddressBin),
{InetAddr, Port}.
-spec(handle_get_services(Namespace :: term(), State :: state()) -> [service()]).
handle_get_services(Namespace, State = #state{netns = NetnsMap}) ->
Pid = maps:get(Namespace, NetnsMap),
Params = [{AF, P} || AF <- ?ADDR_FAMILIES, P <- ?IPVS_PROTOCOLS],
lists:foldl(
fun({AddrFamily, Proto}, Acc) ->
Services = handle_get_services(AddrFamily, Proto, Pid, State),
Acc ++ Services
end, [], Params).
-spec(handle_get_services(AddressFamily :: family(), Protocol :: protocol(),
Namespace :: term(), State :: state()) -> [service()]).
handle_get_services(AddressFamily, Protocol, Pid, #state{family = Family}) ->
AddressFamily1 = netlink_codec:family_to_int(AddressFamily),
Protocol1 = netlink_codec:protocol_to_int(Protocol),
Message =
#get_service{
request =
[{service,
[{address_family, AddressFamily1},
{protocol, Protocol1}
]}
]},
{ok, Replies} = gen_netlink_client:request(Pid, Family, ipvs, [root, match], Message),
[proplists:get_value(service, MaybeService)
|| #netlink{msg = #new_service{request = MaybeService}}
<- Replies, proplists:is_defined(service, MaybeService)].
-spec(handle_remove_service(IP :: inet:ip_address(), Port :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(),
State :: state()) -> ok | error).
handle_remove_service(IP, Port, Protocol, Namespace, State) ->
Protocol1 = netlink_codec:protocol_to_int(Protocol),
Service = ip_to_address(IP) ++ [{port, Port}, {protocol, Protocol1}],
handle_remove_service(Service, Namespace, State).
-spec(handle_remove_service(Service :: service(), Namespace :: term(), State :: state()) -> ok | error).
handle_remove_service(Service, Namespace, #state{netns = NetnsMap, family = Family}) ->
?LOG_INFO("Namespace: ~p, Removing Service: ~p", [Namespace, Service]),
Pid = maps:get(Namespace, NetnsMap),
case gen_netlink_client:request(Pid, Family, ipvs, [], #del_service{request = [{service, Service}]}) of
{ok, _} -> ok;
_ -> error
end.
-spec(handle_add_service(IP :: inet:ip_address(), Port :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(), State :: state()) -> ok | error).
handle_add_service(IP, Port, Protocol, Namespace, #state{netns = NetnsMap, family = Family}) ->
Flags = 0,
Pid = maps:get(Namespace, NetnsMap),
Service0 = [
{protocol, netlink_codec:protocol_to_int(Protocol)},
{port, Port},
{sched_name, "wlc"},
{netmask, netmask_by_addrtype(IP)},
{flags, Flags, 16#ffffffff},
{timeout, 0}
],
Service1 = ip_to_address(IP) ++ Service0,
?LOG_INFO("Namespace: ~p, Adding Service: ~p", [Namespace, Service1]),
case gen_netlink_client:request(Pid, Family, ipvs, [], #new_service{request = [{service, Service1}]}) of
{ok, _} -> ok;
_ -> error
end.
-spec(handle_get_dests(Service :: service(), Namespace :: term(), State :: state()) -> [dest()]).
handle_get_dests(Service, Namespace, #state{netns = NetnsMap, family = Family}) ->
Pid = maps:get(Namespace, NetnsMap),
Message = #get_dest{request = [{service, Service}]},
{ok, Replies} = gen_netlink_client:request(Pid, Family, ipvs, [root, match], Message),
[proplists:get_value(dest, MaybeDest) || #netlink{msg = #new_dest{request = MaybeDest}} <- Replies,
proplists:is_defined(dest, MaybeDest)].
-spec(handle_mod_dest(ServiceIP :: inet:ip_address(), ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(), State :: state(),
Weight :: backend_weight()) -> ok | error).
handle_mod_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol,
Namespace, #state{netns = NetnsMap, family = Family}, Weight) ->
Pid = maps:get(Namespace, NetnsMap),
Protocol1 = netlink_codec:protocol_to_int(Protocol),
Service = ip_to_address(ServiceIP) ++ [{port, ServicePort}, {protocol, Protocol1}],
Base = [{fwd_method, ?IP_VS_CONN_F_MASQ}, {weight, Weight}, {u_threshold, 0}, {l_threshold, 0}],
Dest = [{port, DestPort}] ++ Base ++ ip_to_address(DestIP),
?LOG_INFO("Modifying backend ~p for service ~p~n", [{DestIP, DestPort, Weight}, Service]),
Msg = #set_dest{request = [{dest, Dest}, {service, Service}]},
case gen_netlink_client:request(Pid, Family, ipvs, [], Msg) of
{ok, _} -> ok;
_ -> error
end.
-spec(handle_add_dest(ServiceIP :: inet:ip_address(), ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(), State :: state(),
Weight :: backend_weight()) -> ok | error).
handle_add_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol,
Namespace, #state{netns = NetnsMap, family = Family}, Weight) ->
Pid = maps:get(Namespace, NetnsMap),
Protocol1 = netlink_codec:protocol_to_int(Protocol),
Service = ip_to_address(ServiceIP) ++ [{port, ServicePort}, {protocol, Protocol1}],
handle_add_dest(Pid, Service, DestIP, DestPort, Family, Weight).
handle_add_dest(Pid, Service, IP, Port, Family, Weight) ->
Base = [{fwd_method, ?IP_VS_CONN_F_MASQ}, {weight, Weight}, {u_threshold, 0}, {l_threshold, 0}],
Dest = [{port, Port}] ++ Base ++ ip_to_address(IP),
?LOG_INFO("Adding backend ~p to service ~p~n", [{IP, Port, Weight}, Service]),
Msg = #new_dest{request = [{dest, Dest}, {service, Service}]},
case gen_netlink_client:request(Pid, Family, ipvs, [], Msg) of
{ok, _} -> ok;
_ -> error
end.
-spec(handle_remove_dest(ServiceIP :: inet:ip_address(), ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(), State :: state()) -> ok | error).
handle_remove_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, State) ->
Protocol1 = netlink_codec:protocol_to_int(Protocol),
Service = ip_to_address(ServiceIP) ++ [{port, ServicePort}, {protocol, Protocol1}],
Dest = ip_to_address(DestIP) ++ [{port, DestPort}],
handle_remove_dest(Service, Dest, Namespace, State).
-spec(handle_remove_dest(Service :: service(), Dest :: dest(), Namespace :: term(), State :: state()) -> ok | error).
handle_remove_dest(Service, Dest, Namespace, #state{netns = NetnsMap, family = Family}) ->
?LOG_INFO("Removing Dest ~p to service ~p~n", [Dest, Service]),
Pid = maps:get(Namespace, NetnsMap),
Msg = #del_dest{request = [{dest, Dest}, {service, Service}]},
case gen_netlink_client:request(Pid, Family, ipvs, [], Msg) of
{ok, _} -> ok;
_ -> error
end.
netmask_by_addrtype(IP) when size(IP) == 4 ->
16#ffffffff;
netmask_by_addrtype(IP) when size(IP) == 8 ->
128.
address_to_ip(inet6, <<A:16, B:16, C:16, D:16, E:16, F:16, G:16, H:16>>) ->
{A, B, C, D, E, F, G, H};
address_to_ip(inet, <<A, B, C, D, _Rest/binary>>) ->
{A, B, C, D}.
ip_to_address(IP0) when size(IP0) == 4 ->
[{address_family, netlink_codec:family_to_int(inet)}, {address, ip_to_address2(IP0)}];
ip_to_address(IP0) when size(IP0) == 8 ->
[{address_family, netlink_codec:family_to_int(inet6)}, {address, ip_to_address2(IP0)}].
ip_to_address2({A, B, C, D, E, F, G, H}) ->
<<A:16, B:16, C:16, D:16, E:16, F:16, G:16, H:16>>;
ip_to_address2(IP0) ->
IP1 = tuple_to_list(IP0),
IP2 = binary:list_to_bin(IP1),
Padding = 8 * (16 - size(IP2)),
<<IP2/binary, 0:Padding/integer>>.
handle_add_netns(Netnslist, State = #state{netns = NetnsMap0}) ->
NetnsMap1 = lists:foldl(fun maybe_add_netns/2, maps:new(), Netnslist),
NetnsMap2 = maps:merge(NetnsMap0, NetnsMap1),
{maps:keys(NetnsMap1), State#state{netns = NetnsMap2}}.
handle_remove_netns(Netnslist, State = #state{netns = NetnsMap0}) ->
NetnsMap1 = lists:foldl(fun maybe_remove_netns/2, NetnsMap0, Netnslist),
RemovedNs = lists:subtract(maps:keys(NetnsMap0), maps:keys(NetnsMap1)),
{RemovedNs, State#state{netns = NetnsMap1}}.
maybe_add_netns(Netns = #netns{id = Id}, NetnsMap) ->
maybe_add_netns(maps:is_key(Id, NetnsMap), Netns, NetnsMap).
maybe_add_netns(true, _, NetnsMap) ->
NetnsMap;
maybe_add_netns(false, #netns{id = Id, ns = Namespace}, NetnsMap) ->
case gen_netlink_client:start_link(netns, binary_to_list(Namespace)) of
{ok, Pid} ->
maps:put(Id, Pid, NetnsMap);
{error, Reason} ->
?LOG_ERROR("Couldn't create route netlink client for ~p due to ~p", [Id, Reason]),
NetnsMap
end.
maybe_remove_netns(Netns = #netns{id = Id}, NetnsMap) ->
maybe_remove_netns(maps:is_key(Id, NetnsMap), Netns, NetnsMap).
maybe_remove_netns(true, #netns{id = Id}, NetnsMap) ->
Pid = maps:get(Id, NetnsMap),
erlang:unlink(Pid),
gen_netlink_client:stop(Pid),
maps:remove(Id, NetnsMap);
maybe_remove_netns(false, _, NetnsMap) ->
NetnsMap.
%%%===================================================================
%%% Metrics functions
%%%===================================================================
-spec(call(pid(), term()) -> term()).
call(Pid, Request) ->
prometheus_summary:observe_duration(
l4lb, ipvs_duration_seconds, [],
fun () -> gen_server:call(Pid, Request) end).
-spec(init_metrics() -> ok).
init_metrics() ->
prometheus_summary:new([
{registry, l4lb},
{name, ipvs_duration_seconds},
{help, "The time spent processing IPVS configuration."}]).
%%%===================================================================
%%% Test functions
%%%===================================================================
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
ip_to_address2_test() ->
IP = {16#fd01, 16#0, 16#0, 16#0, 16#0, 16#0, 16#0, 16#1},
IP0 = ip_to_address2(IP),
Expected = <<253, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1>>,
?assertEqual(Expected, IP0).
destination_address_test_() ->
D = [{address, <<10, 10, 0, 83, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0>>},
{port, 9042},
{fwd_method, 0},
{weight, 1},
{u_threshold, 0},
{l_threshold, 0},
{active_conns, 0},
{inact_conns, 0},
{persist_conns, 0},
{stats, [{conns, 0},
{inpkts, 0},
{outpkts, 0},
{inbytes, 0},
{outbytes, 0},
{cps, 0},
{inpps, 0},
{outpps, 0},
{inbps, 0},
{outbps, 0}]}],
DAddr = {{10, 10, 0, 83}, 9042},
AF = netlink_codec:family_to_int(inet),
[?_assertEqual(DAddr, destination_address(AF, D))].
service_address_tcp_test_() ->
service_address_(tcp).
service_address_udp_test_() ->
service_address_(udp).
service_address_(Protocol) ->
AF = netlink_codec:family_to_int(inet),
S = [{address_family, AF},
{protocol, proto_num(Protocol)},
{address, <<11, 197, 245, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0>>},
{port, 9042},
{sched_name, "wlc"},
{flags, 2, 4294967295},
{timeout, 0},
{netmask, 4294967295},
{stats, [{conns, 0},
{inpkts, 0},
{outpkts, 0},
{inbytes, 0},
{outbytes, 0},
{cps, 0},
{inpps, 0},
{outpps, 0},
{inbps, 0},
{outbps, 0}]}],
SAddr = {AF, {Protocol, {11, 197, 245, 133}, 9042}},
[?_assertEqual(SAddr, service_address(S))].
proto_num(tcp) -> 6;
proto_num(udp) -> 17.
-endif.
| null | https://raw.githubusercontent.com/dcos/dcos-net/7bd01ac237ff4b9a12a020ed443e71c45f7063f4/apps/dcos_l4lb/src/dcos_l4lb_ipvs_mgr.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
gen_server callbacks
mask for the fwd methods
local node
tunneling
direct routing
cache bypass
entry created by sync
hashed entry
no output packets
not established
must do output seq adjust
must do input seq adjust
in/out sequence mask
no client port set yet
template, not connection
persistent port */
hashed entry */
protocols to query gen_netlink for
===================================================================
API
===================================================================
@doc Starts the server
===================================================================
gen_server callbacks
===================================================================
===================================================================
===================================================================
===================================================================
Metrics functions
===================================================================
===================================================================
Test functions
=================================================================== | @author sdhillon
( C ) 2016 , < COMPANY >
Created : 01 . Nov 2016 7:35 AM
-module(dcos_l4lb_ipvs_mgr).
-author("sdhillon").
-behaviour(gen_server).
-export([start_link/0]).
-export([get_dests/3,
add_dest/8,
mod_dest/8,
remove_dest/7,
get_services/2,
add_service/5,
remove_service/5,
service_address/1,
destination_address/2,
add_netns/2,
remove_netns/2,
init_metrics/0]).
-export([init/1, handle_call/3,
handle_cast/2, handle_info/2]).
-define(SERVER, ?MODULE).
-record(state, {
netns :: map(),
family
}).
-type state() :: #state{}.
-include_lib("kernel/include/logger.hrl").
-include_lib("gen_netlink/include/netlink.hrl").
-include("dcos_l4lb.hrl").
masquerading / NAT
forward only one packet
one - packet scheduling * /
scheduler flag 1 * /
scheduler flag 2 * /
scheduler flag 3 * /
-define(ADDR_FAMILIES, [inet, inet6]).
-type service() :: term().
-type dest() :: term().
-export_type([service/0, dest/0]).
-type backend_weight() :: dcos_l4lb_mesos_poller:backend_weight().
-spec(get_services(Pid :: pid(), Namespace :: term()) -> [service()]).
get_services(Pid, Namespace) ->
call(Pid, {get_services, Namespace}).
-spec(add_service(Pid :: pid(), IP :: inet:ip_address(), Port :: inet:port_number(),
Protocol :: protocol(), Namespace :: term()) -> ok | error).
add_service(Pid, IP, Port, Protocol, Namespace) ->
call(Pid, {add_service, IP, Port, Protocol, Namespace}).
-spec(remove_service(Pid :: pid(), IP :: inet:ip_address(),
Port :: inet:port_number(),
Protocol :: protocol(), Namespace :: term()) -> ok | error).
remove_service(Pid, IP, Port, Protocol, Namespace) ->
call(Pid, {remove_service, IP, Port, Protocol, Namespace}).
-spec(get_dests(Pid :: pid(), Service :: service(), Namespace :: term()) -> [dest()]).
get_dests(Pid, Service, Namespace) ->
call(Pid, {get_dests, Service, Namespace}).
-spec(remove_dest(Pid :: pid(), ServiceIP :: inet:ip_address(),
ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term()) -> ok | error).
remove_dest(Pid, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace) ->
call(Pid, {remove_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace}).
-spec(add_dest(Pid :: pid(), ServiceIP :: inet:ip_address(), ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(),
Weight :: backend_weight()) -> ok | error).
add_dest(Pid, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight) ->
call(Pid, {add_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight}).
-spec(mod_dest(Pid :: pid(), ServiceIP :: inet:ip_address(), ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(),
Weight :: backend_weight()) -> ok | error).
mod_dest(Pid, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight) ->
gen_server:call(Pid, {mod_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight}).
add_netns(Pid, UpdateValue) ->
call(Pid, {add_netns, UpdateValue}).
remove_netns(Pid, UpdateValue) ->
call(Pid, {remove_netns, UpdateValue}).
-spec(start_link() ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link() ->
gen_server:start_link(?MODULE, [], []).
init([]) ->
{ok, Pid} = gen_netlink_client:start_link(),
{ok, Family} = gen_netlink_client:get_family(Pid, "IPVS"),
{ok, #state{netns = #{host => Pid}, family = Family}}.
handle_call({get_services, Namespace}, _From, State) ->
Reply = handle_get_services(Namespace, State),
{reply, Reply, State};
handle_call({add_service, IP, Port, Protocol, Namespace}, _From, State) ->
Reply = handle_add_service(IP, Port, Protocol, Namespace, State),
{reply, Reply, State};
handle_call({remove_service, IP, Port, Protocol, Namespace}, _From, State) ->
Reply = handle_remove_service(IP, Port, Protocol, Namespace, State),
{reply, Reply, State};
handle_call({get_dests, Service, Namespace}, _From, State) ->
Reply = handle_get_dests(Service, Namespace, State),
{reply, Reply, State};
handle_call({add_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight}, _From, State) ->
Reply = handle_add_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, State, Weight),
{reply, Reply, State};
handle_call({mod_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, Weight}, _From, State) ->
Reply = handle_mod_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, State, Weight),
{reply, Reply, State};
handle_call({remove_dest, ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace}, _From, State) ->
Reply = handle_remove_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, State),
{reply, Reply, State};
handle_call({add_netns, UpdateValue}, _From, State0) ->
{Reply, State1} = handle_add_netns(UpdateValue, State0),
{reply, Reply, State1};
handle_call({remove_netns, UpdateValue}, _From, State0) ->
{Reply, State1} = handle_remove_netns(UpdateValue, State0),
{reply, Reply, State1}.
handle_cast(_Request, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
Internal functions
-spec(service_address(service()) -> {family(), {protocol(), inet:ip_address(), inet:port_number()}}).
service_address(Service) ->
AF = proplists:get_value(address_family, Service),
Protocol = netlink_codec:protocol_to_atom(proplists:get_value(protocol, Service)),
AddressBin = proplists:get_value(address, Service),
Port = proplists:get_value(port, Service),
Family = netlink_codec:family_to_atom(AF),
InetAddr = address_to_ip(Family, AddressBin),
{AF, {Protocol, InetAddr, Port}}.
-spec(destination_address(family(), Destination :: dest()) -> {inet:ip_address(), inet:port_number()}).
destination_address(AF, Destination) ->
AddressBin = proplists:get_value(address, Destination),
Port = proplists:get_value(port, Destination),
Family = netlink_codec:family_to_atom(AF),
InetAddr = address_to_ip(Family, AddressBin),
{InetAddr, Port}.
-spec(handle_get_services(Namespace :: term(), State :: state()) -> [service()]).
handle_get_services(Namespace, State = #state{netns = NetnsMap}) ->
Pid = maps:get(Namespace, NetnsMap),
Params = [{AF, P} || AF <- ?ADDR_FAMILIES, P <- ?IPVS_PROTOCOLS],
lists:foldl(
fun({AddrFamily, Proto}, Acc) ->
Services = handle_get_services(AddrFamily, Proto, Pid, State),
Acc ++ Services
end, [], Params).
-spec(handle_get_services(AddressFamily :: family(), Protocol :: protocol(),
Namespace :: term(), State :: state()) -> [service()]).
handle_get_services(AddressFamily, Protocol, Pid, #state{family = Family}) ->
AddressFamily1 = netlink_codec:family_to_int(AddressFamily),
Protocol1 = netlink_codec:protocol_to_int(Protocol),
Message =
#get_service{
request =
[{service,
[{address_family, AddressFamily1},
{protocol, Protocol1}
]}
]},
{ok, Replies} = gen_netlink_client:request(Pid, Family, ipvs, [root, match], Message),
[proplists:get_value(service, MaybeService)
|| #netlink{msg = #new_service{request = MaybeService}}
<- Replies, proplists:is_defined(service, MaybeService)].
-spec(handle_remove_service(IP :: inet:ip_address(), Port :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(),
State :: state()) -> ok | error).
handle_remove_service(IP, Port, Protocol, Namespace, State) ->
Protocol1 = netlink_codec:protocol_to_int(Protocol),
Service = ip_to_address(IP) ++ [{port, Port}, {protocol, Protocol1}],
handle_remove_service(Service, Namespace, State).
-spec(handle_remove_service(Service :: service(), Namespace :: term(), State :: state()) -> ok | error).
handle_remove_service(Service, Namespace, #state{netns = NetnsMap, family = Family}) ->
?LOG_INFO("Namespace: ~p, Removing Service: ~p", [Namespace, Service]),
Pid = maps:get(Namespace, NetnsMap),
case gen_netlink_client:request(Pid, Family, ipvs, [], #del_service{request = [{service, Service}]}) of
{ok, _} -> ok;
_ -> error
end.
-spec(handle_add_service(IP :: inet:ip_address(), Port :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(), State :: state()) -> ok | error).
handle_add_service(IP, Port, Protocol, Namespace, #state{netns = NetnsMap, family = Family}) ->
Flags = 0,
Pid = maps:get(Namespace, NetnsMap),
Service0 = [
{protocol, netlink_codec:protocol_to_int(Protocol)},
{port, Port},
{sched_name, "wlc"},
{netmask, netmask_by_addrtype(IP)},
{flags, Flags, 16#ffffffff},
{timeout, 0}
],
Service1 = ip_to_address(IP) ++ Service0,
?LOG_INFO("Namespace: ~p, Adding Service: ~p", [Namespace, Service1]),
case gen_netlink_client:request(Pid, Family, ipvs, [], #new_service{request = [{service, Service1}]}) of
{ok, _} -> ok;
_ -> error
end.
-spec(handle_get_dests(Service :: service(), Namespace :: term(), State :: state()) -> [dest()]).
handle_get_dests(Service, Namespace, #state{netns = NetnsMap, family = Family}) ->
Pid = maps:get(Namespace, NetnsMap),
Message = #get_dest{request = [{service, Service}]},
{ok, Replies} = gen_netlink_client:request(Pid, Family, ipvs, [root, match], Message),
[proplists:get_value(dest, MaybeDest) || #netlink{msg = #new_dest{request = MaybeDest}} <- Replies,
proplists:is_defined(dest, MaybeDest)].
-spec(handle_mod_dest(ServiceIP :: inet:ip_address(), ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(), State :: state(),
Weight :: backend_weight()) -> ok | error).
handle_mod_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol,
Namespace, #state{netns = NetnsMap, family = Family}, Weight) ->
Pid = maps:get(Namespace, NetnsMap),
Protocol1 = netlink_codec:protocol_to_int(Protocol),
Service = ip_to_address(ServiceIP) ++ [{port, ServicePort}, {protocol, Protocol1}],
Base = [{fwd_method, ?IP_VS_CONN_F_MASQ}, {weight, Weight}, {u_threshold, 0}, {l_threshold, 0}],
Dest = [{port, DestPort}] ++ Base ++ ip_to_address(DestIP),
?LOG_INFO("Modifying backend ~p for service ~p~n", [{DestIP, DestPort, Weight}, Service]),
Msg = #set_dest{request = [{dest, Dest}, {service, Service}]},
case gen_netlink_client:request(Pid, Family, ipvs, [], Msg) of
{ok, _} -> ok;
_ -> error
end.
-spec(handle_add_dest(ServiceIP :: inet:ip_address(), ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(), State :: state(),
Weight :: backend_weight()) -> ok | error).
handle_add_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol,
Namespace, #state{netns = NetnsMap, family = Family}, Weight) ->
Pid = maps:get(Namespace, NetnsMap),
Protocol1 = netlink_codec:protocol_to_int(Protocol),
Service = ip_to_address(ServiceIP) ++ [{port, ServicePort}, {protocol, Protocol1}],
handle_add_dest(Pid, Service, DestIP, DestPort, Family, Weight).
handle_add_dest(Pid, Service, IP, Port, Family, Weight) ->
Base = [{fwd_method, ?IP_VS_CONN_F_MASQ}, {weight, Weight}, {u_threshold, 0}, {l_threshold, 0}],
Dest = [{port, Port}] ++ Base ++ ip_to_address(IP),
?LOG_INFO("Adding backend ~p to service ~p~n", [{IP, Port, Weight}, Service]),
Msg = #new_dest{request = [{dest, Dest}, {service, Service}]},
case gen_netlink_client:request(Pid, Family, ipvs, [], Msg) of
{ok, _} -> ok;
_ -> error
end.
-spec(handle_remove_dest(ServiceIP :: inet:ip_address(), ServicePort :: inet:port_number(),
DestIP :: inet:ip_address(), DestPort :: inet:port_number(),
Protocol :: protocol(), Namespace :: term(), State :: state()) -> ok | error).
handle_remove_dest(ServiceIP, ServicePort, DestIP, DestPort, Protocol, Namespace, State) ->
Protocol1 = netlink_codec:protocol_to_int(Protocol),
Service = ip_to_address(ServiceIP) ++ [{port, ServicePort}, {protocol, Protocol1}],
Dest = ip_to_address(DestIP) ++ [{port, DestPort}],
handle_remove_dest(Service, Dest, Namespace, State).
-spec(handle_remove_dest(Service :: service(), Dest :: dest(), Namespace :: term(), State :: state()) -> ok | error).
handle_remove_dest(Service, Dest, Namespace, #state{netns = NetnsMap, family = Family}) ->
?LOG_INFO("Removing Dest ~p to service ~p~n", [Dest, Service]),
Pid = maps:get(Namespace, NetnsMap),
Msg = #del_dest{request = [{dest, Dest}, {service, Service}]},
case gen_netlink_client:request(Pid, Family, ipvs, [], Msg) of
{ok, _} -> ok;
_ -> error
end.
netmask_by_addrtype(IP) when size(IP) == 4 ->
16#ffffffff;
netmask_by_addrtype(IP) when size(IP) == 8 ->
128.
address_to_ip(inet6, <<A:16, B:16, C:16, D:16, E:16, F:16, G:16, H:16>>) ->
{A, B, C, D, E, F, G, H};
address_to_ip(inet, <<A, B, C, D, _Rest/binary>>) ->
{A, B, C, D}.
ip_to_address(IP0) when size(IP0) == 4 ->
[{address_family, netlink_codec:family_to_int(inet)}, {address, ip_to_address2(IP0)}];
ip_to_address(IP0) when size(IP0) == 8 ->
[{address_family, netlink_codec:family_to_int(inet6)}, {address, ip_to_address2(IP0)}].
ip_to_address2({A, B, C, D, E, F, G, H}) ->
<<A:16, B:16, C:16, D:16, E:16, F:16, G:16, H:16>>;
ip_to_address2(IP0) ->
IP1 = tuple_to_list(IP0),
IP2 = binary:list_to_bin(IP1),
Padding = 8 * (16 - size(IP2)),
<<IP2/binary, 0:Padding/integer>>.
handle_add_netns(Netnslist, State = #state{netns = NetnsMap0}) ->
NetnsMap1 = lists:foldl(fun maybe_add_netns/2, maps:new(), Netnslist),
NetnsMap2 = maps:merge(NetnsMap0, NetnsMap1),
{maps:keys(NetnsMap1), State#state{netns = NetnsMap2}}.
handle_remove_netns(Netnslist, State = #state{netns = NetnsMap0}) ->
NetnsMap1 = lists:foldl(fun maybe_remove_netns/2, NetnsMap0, Netnslist),
RemovedNs = lists:subtract(maps:keys(NetnsMap0), maps:keys(NetnsMap1)),
{RemovedNs, State#state{netns = NetnsMap1}}.
maybe_add_netns(Netns = #netns{id = Id}, NetnsMap) ->
maybe_add_netns(maps:is_key(Id, NetnsMap), Netns, NetnsMap).
maybe_add_netns(true, _, NetnsMap) ->
NetnsMap;
maybe_add_netns(false, #netns{id = Id, ns = Namespace}, NetnsMap) ->
case gen_netlink_client:start_link(netns, binary_to_list(Namespace)) of
{ok, Pid} ->
maps:put(Id, Pid, NetnsMap);
{error, Reason} ->
?LOG_ERROR("Couldn't create route netlink client for ~p due to ~p", [Id, Reason]),
NetnsMap
end.
maybe_remove_netns(Netns = #netns{id = Id}, NetnsMap) ->
maybe_remove_netns(maps:is_key(Id, NetnsMap), Netns, NetnsMap).
maybe_remove_netns(true, #netns{id = Id}, NetnsMap) ->
Pid = maps:get(Id, NetnsMap),
erlang:unlink(Pid),
gen_netlink_client:stop(Pid),
maps:remove(Id, NetnsMap);
maybe_remove_netns(false, _, NetnsMap) ->
NetnsMap.
-spec(call(pid(), term()) -> term()).
call(Pid, Request) ->
prometheus_summary:observe_duration(
l4lb, ipvs_duration_seconds, [],
fun () -> gen_server:call(Pid, Request) end).
-spec(init_metrics() -> ok).
init_metrics() ->
prometheus_summary:new([
{registry, l4lb},
{name, ipvs_duration_seconds},
{help, "The time spent processing IPVS configuration."}]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
ip_to_address2_test() ->
IP = {16#fd01, 16#0, 16#0, 16#0, 16#0, 16#0, 16#0, 16#1},
IP0 = ip_to_address2(IP),
Expected = <<253, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1>>,
?assertEqual(Expected, IP0).
destination_address_test_() ->
D = [{address, <<10, 10, 0, 83, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0>>},
{port, 9042},
{fwd_method, 0},
{weight, 1},
{u_threshold, 0},
{l_threshold, 0},
{active_conns, 0},
{inact_conns, 0},
{persist_conns, 0},
{stats, [{conns, 0},
{inpkts, 0},
{outpkts, 0},
{inbytes, 0},
{outbytes, 0},
{cps, 0},
{inpps, 0},
{outpps, 0},
{inbps, 0},
{outbps, 0}]}],
DAddr = {{10, 10, 0, 83}, 9042},
AF = netlink_codec:family_to_int(inet),
[?_assertEqual(DAddr, destination_address(AF, D))].
service_address_tcp_test_() ->
service_address_(tcp).
service_address_udp_test_() ->
service_address_(udp).
service_address_(Protocol) ->
AF = netlink_codec:family_to_int(inet),
S = [{address_family, AF},
{protocol, proto_num(Protocol)},
{address, <<11, 197, 245, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0>>},
{port, 9042},
{sched_name, "wlc"},
{flags, 2, 4294967295},
{timeout, 0},
{netmask, 4294967295},
{stats, [{conns, 0},
{inpkts, 0},
{outpkts, 0},
{inbytes, 0},
{outbytes, 0},
{cps, 0},
{inpps, 0},
{outpps, 0},
{inbps, 0},
{outbps, 0}]}],
SAddr = {AF, {Protocol, {11, 197, 245, 133}, 9042}},
[?_assertEqual(SAddr, service_address(S))].
proto_num(tcp) -> 6;
proto_num(udp) -> 17.
-endif.
|
1e18a8258f04398ec6474bbb37d0b12737ac1526920db2a5899d05b00b73b9ed | agda/agda | Issue2728-3.hs | #!/usr/bin/env runhaskell
# LANGUAGE RecordWildCards #
import System.Directory
import RunAgda
file = "Issue2728-3.agda"
firstCode = unlines
[ "{-# OPTIONS --safe #-}"
, "module Issue2728-3 where"
, "foo = Set -- something to cache"
]
secondCode = firstCode ++ "postulate B : Set\n"
main :: IO ()
main = runAgda [ "--no-libraries"
, "--caching"
]
$ \(AgdaCommands { .. }) -> do
Discard the first prompt .
echoUntilPrompt
-- Create the file.
writeUTF8File file firstCode
Load the file , and wait for to complete .
loadAndEcho file
-- Edit the file.
writeUTF8File file secondCode
-- Reload.
loadAndEcho file
return ()
| null | https://raw.githubusercontent.com/agda/agda/f50c14d3a4e92ed695783e26dbe11ad1ad7b73f7/test/interaction/Issue2728-3.hs | haskell | Create the file.
Edit the file.
Reload. | #!/usr/bin/env runhaskell
# LANGUAGE RecordWildCards #
import System.Directory
import RunAgda
file = "Issue2728-3.agda"
firstCode = unlines
[ "{-# OPTIONS --safe #-}"
, "module Issue2728-3 where"
, "foo = Set -- something to cache"
]
secondCode = firstCode ++ "postulate B : Set\n"
main :: IO ()
main = runAgda [ "--no-libraries"
, "--caching"
]
$ \(AgdaCommands { .. }) -> do
Discard the first prompt .
echoUntilPrompt
writeUTF8File file firstCode
Load the file , and wait for to complete .
loadAndEcho file
writeUTF8File file secondCode
loadAndEcho file
return ()
|
d2dac7ec835423b88f4257c9076e81e3467bb1cf3f6be34879e802d13038a7ef | aaronc/ClojureClrEx | emit.clj | (ns clojure.clr.emit
(:import
[System.Reflection TypeAttributes PropertyAttributes MethodAttributes FieldAttributes EventAttributes CallingConventions MethodImplAttributes BindingFlags AssemblyName Assembly]
[System.Reflection.Emit TypeBuilder PropertyBuilder MethodBuilder ILGenerator AssemblyBuilder AssemblyBuilderAccess OpCodes EnumBuilder CustomAttributeBuilder]
[System.Runtime.InteropServices CallingConvention CharSet Marshal]
[clojure.lang Compiler]
[clojure.lang.CljCompiler.Ast GenContext]))
(def ^:private _save-id (atom 0))
(defn- enum-keys [enum-type keys]
(apply enum-or (map #(enum-val enum-type (name %)) keys)))
(defn- enum-key [enum-type key]
(enum-val enum-type (name key)))
(def ^:dynamic *gen-context* nil)
(let [ctxt-field (.GetField Compiler "CompilerContextVar" (enum-keys BindingFlags [:Static :NonPublic :Public]))]
(def cur-gen-context-var (.GetValue ctxt-field nil)))
(defn cur-gen-context []
(or *gen-context* @cur-gen-context-var Compiler/EvalContext))
(defn make-typed-array [type elems]
(let [n (count elems)
res (make-array type n)]
(doall (map-indexed #(aset res % %2) elems))
res))
(defn type-array [& elems]
(make-typed-array Type elems))
(defn obj-array [& elems]
(make-typed-array Object elems))
(comment (defn wrap-gen-context [gen-func]
(let [ctxt (GenContext/CreateWithInternalAssembly (str "__data__gen__" (swap! _save-id inc)) false)]
(gen-func ctxt))))
(defn clr-assembly* [name access]
(AssemblyBuilder/DefineDynamicAssembly
(AssemblyName. name)
(enum-key AssemblyBuilderAccess access)))
(defn clr-module*
([^AssemblyBuilder asm
]))
(defn clr-type*
([^GenContext gen-ctxt name attrs parent ifaces]
(.DefineType (.ModuleBuilder gen-ctxt)
name (enum-keys TypeAttributes attrs)
parent (make-typed-array Type ifaces)))
([^GenContext gen-ctxt name]
(clr-type* gen-ctxt name [:Public] nil nil)))
(defn clr-constructor*
[^TypeBuilder tb attrs calling-convs param-types]
(.DefineConstructor tb (enum-keys MethodAttributes attrs)
(enum-keys CallingConventions calling-convs)
(make-typed-array Type param-types)))
(defn clr-field*
[^TypeBuilder tb name type attrs]
(.DefineField tb name type (enum-keys FieldAttributes attrs)))
(defn clr-property*
([^TypeBuilder tb name type attrs param-types]
(.DefineProperty tb name (enum-keys PropertyAttributes attrs) type param-types))
([^TypeBuilder tb name type]
(clr-property* tb name type :None nil)))
(def ^:private get-set-attrs [:Public :SpecialName :HideBySig])
(def ^:dynamic *type-builder* nil)
(def ^:dynamic *property-builder* nil)
(def ^:dynamic *ilgen* nil)
(def ^:dynamic *method-builder* nil)
(defn clr-method*
([^TypeBuilder tb name attrs ret-type param-types]
(.DefineMethod tb name (enum-keys MethodAttributes attrs)
ret-type (make-typed-array Type param-types))))
(defn clr-getter*
[^TypeBuilder tb ^PropertyBuilder prop]
(clr-method* tb (str "get_" (.Name prop))
get-set-attrs (.PropertyType prop) nil))
(defn clr-setter*
[^TypeBuilder tb ^PropertyBuilder prop]
(clr-method* tb (str "set_" (.Name prop))
get-set-attrs nil [(.PropertyType prop)]))
(defn clr-event*
([^TypeBuilder tb name attrs type]
(.DefineEvent tb name (enum-keys EventAttributes attrs) type)))
(defn clr-pinvoke*
([^TypeBuilder tb name dll-name attrs calling-convs ret-type param-types native-call-conv native-char-set]
(let [^MethodBuilder mb (.DefinePInvokeMethod tb name dll-name
(enum-keys MethodAttributes attrs)
(enum-keys CallingConventions calling-convs)
ret-type
(make-typed-array Type param-types)
(enum-key CallingConvention native-call-conv)
(enum-key CharSet native-char-set))]
(.SetImplementationFlags mb (enum-or (.GetMethodImplementationFlags mb) MethodImplAttributes/PreserveSig))
mb))
([^TypeBuilder tb name dll-name attrs ret-type param-types]
(clr-pinvoke* tb name dll-name attrs [:Standard] ret-type param-types :Winapi :Ansi))
([^TypeBuilder tb name dll-name ret-type param-types]
(clr-pinvoke* tb name dll-name [:Public :Static :PinvokeImpl] ret-type param-types)))
(defn- set-dg-impl-flags [mb]
(.SetImplementationFlags mb (enum-keys MethodImplAttributes [:Runtime :Managed])))
(defn clr-delegate* [ret params]
(let [gen-ctxt (cur-gen-context)
tb (clr-type* gen-ctxt (str "gendg__" (swap! _save-id inc))
[:Class :Public :Sealed :AnsiClass :AutoClass]
System.MulticastDelegate nil)
cb (clr-constructor* tb [:RTSpecialName :HideBySig :Public] [:Standard] [Object IntPtr])
mb (clr-method* tb "Invoke" [:Public :HideBySig :NewSlot :Virtual] ret params)]
(set-dg-impl-flags cb)
(set-dg-impl-flags mb)
(.CreateType tb)))
(defn clr-enum*
([gen-ctxt name attrs ^Type underlying-type flags? literals]
(let [^EnumBuilder enum-builder (.DefineEnum (.ModuleBuilder gen-ctxt)
name
(enum-keys TypeAttributes attrs)
underlying-type)]
(when flags?
(.SetCustomAttribute enum-builder
(CustomAttributeBuilder.
(.GetConstructor FlagsAttribute
Type/EmptyTypes)
(obj-array))))
(doseq [[name value] literals]
(.DefineLiteral (name name) value))
(.CreateType enum-builder))))
(defn- get-opcode [opcode]
(.GetValue (.GetField OpCodes (name opcode)) nil))
(defn op
([opcode]
(.Emit *ilgen* (get-opcode opcode)))
([opcode arg]
(.Emit *ilgen* (get-opcode opcode) arg)))
(defmacro get-member [])
(defmacro get-local [])
(defn method*
[name metadata params body-func])
(defmacro method [])
(defmacro property [])
( defmacro event )
(defn defclrtype* [name metadata body-fn])
(defmacro defclrtype [name & body]
`(defclrtype* ~(name name) ~(meta name)
(fn ~(symbol (str (name name) "-body-fn"))
~@body)))
| null | https://raw.githubusercontent.com/aaronc/ClojureClrEx/465e05b5872816056544c89b47c1997f6067ae89/src/clojure/clr/emit.clj | clojure | (ns clojure.clr.emit
(:import
[System.Reflection TypeAttributes PropertyAttributes MethodAttributes FieldAttributes EventAttributes CallingConventions MethodImplAttributes BindingFlags AssemblyName Assembly]
[System.Reflection.Emit TypeBuilder PropertyBuilder MethodBuilder ILGenerator AssemblyBuilder AssemblyBuilderAccess OpCodes EnumBuilder CustomAttributeBuilder]
[System.Runtime.InteropServices CallingConvention CharSet Marshal]
[clojure.lang Compiler]
[clojure.lang.CljCompiler.Ast GenContext]))
(def ^:private _save-id (atom 0))
(defn- enum-keys [enum-type keys]
(apply enum-or (map #(enum-val enum-type (name %)) keys)))
(defn- enum-key [enum-type key]
(enum-val enum-type (name key)))
(def ^:dynamic *gen-context* nil)
(let [ctxt-field (.GetField Compiler "CompilerContextVar" (enum-keys BindingFlags [:Static :NonPublic :Public]))]
(def cur-gen-context-var (.GetValue ctxt-field nil)))
(defn cur-gen-context []
(or *gen-context* @cur-gen-context-var Compiler/EvalContext))
(defn make-typed-array [type elems]
(let [n (count elems)
res (make-array type n)]
(doall (map-indexed #(aset res % %2) elems))
res))
(defn type-array [& elems]
(make-typed-array Type elems))
(defn obj-array [& elems]
(make-typed-array Object elems))
(comment (defn wrap-gen-context [gen-func]
(let [ctxt (GenContext/CreateWithInternalAssembly (str "__data__gen__" (swap! _save-id inc)) false)]
(gen-func ctxt))))
(defn clr-assembly* [name access]
(AssemblyBuilder/DefineDynamicAssembly
(AssemblyName. name)
(enum-key AssemblyBuilderAccess access)))
(defn clr-module*
([^AssemblyBuilder asm
]))
(defn clr-type*
([^GenContext gen-ctxt name attrs parent ifaces]
(.DefineType (.ModuleBuilder gen-ctxt)
name (enum-keys TypeAttributes attrs)
parent (make-typed-array Type ifaces)))
([^GenContext gen-ctxt name]
(clr-type* gen-ctxt name [:Public] nil nil)))
(defn clr-constructor*
[^TypeBuilder tb attrs calling-convs param-types]
(.DefineConstructor tb (enum-keys MethodAttributes attrs)
(enum-keys CallingConventions calling-convs)
(make-typed-array Type param-types)))
(defn clr-field*
[^TypeBuilder tb name type attrs]
(.DefineField tb name type (enum-keys FieldAttributes attrs)))
(defn clr-property*
([^TypeBuilder tb name type attrs param-types]
(.DefineProperty tb name (enum-keys PropertyAttributes attrs) type param-types))
([^TypeBuilder tb name type]
(clr-property* tb name type :None nil)))
(def ^:private get-set-attrs [:Public :SpecialName :HideBySig])
(def ^:dynamic *type-builder* nil)
(def ^:dynamic *property-builder* nil)
(def ^:dynamic *ilgen* nil)
(def ^:dynamic *method-builder* nil)
(defn clr-method*
([^TypeBuilder tb name attrs ret-type param-types]
(.DefineMethod tb name (enum-keys MethodAttributes attrs)
ret-type (make-typed-array Type param-types))))
(defn clr-getter*
[^TypeBuilder tb ^PropertyBuilder prop]
(clr-method* tb (str "get_" (.Name prop))
get-set-attrs (.PropertyType prop) nil))
(defn clr-setter*
[^TypeBuilder tb ^PropertyBuilder prop]
(clr-method* tb (str "set_" (.Name prop))
get-set-attrs nil [(.PropertyType prop)]))
(defn clr-event*
([^TypeBuilder tb name attrs type]
(.DefineEvent tb name (enum-keys EventAttributes attrs) type)))
(defn clr-pinvoke*
([^TypeBuilder tb name dll-name attrs calling-convs ret-type param-types native-call-conv native-char-set]
(let [^MethodBuilder mb (.DefinePInvokeMethod tb name dll-name
(enum-keys MethodAttributes attrs)
(enum-keys CallingConventions calling-convs)
ret-type
(make-typed-array Type param-types)
(enum-key CallingConvention native-call-conv)
(enum-key CharSet native-char-set))]
(.SetImplementationFlags mb (enum-or (.GetMethodImplementationFlags mb) MethodImplAttributes/PreserveSig))
mb))
([^TypeBuilder tb name dll-name attrs ret-type param-types]
(clr-pinvoke* tb name dll-name attrs [:Standard] ret-type param-types :Winapi :Ansi))
([^TypeBuilder tb name dll-name ret-type param-types]
(clr-pinvoke* tb name dll-name [:Public :Static :PinvokeImpl] ret-type param-types)))
(defn- set-dg-impl-flags [mb]
(.SetImplementationFlags mb (enum-keys MethodImplAttributes [:Runtime :Managed])))
(defn clr-delegate* [ret params]
(let [gen-ctxt (cur-gen-context)
tb (clr-type* gen-ctxt (str "gendg__" (swap! _save-id inc))
[:Class :Public :Sealed :AnsiClass :AutoClass]
System.MulticastDelegate nil)
cb (clr-constructor* tb [:RTSpecialName :HideBySig :Public] [:Standard] [Object IntPtr])
mb (clr-method* tb "Invoke" [:Public :HideBySig :NewSlot :Virtual] ret params)]
(set-dg-impl-flags cb)
(set-dg-impl-flags mb)
(.CreateType tb)))
(defn clr-enum*
([gen-ctxt name attrs ^Type underlying-type flags? literals]
(let [^EnumBuilder enum-builder (.DefineEnum (.ModuleBuilder gen-ctxt)
name
(enum-keys TypeAttributes attrs)
underlying-type)]
(when flags?
(.SetCustomAttribute enum-builder
(CustomAttributeBuilder.
(.GetConstructor FlagsAttribute
Type/EmptyTypes)
(obj-array))))
(doseq [[name value] literals]
(.DefineLiteral (name name) value))
(.CreateType enum-builder))))
(defn- get-opcode [opcode]
(.GetValue (.GetField OpCodes (name opcode)) nil))
(defn op
([opcode]
(.Emit *ilgen* (get-opcode opcode)))
([opcode arg]
(.Emit *ilgen* (get-opcode opcode) arg)))
(defmacro get-member [])
(defmacro get-local [])
(defn method*
[name metadata params body-func])
(defmacro method [])
(defmacro property [])
( defmacro event )
(defn defclrtype* [name metadata body-fn])
(defmacro defclrtype [name & body]
`(defclrtype* ~(name name) ~(meta name)
(fn ~(symbol (str (name name) "-body-fn"))
~@body)))
| |
9253afb017de41bfe78783f9808221325ef28c9c7717372d96ae1da17daadc70 | aarkerio/ZentaurLMS | test_views.cljs | (ns zentaur.reframe.tests.test-views
(:require [goog.dom :as gdom]
[reagent.core :as r]
[re-frame.core :as rf]
[zentaur.reframe.libs.commons :as cms]))
(defn edit-question [{:keys [id question hint explanation qtype points]}]
(let [aquestion (r/atom question)
ahint (r/atom hint)
aexplanation (r/atom explanation)
aqtype (r/atom qtype)
apoints (r/atom points)
uurlid @(rf/subscribe [:test-uurlid])]
(fn []
[:div.edit_question
[:div "Question: " [:br]
[:input {:type "text"
:value @aquestion
:maxLength 180
:size 100
:on-change #(reset! aquestion (-> % .-target .-value))}]]
[:div "Hint: " [:br]
[:input {:type "text"
:value @ahint
:maxLength 180
:size 100
:on-change #(reset! ahint (-> % .-target .-value))}]]
[:div "Explanation: " [:br]
[:input {:type "text"
:value @aexplanation
:maxLength 180
:size 100
:on-change #(reset! aexplanation (-> % .-target .-value))}]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "points"
:value @apoints
:title "Points"
:on-change #(reset! apoints (-> % .-target .-value))}
(for [pvalue (range 1 6)]
^{:key pvalue} [:option {:value pvalue} pvalue])]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "qtype"
:value @aqtype
:title "Type of question"
:on-change #(reset! aqtype (-> % .-target .-value))}
[:option {:value "1"} "Multiple"]
[:option {:value "2"} "Open"]
[:option {:value "3"} "Fullfill"]
[: option { : value " 4 " } " Columns " ]
]]
[:div [:input.btn {:type "button" :class "btn btn btn-outline-primary-green" :value "Speichern"
:on-click #(rf/dispatch [:update-question {:id id
:question @aquestion
:hint @ahint
:points @apoints
:qtype @aqtype
:explanation @aexplanation
:uurlid uurlid}])}]]])))
(defn answer-editing-input [{:keys [answer correct id]}]
(let [aanswer (r/atom answer)
acorrect (r/atom correct)]
(fn []
[:div.edit_question
[:div "Answer: " [:br]
[:input {:type "text"
:value @aanswer
:maxLength 180
:size 100
:on-change #(reset! aanswer (-> % .-target .-value))}]]
[:input {:type "checkbox"
:title "richtig?"
:checked @acorrect
:on-change #(swap! acorrect not)}]
[:div [:input.btn {:type "button" :class "btn btn btn-outline-primary-green" :value "Speichern"
:on-click #(rf/dispatch [:update-answer {:answer @aanswer
:correct @acorrect
:answer_id id}])}]]])))
(defn display-answer [{:keys [id answer correct ordnen acounter question_id key idx] :as answer-record}]
(let [answer-class (if-not correct "all-width-red" "all-width-green")
answer-text (if-not correct "answer-text-red" "answer-text-green")
editing-answer (r/atom false)]
(fn []
[:div {:class answer-class}
(when (> idx 1)
[:img.img-float-right {:title "Antwort an up senden"
:alt "Antwort an up senden"
:src "/img/icon_blue_up.png"
:on-click #(rf/dispatch [:reorder-answer {:ordnen ordnen :question-id question_id :direction "up"}])}])
(when (< idx acounter)
[:img.img-float-right {:title "Senden Sie nach unten"
:alt "Senden Sie nach unten"
:src "/img/icon_blue_down.png"
:on-click #(rf/dispatch [:reorder-answer {:ordnen ordnen :question-id question_id :direction "down"}])}])
[:img.img-float-right {:title "Antwort löschen"
:alt "Antwort löschen"
:src "/img/icon_delete.png"
:on-click #(rf/dispatch [:delete-answer {:answer-id id :question-id question_id}])}]
(if @editing-answer
[:div
[:img.img-float-right {:title "Antwort abbrechen"
:alt "Antwort abbrechen"
:src "/img/icon_cancel.png"
:on-click #(swap! editing-answer not)}]
[answer-editing-input answer-record]]
[:div
[:img.img-float-right {:title "Antwort bearbeiten"
:alt "Antwort bearbeiten"
:src "/img/icon_edit.png"
:on-click #(swap! editing-answer not)}]
[:div [:span {:class answer-text} (str key ".- ("correct")")] " " answer ]])])))
(defn input-new-answer
"Note: this is one-way bound to the global atom, it doesn't subscribe to it"
[{:keys [question-id on-stop props]}]
(let [inner (r/atom "")
checked (r/atom false)]
(fn []
[:div.div-new-answer
[:input (merge props
{:type "text"
:maxLength 180
:size 80
:value @inner
:on-change #(reset! inner (-> % .-target .-value))
:on-key-down #(case (.-which %)
27 (on-stop) ; esc
nil)})]
[:input.btn {:type "checkbox" :title "Richtig?" :aria-label "Richting?"
:checked @checked :on-change #(swap! checked not)}]
[:input.btn {:type "button" :class "btn btn btn-outline-primary-green" :value "Antwort hinzufügen"
:on-click #(do (rf/dispatch [:create-answer {:question-id question-id
:correct @checked
:answer @inner}])
(reset! checked false)
(reset! inner ""))}]])))
(defn fulfill-question-form
[question]
(let [afulfill (r/atom (:fulfill question))
id (:id question)
ats (fnil cms/asterisks-to-spaces "")]
(fn []
[:div
[:div.div-separator "Preview:" [:br] (ats @afulfill)]
[:div.div-separator
[:textarea {:value @afulfill :on-change #(reset! afulfill (-> % .-target .-value))
:placeholder "Text and asterisks" :title "Text and asterisks" :cols 120 :rows 10}]]
[:input.btn {:type "button" :class "btn btn btn-outline-primary-green" :value "Speichern"
:on-click #(rf/dispatch [:update-fulfill {:id id
:fulfill @afulfill}])}]])))
Polimorphysm to the kind of question
(defmulti display-question (fn [question] (:qtype question)))
1 : multi 2 : open , 3 : fullfill , 4 : composite questions ( columns )
(defmethod display-question 1
[{:keys [question explanation hint key qtype id ordnen] :as q}]
(let [counter (r/atom 0)
idx-answers (map-indexed (fn [idx answer] (assoc (second answer) :idx (inc idx))) (:answers q))
acounter (count idx-answers)]
(fn [{:keys [question explanation hint qtype id ordnen] :as q}]
[:div.question-items-divs
[input-new-answer {:question-id id :on-stop #(js/console.log "stop") :props {:placeholder "Neue antwort"}}]
(when-not (nil? idx-answers)
(for [answer idx-answers]
[display-answer (assoc answer :acounter acounter :key (swap! counter inc))]))])))
(defmethod display-question 2
[question]
[:div.div-separator "(Dies ist eine offene Frage)"])
(defmethod display-question 3
[question]
[fulfill-question-form question])
(defmethod display-question 4
[question]
[:p "Question columns"])
(defn question-item
"Display any type of question"
[{:keys [question explanation hint qtype id ordnen points counter uurlid qcount] :as q}]
(let [editing-question (r/atom false)]
(.log js/console (str ">>> VALUE qcounter >>>>> " qcount " >>>> counter >>> " counter " >>>> uurlid >>>> " uurlid " >>>> " q " >>>> " question))
(fn []
Flex container
[:div.question-items-divs
(when (> counter 1)
[:img.img-float-right {:title "Frage nachbestellen"
:alt "Frage nachbestellen"
:src "/img/icon_up_green.png"
:on-click #(rf/dispatch [:reorder-question {:uurlid uurlid :ordnen ordnen :direction "up"}])}])
(when (< counter qcount)
[:img.img-float-right {:title "Senden Sie nach unten"
:alt "Senden Sie nach unten"
:src "/img/icon_down_green.png"
:on-click #(rf/dispatch [:reorder-question {:uurlid uurlid :ordnen ordnen :direction "down"}])}])
(if @editing-question
[:img.img-float-right {:title "Frage abbrechen"
:alt "Frage abbrechen"
:src "/img/icon_cancel.png"
:on-click #(swap! editing-question not)}]
[:img.img-float-right {:title "Frage bearbeiten"
:alt "Frage bearbeiten"
:src "/img/icon_edit.png"
:on-click #(swap! editing-question not)}])] ;; editing ends
[:div.question-items-divs
[:div [:span.bold-font (str counter ".- Frage: ")] question " >>>>ordnen:>>>" ordnen " question id:" id]
[:div [:span.bold-font "Hint: "] hint]
[:div [:span.bold-font "Points: "] points]
[:div [:span.bold-font "Erläuterung: "] explanation]]
(when @editing-question
[edit-question q])
Polimorphysm for the kind of question
[:div.question-items-divs
[:img {:src "/img/icon_delete.png"
:title "Frage löschen"
:alt "Frage löschen"
:on-click #(rf/dispatch [:delete-question id])}]]])))
(defn display-questions-list
[uurlid question-count]
(let [questions (rf/subscribe [:questions])]
(fn [uurlid question-count]
[:div
(for [{:keys [idx question]} (cms/indexado @questions)]
^{:key (hash question)}
[question-item (assoc question :counter idx :uurlid uurlid :qcount question-count)])])))
(defn test-editor-form [test title description tags subject-id level-id]
[:div {:id "test-whole-display"}
[:div.edit-icon-div
(if @(rf/subscribe [:toggle-testform])
[:img.img-float-right {:title "Bearbeiten test abbrechen" :alt "Bearbeiten test abbrechen" :src "/img/icon_cancel.png"
:on-click #(rf/dispatch [:toggle-testform]) }]
[:img.img-float-right {:title "Test bearbeiten" :alt "Test bearbeiten" :src "/img/icon_edit_test.png"
:on-click #(rf/dispatch [:toggle-testform])}])]
[:div {:id "hidden-form" :class (if @(rf/subscribe [:toggle-testform]) "visible-div" "hidden-div")}
[:h3.class "Bearbeit test"]
[:div.div-separator
[:label {:class "tiny-label"} "Title"]
[:input {:type "text" :value @title :placeholder "Title" :title "Title" :maxLength 100
:on-change #(reset! title (-> % .-target .-value)) :size 100}]]
[:div.div-separator
[:label {:class "tiny-label"} "Description"]
[:input {:type "text" :value @description :on-change #(reset! description (-> % .-target .-value))
:placeholder "Erklärung" :title "Erklärung" :maxLength 180 :size 100}]]
[:div.div-separator
[:label {:class "tiny-label"} "Tags"]
[:input {:type "text" :value @tags :on-change #(reset! tags (-> % .-target .-value))
:placeholder "Tags" :title "Tags" :maxLength 100 :size 100}]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "subject-id"
:value @subject-id
:on-change #(reset! subject-id (-> % .-target .-value))}
(for [row-subject @(rf/subscribe [:subjects])]
^{:key (:id row-subject)} [:option {:value (:id row-subject)} (:subject row-subject)])
]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "level-id"
:value @level-id
:on-change #(reset! level-id (-> % .-target .-value))}
(for [row-level @(rf/subscribe [:levels])]
^{:key (:id row-level)} [:option {:value (:id row-level)} (:level row-level)])
]]
[:div
[:input {:class "btn btn-outline-primary-green" :type "button" :value "Speichern"
:on-click #(rf/dispatch [:update-test {:title @title
:description @description
:tags @tags
:level_id @level-id
:subject_id @subject-id
:uurlid (:uurlid test)}])}]]]
[:div
[:h1 @title]
[:div.div-simple-separator [:span {:class "bold-font"} "Tags: "] @tags [:span {:class "bold-font"} " Created:"] (:created_at test)]
[:div.div-simple-separator [:span {:class "bold-font"} "Description: "] @description [:span {:class "bold-font"} " Subject: "] (:subject test)
[:span {:class "bold-font"} " Level: "] (:level test) ]]])
(defn test-editor-view
[]
(let [test (rf/subscribe [:test])
title (r/atom nil)
subject-id (r/atom nil)
level-id (r/atom nil)
description (r/atom nil)
tags (r/atom nil)]
(fn []
(reset! title (:title @test))
(reset! subject-id (:subject_id @test))
(reset! level-id (:level_id @test))
(reset! description (:description @test))
(reset! tags (:tags @test))
[:div
[test-editor-form @test title description tags subject-id level-id]
[:img {:src "/img/icon_add_question.png" :alt "Fragen hinzüfugen" :title "Fragen hinzüfugen"
:on-click #(rf/dispatch [:toggle-qform])}]])))
(defn create-question-form
"Verstecken Form for a neue fragen"
[]
(let [qform (rf/subscribe [:qform])
uurlid (rf/subscribe [:test-uurlid])
user-id (rf/subscribe [:test-user-id])
new-question (r/atom "")
hint (r/atom "")
explanation (r/atom "")
qtype (r/atom "1")
points (r/atom "1")]
(fn []
[:div {:id "hidden-form" :class (if @qform "visible-div" "hidden-div")}
[:h3.class "Hinzifugen neue fragen"]
[:div.div-separator
[:input {:type "text" :value @new-question
:placeholder "Neue Frage"
:title "Neue Frage"
:maxLength 180
:on-change #(reset! new-question (-> % .-target .-value))
:size 100}]]
[:div.div-separator
[:input {:type "text"
:value @hint
:on-change #(reset! hint (-> % .-target .-value))
:placeholder "Frage Hinweis"
:title "Frage Hinweis"
:maxLength 180
:size 100}]]
[:div.div-separator
[:input {:type "text"
:value @explanation
:on-change #(reset! explanation (-> % .-target .-value))
:placeholder "Frage erklärung"
:title "Frage erklärung"
:maxLength 180
:size 100}]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "points"
:value @points
:on-change #(reset! points (-> % .-target .-value))}
(for [pvalue (range 1 6)]
^{:key pvalue} [:option {:value pvalue} pvalue])]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "qtype"
:value @qtype
:on-change #(reset! qtype (-> % .-target .-value))}
[:option {:value "1"} "Multiple"]
[:option {:value "2"} "Open"]
[:option {:value "3"} "Fullfill"]
[: option { : value " 4 " } " Columns " ]
]]
[:div
[:input.btn {:class "btn btn-outline-primary-green" :type "button" :value "Neue Frage speichern"
:on-click #(do (rf/dispatch [:create-question {:question @new-question
:hint @hint
:qtype @qtype
:points @points
:explanation @explanation
:uurlid @uurlid
:user-id @user-id}])
(reset! new-question "")
(reset! hint "")
(reset! explanation ""))}]]])))
(defn test-app
[]
(let [question-count (rf/subscribe [:question-count])
uurlid (rf/subscribe [:test-uurlid])]
[:div {:id "page-container"}
[test-editor-view]
[create-question-form]
[display-questions-list @uurlid @question-count]
[:div {:class "footer"}
[:p "Ziehen Sie die Fragen per Drag & Drop in eine andere Reihenfolge."]]]))
| null | https://raw.githubusercontent.com/aarkerio/ZentaurLMS/adb43fb879b88d6a35f7f556cb225f7930d524f9/src/cljs/zentaur/reframe/tests/test_views.cljs | clojure | esc
editing ends | (ns zentaur.reframe.tests.test-views
(:require [goog.dom :as gdom]
[reagent.core :as r]
[re-frame.core :as rf]
[zentaur.reframe.libs.commons :as cms]))
(defn edit-question [{:keys [id question hint explanation qtype points]}]
(let [aquestion (r/atom question)
ahint (r/atom hint)
aexplanation (r/atom explanation)
aqtype (r/atom qtype)
apoints (r/atom points)
uurlid @(rf/subscribe [:test-uurlid])]
(fn []
[:div.edit_question
[:div "Question: " [:br]
[:input {:type "text"
:value @aquestion
:maxLength 180
:size 100
:on-change #(reset! aquestion (-> % .-target .-value))}]]
[:div "Hint: " [:br]
[:input {:type "text"
:value @ahint
:maxLength 180
:size 100
:on-change #(reset! ahint (-> % .-target .-value))}]]
[:div "Explanation: " [:br]
[:input {:type "text"
:value @aexplanation
:maxLength 180
:size 100
:on-change #(reset! aexplanation (-> % .-target .-value))}]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "points"
:value @apoints
:title "Points"
:on-change #(reset! apoints (-> % .-target .-value))}
(for [pvalue (range 1 6)]
^{:key pvalue} [:option {:value pvalue} pvalue])]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "qtype"
:value @aqtype
:title "Type of question"
:on-change #(reset! aqtype (-> % .-target .-value))}
[:option {:value "1"} "Multiple"]
[:option {:value "2"} "Open"]
[:option {:value "3"} "Fullfill"]
[: option { : value " 4 " } " Columns " ]
]]
[:div [:input.btn {:type "button" :class "btn btn btn-outline-primary-green" :value "Speichern"
:on-click #(rf/dispatch [:update-question {:id id
:question @aquestion
:hint @ahint
:points @apoints
:qtype @aqtype
:explanation @aexplanation
:uurlid uurlid}])}]]])))
(defn answer-editing-input [{:keys [answer correct id]}]
(let [aanswer (r/atom answer)
acorrect (r/atom correct)]
(fn []
[:div.edit_question
[:div "Answer: " [:br]
[:input {:type "text"
:value @aanswer
:maxLength 180
:size 100
:on-change #(reset! aanswer (-> % .-target .-value))}]]
[:input {:type "checkbox"
:title "richtig?"
:checked @acorrect
:on-change #(swap! acorrect not)}]
[:div [:input.btn {:type "button" :class "btn btn btn-outline-primary-green" :value "Speichern"
:on-click #(rf/dispatch [:update-answer {:answer @aanswer
:correct @acorrect
:answer_id id}])}]]])))
(defn display-answer [{:keys [id answer correct ordnen acounter question_id key idx] :as answer-record}]
(let [answer-class (if-not correct "all-width-red" "all-width-green")
answer-text (if-not correct "answer-text-red" "answer-text-green")
editing-answer (r/atom false)]
(fn []
[:div {:class answer-class}
(when (> idx 1)
[:img.img-float-right {:title "Antwort an up senden"
:alt "Antwort an up senden"
:src "/img/icon_blue_up.png"
:on-click #(rf/dispatch [:reorder-answer {:ordnen ordnen :question-id question_id :direction "up"}])}])
(when (< idx acounter)
[:img.img-float-right {:title "Senden Sie nach unten"
:alt "Senden Sie nach unten"
:src "/img/icon_blue_down.png"
:on-click #(rf/dispatch [:reorder-answer {:ordnen ordnen :question-id question_id :direction "down"}])}])
[:img.img-float-right {:title "Antwort löschen"
:alt "Antwort löschen"
:src "/img/icon_delete.png"
:on-click #(rf/dispatch [:delete-answer {:answer-id id :question-id question_id}])}]
(if @editing-answer
[:div
[:img.img-float-right {:title "Antwort abbrechen"
:alt "Antwort abbrechen"
:src "/img/icon_cancel.png"
:on-click #(swap! editing-answer not)}]
[answer-editing-input answer-record]]
[:div
[:img.img-float-right {:title "Antwort bearbeiten"
:alt "Antwort bearbeiten"
:src "/img/icon_edit.png"
:on-click #(swap! editing-answer not)}]
[:div [:span {:class answer-text} (str key ".- ("correct")")] " " answer ]])])))
(defn input-new-answer
"Note: this is one-way bound to the global atom, it doesn't subscribe to it"
[{:keys [question-id on-stop props]}]
(let [inner (r/atom "")
checked (r/atom false)]
(fn []
[:div.div-new-answer
[:input (merge props
{:type "text"
:maxLength 180
:size 80
:value @inner
:on-change #(reset! inner (-> % .-target .-value))
:on-key-down #(case (.-which %)
nil)})]
[:input.btn {:type "checkbox" :title "Richtig?" :aria-label "Richting?"
:checked @checked :on-change #(swap! checked not)}]
[:input.btn {:type "button" :class "btn btn btn-outline-primary-green" :value "Antwort hinzufügen"
:on-click #(do (rf/dispatch [:create-answer {:question-id question-id
:correct @checked
:answer @inner}])
(reset! checked false)
(reset! inner ""))}]])))
(defn fulfill-question-form
[question]
(let [afulfill (r/atom (:fulfill question))
id (:id question)
ats (fnil cms/asterisks-to-spaces "")]
(fn []
[:div
[:div.div-separator "Preview:" [:br] (ats @afulfill)]
[:div.div-separator
[:textarea {:value @afulfill :on-change #(reset! afulfill (-> % .-target .-value))
:placeholder "Text and asterisks" :title "Text and asterisks" :cols 120 :rows 10}]]
[:input.btn {:type "button" :class "btn btn btn-outline-primary-green" :value "Speichern"
:on-click #(rf/dispatch [:update-fulfill {:id id
:fulfill @afulfill}])}]])))
Polimorphysm to the kind of question
(defmulti display-question (fn [question] (:qtype question)))
1 : multi 2 : open , 3 : fullfill , 4 : composite questions ( columns )
(defmethod display-question 1
[{:keys [question explanation hint key qtype id ordnen] :as q}]
(let [counter (r/atom 0)
idx-answers (map-indexed (fn [idx answer] (assoc (second answer) :idx (inc idx))) (:answers q))
acounter (count idx-answers)]
(fn [{:keys [question explanation hint qtype id ordnen] :as q}]
[:div.question-items-divs
[input-new-answer {:question-id id :on-stop #(js/console.log "stop") :props {:placeholder "Neue antwort"}}]
(when-not (nil? idx-answers)
(for [answer idx-answers]
[display-answer (assoc answer :acounter acounter :key (swap! counter inc))]))])))
(defmethod display-question 2
[question]
[:div.div-separator "(Dies ist eine offene Frage)"])
(defmethod display-question 3
[question]
[fulfill-question-form question])
(defmethod display-question 4
[question]
[:p "Question columns"])
(defn question-item
"Display any type of question"
[{:keys [question explanation hint qtype id ordnen points counter uurlid qcount] :as q}]
(let [editing-question (r/atom false)]
(.log js/console (str ">>> VALUE qcounter >>>>> " qcount " >>>> counter >>> " counter " >>>> uurlid >>>> " uurlid " >>>> " q " >>>> " question))
(fn []
Flex container
[:div.question-items-divs
(when (> counter 1)
[:img.img-float-right {:title "Frage nachbestellen"
:alt "Frage nachbestellen"
:src "/img/icon_up_green.png"
:on-click #(rf/dispatch [:reorder-question {:uurlid uurlid :ordnen ordnen :direction "up"}])}])
(when (< counter qcount)
[:img.img-float-right {:title "Senden Sie nach unten"
:alt "Senden Sie nach unten"
:src "/img/icon_down_green.png"
:on-click #(rf/dispatch [:reorder-question {:uurlid uurlid :ordnen ordnen :direction "down"}])}])
(if @editing-question
[:img.img-float-right {:title "Frage abbrechen"
:alt "Frage abbrechen"
:src "/img/icon_cancel.png"
:on-click #(swap! editing-question not)}]
[:img.img-float-right {:title "Frage bearbeiten"
:alt "Frage bearbeiten"
:src "/img/icon_edit.png"
[:div.question-items-divs
[:div [:span.bold-font (str counter ".- Frage: ")] question " >>>>ordnen:>>>" ordnen " question id:" id]
[:div [:span.bold-font "Hint: "] hint]
[:div [:span.bold-font "Points: "] points]
[:div [:span.bold-font "Erläuterung: "] explanation]]
(when @editing-question
[edit-question q])
Polimorphysm for the kind of question
[:div.question-items-divs
[:img {:src "/img/icon_delete.png"
:title "Frage löschen"
:alt "Frage löschen"
:on-click #(rf/dispatch [:delete-question id])}]]])))
(defn display-questions-list
[uurlid question-count]
(let [questions (rf/subscribe [:questions])]
(fn [uurlid question-count]
[:div
(for [{:keys [idx question]} (cms/indexado @questions)]
^{:key (hash question)}
[question-item (assoc question :counter idx :uurlid uurlid :qcount question-count)])])))
(defn test-editor-form [test title description tags subject-id level-id]
[:div {:id "test-whole-display"}
[:div.edit-icon-div
(if @(rf/subscribe [:toggle-testform])
[:img.img-float-right {:title "Bearbeiten test abbrechen" :alt "Bearbeiten test abbrechen" :src "/img/icon_cancel.png"
:on-click #(rf/dispatch [:toggle-testform]) }]
[:img.img-float-right {:title "Test bearbeiten" :alt "Test bearbeiten" :src "/img/icon_edit_test.png"
:on-click #(rf/dispatch [:toggle-testform])}])]
[:div {:id "hidden-form" :class (if @(rf/subscribe [:toggle-testform]) "visible-div" "hidden-div")}
[:h3.class "Bearbeit test"]
[:div.div-separator
[:label {:class "tiny-label"} "Title"]
[:input {:type "text" :value @title :placeholder "Title" :title "Title" :maxLength 100
:on-change #(reset! title (-> % .-target .-value)) :size 100}]]
[:div.div-separator
[:label {:class "tiny-label"} "Description"]
[:input {:type "text" :value @description :on-change #(reset! description (-> % .-target .-value))
:placeholder "Erklärung" :title "Erklärung" :maxLength 180 :size 100}]]
[:div.div-separator
[:label {:class "tiny-label"} "Tags"]
[:input {:type "text" :value @tags :on-change #(reset! tags (-> % .-target .-value))
:placeholder "Tags" :title "Tags" :maxLength 100 :size 100}]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "subject-id"
:value @subject-id
:on-change #(reset! subject-id (-> % .-target .-value))}
(for [row-subject @(rf/subscribe [:subjects])]
^{:key (:id row-subject)} [:option {:value (:id row-subject)} (:subject row-subject)])
]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "level-id"
:value @level-id
:on-change #(reset! level-id (-> % .-target .-value))}
(for [row-level @(rf/subscribe [:levels])]
^{:key (:id row-level)} [:option {:value (:id row-level)} (:level row-level)])
]]
[:div
[:input {:class "btn btn-outline-primary-green" :type "button" :value "Speichern"
:on-click #(rf/dispatch [:update-test {:title @title
:description @description
:tags @tags
:level_id @level-id
:subject_id @subject-id
:uurlid (:uurlid test)}])}]]]
[:div
[:h1 @title]
[:div.div-simple-separator [:span {:class "bold-font"} "Tags: "] @tags [:span {:class "bold-font"} " Created:"] (:created_at test)]
[:div.div-simple-separator [:span {:class "bold-font"} "Description: "] @description [:span {:class "bold-font"} " Subject: "] (:subject test)
[:span {:class "bold-font"} " Level: "] (:level test) ]]])
(defn test-editor-view
[]
(let [test (rf/subscribe [:test])
title (r/atom nil)
subject-id (r/atom nil)
level-id (r/atom nil)
description (r/atom nil)
tags (r/atom nil)]
(fn []
(reset! title (:title @test))
(reset! subject-id (:subject_id @test))
(reset! level-id (:level_id @test))
(reset! description (:description @test))
(reset! tags (:tags @test))
[:div
[test-editor-form @test title description tags subject-id level-id]
[:img {:src "/img/icon_add_question.png" :alt "Fragen hinzüfugen" :title "Fragen hinzüfugen"
:on-click #(rf/dispatch [:toggle-qform])}]])))
(defn create-question-form
"Verstecken Form for a neue fragen"
[]
(let [qform (rf/subscribe [:qform])
uurlid (rf/subscribe [:test-uurlid])
user-id (rf/subscribe [:test-user-id])
new-question (r/atom "")
hint (r/atom "")
explanation (r/atom "")
qtype (r/atom "1")
points (r/atom "1")]
(fn []
[:div {:id "hidden-form" :class (if @qform "visible-div" "hidden-div")}
[:h3.class "Hinzifugen neue fragen"]
[:div.div-separator
[:input {:type "text" :value @new-question
:placeholder "Neue Frage"
:title "Neue Frage"
:maxLength 180
:on-change #(reset! new-question (-> % .-target .-value))
:size 100}]]
[:div.div-separator
[:input {:type "text"
:value @hint
:on-change #(reset! hint (-> % .-target .-value))
:placeholder "Frage Hinweis"
:title "Frage Hinweis"
:maxLength 180
:size 100}]]
[:div.div-separator
[:input {:type "text"
:value @explanation
:on-change #(reset! explanation (-> % .-target .-value))
:placeholder "Frage erklärung"
:title "Frage erklärung"
:maxLength 180
:size 100}]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "points"
:value @points
:on-change #(reset! points (-> % .-target .-value))}
(for [pvalue (range 1 6)]
^{:key pvalue} [:option {:value pvalue} pvalue])]]
[:div.div-separator
[:select.form-control.mr-sm-2 {:name "qtype"
:value @qtype
:on-change #(reset! qtype (-> % .-target .-value))}
[:option {:value "1"} "Multiple"]
[:option {:value "2"} "Open"]
[:option {:value "3"} "Fullfill"]
[: option { : value " 4 " } " Columns " ]
]]
[:div
[:input.btn {:class "btn btn-outline-primary-green" :type "button" :value "Neue Frage speichern"
:on-click #(do (rf/dispatch [:create-question {:question @new-question
:hint @hint
:qtype @qtype
:points @points
:explanation @explanation
:uurlid @uurlid
:user-id @user-id}])
(reset! new-question "")
(reset! hint "")
(reset! explanation ""))}]]])))
(defn test-app
[]
(let [question-count (rf/subscribe [:question-count])
uurlid (rf/subscribe [:test-uurlid])]
[:div {:id "page-container"}
[test-editor-view]
[create-question-form]
[display-questions-list @uurlid @question-count]
[:div {:class "footer"}
[:p "Ziehen Sie die Fragen per Drag & Drop in eine andere Reihenfolge."]]]))
|
9c0ed697b19db288e6790fc64f0c1e589746cbcbc3937990711936fd1d20c255 | Frechmatz/cl-synthesizer | packages.lisp | (defpackage :cl-synthesizer-modules-mixer
(:use :cl)
(:export :make-module))
| null | https://raw.githubusercontent.com/Frechmatz/cl-synthesizer/4dfc5c804e56cffbba57744b92b2eebc3b514d1e/src/modules/mixer/packages.lisp | lisp | (defpackage :cl-synthesizer-modules-mixer
(:use :cl)
(:export :make-module))
| |
6488a6e920ebc0fc87e997915c265bc867d762d8fae99926a7aa60874f138865 | florentc/youbrick | Actions.hs | {-# LANGUAGE OverloadedStrings #-}
|
Module : Tui . Actions
Description : Operations triggered from the TUI
Copyright : ( c ) , 2021
License : GPL-3.0 - or - later
Operations with an effect on the state of the database or the TUI that results
from user interactions .
Module : Tui.Actions
Description : Operations triggered from the TUI
Copyright : (c) Florent Ch., 2021
License : GPL-3.0-or-later
Operations with an effect on the state of the database or the TUI that results
from user interactions.
-}
module Tui.Actions
( deleteJob
, jobAddChannel
, jobUpdateChannel
, jobsUpdateAllChannels
, reportError
, reportJobError
, openAddChannelPrompt
, browseChannelList
, browseSelectedChannelLastContent
, browseNotWatchedVideos
, setSelectedChannelWatched
, updateChannel
, deleteSelectedChannel
, playSelectedVideo
, webbrowseSelectedVideo
, webbrowseSelectedChannel
, toggleSelectedVideoWatchStatus
) where
import Config (viewerApplication, browserApplication)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Database as D
import Control.Monad (void)
import System.Process (createProcess, proc, std_in, std_out, std_err, StdStream(NoStream))
import Lens.Micro.Platform
import Tui.State
import Tui.Job (Job)
import qualified Tui.Job as Job
import qualified Tui.ChannelList as WChannelList
import qualified Tui.VideoList as WVideoList
import qualified Tui.AddChannel as WAddChannel
-- | Report a direct error.
reportError :: Text -> State -> State
reportError description = sView . vReports %~ ((Nothing, description) :)
-- | Report an error related to a job failure (e.g. network error when fetching
-- new content).
reportJobError :: Job -> Text -> State -> State
reportJobError job description = sView . vReports %~ ((Just job, description) :)
addJob :: Job -> State -> State
addJob = (sView . vJobs %~) . Set.insert
addJobs :: Set Job -> State -> State
addJobs = (sView . vJobs %~) . Set.union
deleteJob :: Job -> State -> State
deleteJob = (sView . vJobs %~) . Set.delete
-- | Clear the text field of the "add channel" widget.
emptyAddChannelPrompt :: State -> State
emptyAddChannelPrompt = sView . vWidgetBank . wAddChannel .~ WAddChannel.new
-- | Add a new channel in a parallel job.
jobAddChannel :: State -> (Job, State)
jobAddChannel s =
let job = Job.AddChannel $ WAddChannel.content (s ^. sView . vWidgetBank . wAddChannel)
in (job, s & browseChannelList . addJob job . emptyAddChannelPrompt)
-- | Update (fetch new content) a channel in a parallel job.
jobUpdateChannel :: D.ChannelId -> Bool -> State -> (Job, State)
jobUpdateChannel cid silent s = let job = Job.UpdateChannel cid silent in (job, addJob job s)
-- | Update (fetch new content) all channels each in a parallel job.
jobsUpdateAllChannels :: State -> (Set Job, State)
jobsUpdateAllChannels s =
let jobs = Set.map (\cid -> Job.UpdateChannel cid False) (D.channelIds $ s ^. sDatabase)
s' = s & addJobs jobs
updatingChannels = Job.updatingChannels (s' ^. sView . vJobs)
updateChannelList = sView . vWidgetBank . wChannelList %~ WChannelList.update (s' ^. sDatabase) updatingChannels
in (jobs, s' & updateChannelList)
-- | Update the state of the app given fresh content about a channel. An update
-- can be silent which means new content will already be considered watched.
-- This is used when adding a new channel.
updateChannel :: Bool -- ^ Whether to update "silently"
^ Channel i d and its maybe new title
-> Set D.VideoImport -- ^ Raw info about latest content
-> State
-> State
updateChannel silent channel videos s =
let database' =
(if silent then D.updateChannelSilently else D.updateChannel)
channel videos (s ^. sDatabase)
updatingChannels = Job.updatingChannels (s ^. sView . vJobs)
in s
& sDatabase .~ database'
& sView . vWidgetBank . wChannelList %~ WChannelList.update database' updatingChannels
& sView . vWidgetBank . wVideoList %~
case s ^. sView . vActivity of
ConsultVideoList (VideoListChannel cid) ->
if cid == D.channelId channel then WVideoList.update database' else id
ConsultVideoList VideoListToWatch ->
let videos' = D.lookupNotWatched database'
in WVideoList.update database'
_ -> id
-- | Open and focus the "add channel" widget.
openAddChannelPrompt :: State -> State
openAddChannelPrompt = sView . vActivity .~ AddChannel
-- | Current selected channel in the channel list.
selectedChannelId :: State -> Maybe D.ChannelId
selectedChannelId = WChannelList.selectedChannel . (^. sView . vWidgetBank . wChannelList)
-- | Open the list of latest video on the currently selected channel.
browseSelectedChannelLastContent :: State -> State
browseSelectedChannelLastContent s =
case selectedChannelId s of
Nothing -> s & reportError "No channel selected."
Just cid ->
case WVideoList.newChannelWidget cid (s ^. sDatabase) of
Nothing -> s & reportError "Could not browse channel content."
Just w -> s
& sView . vActivity .~ ConsultVideoList (VideoListChannel cid)
& sView . vWidgetBank . wVideoList .~ w
-- | Open the list of videos that have not been watched yet.
browseNotWatchedVideos :: State -> State
browseNotWatchedVideos s =
let videos = D.lookupNotWatched (s ^. sDatabase)
in s
& sView . vActivity .~ ConsultVideoList VideoListToWatch
& sView . vWidgetBank . wVideoList .~ WVideoList.newWatchlistWidget (s ^. sDatabase)
-- | Remove selected channel from the database.
deleteSelectedChannel :: State -> State
deleteSelectedChannel s =
case selectedChannelId s of
Nothing -> s & reportError "No channel selected."
Just cid ->
let database' = D.removeChannel cid (s ^. sDatabase)
updatingChannels = Job.updatingChannels (s ^. sView . vJobs)
in s
& sDatabase .~ database'
& sView . vWidgetBank . wChannelList %~ WChannelList.update database' updatingChannels
-- | Go back to the list of channels.
browseChannelList :: State -> State
browseChannelList = sView . vActivity .~ ConsultChannelList
-- | Currently selected video in the video list.
selectedVideoId :: State -> Maybe D.VideoId
selectedVideoId = WVideoList.selectedVideo . (^. sView . vWidgetBank . wVideoList)
-- | Toggle the watch status of the selected video.
toggleSelectedVideoWatchStatus :: State -> State
toggleSelectedVideoWatchStatus s =
case selectedVideoId s of
Nothing -> s & reportError "No video selected."
Just vid ->
let database' = D.toggleWatched vid (s ^. sDatabase)
updatingChannels = Job.updatingChannels (s ^. sView . vJobs)
in s
& sDatabase .~ database'
& sView . vWidgetBank . wVideoList %~ WVideoList.updateSelectedItem database'
& sView . vWidgetBank . wChannelList %~ WChannelList.update database' updatingChannels
| the selected video watched .
setSelectedVideoWatched :: State -> State
setSelectedVideoWatched s =
case selectedVideoId s of
Nothing -> s & reportError "No video selected."
Just vid ->
let database' = D.setWatched (Set.singleton vid) (s ^. sDatabase)
updatingChannels = Job.updatingChannels (s ^. sView . vJobs)
in s
& sDatabase .~ database'
& sView . vWidgetBank . wVideoList %~ WVideoList.updateSelectedItem database'
& sView . vWidgetBank . wChannelList %~ WChannelList.update database' updatingChannels
| all the videos of the selected channel watched .
setSelectedChannelWatched :: State -> State
setSelectedChannelWatched s =
case selectedChannelId s of
Nothing -> s & reportError "No channel selected."
Just cid ->
let videos = D.lookupLatestContentOnChannel cid (s ^. sDatabase)
database' = D.setWatched (Set.map D.videoId videos) (s ^. sDatabase)
updatingChannels = Job.updatingChannels (s ^. sView . vJobs)
in s & sDatabase .~ database'
& sView . vWidgetBank . wChannelList %~ WChannelList.update database' updatingChannels
-- | Open the selected video with the video player in a new process.
playSelectedVideo :: State -> (IO (), State)
playSelectedVideo s =
case selectedVideoId s of
Nothing -> (return (), s & reportError "No video selected.")
Just vid ->
( void $ createProcess (proc viewerApplication [Text.unpack $ D.genVideoUrl vid])
{std_in = NoStream, std_err = NoStream, std_out = NoStream}
, setSelectedVideoWatched s)
-- | Open the selected video with the web browser.
webbrowseSelectedVideo :: State -> (IO (), State)
webbrowseSelectedVideo s =
case selectedVideoId s of
Nothing -> (return (), s & reportError "No video selected.")
Just vid ->
( void $ createProcess (proc browserApplication [Text.unpack $ D.genVideoUrl vid])
{std_in = NoStream, std_err = NoStream, std_out = NoStream}
, s)
-- | Open the selected channel in the web browser.
webbrowseSelectedChannel :: State -> (IO (), State)
webbrowseSelectedChannel s =
case selectedChannelId s of
Nothing -> (return (), s & reportError "No channel selected.")
Just cid ->
( void $ createProcess (proc browserApplication [Text.unpack $ D.genChannelUrl cid])
{std_in = NoStream, std_err = NoStream, std_out = NoStream}
, s)
| null | https://raw.githubusercontent.com/florentc/youbrick/0b0dae7c94773df904b9d6c9172d503d65e86281/src/Tui/Actions.hs | haskell | # LANGUAGE OverloadedStrings #
| Report a direct error.
| Report an error related to a job failure (e.g. network error when fetching
new content).
| Clear the text field of the "add channel" widget.
| Add a new channel in a parallel job.
| Update (fetch new content) a channel in a parallel job.
| Update (fetch new content) all channels each in a parallel job.
| Update the state of the app given fresh content about a channel. An update
can be silent which means new content will already be considered watched.
This is used when adding a new channel.
^ Whether to update "silently"
^ Raw info about latest content
| Open and focus the "add channel" widget.
| Current selected channel in the channel list.
| Open the list of latest video on the currently selected channel.
| Open the list of videos that have not been watched yet.
| Remove selected channel from the database.
| Go back to the list of channels.
| Currently selected video in the video list.
| Toggle the watch status of the selected video.
| Open the selected video with the video player in a new process.
| Open the selected video with the web browser.
| Open the selected channel in the web browser. |
|
Module : Tui . Actions
Description : Operations triggered from the TUI
Copyright : ( c ) , 2021
License : GPL-3.0 - or - later
Operations with an effect on the state of the database or the TUI that results
from user interactions .
Module : Tui.Actions
Description : Operations triggered from the TUI
Copyright : (c) Florent Ch., 2021
License : GPL-3.0-or-later
Operations with an effect on the state of the database or the TUI that results
from user interactions.
-}
module Tui.Actions
( deleteJob
, jobAddChannel
, jobUpdateChannel
, jobsUpdateAllChannels
, reportError
, reportJobError
, openAddChannelPrompt
, browseChannelList
, browseSelectedChannelLastContent
, browseNotWatchedVideos
, setSelectedChannelWatched
, updateChannel
, deleteSelectedChannel
, playSelectedVideo
, webbrowseSelectedVideo
, webbrowseSelectedChannel
, toggleSelectedVideoWatchStatus
) where
import Config (viewerApplication, browserApplication)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Database as D
import Control.Monad (void)
import System.Process (createProcess, proc, std_in, std_out, std_err, StdStream(NoStream))
import Lens.Micro.Platform
import Tui.State
import Tui.Job (Job)
import qualified Tui.Job as Job
import qualified Tui.ChannelList as WChannelList
import qualified Tui.VideoList as WVideoList
import qualified Tui.AddChannel as WAddChannel
reportError :: Text -> State -> State
reportError description = sView . vReports %~ ((Nothing, description) :)
reportJobError :: Job -> Text -> State -> State
reportJobError job description = sView . vReports %~ ((Just job, description) :)
addJob :: Job -> State -> State
addJob = (sView . vJobs %~) . Set.insert
addJobs :: Set Job -> State -> State
addJobs = (sView . vJobs %~) . Set.union
deleteJob :: Job -> State -> State
deleteJob = (sView . vJobs %~) . Set.delete
emptyAddChannelPrompt :: State -> State
emptyAddChannelPrompt = sView . vWidgetBank . wAddChannel .~ WAddChannel.new
jobAddChannel :: State -> (Job, State)
jobAddChannel s =
let job = Job.AddChannel $ WAddChannel.content (s ^. sView . vWidgetBank . wAddChannel)
in (job, s & browseChannelList . addJob job . emptyAddChannelPrompt)
jobUpdateChannel :: D.ChannelId -> Bool -> State -> (Job, State)
jobUpdateChannel cid silent s = let job = Job.UpdateChannel cid silent in (job, addJob job s)
jobsUpdateAllChannels :: State -> (Set Job, State)
jobsUpdateAllChannels s =
let jobs = Set.map (\cid -> Job.UpdateChannel cid False) (D.channelIds $ s ^. sDatabase)
s' = s & addJobs jobs
updatingChannels = Job.updatingChannels (s' ^. sView . vJobs)
updateChannelList = sView . vWidgetBank . wChannelList %~ WChannelList.update (s' ^. sDatabase) updatingChannels
in (jobs, s' & updateChannelList)
^ Channel i d and its maybe new title
-> State
-> State
updateChannel silent channel videos s =
let database' =
(if silent then D.updateChannelSilently else D.updateChannel)
channel videos (s ^. sDatabase)
updatingChannels = Job.updatingChannels (s ^. sView . vJobs)
in s
& sDatabase .~ database'
& sView . vWidgetBank . wChannelList %~ WChannelList.update database' updatingChannels
& sView . vWidgetBank . wVideoList %~
case s ^. sView . vActivity of
ConsultVideoList (VideoListChannel cid) ->
if cid == D.channelId channel then WVideoList.update database' else id
ConsultVideoList VideoListToWatch ->
let videos' = D.lookupNotWatched database'
in WVideoList.update database'
_ -> id
openAddChannelPrompt :: State -> State
openAddChannelPrompt = sView . vActivity .~ AddChannel
selectedChannelId :: State -> Maybe D.ChannelId
selectedChannelId = WChannelList.selectedChannel . (^. sView . vWidgetBank . wChannelList)
browseSelectedChannelLastContent :: State -> State
browseSelectedChannelLastContent s =
case selectedChannelId s of
Nothing -> s & reportError "No channel selected."
Just cid ->
case WVideoList.newChannelWidget cid (s ^. sDatabase) of
Nothing -> s & reportError "Could not browse channel content."
Just w -> s
& sView . vActivity .~ ConsultVideoList (VideoListChannel cid)
& sView . vWidgetBank . wVideoList .~ w
browseNotWatchedVideos :: State -> State
browseNotWatchedVideos s =
let videos = D.lookupNotWatched (s ^. sDatabase)
in s
& sView . vActivity .~ ConsultVideoList VideoListToWatch
& sView . vWidgetBank . wVideoList .~ WVideoList.newWatchlistWidget (s ^. sDatabase)
deleteSelectedChannel :: State -> State
deleteSelectedChannel s =
case selectedChannelId s of
Nothing -> s & reportError "No channel selected."
Just cid ->
let database' = D.removeChannel cid (s ^. sDatabase)
updatingChannels = Job.updatingChannels (s ^. sView . vJobs)
in s
& sDatabase .~ database'
& sView . vWidgetBank . wChannelList %~ WChannelList.update database' updatingChannels
browseChannelList :: State -> State
browseChannelList = sView . vActivity .~ ConsultChannelList
selectedVideoId :: State -> Maybe D.VideoId
selectedVideoId = WVideoList.selectedVideo . (^. sView . vWidgetBank . wVideoList)
toggleSelectedVideoWatchStatus :: State -> State
toggleSelectedVideoWatchStatus s =
case selectedVideoId s of
Nothing -> s & reportError "No video selected."
Just vid ->
let database' = D.toggleWatched vid (s ^. sDatabase)
updatingChannels = Job.updatingChannels (s ^. sView . vJobs)
in s
& sDatabase .~ database'
& sView . vWidgetBank . wVideoList %~ WVideoList.updateSelectedItem database'
& sView . vWidgetBank . wChannelList %~ WChannelList.update database' updatingChannels
| the selected video watched .
setSelectedVideoWatched :: State -> State
setSelectedVideoWatched s =
case selectedVideoId s of
Nothing -> s & reportError "No video selected."
Just vid ->
let database' = D.setWatched (Set.singleton vid) (s ^. sDatabase)
updatingChannels = Job.updatingChannels (s ^. sView . vJobs)
in s
& sDatabase .~ database'
& sView . vWidgetBank . wVideoList %~ WVideoList.updateSelectedItem database'
& sView . vWidgetBank . wChannelList %~ WChannelList.update database' updatingChannels
| all the videos of the selected channel watched .
setSelectedChannelWatched :: State -> State
setSelectedChannelWatched s =
case selectedChannelId s of
Nothing -> s & reportError "No channel selected."
Just cid ->
let videos = D.lookupLatestContentOnChannel cid (s ^. sDatabase)
database' = D.setWatched (Set.map D.videoId videos) (s ^. sDatabase)
updatingChannels = Job.updatingChannels (s ^. sView . vJobs)
in s & sDatabase .~ database'
& sView . vWidgetBank . wChannelList %~ WChannelList.update database' updatingChannels
playSelectedVideo :: State -> (IO (), State)
playSelectedVideo s =
case selectedVideoId s of
Nothing -> (return (), s & reportError "No video selected.")
Just vid ->
( void $ createProcess (proc viewerApplication [Text.unpack $ D.genVideoUrl vid])
{std_in = NoStream, std_err = NoStream, std_out = NoStream}
, setSelectedVideoWatched s)
webbrowseSelectedVideo :: State -> (IO (), State)
webbrowseSelectedVideo s =
case selectedVideoId s of
Nothing -> (return (), s & reportError "No video selected.")
Just vid ->
( void $ createProcess (proc browserApplication [Text.unpack $ D.genVideoUrl vid])
{std_in = NoStream, std_err = NoStream, std_out = NoStream}
, s)
webbrowseSelectedChannel :: State -> (IO (), State)
webbrowseSelectedChannel s =
case selectedChannelId s of
Nothing -> (return (), s & reportError "No channel selected.")
Just cid ->
( void $ createProcess (proc browserApplication [Text.unpack $ D.genChannelUrl cid])
{std_in = NoStream, std_err = NoStream, std_out = NoStream}
, s)
|
b0ea923ff5edb2651a4d20a023c3001af852372e4910a56d8a904c40ea03f044 | elastic/eui-cljs | icon_token_metric_gauge.cljs | (ns eui.icon-token-metric-gauge
(:require ["@elastic/eui/lib/components/icon/assets/tokenMetricGauge.js" :as eui]))
(def tokenMetricGauge eui/icon)
| null | https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/icon_token_metric_gauge.cljs | clojure | (ns eui.icon-token-metric-gauge
(:require ["@elastic/eui/lib/components/icon/assets/tokenMetricGauge.js" :as eui]))
(def tokenMetricGauge eui/icon)
| |
06209aef949d3d2131c7be51b9feb32463ab839ba6ee3c928c6ca000871703ed | collaborativetrust/WikiTrust | compute_robust_trust.ml |
Copyright ( c ) 2007 - 2009 The Regents of the University of California
All rights reserved .
Authors :
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
1 . Redistributions of source code must retain the above copyright notice ,
this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright notice ,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution .
3 . The names of the contributors may not 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 OWNER OR
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 , 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 .
Copyright (c) 2007-2009 The Regents of the University of California
All rights reserved.
Authors: Luca de Alfaro
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The names of the contributors may not 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
(** The functions in this module are used to compute the trust of the
words of a revision, taking into account the "locality effect" of
the attention of the revisor.
The computation uses a robust method, that includes the consideration
of author signatures. *)
type word = string
open Eval_defs
* [ compute_trust_chunks chunks_trust_a new_chunks_a new_seps medit_l
rep_float trust_coeff ... ] computes the new word trust values of
the revision with chunks [ new_chunks_a ] , obtained from the version
with word trust values [ chunks_trust_a ] via the edit list
[ medit_l ] . [ new_seps ] are the new seps of the latest
revision . [ rep_float ] is the reputation of the author of the new
revision . What is new about this method , compared to the
classical compute_word_trust one , is that this one takes into
account syntactical units to spread the trust . The
trust_coeff _ ... parameters are for trust computation .
rep_float trust_coeff...] computes the new word trust values of
the revision with chunks [new_chunks_a], obtained from the version
with word trust values [chunks_trust_a] via the edit list
[medit_l]. [new_seps] are the new seps of the latest
revision. [rep_float] is the reputation of the author of the new
revision. What is new about this method, compared to the
classical compute_word_trust one, is that this one takes into
account syntactical units to spread the trust. The
trust_coeff_... parameters are for trust computation. *)
let compute_robust_trust
(chunks_trust_a: float array array)
(chunks_authorsig_a: Author_sig.packed_author_signature_t array array)
(new_chunks_a: word array array)
(new_seps: Text.sep_t array)
(medit_l: Editlist.medit list)
(rep_float: float)
(user_id: int)
(trust_coeff_lends_rep: float)
(trust_coeff_kill_decrease: float)
(trust_coeff_cut_rep_radius: float)
(trust_coeff_read_all: float)
(trust_coeff_read_part: float)
(trust_coeff_local_decay: float)
: (float array array * Author_sig.packed_author_signature_t array array) =
(* Produces the new trust array *)
let f x = Array.make (Array.length x) 0.0 in
let new_chunks_trust_a = Array.map f new_chunks_a in
let old_live_len = Array.length chunks_trust_a.(0) in
let new_live_len = Array.length new_chunks_a.(0) in
(* Produces the new signature array *)
let f x = Array.make (Array.length x) Author_sig.empty_sigs in
let new_chunks_authorsig_a = Array.map f new_chunks_a in
Produces two auxiliary arrays : one keeps track of whether the author can
increase the trust of a word , the second keeps track of whether the author
has increased the trust of a word . These are just filled with default
values initially .
increase the trust of a word, the second keeps track of whether the author
has increased the trust of a word. These are just filled with default
values initially. *)
let f x = Array.make (Array.length x) true in
let new_chunks_canincrease_a = Array.map f new_chunks_a in
let f x = Array.make (Array.length x) false in
let new_chunks_hasincreased_a = Array.map f new_chunks_a in
This array keeps track of the syntactic units that have been checked
by the author . It contains one bool per word , which indicates whether
the author is likely to have read the word or not .
by the author. It contains one bool per word, which indicates whether
the author is likely to have read the word or not. *)
let looked_at = Array.make new_live_len false in
(* We need to have the conversion from words to seps, and the seps,
for the current revision. *)
let seps = new_seps in
(* This array contains, for each word, the number of the sectional unit
to which the word belongs. *)
let section_of_word = Array.make new_live_len 0 in
(* Initializes section_of_word *)
let n_seps = Array.length seps in
let n_section = ref 0 in
for i = 0 to n_seps - 1 do begin
match seps.(i) with
(* Syntax breaks, no word increase *)
Text.Par_break _ ->
n_section := !n_section + 1
(* Syntax break before, word increase *)
| Text.Title_start (_, k) | Text.Bullet (_, k) | Text.Table_cell (_, k)
| Text.Table_line (_, k) | Text.Table_caption (_,k) | Text.Indent (_, k) -> begin
n_section := !n_section + 1;
section_of_word.(k) <- !n_section
end
(* Syntax break after, word increase *)
| Text.Title_end (_, k) -> begin
section_of_word.(k) <- !n_section;
n_section := !n_section + 1
end
(* No syntax break, word increase *)
| Text.Tag (_, k) | Text.Word (_, k) | Text.Redirect (_, k)
| Text.Armored_char (_, k) ->
section_of_word.(k) <- !n_section
(* No syntax break, no word increase *)
| Text.Space _ | Text.Newline _ -> ()
end done;
(* [spread_look n] marks the array looked_at so that all the syntactic unit
(paragraph, itemization point) of [n] is labeled true. *)
let spread_look (n: int) : unit =
(* Spreads upward *)
if not looked_at.(n) then begin
let word_idx = ref n in
let fatto = ref false in
while not !fatto do begin
looked_at.(!word_idx) <- true;
if !word_idx = new_live_len - 1
then fatto := true
else begin
word_idx := !word_idx + 1;
fatto := looked_at.(!word_idx) || section_of_word.(!word_idx - 1) <> section_of_word.(!word_idx)
end
end done;
(* Spreads downwards *)
let word_idx = ref n in
let fatto = ref false in
while not !fatto do begin
looked_at.(!word_idx) <- true;
if !word_idx = 0
then fatto := true
else begin
word_idx := !word_idx - 1;
fatto := looked_at.(!word_idx) || section_of_word.(!word_idx + 1) <> section_of_word.(!word_idx)
end
end done
end (* if not looked_at.(n) *)
in (* end of spread_look *)
This function is used to determine whether the beginning of a move ,
that begins at position k , should be marked in trust .
The rule is :
- text moved from the beginning to the beginning is not marked
( this is taken care by the caller )
- if the previous text has been inserted , and belongs to a
different section , and is of length
at least 2 , the cut is not marked . The length 2 requirement
is used to ensure that the coloring will be visible .
- otherwise , it is marked . Thus , text after an insertion in
the same sectional unit , and text
that has been rearranged , is marked .
that begins at position k, should be marked in trust.
The rule is:
- text moved from the beginning to the beginning is not marked
(this is taken care by the caller)
- if the previous text has been inserted, and belongs to a
different section, and is of length
at least 2, the cut is not marked. The length 2 requirement
is used to ensure that the coloring will be visible.
- otherwise, it is marked. Thus, text after an insertion in
the same sectional unit, and text
that has been rearranged, is marked. *)
let mark_begin_cut (n: int): bool =
(* If the cut starts at 0, then it has been re-arranged, since the
0 to 0 case is taken care by the caller *)
if n = 0 then true
(* If the sectional unit has not changed, we do not need to
figure out what is the type of the previous block
(inserted/moved), we mark it anyway *)
else if section_of_word.(n) = section_of_word.(n - 1) then true
else begin
(* The previous block is in a different sectional unit. Checks
whether it is an insert. *)
let rec is_moved = function
[] -> true
| Editlist.Mins (word_idx, l) :: rest ->
if word_idx + l = n then l < 2 else is_moved rest
| Editlist.Mmov (src_word_idx, src_chunk_idx, dst_word_idx, dst_chunk_idx, l) :: rest ->
if dst_chunk_idx = 0 && dst_word_idx + l = n
then true
else is_moved rest
| _ :: rest -> is_moved rest
in is_moved medit_l
end
in (* end of mark_begin_cut *)
(* This function is analogous to mark_begin_cut, but for the end of
the cut *)
let mark_end_cut (n: int): bool =
(* If the cut starts at 0, then it has been re-arranged, since the
0 to 0 case is taken care by the caller *)
if n = new_live_len - 1 then true
(* If the sectional unit has not changed, we do not need to
figure out what is the type of the previous block
(inserted/moved), we mark it anyway *)
else if section_of_word.(n) = section_of_word.(n + 1) then true
else begin
(* The previous block is in a different sectional unit. Checks
whether it is an insert. *)
let rec is_moved = function
[] -> true
| Editlist.Mins (word_idx, l) :: rest ->
if word_idx - 1 = n
then l < 2 (* it is an insert *)
else is_moved rest
| Editlist.Mmov (src_word_idx, src_chunk_idx, dst_word_idx, dst_chunk_idx, l) :: rest ->
if dst_chunk_idx = 0 && dst_word_idx - 1 = n
then true
else is_moved rest
| _ :: rest -> is_moved rest
in is_moved medit_l
end
end of mark_end_cut
(* This is a trust bonus that the fresh text is awarded.
Note that in any case, this value undergoes the trust increase
due to both reading the section where the text is inserted, and
reading the whole page. *)
let new_text_trust = rep_float *. trust_coeff_lends_rep in
(* Now, goes over medit_l via f, and fills in new_chunks_trust_a and
the new signatures properly. *)
let f = function
Editlist.Mins (word_idx, l) -> begin
(* This is text added in the current version *)
(* Credits the reputation range for the current text *)
for i = word_idx to word_idx + l - 1 do begin
new_chunks_trust_a.(0).(i) <- new_text_trust;
looked_at.(i) <- true;
new_chunks_hasincreased_a.(0).(i) <- true;
(* new_chunks_canincrease_a.(0).(i) <- true; *) (* true is
the default *)
end done;
One generally looks in the whole syntactic unit where one
is editing
is editing *)
spread_look word_idx;
spread_look (word_idx + l - 1)
end
| Editlist.Mmov (src_word_idx, src_chunk_idx, dst_word_idx, dst_chunk_idx, l) -> begin
(* Checks whether the text is live in the new version *)
if dst_chunk_idx = 0 then begin
(* It is live text *)
First , copies the trust and signatures
for i = 0 to l - 1 do begin
(* trust *)
let trust = chunks_trust_a.(src_chunk_idx).(src_word_idx + i) in
new_chunks_trust_a.(0).(dst_word_idx + i) <- trust;
(* This is the word under consideration *)
let w = new_chunks_a.(0).(dst_word_idx + i) in
(* Packed signature of the word *)
let hsig = chunks_authorsig_a.(src_chunk_idx).(src_word_idx + i) in
new_chunks_authorsig_a.(0).(dst_word_idx + i) <- hsig;
(* This encodes the all-important logic that decides
whether a user can increase the trust of a word. The
user has to be not anonymous, and not present in the
signature. *)
new_chunks_canincrease_a.(0).(dst_word_idx + i) <-
(user_id <> 0) && not (Author_sig.is_author_in_sigs user_id w hsig);
new_chunks_hasincreased_a.(0).(dst_word_idx + i) <- false;
end done;
(* Then, applies corrective effects. *)
The first corrective effect is the fact that , at cut
places , the text becomes of trust equal to the reputation
of the author multiplied by a scaling effect . The
scaling effect is there so that even high - reputation
authors can not single - handedly create trusted content ;
revisions are always needed .
places, the text becomes of trust equal to the reputation
of the author multiplied by a scaling effect. The
scaling effect is there so that even high-reputation
authors cannot single-handedly create trusted content;
revisions are always needed. *)
(* Processes the beginning *)
if (src_word_idx <> 0 || dst_word_idx <> 0 || src_chunk_idx <> 0)
&& (mark_begin_cut dst_word_idx) then begin
(* Spreads the information that the author looked at
this chunk of text. *)
spread_look dst_word_idx;
(* Now computes the correction to the trust from the
beginning of the cut block *)
let word_idx = ref dst_word_idx in
let fatto = ref false in
while not !fatto do begin
(* Changes the trust of this word *)
(* Cut points are discontinuities, and they inherit
trust from the author. *)
let d = !word_idx - dst_word_idx in
let old_trust = new_chunks_trust_a.(0).(!word_idx) in
let new_trust = old_trust +.
(new_text_trust -. old_trust) *. exp (-. (float_of_int d) /. trust_coeff_cut_rep_radius) in
if new_trust <= old_trust then begin
new_chunks_trust_a.(0).(!word_idx) <- new_trust;
end;
if new_trust > old_trust && new_chunks_canincrease_a.(0).(!word_idx) then begin
new_chunks_trust_a.(0).(!word_idx) <- new_trust;
new_chunks_hasincreased_a.(0).(!word_idx) <- true;
end;
(* Moves, but not beyond a sectional boundary *)
if !word_idx = dst_word_idx + l - 1
then fatto := true
else begin
word_idx := !word_idx + 1;
fatto := section_of_word.(!word_idx - 1) <> section_of_word.(!word_idx)
end
end done
end;
(* processes the end *)
if (src_word_idx + l <> old_live_len || dst_word_idx + l <> new_live_len || src_chunk_idx <> 0)
&& (mark_end_cut (dst_word_idx + l - 1)) then begin
(* Spreads the information that the author looked at
this chunk of text. *)
spread_look (dst_word_idx + l - 1);
(* Computes the correction from the end of the cut block *)
let word_idx = ref (dst_word_idx + l - 1) in
let fatto = ref false in
while not !fatto do begin
(* Changes the trust of this word *)
(* Cut points are discontinuities, and they inherit
trust from the author. *)
let d = (dst_word_idx + l - 1) - !word_idx in
let old_trust = new_chunks_trust_a.(0).(!word_idx) in
let new_trust = old_trust +.
(new_text_trust -. old_trust) *. exp (-. (float_of_int d) /. trust_coeff_cut_rep_radius) in
if new_trust <= old_trust then begin
new_chunks_trust_a.(0).(!word_idx) <- new_trust;
end;
if new_trust > old_trust && new_chunks_canincrease_a.(0).(!word_idx) then begin
new_chunks_trust_a.(0).(!word_idx) <- new_trust;
new_chunks_hasincreased_a.(0).(!word_idx) <- true;
end;
(* Moves, but not beyond a sectional boundary *)
if !word_idx = dst_word_idx
then fatto := true
else begin
word_idx := !word_idx - 1;
fatto := section_of_word.(!word_idx + 1) <> section_of_word.(!word_idx)
end
end done
end
end else begin
(* dst_chunk_idx > 0, and the text is dead *)
for i = 0 to l - 1 do begin
First , copies the trust
let old_trust = chunks_trust_a.(src_chunk_idx).(src_word_idx + i) in
let new_trust =
if src_chunk_idx = 0
then old_trust *. exp (-. rep_float *. trust_coeff_kill_decrease)
else old_trust
in
new_chunks_trust_a.(dst_chunk_idx).(dst_word_idx + i) <- new_trust;
(* Then, copies the signature *)
let hsig = chunks_authorsig_a.(src_chunk_idx).(src_word_idx + i) in
new_chunks_canincrease_a.(dst_chunk_idx).(dst_word_idx + i) <- false;
new_chunks_authorsig_a.(dst_chunk_idx).(dst_word_idx + i) <- hsig;
end done
end
end
| Editlist.Mdel _ -> ()
in
List.iter f medit_l;
Spreads looked_at according to trust_coeff_local_decay , first
forward ...
forward ... *)
let spread_looked_at = Array.make new_live_len 0.0 in
let spread = ref 0.0 in
for i = 0 to new_live_len - 1 do begin
if looked_at.(i) then spread := 1.0 else spread := !spread *. trust_coeff_local_decay;
spread_looked_at.(i) <- !spread
end done;
(* ... and then backwards *)
let spread = ref 0.0 in
for i = new_live_len - 1 downto 0 do begin
if looked_at.(i) then spread := 1.0 else spread := !spread *. trust_coeff_local_decay;
spread_looked_at.(i) <- spread_looked_at.(i) +. (1.0 -. spread_looked_at.(i)) *. trust_coeff_local_decay
end done;
(* Uses spread_looked_at to increase the quality of text due to revision. *)
for i = 0 to new_live_len - 1 do begin
let old_trust = new_chunks_trust_a.(0).(i) in
if old_trust < rep_float then
let new_trust = old_trust +.
(rep_float -. old_trust) *. trust_coeff_read_part *. spread_looked_at.(i) in
(* Here I know that new_trust > old_trust *)
if new_chunks_canincrease_a.(0).(i) then begin
new_chunks_trust_a.(0).(i) <- new_trust;
new_chunks_hasincreased_a.(0).(i) <- true;
end
end done;
(* Now there is the last of the effects that affect text trust: We
give a little bit of prize to all the text, according to the
reputation of the author who has made the last edit. *)
let len0 = Array.length new_chunks_trust_a.(0) in
for i = 0 to len0 - 1 do begin
let old_trust = new_chunks_trust_a.(0).(i) in
if rep_float > old_trust then begin
let increased_trust = old_trust +. (rep_float -. old_trust) *. trust_coeff_read_all in
(* Here I know that new_trust > old_trust *)
if new_chunks_canincrease_a.(0).(i) then begin
(* If the author can increase the reputation, because it does
not appear in the signature, it increases it. *)
new_chunks_trust_a.(0).(i) <- increased_trust;
new_chunks_hasincreased_a.(0).(i) <- true;
end else begin
(* The author cannot perform a normal reputation increase,
because it appears in the signatures. Nevertheless, it is
still reasonable to ensure that the text has at least the
same trust as freshly created text by the same author. *)
if old_trust < new_text_trust then begin
new_chunks_trust_a.(0).(i) <- new_text_trust;
(* As the signature is already present, we do not re-add it,
so we do not set new_chunks_hasincreased_a.(0).(i) <- true *)
end
end
end
end done;
(* Now adds the signature to all places where the trust has increased *)
for i = 0 to len0 - 1 do begin
if new_chunks_hasincreased_a.(0).(i) then
let w = new_chunks_a.(0).(i) in
let old_sig = new_chunks_authorsig_a.(0).(i) in
new_chunks_authorsig_a.(0).(i) <- Author_sig.add_author user_id w old_sig
end done;
(* Returns the new trust *)
(new_chunks_trust_a, new_chunks_authorsig_a)
* [ compute_origin chunks_origin_a new_chunks_a medit_l revid author_name ]
computes the origin of the text in the chunks [ new_chunks_a ] ,
belonging to a revision with i d [ revid ] written by a user with
name [ author_name ] . [ medit_l ] is the edit list explaining the
change from previous to current revision .
The information on origin and authors of the old text is given
in [ chunks_origin_a ] and [ chunks_author_a ] , respectively .
The function returns a pair [ new_origin_a , ] ,
describing the new origin and author .
computes the origin of the text in the chunks [new_chunks_a],
belonging to a revision with id [revid] written by a user with
name [author_name]. [medit_l] is the edit list explaining the
change from previous to current revision.
The information on origin and authors of the old text is given
in [chunks_origin_a] and [chunks_author_a], respectively.
The function returns a pair [new_origin_a, new_author_a],
describing the new origin and author. *)
let compute_origin
(chunks_origin_a: int array array)
(chunks_author_a: string array array)
(new_chunks_a: word array array)
(medit_l: Editlist.medit list)
(revid: int)
(author_name: string): (int array array * string array array) =
(* Creates the chunks for origin and authors with defaults. *)
let f x = Array.make (Array.length x) 0 in
let new_chunks_origin_a = Array.map f new_chunks_a in
let f x = Array.make (Array.length x) "" in
let new_chunks_author_a = Array.map f new_chunks_a in
(* Now, goes over medit_l, and fills in new_chunks_origin_a properly. *)
let f = function
Editlist.Mins (word_idx, l) -> begin
for i = word_idx to word_idx + l - 1 do begin
new_chunks_origin_a.(0).(i) <- revid;
new_chunks_author_a.(0).(i) <- author_name
end done
end
| Editlist.Mmov (src_word_idx, src_chunk_idx, dst_word_idx, dst_chunk_idx, l) -> begin
for i = 0 to l - 1 do begin
new_chunks_origin_a.(dst_chunk_idx).(dst_word_idx + i) <-
chunks_origin_a.(src_chunk_idx).(src_word_idx + i);
new_chunks_author_a.(dst_chunk_idx).(dst_word_idx + i) <-
chunks_author_a.(src_chunk_idx).(src_word_idx + i);
end done
end
| _ -> ()
in
List.iter f medit_l;
(new_chunks_origin_a, new_chunks_author_a)
(** [compute_overall_trust th] computes the overall trust of a revision
where the word trust has a histogram [th]. *)
let compute_overall_trust (th: int array) : float =
First , computes the quality content of a revision .
let qual_content = ref 0. in
let f i x = qual_content := !qual_content +. (float_of_int (x * i)) in
Array.iteri f th;
(* Then, computes a reduction factor due to low-quality words. *)
let total_reduction = ref 0. in
let f i x = total_reduction := !total_reduction +.
(float_of_int x) /. (2. ** (float_of_int i)) in
Array.iteri f th;
Puts the two together
!qual_content *. exp (0. -. Online_types.coeff_spam_reduction *. !total_reduction)
* [ compute_trust_histogram trust_a ] computes the trust histogram of a page
with an array [ trust_a ] of trust values .
The histogram is a 10 - integer array , where the entry with index i
specifies how many words have trust t with i < = t < i+1 .
with an array [trust_a] of trust values.
The histogram is a 10-integer array, where the entry with index i
specifies how many words have trust t with i <= t < i+1. *)
let compute_trust_histogram (trust_a: float array) : int array =
let histogram = Array.make 10 0 in
let l = Array.length trust_a in
for i = 0 to l - 1 do begin
let idx = max 0 (min 9 (int_of_float (trust_a.(i) +. 0.5))) in
histogram.(idx) <- histogram.(idx) + 1
end done;
histogram
| null | https://raw.githubusercontent.com/collaborativetrust/WikiTrust/9dd056e65c37a22f67d600dd1e87753aa0ec9e2c/analysis/compute_robust_trust.ml | ocaml | * The functions in this module are used to compute the trust of the
words of a revision, taking into account the "locality effect" of
the attention of the revisor.
The computation uses a robust method, that includes the consideration
of author signatures.
Produces the new trust array
Produces the new signature array
We need to have the conversion from words to seps, and the seps,
for the current revision.
This array contains, for each word, the number of the sectional unit
to which the word belongs.
Initializes section_of_word
Syntax breaks, no word increase
Syntax break before, word increase
Syntax break after, word increase
No syntax break, word increase
No syntax break, no word increase
[spread_look n] marks the array looked_at so that all the syntactic unit
(paragraph, itemization point) of [n] is labeled true.
Spreads upward
Spreads downwards
if not looked_at.(n)
end of spread_look
If the cut starts at 0, then it has been re-arranged, since the
0 to 0 case is taken care by the caller
If the sectional unit has not changed, we do not need to
figure out what is the type of the previous block
(inserted/moved), we mark it anyway
The previous block is in a different sectional unit. Checks
whether it is an insert.
end of mark_begin_cut
This function is analogous to mark_begin_cut, but for the end of
the cut
If the cut starts at 0, then it has been re-arranged, since the
0 to 0 case is taken care by the caller
If the sectional unit has not changed, we do not need to
figure out what is the type of the previous block
(inserted/moved), we mark it anyway
The previous block is in a different sectional unit. Checks
whether it is an insert.
it is an insert
This is a trust bonus that the fresh text is awarded.
Note that in any case, this value undergoes the trust increase
due to both reading the section where the text is inserted, and
reading the whole page.
Now, goes over medit_l via f, and fills in new_chunks_trust_a and
the new signatures properly.
This is text added in the current version
Credits the reputation range for the current text
new_chunks_canincrease_a.(0).(i) <- true;
true is
the default
Checks whether the text is live in the new version
It is live text
trust
This is the word under consideration
Packed signature of the word
This encodes the all-important logic that decides
whether a user can increase the trust of a word. The
user has to be not anonymous, and not present in the
signature.
Then, applies corrective effects.
Processes the beginning
Spreads the information that the author looked at
this chunk of text.
Now computes the correction to the trust from the
beginning of the cut block
Changes the trust of this word
Cut points are discontinuities, and they inherit
trust from the author.
Moves, but not beyond a sectional boundary
processes the end
Spreads the information that the author looked at
this chunk of text.
Computes the correction from the end of the cut block
Changes the trust of this word
Cut points are discontinuities, and they inherit
trust from the author.
Moves, but not beyond a sectional boundary
dst_chunk_idx > 0, and the text is dead
Then, copies the signature
... and then backwards
Uses spread_looked_at to increase the quality of text due to revision.
Here I know that new_trust > old_trust
Now there is the last of the effects that affect text trust: We
give a little bit of prize to all the text, according to the
reputation of the author who has made the last edit.
Here I know that new_trust > old_trust
If the author can increase the reputation, because it does
not appear in the signature, it increases it.
The author cannot perform a normal reputation increase,
because it appears in the signatures. Nevertheless, it is
still reasonable to ensure that the text has at least the
same trust as freshly created text by the same author.
As the signature is already present, we do not re-add it,
so we do not set new_chunks_hasincreased_a.(0).(i) <- true
Now adds the signature to all places where the trust has increased
Returns the new trust
Creates the chunks for origin and authors with defaults.
Now, goes over medit_l, and fills in new_chunks_origin_a properly.
* [compute_overall_trust th] computes the overall trust of a revision
where the word trust has a histogram [th].
Then, computes a reduction factor due to low-quality words. |
Copyright ( c ) 2007 - 2009 The Regents of the University of California
All rights reserved .
Authors :
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
1 . Redistributions of source code must retain the above copyright notice ,
this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright notice ,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution .
3 . The names of the contributors may not 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 OWNER OR
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 , 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 .
Copyright (c) 2007-2009 The Regents of the University of California
All rights reserved.
Authors: Luca de Alfaro
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The names of the contributors may not 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 OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
type word = string
open Eval_defs
* [ compute_trust_chunks chunks_trust_a new_chunks_a new_seps medit_l
rep_float trust_coeff ... ] computes the new word trust values of
the revision with chunks [ new_chunks_a ] , obtained from the version
with word trust values [ chunks_trust_a ] via the edit list
[ medit_l ] . [ new_seps ] are the new seps of the latest
revision . [ rep_float ] is the reputation of the author of the new
revision . What is new about this method , compared to the
classical compute_word_trust one , is that this one takes into
account syntactical units to spread the trust . The
trust_coeff _ ... parameters are for trust computation .
rep_float trust_coeff...] computes the new word trust values of
the revision with chunks [new_chunks_a], obtained from the version
with word trust values [chunks_trust_a] via the edit list
[medit_l]. [new_seps] are the new seps of the latest
revision. [rep_float] is the reputation of the author of the new
revision. What is new about this method, compared to the
classical compute_word_trust one, is that this one takes into
account syntactical units to spread the trust. The
trust_coeff_... parameters are for trust computation. *)
let compute_robust_trust
(chunks_trust_a: float array array)
(chunks_authorsig_a: Author_sig.packed_author_signature_t array array)
(new_chunks_a: word array array)
(new_seps: Text.sep_t array)
(medit_l: Editlist.medit list)
(rep_float: float)
(user_id: int)
(trust_coeff_lends_rep: float)
(trust_coeff_kill_decrease: float)
(trust_coeff_cut_rep_radius: float)
(trust_coeff_read_all: float)
(trust_coeff_read_part: float)
(trust_coeff_local_decay: float)
: (float array array * Author_sig.packed_author_signature_t array array) =
let f x = Array.make (Array.length x) 0.0 in
let new_chunks_trust_a = Array.map f new_chunks_a in
let old_live_len = Array.length chunks_trust_a.(0) in
let new_live_len = Array.length new_chunks_a.(0) in
let f x = Array.make (Array.length x) Author_sig.empty_sigs in
let new_chunks_authorsig_a = Array.map f new_chunks_a in
Produces two auxiliary arrays : one keeps track of whether the author can
increase the trust of a word , the second keeps track of whether the author
has increased the trust of a word . These are just filled with default
values initially .
increase the trust of a word, the second keeps track of whether the author
has increased the trust of a word. These are just filled with default
values initially. *)
let f x = Array.make (Array.length x) true in
let new_chunks_canincrease_a = Array.map f new_chunks_a in
let f x = Array.make (Array.length x) false in
let new_chunks_hasincreased_a = Array.map f new_chunks_a in
This array keeps track of the syntactic units that have been checked
by the author . It contains one bool per word , which indicates whether
the author is likely to have read the word or not .
by the author. It contains one bool per word, which indicates whether
the author is likely to have read the word or not. *)
let looked_at = Array.make new_live_len false in
let seps = new_seps in
let section_of_word = Array.make new_live_len 0 in
let n_seps = Array.length seps in
let n_section = ref 0 in
for i = 0 to n_seps - 1 do begin
match seps.(i) with
Text.Par_break _ ->
n_section := !n_section + 1
| Text.Title_start (_, k) | Text.Bullet (_, k) | Text.Table_cell (_, k)
| Text.Table_line (_, k) | Text.Table_caption (_,k) | Text.Indent (_, k) -> begin
n_section := !n_section + 1;
section_of_word.(k) <- !n_section
end
| Text.Title_end (_, k) -> begin
section_of_word.(k) <- !n_section;
n_section := !n_section + 1
end
| Text.Tag (_, k) | Text.Word (_, k) | Text.Redirect (_, k)
| Text.Armored_char (_, k) ->
section_of_word.(k) <- !n_section
| Text.Space _ | Text.Newline _ -> ()
end done;
let spread_look (n: int) : unit =
if not looked_at.(n) then begin
let word_idx = ref n in
let fatto = ref false in
while not !fatto do begin
looked_at.(!word_idx) <- true;
if !word_idx = new_live_len - 1
then fatto := true
else begin
word_idx := !word_idx + 1;
fatto := looked_at.(!word_idx) || section_of_word.(!word_idx - 1) <> section_of_word.(!word_idx)
end
end done;
let word_idx = ref n in
let fatto = ref false in
while not !fatto do begin
looked_at.(!word_idx) <- true;
if !word_idx = 0
then fatto := true
else begin
word_idx := !word_idx - 1;
fatto := looked_at.(!word_idx) || section_of_word.(!word_idx + 1) <> section_of_word.(!word_idx)
end
end done
This function is used to determine whether the beginning of a move ,
that begins at position k , should be marked in trust .
The rule is :
- text moved from the beginning to the beginning is not marked
( this is taken care by the caller )
- if the previous text has been inserted , and belongs to a
different section , and is of length
at least 2 , the cut is not marked . The length 2 requirement
is used to ensure that the coloring will be visible .
- otherwise , it is marked . Thus , text after an insertion in
the same sectional unit , and text
that has been rearranged , is marked .
that begins at position k, should be marked in trust.
The rule is:
- text moved from the beginning to the beginning is not marked
(this is taken care by the caller)
- if the previous text has been inserted, and belongs to a
different section, and is of length
at least 2, the cut is not marked. The length 2 requirement
is used to ensure that the coloring will be visible.
- otherwise, it is marked. Thus, text after an insertion in
the same sectional unit, and text
that has been rearranged, is marked. *)
let mark_begin_cut (n: int): bool =
if n = 0 then true
else if section_of_word.(n) = section_of_word.(n - 1) then true
else begin
let rec is_moved = function
[] -> true
| Editlist.Mins (word_idx, l) :: rest ->
if word_idx + l = n then l < 2 else is_moved rest
| Editlist.Mmov (src_word_idx, src_chunk_idx, dst_word_idx, dst_chunk_idx, l) :: rest ->
if dst_chunk_idx = 0 && dst_word_idx + l = n
then true
else is_moved rest
| _ :: rest -> is_moved rest
in is_moved medit_l
end
let mark_end_cut (n: int): bool =
if n = new_live_len - 1 then true
else if section_of_word.(n) = section_of_word.(n + 1) then true
else begin
let rec is_moved = function
[] -> true
| Editlist.Mins (word_idx, l) :: rest ->
if word_idx - 1 = n
else is_moved rest
| Editlist.Mmov (src_word_idx, src_chunk_idx, dst_word_idx, dst_chunk_idx, l) :: rest ->
if dst_chunk_idx = 0 && dst_word_idx - 1 = n
then true
else is_moved rest
| _ :: rest -> is_moved rest
in is_moved medit_l
end
end of mark_end_cut
let new_text_trust = rep_float *. trust_coeff_lends_rep in
let f = function
Editlist.Mins (word_idx, l) -> begin
for i = word_idx to word_idx + l - 1 do begin
new_chunks_trust_a.(0).(i) <- new_text_trust;
looked_at.(i) <- true;
new_chunks_hasincreased_a.(0).(i) <- true;
end done;
One generally looks in the whole syntactic unit where one
is editing
is editing *)
spread_look word_idx;
spread_look (word_idx + l - 1)
end
| Editlist.Mmov (src_word_idx, src_chunk_idx, dst_word_idx, dst_chunk_idx, l) -> begin
if dst_chunk_idx = 0 then begin
First , copies the trust and signatures
for i = 0 to l - 1 do begin
let trust = chunks_trust_a.(src_chunk_idx).(src_word_idx + i) in
new_chunks_trust_a.(0).(dst_word_idx + i) <- trust;
let w = new_chunks_a.(0).(dst_word_idx + i) in
let hsig = chunks_authorsig_a.(src_chunk_idx).(src_word_idx + i) in
new_chunks_authorsig_a.(0).(dst_word_idx + i) <- hsig;
new_chunks_canincrease_a.(0).(dst_word_idx + i) <-
(user_id <> 0) && not (Author_sig.is_author_in_sigs user_id w hsig);
new_chunks_hasincreased_a.(0).(dst_word_idx + i) <- false;
end done;
The first corrective effect is the fact that , at cut
places , the text becomes of trust equal to the reputation
of the author multiplied by a scaling effect . The
scaling effect is there so that even high - reputation
authors can not single - handedly create trusted content ;
revisions are always needed .
places, the text becomes of trust equal to the reputation
of the author multiplied by a scaling effect. The
scaling effect is there so that even high-reputation
authors cannot single-handedly create trusted content;
revisions are always needed. *)
if (src_word_idx <> 0 || dst_word_idx <> 0 || src_chunk_idx <> 0)
&& (mark_begin_cut dst_word_idx) then begin
spread_look dst_word_idx;
let word_idx = ref dst_word_idx in
let fatto = ref false in
while not !fatto do begin
let d = !word_idx - dst_word_idx in
let old_trust = new_chunks_trust_a.(0).(!word_idx) in
let new_trust = old_trust +.
(new_text_trust -. old_trust) *. exp (-. (float_of_int d) /. trust_coeff_cut_rep_radius) in
if new_trust <= old_trust then begin
new_chunks_trust_a.(0).(!word_idx) <- new_trust;
end;
if new_trust > old_trust && new_chunks_canincrease_a.(0).(!word_idx) then begin
new_chunks_trust_a.(0).(!word_idx) <- new_trust;
new_chunks_hasincreased_a.(0).(!word_idx) <- true;
end;
if !word_idx = dst_word_idx + l - 1
then fatto := true
else begin
word_idx := !word_idx + 1;
fatto := section_of_word.(!word_idx - 1) <> section_of_word.(!word_idx)
end
end done
end;
if (src_word_idx + l <> old_live_len || dst_word_idx + l <> new_live_len || src_chunk_idx <> 0)
&& (mark_end_cut (dst_word_idx + l - 1)) then begin
spread_look (dst_word_idx + l - 1);
let word_idx = ref (dst_word_idx + l - 1) in
let fatto = ref false in
while not !fatto do begin
let d = (dst_word_idx + l - 1) - !word_idx in
let old_trust = new_chunks_trust_a.(0).(!word_idx) in
let new_trust = old_trust +.
(new_text_trust -. old_trust) *. exp (-. (float_of_int d) /. trust_coeff_cut_rep_radius) in
if new_trust <= old_trust then begin
new_chunks_trust_a.(0).(!word_idx) <- new_trust;
end;
if new_trust > old_trust && new_chunks_canincrease_a.(0).(!word_idx) then begin
new_chunks_trust_a.(0).(!word_idx) <- new_trust;
new_chunks_hasincreased_a.(0).(!word_idx) <- true;
end;
if !word_idx = dst_word_idx
then fatto := true
else begin
word_idx := !word_idx - 1;
fatto := section_of_word.(!word_idx + 1) <> section_of_word.(!word_idx)
end
end done
end
end else begin
for i = 0 to l - 1 do begin
First , copies the trust
let old_trust = chunks_trust_a.(src_chunk_idx).(src_word_idx + i) in
let new_trust =
if src_chunk_idx = 0
then old_trust *. exp (-. rep_float *. trust_coeff_kill_decrease)
else old_trust
in
new_chunks_trust_a.(dst_chunk_idx).(dst_word_idx + i) <- new_trust;
let hsig = chunks_authorsig_a.(src_chunk_idx).(src_word_idx + i) in
new_chunks_canincrease_a.(dst_chunk_idx).(dst_word_idx + i) <- false;
new_chunks_authorsig_a.(dst_chunk_idx).(dst_word_idx + i) <- hsig;
end done
end
end
| Editlist.Mdel _ -> ()
in
List.iter f medit_l;
Spreads looked_at according to trust_coeff_local_decay , first
forward ...
forward ... *)
let spread_looked_at = Array.make new_live_len 0.0 in
let spread = ref 0.0 in
for i = 0 to new_live_len - 1 do begin
if looked_at.(i) then spread := 1.0 else spread := !spread *. trust_coeff_local_decay;
spread_looked_at.(i) <- !spread
end done;
let spread = ref 0.0 in
for i = new_live_len - 1 downto 0 do begin
if looked_at.(i) then spread := 1.0 else spread := !spread *. trust_coeff_local_decay;
spread_looked_at.(i) <- spread_looked_at.(i) +. (1.0 -. spread_looked_at.(i)) *. trust_coeff_local_decay
end done;
for i = 0 to new_live_len - 1 do begin
let old_trust = new_chunks_trust_a.(0).(i) in
if old_trust < rep_float then
let new_trust = old_trust +.
(rep_float -. old_trust) *. trust_coeff_read_part *. spread_looked_at.(i) in
if new_chunks_canincrease_a.(0).(i) then begin
new_chunks_trust_a.(0).(i) <- new_trust;
new_chunks_hasincreased_a.(0).(i) <- true;
end
end done;
let len0 = Array.length new_chunks_trust_a.(0) in
for i = 0 to len0 - 1 do begin
let old_trust = new_chunks_trust_a.(0).(i) in
if rep_float > old_trust then begin
let increased_trust = old_trust +. (rep_float -. old_trust) *. trust_coeff_read_all in
if new_chunks_canincrease_a.(0).(i) then begin
new_chunks_trust_a.(0).(i) <- increased_trust;
new_chunks_hasincreased_a.(0).(i) <- true;
end else begin
if old_trust < new_text_trust then begin
new_chunks_trust_a.(0).(i) <- new_text_trust;
end
end
end
end done;
for i = 0 to len0 - 1 do begin
if new_chunks_hasincreased_a.(0).(i) then
let w = new_chunks_a.(0).(i) in
let old_sig = new_chunks_authorsig_a.(0).(i) in
new_chunks_authorsig_a.(0).(i) <- Author_sig.add_author user_id w old_sig
end done;
(new_chunks_trust_a, new_chunks_authorsig_a)
* [ compute_origin chunks_origin_a new_chunks_a medit_l revid author_name ]
computes the origin of the text in the chunks [ new_chunks_a ] ,
belonging to a revision with i d [ revid ] written by a user with
name [ author_name ] . [ medit_l ] is the edit list explaining the
change from previous to current revision .
The information on origin and authors of the old text is given
in [ chunks_origin_a ] and [ chunks_author_a ] , respectively .
The function returns a pair [ new_origin_a , ] ,
describing the new origin and author .
computes the origin of the text in the chunks [new_chunks_a],
belonging to a revision with id [revid] written by a user with
name [author_name]. [medit_l] is the edit list explaining the
change from previous to current revision.
The information on origin and authors of the old text is given
in [chunks_origin_a] and [chunks_author_a], respectively.
The function returns a pair [new_origin_a, new_author_a],
describing the new origin and author. *)
let compute_origin
(chunks_origin_a: int array array)
(chunks_author_a: string array array)
(new_chunks_a: word array array)
(medit_l: Editlist.medit list)
(revid: int)
(author_name: string): (int array array * string array array) =
let f x = Array.make (Array.length x) 0 in
let new_chunks_origin_a = Array.map f new_chunks_a in
let f x = Array.make (Array.length x) "" in
let new_chunks_author_a = Array.map f new_chunks_a in
let f = function
Editlist.Mins (word_idx, l) -> begin
for i = word_idx to word_idx + l - 1 do begin
new_chunks_origin_a.(0).(i) <- revid;
new_chunks_author_a.(0).(i) <- author_name
end done
end
| Editlist.Mmov (src_word_idx, src_chunk_idx, dst_word_idx, dst_chunk_idx, l) -> begin
for i = 0 to l - 1 do begin
new_chunks_origin_a.(dst_chunk_idx).(dst_word_idx + i) <-
chunks_origin_a.(src_chunk_idx).(src_word_idx + i);
new_chunks_author_a.(dst_chunk_idx).(dst_word_idx + i) <-
chunks_author_a.(src_chunk_idx).(src_word_idx + i);
end done
end
| _ -> ()
in
List.iter f medit_l;
(new_chunks_origin_a, new_chunks_author_a)
let compute_overall_trust (th: int array) : float =
First , computes the quality content of a revision .
let qual_content = ref 0. in
let f i x = qual_content := !qual_content +. (float_of_int (x * i)) in
Array.iteri f th;
let total_reduction = ref 0. in
let f i x = total_reduction := !total_reduction +.
(float_of_int x) /. (2. ** (float_of_int i)) in
Array.iteri f th;
Puts the two together
!qual_content *. exp (0. -. Online_types.coeff_spam_reduction *. !total_reduction)
* [ compute_trust_histogram trust_a ] computes the trust histogram of a page
with an array [ trust_a ] of trust values .
The histogram is a 10 - integer array , where the entry with index i
specifies how many words have trust t with i < = t < i+1 .
with an array [trust_a] of trust values.
The histogram is a 10-integer array, where the entry with index i
specifies how many words have trust t with i <= t < i+1. *)
let compute_trust_histogram (trust_a: float array) : int array =
let histogram = Array.make 10 0 in
let l = Array.length trust_a in
for i = 0 to l - 1 do begin
let idx = max 0 (min 9 (int_of_float (trust_a.(i) +. 0.5))) in
histogram.(idx) <- histogram.(idx) + 1
end done;
histogram
|
285f4461ab96c52873a68d6b21443b5dfe2b5e7d28a94a1320c35da7ce2036eb | aztek/tptp | Text.hs | -- |
-- Module : Data.TPTP.Parse.Text
Description : An attoparsec - based parser for the TPTP language .
Copyright : ( c ) , 2019 - 2021
-- License : GPL-3
Maintainer :
-- Stability : experimental
--
module Data.TPTP.Parse.Text (
* Runners of parsers for TPTP units
parseUnit,
parseUnitOnly,
parseUnitWith,
* Runners of parsers for TPTP inputs
parseTPTP,
parseTPTPOnly,
parseTPTPWith,
-- * Runners of parsers for TSTP inputs
parseTSTP,
parseTSTPOnly,
parseTSTPWith,
) where
import Data.Attoparsec.Text (Result, parse, parseOnly, parseWith)
import Data.Text (Text)
import Data.TPTP (Unit, TPTP, TSTP)
import Data.TPTP.Parse.Combinators (input, unit, tptp, tstp)
| Run a parser for a single TPTP unit on ' Text ' .
parseUnit :: Text -> Result Unit
parseUnit = parse (input unit)
| Run a parser for a single TPTP unit that can not be resupplied
via a ' Data . . Text . Partial ' result .
parseUnitOnly :: Text -> Either String Unit
parseUnitOnly = parseOnly (input unit)
| Run a parser for a single TPTP unit with an initial input string ,
-- and a monadic action that can supply more input if needed.
parseUnitWith :: Monad m => m Text -> Text -> m (Result Unit)
parseUnitWith m = parseWith m (input unit)
-- | Run a parser for a TPTP input on 'Text'.
parseTPTP :: Text -> Result TPTP
parseTPTP = parse (input tptp)
-- | Run a parser for a TPTP input that cannot be resupplied
via a ' Data . . Text . Partial ' result .
parseTPTPOnly :: Text -> Either String TPTP
parseTPTPOnly = parseOnly (input tptp)
-- | Run a parser for a TPTP input with an initial input string,
-- and a monadic action that can supply more input if needed.
parseTPTPWith :: Monad m => m Text -> Text -> m (Result TPTP)
parseTPTPWith m = parseWith m (input tptp)
-- | Run a parser for a TSTP input on 'Text'.
parseTSTP :: Text -> Result TSTP
parseTSTP = parse tstp
-- | Run a parser for a TSTP input that cannot be resupplied
via a ' Data . . Text . Partial ' result .
parseTSTPOnly :: Text -> Either String TSTP
parseTSTPOnly = parseOnly tstp
-- | Run a parser for a TSTP input with an initial input string,
-- and a monadic action that can supply more input if needed.
parseTSTPWith :: Monad m => m Text -> Text -> m (Result TSTP)
parseTSTPWith m = parseWith m tstp
| null | https://raw.githubusercontent.com/aztek/tptp/7b850b5680debcf2f9245a328102c4aadcb6da2c/src/Data/TPTP/Parse/Text.hs | haskell | |
Module : Data.TPTP.Parse.Text
License : GPL-3
Stability : experimental
* Runners of parsers for TSTP inputs
and a monadic action that can supply more input if needed.
| Run a parser for a TPTP input on 'Text'.
| Run a parser for a TPTP input that cannot be resupplied
| Run a parser for a TPTP input with an initial input string,
and a monadic action that can supply more input if needed.
| Run a parser for a TSTP input on 'Text'.
| Run a parser for a TSTP input that cannot be resupplied
| Run a parser for a TSTP input with an initial input string,
and a monadic action that can supply more input if needed. | Description : An attoparsec - based parser for the TPTP language .
Copyright : ( c ) , 2019 - 2021
Maintainer :
module Data.TPTP.Parse.Text (
* Runners of parsers for TPTP units
parseUnit,
parseUnitOnly,
parseUnitWith,
* Runners of parsers for TPTP inputs
parseTPTP,
parseTPTPOnly,
parseTPTPWith,
parseTSTP,
parseTSTPOnly,
parseTSTPWith,
) where
import Data.Attoparsec.Text (Result, parse, parseOnly, parseWith)
import Data.Text (Text)
import Data.TPTP (Unit, TPTP, TSTP)
import Data.TPTP.Parse.Combinators (input, unit, tptp, tstp)
| Run a parser for a single TPTP unit on ' Text ' .
parseUnit :: Text -> Result Unit
parseUnit = parse (input unit)
| Run a parser for a single TPTP unit that can not be resupplied
via a ' Data . . Text . Partial ' result .
parseUnitOnly :: Text -> Either String Unit
parseUnitOnly = parseOnly (input unit)
| Run a parser for a single TPTP unit with an initial input string ,
parseUnitWith :: Monad m => m Text -> Text -> m (Result Unit)
parseUnitWith m = parseWith m (input unit)
parseTPTP :: Text -> Result TPTP
parseTPTP = parse (input tptp)
via a ' Data . . Text . Partial ' result .
parseTPTPOnly :: Text -> Either String TPTP
parseTPTPOnly = parseOnly (input tptp)
parseTPTPWith :: Monad m => m Text -> Text -> m (Result TPTP)
parseTPTPWith m = parseWith m (input tptp)
parseTSTP :: Text -> Result TSTP
parseTSTP = parse tstp
via a ' Data . . Text . Partial ' result .
parseTSTPOnly :: Text -> Either String TSTP
parseTSTPOnly = parseOnly tstp
parseTSTPWith :: Monad m => m Text -> Text -> m (Result TSTP)
parseTSTPWith m = parseWith m tstp
|
f6adf5df833305de8f385a9037f8a567b3cb86d22c5489d2d6cf9674b87ecd59 | Decentralized-Pictures/T4L3NT | test_consensus_filter.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Nomadic Labs , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Lib_test.Qcheck_helpers
open Plugin.Mempool
open Alpha_context
let config drift_opt =
{
default_config with
clock_drift =
Option.map
(fun drift -> Period.of_seconds_exn (Int64.of_int drift))
drift_opt;
}
type Environment.Error_monad.error += Generation_failure
(** Conversion helpers *)
let int32_of_timestamp ts =
let i64 = Timestamp.to_seconds ts in
let i32 = Int64.to_int32 i64 in
if Int64.(equal (of_int32 i32) i64) then Ok i32
else Environment.Error_monad.error Generation_failure
let int32_of_timestamp_exn ts =
match int32_of_timestamp ts with
| Ok i32 -> i32
| Error _err -> Stdlib.failwith "int32_of_timestamp_exn: number too big"
let timestamp_of_int32 ts = Timestamp.of_seconds (Int64.of_int32 ts)
(** Data Generators *)
module Generator = struct
open QCheck
let decorate ?(prefix = "") ?(suffix = "") printer gen =
set_print (fun d -> prefix ^ printer d ^ suffix) gen
let config =
decorate ~prefix:"clock_drift " (fun config ->
Option.fold
~none:"round_0 duration"
~some:(fun drift -> Int64.to_string @@ Period.to_seconds drift)
config.clock_drift)
@@ map
~rev:(fun {clock_drift; _} ->
Option.map
(fun drift -> Int64.to_int @@ Period.to_seconds drift)
clock_drift)
config
(option small_nat)
let of_error_arb gen =
of_option_arb
@@ map
~rev:(function
| Some x -> Ok x
| None -> Environment.Error_monad.error Generation_failure)
(function Ok x -> Some x | Error _err -> None)
gen
let small_nat_32 ?prefix ?suffix () =
decorate ?prefix ?suffix Int32.to_string
@@ map ~rev:Int32.to_int Int32.of_int small_nat
let small_signed_32 ?prefix ?suffix () =
decorate ?prefix ?suffix Int32.to_string
@@ map ~rev:Int32.to_int Int32.of_int small_signed_int
let decorated_small_nat ?prefix ?suffix () =
decorate ?prefix ?suffix string_of_int small_nat
let dup gen = map ~rev:fst (fun x -> (x, x)) gen
let round =
of_error_arb
@@ map
~rev:(function Ok l -> Round.to_int32 l | Error _ -> -1l)
(fun i32 -> Round.of_int32 i32)
(small_nat_32 ~prefix:"rnd " ())
let same_rounds = dup round
let level =
of_error_arb
@@ map
~rev:(function Ok l -> Raw_level.to_int32 l | Error _ -> -1l)
Raw_level.of_int32
(small_nat_32 ~prefix:"lev " ())
let same_levels = dup level
let timestamp =
set_print Timestamp.to_notation
@@ map ~rev:int32_of_timestamp_exn (fun f -> timestamp_of_int32 f) int32
let near_timestamps =
map
~rev:(fun (ts1, ts2) ->
let its1 = int32_of_timestamp_exn ts1 in
let its2 = int32_of_timestamp_exn ts2 in
Int32.(its1, sub its2 its1))
(fun (i, diff) ->
timestamp_of_int32 i |> fun ts1 ->
timestamp_of_int32 Int32.(add i diff) |> fun ts2 -> (ts1, ts2))
(pair int32 (small_signed_32 ~prefix:"+" ~suffix:"sec." ()))
let dummy_timestamp =
match Timestamp.of_seconds_string "0" with
| Some ts -> ts
| _ -> assert false
let unsafe_sub ts1 ts2 =
Int64.to_int @@ Period.to_seconds
@@
match Timestamp.(ts1 -? ts2) with
| Ok diff -> diff
| Error _ -> assert false
let successive_timestamp =
of_error_arb
@@ map
~rev:(function
| Ok (ts1, ts2) -> (ts1, unsafe_sub ts2 ts1)
| Error _ -> (dummy_timestamp, -1))
(fun (ts, (diff : int)) ->
Period.of_seconds (Int64.of_int diff) >>? fun diff ->
Timestamp.(ts +? diff) >>? fun ts2 -> Ok (ts, ts2))
(pair timestamp (decorated_small_nat ~prefix:"+" ~suffix:"sec." ()))
let param_acceptable ?(rounds = pair round round) ?(levels = pair level level)
?(timestamps = near_timestamps) () =
pair config (pair (pair rounds levels) timestamps)
end
let assert_no_error d = match d with Error _ -> assert false | Ok d -> d
(** Constants :
This could be generated but it would largely increase the search space. *)
let round_durations : Round.round_durations =
assert_no_error
@@ Round.Durations.create
~first_round_duration:Period.(of_seconds_exn 4L)
~delay_increment_per_round:Period.(of_seconds_exn 10L)
let round_zero_duration = Round.round_duration round_durations Round.zero
(** Don't allow test to fail *)
let no_error = function
| Ok b -> b
| Error errs ->
Format.printf
"test fail due to error : %a@."
Error_monad.pp_print_trace
(Environment.wrap_tztrace errs) ;
false
(** Helper to compute *)
let durations round_durations start stop =
List.map_e
(fun round ->
Round.of_int round >|? fun round ->
Round.round_duration round_durations round |> Period.to_seconds)
Tezos_stdlib.Utils.Infix.(start -- stop)
(** Expected timestamp for the begining of a round at same level that
the proposal.
It has been developped before the Round.timestamp_of_round_same_level and has a
different implementation.
*)
let timestamp_of_round round_durations ~proposal_timestamp ~proposal_round
~round =
(let iproposal_round = Int32.to_int @@ Round.to_int32 proposal_round in
let iround = Int32.to_int @@ Round.to_int32 round in
if Round.(proposal_round = round) then ok (Period.zero, proposal_timestamp)
else if Round.(proposal_round < round) then
durations round_durations iproposal_round (iround - 1) >>? fun durations ->
Period.of_seconds @@ List.fold_left Int64.add Int64.zero durations
>>? fun rounds_duration ->
Timestamp.(proposal_timestamp +? rounds_duration) >|? fun ts ->
(rounds_duration, ts)
else
durations round_durations iround (iproposal_round - 1) >>? fun durations ->
List.fold_left Int64.add Int64.zero durations |> fun rounds_duration ->
Timestamp.of_seconds
@@ Int64.sub (Timestamp.to_seconds proposal_timestamp) rounds_duration
|> fun ts ->
Period.of_seconds rounds_duration >|? fun rounds_duration ->
(rounds_duration, ts))
>>? fun (_rnd_dur, exp_ts) -> ok exp_ts
let drift_of =
let r0_dur = Round.round_duration round_durations Round.zero in
fun clock_drift -> Option.value ~default:r0_dur clock_drift
(** [max_ts] computes the upper bound on future timestamps given the
accepted round drift.
*)
let max_ts clock_drift prop_ts now =
Timestamp.(max prop_ts now +? drift_of clock_drift)
let count = None
let predecessor_start proposal_timestamp proposal_round grandparent_round =
assert_no_error
@@ ( Round.level_offset_of_round
round_durations
~round:Round.(succ grandparent_round)
>>? fun proposal_level_offset ->
Round.level_offset_of_round round_durations ~round:proposal_round
>>? fun proposal_round_offset ->
Period.(add proposal_level_offset proposal_round_offset)
>>? fun proposal_offset ->
Ok Timestamp.(proposal_timestamp - proposal_offset) )
(** TESTS *)
(** Test past operations that are accepted whatever the current timestamp is:
strictly before the predecessor level or at the current level and with a
strictly lower round than the head. *)
let test_acceptable_past_level =
QCheck.Test.make
~name:"acceptable past op "
(Generator.param_acceptable ())
(fun
( config,
( ((proposal_round, op_round), (proposal_level, op_level)),
(proposal_timestamp, now_timestamp) ) )
->
QCheck.(
Raw_level.(
proposal_level > succ op_level
|| (proposal_level = op_level && Round.(proposal_round > op_round)))
==> no_error
@@ acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start
proposal_timestamp
proposal_round
Round.zero)
~op_level
~op_round
~now_timestamp))
(** Test acceptable operations at current level, current round, i.e. on the
currently considered proposal *)
let test_acceptable_current_level_current_round =
let open QCheck in
Test.make
?count
~name:"same round, same level "
Generator.(param_acceptable ~rounds:same_rounds ~levels:same_levels ())
(fun ( config,
(((op_round, _), (_, op_level)), (proposal_timestamp, now_timestamp))
) ->
let proposal_level = op_level in
let proposal_round = op_round in
no_error
@@ acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start proposal_timestamp proposal_round Round.zero)
~op_level
~op_round
~now_timestamp)
(** Test operations at same level, different round, with an acceptable expected
timestamp for the operation. *)
let test_acceptable_current_level =
let open QCheck in
Test.make
?count
~name:"same level, different round, acceptable op"
Generator.(param_acceptable ~levels:same_levels ())
(fun ( config,
( ((proposal_round, op_round), (_, op_level)),
(proposal_timestamp, now_timestamp) ) ) ->
let proposal_level = op_level in
no_error
( timestamp_of_round
round_durations
~proposal_timestamp
~proposal_round
~round:op_round
>>? fun expected_time ->
max_ts config.clock_drift proposal_timestamp now_timestamp
>>? fun max_timestamp -> ok Timestamp.(expected_time <= max_timestamp)
)
==> no_error
@@ acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start
proposal_timestamp
proposal_round
Round.zero)
~op_level
~op_round
~now_timestamp)
(** Test operations at same level, different round, with a too high expected
timestamp for the operation, and not at current round (which is always accepted). *)
let test_not_acceptable_current_level =
let open QCheck in
Test.make
?count
~name:"same level, different round, too far"
Generator.(param_acceptable ~levels:same_levels ())
(fun ( config,
( ((proposal_round, op_round), (_, op_level)),
(proposal_timestamp, now_timestamp) ) ) ->
let proposal_level = op_level in
no_error
( timestamp_of_round
round_durations
~proposal_timestamp
~proposal_round
~round:op_round
>>? fun expected_time ->
max_ts config.clock_drift proposal_timestamp now_timestamp
>>? fun max_timestamp ->
ok
Timestamp.(
expected_time > max_timestamp
&& Round.(proposal_round <> op_round)) )
==> no_error
(acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start
proposal_timestamp
proposal_round
Round.zero)
~op_level
~op_round
~now_timestamp
>|? not))
(** Test operations at next level, different round, with an acceptable timestamp for
the operation. *)
let test_acceptable_next_level =
let open QCheck in
Test.make
?count
~name:"next level, acceptable op"
Generator.(param_acceptable ~levels:same_levels ())
(fun ( config,
( ((proposal_round, op_round), (proposal_level, _)),
(proposal_timestamp, now_timestamp) ) ) ->
let op_level = Raw_level.succ proposal_level in
no_error
( timestamp_of_round
round_durations
~proposal_timestamp
~proposal_round
~round:Round.zero
>>? fun current_level_start ->
Round.timestamp_of_round
round_durations
~predecessor_timestamp:current_level_start
~predecessor_round:Round.zero
~round:op_round
>>? fun expected_time ->
max_ts config.clock_drift proposal_timestamp now_timestamp
>>? fun max_timestamp -> ok Timestamp.(expected_time <= max_timestamp)
)
==> no_error
@@ acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start
proposal_timestamp
proposal_round
Round.zero)
~op_level
~op_round
~now_timestamp)
(** Test operations at next level, different round, with a too high timestamp
for the operation. *)
let test_not_acceptable_next_level =
let open QCheck in
Test.make
?count
~name:"next level, too far"
Generator.(
param_acceptable ~levels:same_levels ~timestamps:successive_timestamp ())
(fun ( config,
( ((proposal_round, op_round), (proposal_level, _)),
(proposal_timestamp, now_timestamp) ) ) ->
let op_level = Raw_level.succ proposal_level in
QCheck.assume
@@ no_error
( timestamp_of_round
round_durations
~proposal_timestamp
~proposal_round
~round:Round.zero
>>? fun current_level_start ->
Round.timestamp_of_round
round_durations
~predecessor_timestamp:current_level_start
~predecessor_round:Round.zero
~round:op_round
>>? fun expected_time ->
Timestamp.(
proposal_timestamp
+? Round.round_duration round_durations proposal_round)
>>? fun next_level_ts ->
max_ts config.clock_drift next_level_ts now_timestamp
>>? fun max_timestamp ->
ok Timestamp.(expected_time > max_timestamp) ) ;
no_error
@@ (acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start proposal_timestamp proposal_round Round.zero)
~op_level
~op_round
~now_timestamp
>|? not))
let () =
Alcotest.run
"Filter"
[
( "pre_filter",
qcheck_wrap
[
test_acceptable_past_level;
test_acceptable_current_level_current_round;
test_acceptable_current_level;
test_not_acceptable_current_level;
test_acceptable_next_level;
test_not_acceptable_next_level;
] );
]
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_alpha/lib_plugin/test/test_consensus_filter.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* Conversion helpers
* Data Generators
* Constants :
This could be generated but it would largely increase the search space.
* Don't allow test to fail
* Helper to compute
* Expected timestamp for the begining of a round at same level that
the proposal.
It has been developped before the Round.timestamp_of_round_same_level and has a
different implementation.
* [max_ts] computes the upper bound on future timestamps given the
accepted round drift.
* TESTS
* Test past operations that are accepted whatever the current timestamp is:
strictly before the predecessor level or at the current level and with a
strictly lower round than the head.
* Test acceptable operations at current level, current round, i.e. on the
currently considered proposal
* Test operations at same level, different round, with an acceptable expected
timestamp for the operation.
* Test operations at same level, different round, with a too high expected
timestamp for the operation, and not at current round (which is always accepted).
* Test operations at next level, different round, with an acceptable timestamp for
the operation.
* Test operations at next level, different round, with a too high timestamp
for the operation. | Copyright ( c ) 2021 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Lib_test.Qcheck_helpers
open Plugin.Mempool
open Alpha_context
let config drift_opt =
{
default_config with
clock_drift =
Option.map
(fun drift -> Period.of_seconds_exn (Int64.of_int drift))
drift_opt;
}
type Environment.Error_monad.error += Generation_failure
let int32_of_timestamp ts =
let i64 = Timestamp.to_seconds ts in
let i32 = Int64.to_int32 i64 in
if Int64.(equal (of_int32 i32) i64) then Ok i32
else Environment.Error_monad.error Generation_failure
let int32_of_timestamp_exn ts =
match int32_of_timestamp ts with
| Ok i32 -> i32
| Error _err -> Stdlib.failwith "int32_of_timestamp_exn: number too big"
let timestamp_of_int32 ts = Timestamp.of_seconds (Int64.of_int32 ts)
module Generator = struct
open QCheck
let decorate ?(prefix = "") ?(suffix = "") printer gen =
set_print (fun d -> prefix ^ printer d ^ suffix) gen
let config =
decorate ~prefix:"clock_drift " (fun config ->
Option.fold
~none:"round_0 duration"
~some:(fun drift -> Int64.to_string @@ Period.to_seconds drift)
config.clock_drift)
@@ map
~rev:(fun {clock_drift; _} ->
Option.map
(fun drift -> Int64.to_int @@ Period.to_seconds drift)
clock_drift)
config
(option small_nat)
let of_error_arb gen =
of_option_arb
@@ map
~rev:(function
| Some x -> Ok x
| None -> Environment.Error_monad.error Generation_failure)
(function Ok x -> Some x | Error _err -> None)
gen
let small_nat_32 ?prefix ?suffix () =
decorate ?prefix ?suffix Int32.to_string
@@ map ~rev:Int32.to_int Int32.of_int small_nat
let small_signed_32 ?prefix ?suffix () =
decorate ?prefix ?suffix Int32.to_string
@@ map ~rev:Int32.to_int Int32.of_int small_signed_int
let decorated_small_nat ?prefix ?suffix () =
decorate ?prefix ?suffix string_of_int small_nat
let dup gen = map ~rev:fst (fun x -> (x, x)) gen
let round =
of_error_arb
@@ map
~rev:(function Ok l -> Round.to_int32 l | Error _ -> -1l)
(fun i32 -> Round.of_int32 i32)
(small_nat_32 ~prefix:"rnd " ())
let same_rounds = dup round
let level =
of_error_arb
@@ map
~rev:(function Ok l -> Raw_level.to_int32 l | Error _ -> -1l)
Raw_level.of_int32
(small_nat_32 ~prefix:"lev " ())
let same_levels = dup level
let timestamp =
set_print Timestamp.to_notation
@@ map ~rev:int32_of_timestamp_exn (fun f -> timestamp_of_int32 f) int32
let near_timestamps =
map
~rev:(fun (ts1, ts2) ->
let its1 = int32_of_timestamp_exn ts1 in
let its2 = int32_of_timestamp_exn ts2 in
Int32.(its1, sub its2 its1))
(fun (i, diff) ->
timestamp_of_int32 i |> fun ts1 ->
timestamp_of_int32 Int32.(add i diff) |> fun ts2 -> (ts1, ts2))
(pair int32 (small_signed_32 ~prefix:"+" ~suffix:"sec." ()))
let dummy_timestamp =
match Timestamp.of_seconds_string "0" with
| Some ts -> ts
| _ -> assert false
let unsafe_sub ts1 ts2 =
Int64.to_int @@ Period.to_seconds
@@
match Timestamp.(ts1 -? ts2) with
| Ok diff -> diff
| Error _ -> assert false
let successive_timestamp =
of_error_arb
@@ map
~rev:(function
| Ok (ts1, ts2) -> (ts1, unsafe_sub ts2 ts1)
| Error _ -> (dummy_timestamp, -1))
(fun (ts, (diff : int)) ->
Period.of_seconds (Int64.of_int diff) >>? fun diff ->
Timestamp.(ts +? diff) >>? fun ts2 -> Ok (ts, ts2))
(pair timestamp (decorated_small_nat ~prefix:"+" ~suffix:"sec." ()))
let param_acceptable ?(rounds = pair round round) ?(levels = pair level level)
?(timestamps = near_timestamps) () =
pair config (pair (pair rounds levels) timestamps)
end
let assert_no_error d = match d with Error _ -> assert false | Ok d -> d
let round_durations : Round.round_durations =
assert_no_error
@@ Round.Durations.create
~first_round_duration:Period.(of_seconds_exn 4L)
~delay_increment_per_round:Period.(of_seconds_exn 10L)
let round_zero_duration = Round.round_duration round_durations Round.zero
let no_error = function
| Ok b -> b
| Error errs ->
Format.printf
"test fail due to error : %a@."
Error_monad.pp_print_trace
(Environment.wrap_tztrace errs) ;
false
let durations round_durations start stop =
List.map_e
(fun round ->
Round.of_int round >|? fun round ->
Round.round_duration round_durations round |> Period.to_seconds)
Tezos_stdlib.Utils.Infix.(start -- stop)
let timestamp_of_round round_durations ~proposal_timestamp ~proposal_round
~round =
(let iproposal_round = Int32.to_int @@ Round.to_int32 proposal_round in
let iround = Int32.to_int @@ Round.to_int32 round in
if Round.(proposal_round = round) then ok (Period.zero, proposal_timestamp)
else if Round.(proposal_round < round) then
durations round_durations iproposal_round (iround - 1) >>? fun durations ->
Period.of_seconds @@ List.fold_left Int64.add Int64.zero durations
>>? fun rounds_duration ->
Timestamp.(proposal_timestamp +? rounds_duration) >|? fun ts ->
(rounds_duration, ts)
else
durations round_durations iround (iproposal_round - 1) >>? fun durations ->
List.fold_left Int64.add Int64.zero durations |> fun rounds_duration ->
Timestamp.of_seconds
@@ Int64.sub (Timestamp.to_seconds proposal_timestamp) rounds_duration
|> fun ts ->
Period.of_seconds rounds_duration >|? fun rounds_duration ->
(rounds_duration, ts))
>>? fun (_rnd_dur, exp_ts) -> ok exp_ts
let drift_of =
let r0_dur = Round.round_duration round_durations Round.zero in
fun clock_drift -> Option.value ~default:r0_dur clock_drift
let max_ts clock_drift prop_ts now =
Timestamp.(max prop_ts now +? drift_of clock_drift)
let count = None
let predecessor_start proposal_timestamp proposal_round grandparent_round =
assert_no_error
@@ ( Round.level_offset_of_round
round_durations
~round:Round.(succ grandparent_round)
>>? fun proposal_level_offset ->
Round.level_offset_of_round round_durations ~round:proposal_round
>>? fun proposal_round_offset ->
Period.(add proposal_level_offset proposal_round_offset)
>>? fun proposal_offset ->
Ok Timestamp.(proposal_timestamp - proposal_offset) )
let test_acceptable_past_level =
QCheck.Test.make
~name:"acceptable past op "
(Generator.param_acceptable ())
(fun
( config,
( ((proposal_round, op_round), (proposal_level, op_level)),
(proposal_timestamp, now_timestamp) ) )
->
QCheck.(
Raw_level.(
proposal_level > succ op_level
|| (proposal_level = op_level && Round.(proposal_round > op_round)))
==> no_error
@@ acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start
proposal_timestamp
proposal_round
Round.zero)
~op_level
~op_round
~now_timestamp))
let test_acceptable_current_level_current_round =
let open QCheck in
Test.make
?count
~name:"same round, same level "
Generator.(param_acceptable ~rounds:same_rounds ~levels:same_levels ())
(fun ( config,
(((op_round, _), (_, op_level)), (proposal_timestamp, now_timestamp))
) ->
let proposal_level = op_level in
let proposal_round = op_round in
no_error
@@ acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start proposal_timestamp proposal_round Round.zero)
~op_level
~op_round
~now_timestamp)
let test_acceptable_current_level =
let open QCheck in
Test.make
?count
~name:"same level, different round, acceptable op"
Generator.(param_acceptable ~levels:same_levels ())
(fun ( config,
( ((proposal_round, op_round), (_, op_level)),
(proposal_timestamp, now_timestamp) ) ) ->
let proposal_level = op_level in
no_error
( timestamp_of_round
round_durations
~proposal_timestamp
~proposal_round
~round:op_round
>>? fun expected_time ->
max_ts config.clock_drift proposal_timestamp now_timestamp
>>? fun max_timestamp -> ok Timestamp.(expected_time <= max_timestamp)
)
==> no_error
@@ acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start
proposal_timestamp
proposal_round
Round.zero)
~op_level
~op_round
~now_timestamp)
let test_not_acceptable_current_level =
let open QCheck in
Test.make
?count
~name:"same level, different round, too far"
Generator.(param_acceptable ~levels:same_levels ())
(fun ( config,
( ((proposal_round, op_round), (_, op_level)),
(proposal_timestamp, now_timestamp) ) ) ->
let proposal_level = op_level in
no_error
( timestamp_of_round
round_durations
~proposal_timestamp
~proposal_round
~round:op_round
>>? fun expected_time ->
max_ts config.clock_drift proposal_timestamp now_timestamp
>>? fun max_timestamp ->
ok
Timestamp.(
expected_time > max_timestamp
&& Round.(proposal_round <> op_round)) )
==> no_error
(acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start
proposal_timestamp
proposal_round
Round.zero)
~op_level
~op_round
~now_timestamp
>|? not))
let test_acceptable_next_level =
let open QCheck in
Test.make
?count
~name:"next level, acceptable op"
Generator.(param_acceptable ~levels:same_levels ())
(fun ( config,
( ((proposal_round, op_round), (proposal_level, _)),
(proposal_timestamp, now_timestamp) ) ) ->
let op_level = Raw_level.succ proposal_level in
no_error
( timestamp_of_round
round_durations
~proposal_timestamp
~proposal_round
~round:Round.zero
>>? fun current_level_start ->
Round.timestamp_of_round
round_durations
~predecessor_timestamp:current_level_start
~predecessor_round:Round.zero
~round:op_round
>>? fun expected_time ->
max_ts config.clock_drift proposal_timestamp now_timestamp
>>? fun max_timestamp -> ok Timestamp.(expected_time <= max_timestamp)
)
==> no_error
@@ acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start
proposal_timestamp
proposal_round
Round.zero)
~op_level
~op_round
~now_timestamp)
let test_not_acceptable_next_level =
let open QCheck in
Test.make
?count
~name:"next level, too far"
Generator.(
param_acceptable ~levels:same_levels ~timestamps:successive_timestamp ())
(fun ( config,
( ((proposal_round, op_round), (proposal_level, _)),
(proposal_timestamp, now_timestamp) ) ) ->
let op_level = Raw_level.succ proposal_level in
QCheck.assume
@@ no_error
( timestamp_of_round
round_durations
~proposal_timestamp
~proposal_round
~round:Round.zero
>>? fun current_level_start ->
Round.timestamp_of_round
round_durations
~predecessor_timestamp:current_level_start
~predecessor_round:Round.zero
~round:op_round
>>? fun expected_time ->
Timestamp.(
proposal_timestamp
+? Round.round_duration round_durations proposal_round)
>>? fun next_level_ts ->
max_ts config.clock_drift next_level_ts now_timestamp
>>? fun max_timestamp ->
ok Timestamp.(expected_time > max_timestamp) ) ;
no_error
@@ (acceptable_op
~config
~round_durations
~round_zero_duration
~proposal_level
~proposal_round
~proposal_timestamp
~proposal_predecessor_level_start:
(predecessor_start proposal_timestamp proposal_round Round.zero)
~op_level
~op_round
~now_timestamp
>|? not))
let () =
Alcotest.run
"Filter"
[
( "pre_filter",
qcheck_wrap
[
test_acceptable_past_level;
test_acceptable_current_level_current_round;
test_acceptable_current_level;
test_not_acceptable_current_level;
test_acceptable_next_level;
test_not_acceptable_next_level;
] );
]
|
5845e6dccaed0cc464badfe6e74e531d3b071c7504dfaf91e13279cd21a25e73 | ndmitchell/catch | Files.hs |
Figure out which files a command line refers to :
# A Haskell source file
# A Text file , giving one file per line
# A directory of files
Figure out which files a command line refers to:
# A Haskell source file
# A Text file, giving one file per line
# A directory of files
-}
module Files(findFiles) where
import Control.Monad
import Data.List
import General.General
import System.Directory
import System.Exit
import System.FilePath
findFiles :: [String] -> IO [FilePath]
findFiles = concatMapM findStartFiles
-- file must be in <directory>/givenname.<extension>
findStartFiles :: String -> IO [FilePath]
findStartFiles file = do
dirs <- findStartDirs
let exts = ["","hs","lhs","txt"]
poss = [d </> file <.> e | d <- dirs, e <- exts]
f poss
where
f [] = putStrLn ("Error: File not found, " ++ file) >> exitFailure
f (x:xs) = do
bFile <- doesFileExist x
bDir <- doesDirectoryExist x
if bFile then (
if takeExtension x == ".txt" then
readFile x >>= concatMapM findStartFiles . lines
else
return [x]
)
else if bDir then do
items <- getDirectoryContents x
items <- return $ map (x </>) $ filter (\x -> takeExtension x `elem` [".hs",".lhs"]) items
if null items then error $ "No files found within, " ++ x
else return items
else f xs
findStartDirs :: IO [FilePath]
findStartDirs = do
base <- baseDir
let examples = base </> "examples"
b <- doesDirectoryExist examples
if not b then return [""] else do
items <- getDirectoryContents examples
items <- return $ map (examples </>) $ filter (not . isPrefixOf ".") items
items <- filterM doesDirectoryExist items
return ("" : examples : items)
| null | https://raw.githubusercontent.com/ndmitchell/catch/5d834416a27b4df3f7ce7830c4757d4505aaf96e/catch_1/Files.hs | haskell | file must be in <directory>/givenname.<extension> |
Figure out which files a command line refers to :
# A Haskell source file
# A Text file , giving one file per line
# A directory of files
Figure out which files a command line refers to:
# A Haskell source file
# A Text file, giving one file per line
# A directory of files
-}
module Files(findFiles) where
import Control.Monad
import Data.List
import General.General
import System.Directory
import System.Exit
import System.FilePath
findFiles :: [String] -> IO [FilePath]
findFiles = concatMapM findStartFiles
findStartFiles :: String -> IO [FilePath]
findStartFiles file = do
dirs <- findStartDirs
let exts = ["","hs","lhs","txt"]
poss = [d </> file <.> e | d <- dirs, e <- exts]
f poss
where
f [] = putStrLn ("Error: File not found, " ++ file) >> exitFailure
f (x:xs) = do
bFile <- doesFileExist x
bDir <- doesDirectoryExist x
if bFile then (
if takeExtension x == ".txt" then
readFile x >>= concatMapM findStartFiles . lines
else
return [x]
)
else if bDir then do
items <- getDirectoryContents x
items <- return $ map (x </>) $ filter (\x -> takeExtension x `elem` [".hs",".lhs"]) items
if null items then error $ "No files found within, " ++ x
else return items
else f xs
findStartDirs :: IO [FilePath]
findStartDirs = do
base <- baseDir
let examples = base </> "examples"
b <- doesDirectoryExist examples
if not b then return [""] else do
items <- getDirectoryContents examples
items <- return $ map (examples </>) $ filter (not . isPrefixOf ".") items
items <- filterM doesDirectoryExist items
return ("" : examples : items)
|
a3a2b8a0264e9a8b6941c11381c04d6d2775dafa30390412fd00f81b8e780ff6 | iskandr/parakeet-retired | GpuCost.ml | (* pp: -parser o pa_macro.cmo *)
open Base
open SSA
let safeFundefCache : (FnId.t, bool) Hashtbl.t = Hashtbl.create 127
TIME IN MILLISECONDS-- ignore device->device copy costs for now
let rec transfer_time shape t : float =
assume 2 MB / millisecond
let transferRate = 2097152. in
let nbytes = Shape.nelts shape * DynType.sizeof t in
assume initiating a transfer requires at least 1 millisecond
1. +. (float_of_int nbytes) /. transferRate
type gpu_data_info = Shape.t * DynType.t * bool
time to transfer a set of value to gpu , which are tagged with whether
they 're already on the gpu
they're already on the gpu
*)
let rec sum_transfer_time = function
| [] -> 0.
| (t,shape,onGpu)::rest ->
if onGpu then sum_transfer_time rest
else transfer_time shape t +. sum_transfer_time rest
(* constants useful for computing adverb costs on the GPU *)
let parallelism = 240.
let launchCost = 3.
let map
~(fnTable:FnTable.t)
~(fn:SSA.fundef)
~(closureArgs : Shape.t list)
~(args : Shape.t list) =
let outerDim, nestedArgs = Shape.split_nested_shapes args in
let nestedShapes = closureArgs @ nestedArgs in
let nestedCost = SeqCost.seq_cost fnTable fn nestedShapes in
let runCost = (float_of_int outerDim) *. nestedCost /. parallelism in
IFDEF DEBUG THEN
Printf.printf "[GpuCost] Computing GPU map cost for %s, %s\n"
(String.concat ", " (List.map Shape.to_str closureArgs))
(String.concat ", " (List.map Shape.to_str args))
;
Printf.printf "[GpuCost] nestedArgs: {%s}, nestedCost: %f, runCost: %f\n"
(String.concat ", " (List.map Shape.to_str nestedShapes))
nestedCost
runCost
;
ENDIF;
launchCost +. runCost
let reduce
~(fnTable:FnTable.t)
~(init:SSA.fundef)
~(initClosureArgs:Shape.t list)
~(fn:SSA.fundef)
~(closureArgs:Shape.t list)
~(initArgs:Shape.t list)
~(args:Shape.t list) =
for now , assume the initFn takes as much time as the normal fn
let outerDim, nestedArgs = Shape.split_nested_shapes args in
let nestedShapes = initClosureArgs @ initArgs @ nestedArgs in
let nestedCost = SeqCost.seq_cost fnTable init nestedShapes in
let runCost = (float_of_int outerDim) *. nestedCost /. parallelism in
let numLaunches = log (float_of_int outerDim) in
numLaunches *. launchCost +. 2. *. runCost
let array_op op argShapes = match op, argShapes with
| Prim.Where, [x] -> float_of_int (Shape.nelts x)
| Prim.Index, [x;idx] ->
assume x is 1D
let numIndices = Shape.nelts idx in
float_of_int numIndices
| Prim.Find, [x; elt] -> float_of_int $ (Shape.nelts x) * (Shape.nelts elt)
| arrayOp, shapes ->
IFDEF DEBUG THEN
Printf.printf "[GpuCost] Infinite cost for operator: %s with args %s\n"
(Prim.array_op_to_str arrayOp)
(String.concat ", " (List.map Shape.to_str shapes))
ENDIF;
infinity
| null | https://raw.githubusercontent.com/iskandr/parakeet-retired/3d7e6e5b699f83ce8a1c01290beed0b78c0d0945/Runtime/CostModel/GpuCost.ml | ocaml | pp: -parser o pa_macro.cmo
constants useful for computing adverb costs on the GPU |
open Base
open SSA
let safeFundefCache : (FnId.t, bool) Hashtbl.t = Hashtbl.create 127
TIME IN MILLISECONDS-- ignore device->device copy costs for now
let rec transfer_time shape t : float =
assume 2 MB / millisecond
let transferRate = 2097152. in
let nbytes = Shape.nelts shape * DynType.sizeof t in
assume initiating a transfer requires at least 1 millisecond
1. +. (float_of_int nbytes) /. transferRate
type gpu_data_info = Shape.t * DynType.t * bool
time to transfer a set of value to gpu , which are tagged with whether
they 're already on the gpu
they're already on the gpu
*)
let rec sum_transfer_time = function
| [] -> 0.
| (t,shape,onGpu)::rest ->
if onGpu then sum_transfer_time rest
else transfer_time shape t +. sum_transfer_time rest
let parallelism = 240.
let launchCost = 3.
let map
~(fnTable:FnTable.t)
~(fn:SSA.fundef)
~(closureArgs : Shape.t list)
~(args : Shape.t list) =
let outerDim, nestedArgs = Shape.split_nested_shapes args in
let nestedShapes = closureArgs @ nestedArgs in
let nestedCost = SeqCost.seq_cost fnTable fn nestedShapes in
let runCost = (float_of_int outerDim) *. nestedCost /. parallelism in
IFDEF DEBUG THEN
Printf.printf "[GpuCost] Computing GPU map cost for %s, %s\n"
(String.concat ", " (List.map Shape.to_str closureArgs))
(String.concat ", " (List.map Shape.to_str args))
;
Printf.printf "[GpuCost] nestedArgs: {%s}, nestedCost: %f, runCost: %f\n"
(String.concat ", " (List.map Shape.to_str nestedShapes))
nestedCost
runCost
;
ENDIF;
launchCost +. runCost
let reduce
~(fnTable:FnTable.t)
~(init:SSA.fundef)
~(initClosureArgs:Shape.t list)
~(fn:SSA.fundef)
~(closureArgs:Shape.t list)
~(initArgs:Shape.t list)
~(args:Shape.t list) =
for now , assume the initFn takes as much time as the normal fn
let outerDim, nestedArgs = Shape.split_nested_shapes args in
let nestedShapes = initClosureArgs @ initArgs @ nestedArgs in
let nestedCost = SeqCost.seq_cost fnTable init nestedShapes in
let runCost = (float_of_int outerDim) *. nestedCost /. parallelism in
let numLaunches = log (float_of_int outerDim) in
numLaunches *. launchCost +. 2. *. runCost
let array_op op argShapes = match op, argShapes with
| Prim.Where, [x] -> float_of_int (Shape.nelts x)
| Prim.Index, [x;idx] ->
assume x is 1D
let numIndices = Shape.nelts idx in
float_of_int numIndices
| Prim.Find, [x; elt] -> float_of_int $ (Shape.nelts x) * (Shape.nelts elt)
| arrayOp, shapes ->
IFDEF DEBUG THEN
Printf.printf "[GpuCost] Infinite cost for operator: %s with args %s\n"
(Prim.array_op_to_str arrayOp)
(String.concat ", " (List.map Shape.to_str shapes))
ENDIF;
infinity
|
5a157559f9aeca4db7e1dd2fd3c3df8b612d1b3cbfc3c81e986fb5dc7d239269 | wilkerlucio/oge | network.cljs | (ns com.wsscode.oge.pub.network
(:require [fulcro.client.network :as f.network]))
(defn request-transform [req]
(let [token nil]
(-> req
(cond-> token (assoc-in [:headers "Authorization"] (str "Bearer " token)))
(assoc-in [:headers "Accept"] "application/transit+json"))))
(defn network-error-callback [& args]
(js/console.log "Network error" args))
(defrecord DynamicNetwork [url-atom network]
f.network/NetworkBehavior
(serialize-requests? [_] (f.network/serialize-requests? network))
f.network/FulcroNetwork
(send [this edn ok error]
(if @url-atom
(-> network
(assoc :url @url-atom)
(f.network/send edn ok error))
(error (ex-info "No URL set" {}))))
(start [_]))
(defn make-network
([url-atom] (make-network url-atom {}))
([url-atom _]
(let [base-network (f.network/make-fulcro-network nil
:request-transform request-transform
:global-error-callback network-error-callback)]
(map->DynamicNetwork {:url-atom url-atom
:network base-network}))))
| null | https://raw.githubusercontent.com/wilkerlucio/oge/ef25e1f52ff2d9983714ee3c073534c84c3153c4/src/com/wsscode/oge/pub/network.cljs | clojure | (ns com.wsscode.oge.pub.network
(:require [fulcro.client.network :as f.network]))
(defn request-transform [req]
(let [token nil]
(-> req
(cond-> token (assoc-in [:headers "Authorization"] (str "Bearer " token)))
(assoc-in [:headers "Accept"] "application/transit+json"))))
(defn network-error-callback [& args]
(js/console.log "Network error" args))
(defrecord DynamicNetwork [url-atom network]
f.network/NetworkBehavior
(serialize-requests? [_] (f.network/serialize-requests? network))
f.network/FulcroNetwork
(send [this edn ok error]
(if @url-atom
(-> network
(assoc :url @url-atom)
(f.network/send edn ok error))
(error (ex-info "No URL set" {}))))
(start [_]))
(defn make-network
([url-atom] (make-network url-atom {}))
([url-atom _]
(let [base-network (f.network/make-fulcro-network nil
:request-transform request-transform
:global-error-callback network-error-callback)]
(map->DynamicNetwork {:url-atom url-atom
:network base-network}))))
| |
d3ea413ad47c28a237ca11c6f3db71e06196759b7a2656fa08c6c5705f3a0350 | roelvandijk/numerals | TestData.hs | |
[ @ISO639 - 1@ ] hu
[ @ISO639 - 2@ ] hun
[ @ISO639 - 3@ ] hun
[ @Native name@ ] magyar
[ @English name@ ] Hungarian
[@ISO639-1@] hu
[@ISO639-2@] hun
[@ISO639-3@] hun
[@Native name@] magyar
[@English name@] Hungarian
-}
module Text.Numeral.Language.HUN.TestData (cardinals) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "numerals" Text.Numeral.Grammar ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
--------------------------------------------------------------------------------
-- Test data
--------------------------------------------------------------------------------
cardinals :: (Integral i) => TestData i
cardinals =
[ ( "default"
, defaultInflection
, [ (0, "nulla")
, (1, "egy")
, (2, "kettö")
, (3, "három")
, (4, "négy")
, (5, "öt")
, (6, "hat")
, (7, "hét")
, (8, "nyolc")
, (9, "kilenc")
, (10, "tíz")
, (11, "tízenegy")
, (12, "tízenkettö")
, (13, "tízenhárom")
, (14, "tízennégy")
, (15, "tízenöt")
, (16, "tízenhat")
, (17, "tízenhét")
, (18, "tízennyolc")
, (19, "tízenkilenc")
, (20, "húsz")
, (21, "húszonegy")
, (22, "húszonkettö")
, (23, "húszonhárom")
, (24, "húszonnégy")
, (25, "húszonöt")
, (26, "húszonhat")
, (27, "húszonhét")
, (28, "húszonnyolc")
, (29, "húszonkilenc")
, (30, "harminc")
, (31, "harmincegy")
, (32, "harminckettö")
, (33, "harminchárom")
, (34, "harmincnégy")
, (35, "harmincöt")
, (36, "harminchat")
, (37, "harminchét")
, (38, "harmincnyolc")
, (39, "harminckilenc")
, (40, "negyven")
, (41, "negyvenegy")
, (42, "negyvenkettö")
, (43, "negyvenhárom")
, (44, "negyvennégy")
, (45, "negyvenöt")
, (46, "negyvenhat")
, (47, "negyvenhét")
, (48, "negyvennyolc")
, (49, "negyvenkilenc")
, (50, "ötven")
, (51, "ötvenegy")
, (52, "ötvenkettö")
, (53, "ötvenhárom")
, (54, "ötvennégy")
, (55, "ötvenöt")
, (56, "ötvenhat")
, (57, "ötvenhét")
, (58, "ötvennyolc")
, (59, "ötvenkilenc")
, (60, "hatvan")
, (61, "hatvanegy")
, (62, "hatvankettö")
, (63, "hatvanhárom")
, (64, "hatvannégy")
, (65, "hatvanöt")
, (66, "hatvanhat")
, (67, "hatvanhét")
, (68, "hatvannyolc")
, (69, "hatvankilenc")
, (70, "hetven")
, (71, "hetvenegy")
, (72, "hetvenkettö")
, (73, "hetvenhárom")
, (74, "hetvennégy")
, (75, "hetvenöt")
, (76, "hetvenhat")
, (77, "hetvenhét")
, (78, "hetvennyolc")
, (79, "hetvenkilenc")
, (80, "nyolcvan")
, (81, "nyolcvanegy")
, (82, "nyolcvankettö")
, (83, "nyolcvanhárom")
, (84, "nyolcvannégy")
, (85, "nyolcvanöt")
, (86, "nyolcvanhat")
, (87, "nyolcvanhét")
, (88, "nyolcvannyolc")
, (89, "nyolcvankilenc")
, (90, "kilencven")
, (91, "kilencvenegy")
, (92, "kilencvenkettö")
, (93, "kilencvenhárom")
, (94, "kilencvennégy")
, (95, "kilencvenöt")
, (96, "kilencvenhat")
, (97, "kilencvenhét")
, (98, "kilencvennyolc")
, (99, "kilencvenkilenc")
, (100, "száz")
]
)
]
| null | https://raw.githubusercontent.com/roelvandijk/numerals/b1e4121e0824ac0646a3230bd311818e159ec127/src-test/Text/Numeral/Language/HUN/TestData.hs | haskell | ------------------------------------------------------------------------------
Imports
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Test data
------------------------------------------------------------------------------ | |
[ @ISO639 - 1@ ] hu
[ @ISO639 - 2@ ] hun
[ @ISO639 - 3@ ] hun
[ @Native name@ ] magyar
[ @English name@ ] Hungarian
[@ISO639-1@] hu
[@ISO639-2@] hun
[@ISO639-3@] hun
[@Native name@] magyar
[@English name@] Hungarian
-}
module Text.Numeral.Language.HUN.TestData (cardinals) where
import "numerals" Text.Numeral.Grammar ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
cardinals :: (Integral i) => TestData i
cardinals =
[ ( "default"
, defaultInflection
, [ (0, "nulla")
, (1, "egy")
, (2, "kettö")
, (3, "három")
, (4, "négy")
, (5, "öt")
, (6, "hat")
, (7, "hét")
, (8, "nyolc")
, (9, "kilenc")
, (10, "tíz")
, (11, "tízenegy")
, (12, "tízenkettö")
, (13, "tízenhárom")
, (14, "tízennégy")
, (15, "tízenöt")
, (16, "tízenhat")
, (17, "tízenhét")
, (18, "tízennyolc")
, (19, "tízenkilenc")
, (20, "húsz")
, (21, "húszonegy")
, (22, "húszonkettö")
, (23, "húszonhárom")
, (24, "húszonnégy")
, (25, "húszonöt")
, (26, "húszonhat")
, (27, "húszonhét")
, (28, "húszonnyolc")
, (29, "húszonkilenc")
, (30, "harminc")
, (31, "harmincegy")
, (32, "harminckettö")
, (33, "harminchárom")
, (34, "harmincnégy")
, (35, "harmincöt")
, (36, "harminchat")
, (37, "harminchét")
, (38, "harmincnyolc")
, (39, "harminckilenc")
, (40, "negyven")
, (41, "negyvenegy")
, (42, "negyvenkettö")
, (43, "negyvenhárom")
, (44, "negyvennégy")
, (45, "negyvenöt")
, (46, "negyvenhat")
, (47, "negyvenhét")
, (48, "negyvennyolc")
, (49, "negyvenkilenc")
, (50, "ötven")
, (51, "ötvenegy")
, (52, "ötvenkettö")
, (53, "ötvenhárom")
, (54, "ötvennégy")
, (55, "ötvenöt")
, (56, "ötvenhat")
, (57, "ötvenhét")
, (58, "ötvennyolc")
, (59, "ötvenkilenc")
, (60, "hatvan")
, (61, "hatvanegy")
, (62, "hatvankettö")
, (63, "hatvanhárom")
, (64, "hatvannégy")
, (65, "hatvanöt")
, (66, "hatvanhat")
, (67, "hatvanhét")
, (68, "hatvannyolc")
, (69, "hatvankilenc")
, (70, "hetven")
, (71, "hetvenegy")
, (72, "hetvenkettö")
, (73, "hetvenhárom")
, (74, "hetvennégy")
, (75, "hetvenöt")
, (76, "hetvenhat")
, (77, "hetvenhét")
, (78, "hetvennyolc")
, (79, "hetvenkilenc")
, (80, "nyolcvan")
, (81, "nyolcvanegy")
, (82, "nyolcvankettö")
, (83, "nyolcvanhárom")
, (84, "nyolcvannégy")
, (85, "nyolcvanöt")
, (86, "nyolcvanhat")
, (87, "nyolcvanhét")
, (88, "nyolcvannyolc")
, (89, "nyolcvankilenc")
, (90, "kilencven")
, (91, "kilencvenegy")
, (92, "kilencvenkettö")
, (93, "kilencvenhárom")
, (94, "kilencvennégy")
, (95, "kilencvenöt")
, (96, "kilencvenhat")
, (97, "kilencvenhét")
, (98, "kilencvennyolc")
, (99, "kilencvenkilenc")
, (100, "száz")
]
)
]
|
6db032dc9596f45a30c54e5e732dbf16a515d2bae824129889acdbd277528837 | metosin/eines | project.clj | (defproject metosin/eines-client "0.0.10-SNAPSHOT"
:description "Simple clj/cljs library for WebSocket communication"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:plugins [[lein-parent "0.3.2"]]
:parent-project {:path "../../project.clj"
:inherit [:deploy-repositories :managed-dependencies]}
:dependencies [[com.cognitect/transit-cljs]])
| null | https://raw.githubusercontent.com/metosin/eines/e293d0a3b29eb18fb20bdf0c234cd898e7b87ac9/modules/eines-client/project.clj | clojure | (defproject metosin/eines-client "0.0.10-SNAPSHOT"
:description "Simple clj/cljs library for WebSocket communication"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:plugins [[lein-parent "0.3.2"]]
:parent-project {:path "../../project.clj"
:inherit [:deploy-repositories :managed-dependencies]}
:dependencies [[com.cognitect/transit-cljs]])
| |
1c357c8a8c9bc406109beb8cd7d41ab2a19bd29abee45fad4eeb83921e2fb8d6 | puzza007/openpoker | blinds.erl | Copyright ( C ) 2005 Wager Labs , SA
%%%
This file is part of OpenPoker .
%%%
OpenPoker 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 .
%%%
%%% 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 library; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
%%%
Please visit or contact
%%% at for more information.
-module(blinds).
-behaviour(cardgame).
-export([stop/1, test/0]).
-export([init/1, terminate/3]).
-export([handle_event/3, handle_info/3,
handle_sync_event/4, code_change/4]).
-export([small_blind/2, big_blind/2]).
-include("common.hrl").
-include("test.hrl").
-include("texas.hrl").
-include("proto.hrl").
-record(data, {
game,
context,
small_blind_seat,
big_blind_seat,
button_seat,
no_small_blind,
small_blind_amount,
small_blind_bet,
big_blind_amount,
timer,
expected, % {Player, Seat, Amount}
type
}).
init([Game]) ->
init([Game, normal]);
init([Game, Type]) ->
{Small, Big} = gen_server:call(Game, 'BLINDS'),
Data = #data {
game = Game,
small_blind_amount = Small,
big_blind_amount = Big,
small_blind_bet = 0,
no_small_blind = false,
timer = none,
expected = {none, 0},
type = Type
},
{ok, small_blind, Data}.
stop(Ref) ->
cardgame:send_all_state_event(Ref, stop).
%% Theory
Heads - up play . The small blind is the button and acts first
%% before the flop and last after the flop. The player
who does not have the button is dealt the first card .
There are three players remaining and one is eliminated .
%% Determine which player would have been the next big blind
%% ... that player becomes the big blind and the other player
%% is the small blind (and button).
%% Small blind is eliminated. The player who was the big blind
%% now posts the small blind and the player to his left
%% posts the big blind. The button does not move and the player
%% who was the button, will be the button once again.
%% Big blind is eliminated. The player to the left of the eliminated
%% big blind now posts the big blind and there is no small blind
%% for that hand. The button moves to the player who was the small blind.
On the following hand , the button does not move and the two blinds
%% are posted normally.
small_blind({'START', Context}, Data) ->
if
Data#data.type /= irc ->
Data1 = Data#data {
context = Context,
small_blind_seat = Context#texas.small_blind_seat,
big_blind_seat = Context#texas.big_blind_seat,
button_seat = Context#texas.button_seat
};
true ->
Data1 = Data#data {
context = Context,
small_blind_seat = none,
big_blind_seat = none,
button_seat = none
}
end,
Game = Data1#data.game,
%% advance button and broadcast position
{Button1, Bust} = advance_button(Data1),
gen_server:cast(Game, {'BROADCAST', {?PP_NOTIFY_BUTTON, Button1}}),
%% collect blinds
SBPlayers = gen_server:call(Game, {'SEATS', Button1, ?PS_ACTIVE}),
BBPlayers = gen_server:call(Game, {'SEATS', Button1, ?PS_BB_ACTIVE}),
L1 = length(SBPlayers),
L2 = length(BBPlayers),
two active , 0 waiting for bb
one active , one waiting for bb
BB_N = length(BBPlayers),
if
BB_N < 2 ->
{stop, {normal, restart}, Data1};
Bust and not HeadsUp ->
there 's no small blind so the first player
%% after the button is the big blind
Data2 = Data1#data {
button_seat = Button1,
no_small_blind = true,
small_blind_seat = Data1#data.big_blind_seat
},
Amount = Data2#data.big_blind_amount,
%% ask for big blind
Data3 = ask_for_blind(Data2, hd(BBPlayers), Amount),
{next_state, big_blind, Data3};
Bust and HeadsUp ->
the first player after the button
%% is the big blind and the other player
%% is the small blind and button
Data2 = Data1#data {
button_seat = Button1
},
Amount = Data2#data.small_blind_amount,
Data3 = ask_for_blind(Data2, lists:last(SBPlayers), Amount),
{next_state, small_blind, Data3};
true ->
Data2 = Data1#data {
button_seat = Button1
},
Amount = Data2#data.small_blind_amount,
Data3 = ask_for_blind(Data2, hd(SBPlayers), Amount),
{next_state, small_blind, Data3}
end;
small_blind({?PP_CALL, Player, Amount}, Data) ->
Game = Data#data.game,
{ExpPlayer, Seat, ExpAmount} = Data#data.expected,
if
ExpPlayer /= Player ->
{next_state, small_blind, Data};
true ->
%% it's us
cancel_timer(Data),
InPlay = gen_server:call(Player, 'INPLAY'),
if
(ExpAmount /= Amount) and
(InPlay /= Amount) ->
timeout(Data, Player, small_blind);
true ->
%% small blind posted
Data1 = Data#data {
small_blind_seat = Seat,
small_blind_bet = Amount
},
BBPlayers = gen_server:call(Game,
{'SEATS', Seat, ?PS_BB_ACTIVE}),
Data2 = ask_for_blind(Data1,
hd(BBPlayers),
Data1#data.big_blind_amount),
{next_state, big_blind, Data2}
end
end;
small_blind({?PP_FOLD, Player}, Data) ->
{ExpPlayer, _Seat, _ExpAmount} = Data#data.expected,
if
ExpPlayer /= Player ->
{next_state, small_blind, Data};
true ->
timeout(Data, Player, small_blind)
end;
small_blind({timeout, _Timer, Player}, Data) ->
cancel_timer(Data),
Game = Data#data.game,
GID = gen_server:call(Game, 'ID'),
Seat = gen_server:call(Game, {'WHAT SEAT', Player}),
error_logger:warning_report(
[{message, "Player timeout!"},
{module, ?MODULE},
{state, small_blind},
{player, Player},
{game, GID},
{seat, Seat},
{now, now()}]),
timeout(Data, Player, small_blind);
small_blind({?PP_JOIN, Player, SeatNum, BuyIn}, Data) ->
join(Data, Player, SeatNum, BuyIn, small_blind);
small_blind({?PP_LEAVE, Player}, Data) ->
leave(Data, Player, small_blind);
small_blind({?PP_SIT_OUT, Player}, Data) ->
sit_out(Data, Player, small_blind);
small_blind({?PP_COME_BACK, Player}, Data) ->
come_back(Data, Player, small_blind);
small_blind(Event, Data) ->
handle_event(Event, small_blind, Data).
big_blind({?PP_CALL, Player, Amount}, Data) ->
Game = Data#data.game,
{ExpPlayer, Seat, ExpAmount} = Data#data.expected,
if
ExpPlayer /= Player ->
{next_state, big_blind, Data};
true ->
%% it's us
cancel_timer(Data),
InPlay = gen_server:call(Player, 'INPLAY'),
if
(ExpAmount /= Amount) and
(InPlay /= Amount) ->
timeout(Data, Player, big_blind);
true ->
%% big blind posted
SB = Data#data.small_blind_seat,
BB = Seat,
SBPlayer = gen_server:call(Game, {'PLAYER AT', SB}),
BBPlayer = Player,
gen_server:cast(Game, {'SET STATE', SBPlayer, ?PS_PLAY}),
gen_server:cast(Game, {'SET STATE', BBPlayer, ?PS_PLAY}),
%% record blind bets
Small = Data#data.small_blind_bet,
Big = Amount,
if
Data#data.no_small_blind ->
ok;
true ->
gen_server:cast(Game, {'ADD BET', SBPlayer, Small})
end,
gen_server:cast(Game, {'ADD BET', BBPlayer, Big}),
%% adjust button if a heads-up game
Seats = gen_server:call(Game, {'SEATS', ?PS_ACTIVE}),
if
(length(Seats) == 2) and (Data#data.type /= irc) ->
Button = SB;
true ->
Button = Data#data.button_seat
end,
Data1 = Data#data {
big_blind_seat = BB,
button_seat = Button,
expected = {none, none, 0}
},
%% notify players
gen_server:cast(Game, {'BROADCAST', {?PP_NOTIFY_SB, SB}}),
gen_server:cast(Game, {'BROADCAST', {?PP_NOTIFY_BB, BB}}),
gen_server:cast(Game, {'BROADCAST',
{?PP_NOTIFY_BET, SBPlayer, Small}}),
gen_server:cast(Game, {'BROADCAST',
{?PP_NOTIFY_BET, BBPlayer, Big}}),
Ctx = Data#data.context,
Ctx1 = Ctx#texas {
call = Amount,
small_blind_seat = SB,
big_blind_seat = BB,
button_seat = Button
},
{stop, {normal, Ctx1}, Data1}
end
end;
big_blind({?PP_FOLD, Player}, Data) ->
{ExpPlayer, _Seat, _ExpAmount} = Data#data.expected,
if
ExpPlayer /= Player ->
{next_state, big_blind, Data};
true ->
timeout(Data, Player, big_blind)
end;
big_blind({timeout, _Timer, Player}, Data) ->
cancel_timer(Data),
Game = Data#data.game,
GID = gen_server:call(Game, 'ID'),
Seat = gen_server:call(Game, {'WHAT SEAT', Player}),
error_logger:warning_report(
[{message, "Player timeout!"},
{module, ?MODULE},
{state, big_blind},
{player, Player},
{game, GID},
{seat, Seat},
{now, now()}]),
timeout(Data, Player, big_blind);
big_blind({?PP_JOIN, Player, SeatNum, BuyIn}, Data) ->
join(Data, Player, SeatNum, BuyIn, big_blind);
big_blind({?PP_LEAVE, Player}, Data) ->
leave(Data, Player, big_blind);
big_blind({?PP_SIT_OUT, Player}, Data) ->
sit_out(Data, Player, big_blind);
big_blind({?PP_COME_BACK, Player}, Data) ->
come_back(Data, Player, big_blind);
big_blind(Event, Data) ->
handle_event(Event, big_blind, Data).
handle_event(stop, _State, Data) ->
{stop, normal, Data};
handle_event(Event, State, Data) ->
error_logger:error_report([{module, ?MODULE},
{line, ?LINE},
{where, handle_event},
{message, Event},
{self, self()},
{game, Data#data.game},
{expected, Data#data.expected},
{sb, Data#data.small_blind_seat},
{bb, Data#data.big_blind_seat},
{b, Data#data.button_seat}]),
{next_state, State, Data}.
handle_sync_event(Event, From, State, Data) ->
error_logger:error_report([{module, ?MODULE},
{line, ?LINE},
{where, handle_sync_event},
{message, Event},
{from, From},
{self, self()},
{game, Data#data.game},
{expected, Data#data.expected},
{sb, Data#data.small_blind_seat},
{bb, Data#data.big_blind_seat},
{b, Data#data.button_seat}]),
{next_state, State, Data}.
handle_info(Info, State, Data) ->
error_logger:error_report([{module, ?MODULE},
{line, ?LINE},
{where, handle_info},
{message, Info},
{self, self()},
{game, Data#data.game},
{expected, Data#data.expected},
{sb, Data#data.small_blind_seat},
{bb, Data#data.big_blind_seat},
{b, Data#data.button_seat}]),
{next_state, State, Data}.
terminate(_Reason, _State, _Data) ->
ok.
code_change(_OldVsn, State, Data, _Extra) ->
{ok, State, Data}.
%%
%% Utility
%%
timeout(Data, Player, State) ->
cancel_timer(Data),
Game = Data#data.game,
Seat = gen_server:call(Game, {'WHAT SEAT', Player}),
case State of
small_blind ->
Players = gen_server:call(Game, {'SEATS', Seat, ?PS_ACTIVE}),
Amount = Data#data.small_blind_amount,
Expected = 2;
_ ->
Temp = gen_server:call(Game, {'SEATS', Seat, ?PS_BB_ACTIVE}),
%% remove small blind
Players = lists:delete(Data#data.small_blind_seat, Temp),
Amount = Data#data.big_blind_amount,
Expected = 1
end,
Players1 = lists:delete(Seat, Players),
%%gen_server:cast(Game, {?PP_LEAVE, Player}), % kick player
gen_server:cast(Game, {'SET STATE', Player, ?PS_SIT_OUT}),
if
length(Players1) < Expected ->
{stop, {normal, restart}, Data};
true ->
Data1 = ask_for_blind(Data, hd(Players1), Amount),
{next_state, State, Data1}
end.
join(Data, Player, SeatNum, BuyIn, State) ->
Game = Data#data.game,
gen_server:cast(Game, {?PP_JOIN, Player, SeatNum, BuyIn, ?PS_MAKEUP_BB}),
{next_state, State, Data}.
leave(Data, Player, State) ->
Game = Data#data.game,
Seat = gen_server:call(Game, {'WHAT SEAT', Player}),
if
%% small blind can't leave
%% while we are collecting
%% the big blind
(State == big_blind) and
(Seat == Data#data.small_blind_seat) ->
oops;
true ->
gen_server:cast(Game, {?PP_LEAVE, Player})
end,
{next_state, State, Data}.
sit_out(Data, Player, State) ->
gen_server:cast(Data#data.game, {'SET STATE', Player, ?PS_SIT_OUT}),
{next_state, State, Data}.
come_back(Data, Player, State) ->
gen_server:cast(Data#data.game, {'SET STATE', Player, ?PS_PLAY}),
{next_state, State, Data}.
advance_button(Data) ->
Game = Data#data.game,
B = Data#data.button_seat,
if
B == none ->
%% first hand of the game
start with the first player
Players = gen_server:call(Game, {'SEATS', ?PS_ANY}),
Button = lists:last(Players),
Bust = false;
true ->
start with the first
%% player after the button
Players = gen_server:call(Game, {'SEATS', B, ?PS_ANY}),
Button = hd(Players),
%% big blind is bust
BB = Data#data.big_blind_seat,
BBPlayer = gen_server:call(Game, {'PLAYER AT', BB}),
State = gen_server:call(Game, {'STATE', BBPlayer}),
Bust = ?PS_FOLD == State
end,
{Button, Bust}.
ask_for_blind(Data, Seat, Amount) ->
Game = Data#data.game,
FSM = gen_server:call(Game, 'FSM'),
Player = gen_server:call(Game, {'PLAYER AT', Seat}),
gen_server:cast(Player, {?PP_BET_REQ, FSM, Amount, 0, 0}),
Data1 = restart_timer(Data, Player),
Data1#data {
expected = {Player, Seat, Amount}
}.
cancel_timer(Data) ->
catch cardgame:cancel_timer(Data#data.timer).
restart_timer(Data, Msg) ->
Timeout = gen_server:call(Data#data.game, 'TIMEOUT'),
Data#data {
timer = cardgame:start_timer(Timeout, Msg)
}.
%%%
%%% Test suite
%%%
modules() ->
[ { delayed_start , [ 0 ] } ,
%% {blinds, []}].
[{blinds, []}].
make_game_heads_up() ->
Players = test:make_players(2),
Ctx = #texas {
small_blind_seat = none,
big_blind_seat = none,
button_seat = none
},
Game = test:make_test_game(Players, Ctx, modules()),
{Game, Players}.
make_game_3_bust() ->
Players = test:make_players(3),
Ctx = #texas {
small_blind_seat = element(2, lists:nth(2, Players)),
big_blind_seat = element(2, lists:nth(3, Players)),
button_seat = element(2, lists:nth(1, Players))
},
Game = test:make_test_game(Players, Ctx, modules()),
{Game, Players}.
make_game_5_bust() ->
make_game_5_bust(1, 2, 3).
make_game_5_bust(Button_N, SB_N, BB_N) ->
A = test:make_player('A'),
B = test:make_player('B'),
C = test:make_player('C'),
D = test:make_player('D'),
E = test:make_player('E'),
Players = [{A, 2}, {B, 4}, {C, 6}, {D, 8}, {E, 9}],
Ctx = #texas {
small_blind_seat = element(2, lists:nth(SB_N, Players)),
big_blind_seat = element(2, lists:nth(BB_N, Players)),
button_seat = element(2, lists:nth(Button_N, Players))
},
Game = test:make_test_game(10, Players, Ctx, modules()),
{Game, Players}.
test() ->
test3(),
test4(),
test5(),
test6(),
test7(),
test8(),
test9(),
test10(),
test11(),
test12(),
ok.
%% Both blinds are posted
post_blinds_trigger(Game, Event, Pid) ->
case Event of
{in, {'$gen_cast', {?PP_BET_REQ, Game, Amount, 0, 0}}} ->
%% post the blind
cardgame:send_event(Game, {?PP_CALL, Pid, Amount});
_ ->
ok
end,
Game.
test3() ->
{Game, Players} = make_game_heads_up(),
[A, B] = Players,
test:install_trigger(fun post_blinds_trigger/3, Game, [A, B]),
Ctx = #texas {
button_seat = element(2, A),
small_blind_seat = element(2, A),
big_blind_seat = element(2, B),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
%%%
3 players , button is bust
test4() ->
{Game, Players} = make_game_3_bust(),
[A, B, C] = Players,
cardgame:cast(Game, {'SET STATE', element(1, A), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [A, B, C]),
Ctx = #texas {
button_seat = element(2, C),
small_blind_seat = element(2, C),
big_blind_seat = element(2, B),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
3 players , small blind is bust
test5() ->
{Game, Players} = make_game_3_bust(),
[A, B, C] = Players,
cardgame:cast(Game, {'SET STATE', element(1, B), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [A, B, C]),
Ctx = #texas {
button_seat = element(2, C),
small_blind_seat = element(2, C),
big_blind_seat = element(2, A),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
3 players , big blind is bust
test6() ->
{Game, Players} = make_game_3_bust(),
[A, B, C] = Players,
cardgame:cast(Game, {'SET STATE', element(1, C), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [A, B, C]),
Ctx = #texas {
button_seat = element(2, B),
small_blind_seat = element(2, B),
big_blind_seat = element(2, A),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
5 players , small blind is bust
test7() ->
{Game, Players} = make_game_5_bust(),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, B), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, B),
small_blind_seat = element(2, C),
big_blind_seat = element(2, D),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
test8() ->
{Game, Players} = make_game_5_bust(2, 3, 4),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, B), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, C),
small_blind_seat = element(2, D),
big_blind_seat = element(2, E),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
5 players , big blind is bust
test9() ->
{Game, Players} = make_game_5_bust(),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, C), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, B),
small_blind_seat = element(2, C),
big_blind_seat = element(2, D),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
test10() ->
{Game, Players} = make_game_5_bust(2, 3, 4),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, C), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, C),
small_blind_seat = element(2, D),
big_blind_seat = element(2, E),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
5 players , both blinds are bust
test11() ->
{Game, Players} = make_game_5_bust(),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, B), ?PS_FOLD}),
cardgame:cast(Game, {'SET STATE', element(1, C), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, B),
small_blind_seat = element(2, C),
big_blind_seat = element(2, D),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
test12() ->
{Game, Players} = make_game_5_bust(2, 3, 4),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, B), ?PS_FOLD}),
cardgame:cast(Game, {'SET STATE', element(1, C), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, C),
small_blind_seat = element(2, D),
big_blind_seat = element(2, E),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
| null | https://raw.githubusercontent.com/puzza007/openpoker/bbd7158c81ba869f9f04ac7295c9fb7ea099a9d2/src/blinds.erl | erlang |
modify it under the terms of the GNU General Public
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.
License along with this library; if not, write to the Free Software
at for more information.
{Player, Seat, Amount}
Theory
before the flop and last after the flop. The player
Determine which player would have been the next big blind
... that player becomes the big blind and the other player
is the small blind (and button).
Small blind is eliminated. The player who was the big blind
now posts the small blind and the player to his left
posts the big blind. The button does not move and the player
who was the button, will be the button once again.
Big blind is eliminated. The player to the left of the eliminated
big blind now posts the big blind and there is no small blind
for that hand. The button moves to the player who was the small blind.
are posted normally.
advance button and broadcast position
collect blinds
after the button is the big blind
ask for big blind
is the big blind and the other player
is the small blind and button
it's us
small blind posted
it's us
big blind posted
record blind bets
adjust button if a heads-up game
notify players
Utility
remove small blind
gen_server:cast(Game, {?PP_LEAVE, Player}), % kick player
small blind can't leave
while we are collecting
the big blind
first hand of the game
player after the button
big blind is bust
Test suite
{blinds, []}].
Both blinds are posted
post the blind
| Copyright ( C ) 2005 Wager Labs , SA
This file is part of OpenPoker .
OpenPoker is free software ; you can redistribute it and/or
License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
You should have received a copy of the GNU General Public
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
Please visit or contact
-module(blinds).
-behaviour(cardgame).
-export([stop/1, test/0]).
-export([init/1, terminate/3]).
-export([handle_event/3, handle_info/3,
handle_sync_event/4, code_change/4]).
-export([small_blind/2, big_blind/2]).
-include("common.hrl").
-include("test.hrl").
-include("texas.hrl").
-include("proto.hrl").
-record(data, {
game,
context,
small_blind_seat,
big_blind_seat,
button_seat,
no_small_blind,
small_blind_amount,
small_blind_bet,
big_blind_amount,
timer,
type
}).
init([Game]) ->
init([Game, normal]);
init([Game, Type]) ->
{Small, Big} = gen_server:call(Game, 'BLINDS'),
Data = #data {
game = Game,
small_blind_amount = Small,
big_blind_amount = Big,
small_blind_bet = 0,
no_small_blind = false,
timer = none,
expected = {none, 0},
type = Type
},
{ok, small_blind, Data}.
stop(Ref) ->
cardgame:send_all_state_event(Ref, stop).
Heads - up play . The small blind is the button and acts first
who does not have the button is dealt the first card .
There are three players remaining and one is eliminated .
On the following hand , the button does not move and the two blinds
small_blind({'START', Context}, Data) ->
if
Data#data.type /= irc ->
Data1 = Data#data {
context = Context,
small_blind_seat = Context#texas.small_blind_seat,
big_blind_seat = Context#texas.big_blind_seat,
button_seat = Context#texas.button_seat
};
true ->
Data1 = Data#data {
context = Context,
small_blind_seat = none,
big_blind_seat = none,
button_seat = none
}
end,
Game = Data1#data.game,
{Button1, Bust} = advance_button(Data1),
gen_server:cast(Game, {'BROADCAST', {?PP_NOTIFY_BUTTON, Button1}}),
SBPlayers = gen_server:call(Game, {'SEATS', Button1, ?PS_ACTIVE}),
BBPlayers = gen_server:call(Game, {'SEATS', Button1, ?PS_BB_ACTIVE}),
L1 = length(SBPlayers),
L2 = length(BBPlayers),
two active , 0 waiting for bb
one active , one waiting for bb
BB_N = length(BBPlayers),
if
BB_N < 2 ->
{stop, {normal, restart}, Data1};
Bust and not HeadsUp ->
there 's no small blind so the first player
Data2 = Data1#data {
button_seat = Button1,
no_small_blind = true,
small_blind_seat = Data1#data.big_blind_seat
},
Amount = Data2#data.big_blind_amount,
Data3 = ask_for_blind(Data2, hd(BBPlayers), Amount),
{next_state, big_blind, Data3};
Bust and HeadsUp ->
the first player after the button
Data2 = Data1#data {
button_seat = Button1
},
Amount = Data2#data.small_blind_amount,
Data3 = ask_for_blind(Data2, lists:last(SBPlayers), Amount),
{next_state, small_blind, Data3};
true ->
Data2 = Data1#data {
button_seat = Button1
},
Amount = Data2#data.small_blind_amount,
Data3 = ask_for_blind(Data2, hd(SBPlayers), Amount),
{next_state, small_blind, Data3}
end;
small_blind({?PP_CALL, Player, Amount}, Data) ->
Game = Data#data.game,
{ExpPlayer, Seat, ExpAmount} = Data#data.expected,
if
ExpPlayer /= Player ->
{next_state, small_blind, Data};
true ->
cancel_timer(Data),
InPlay = gen_server:call(Player, 'INPLAY'),
if
(ExpAmount /= Amount) and
(InPlay /= Amount) ->
timeout(Data, Player, small_blind);
true ->
Data1 = Data#data {
small_blind_seat = Seat,
small_blind_bet = Amount
},
BBPlayers = gen_server:call(Game,
{'SEATS', Seat, ?PS_BB_ACTIVE}),
Data2 = ask_for_blind(Data1,
hd(BBPlayers),
Data1#data.big_blind_amount),
{next_state, big_blind, Data2}
end
end;
small_blind({?PP_FOLD, Player}, Data) ->
{ExpPlayer, _Seat, _ExpAmount} = Data#data.expected,
if
ExpPlayer /= Player ->
{next_state, small_blind, Data};
true ->
timeout(Data, Player, small_blind)
end;
small_blind({timeout, _Timer, Player}, Data) ->
cancel_timer(Data),
Game = Data#data.game,
GID = gen_server:call(Game, 'ID'),
Seat = gen_server:call(Game, {'WHAT SEAT', Player}),
error_logger:warning_report(
[{message, "Player timeout!"},
{module, ?MODULE},
{state, small_blind},
{player, Player},
{game, GID},
{seat, Seat},
{now, now()}]),
timeout(Data, Player, small_blind);
small_blind({?PP_JOIN, Player, SeatNum, BuyIn}, Data) ->
join(Data, Player, SeatNum, BuyIn, small_blind);
small_blind({?PP_LEAVE, Player}, Data) ->
leave(Data, Player, small_blind);
small_blind({?PP_SIT_OUT, Player}, Data) ->
sit_out(Data, Player, small_blind);
small_blind({?PP_COME_BACK, Player}, Data) ->
come_back(Data, Player, small_blind);
small_blind(Event, Data) ->
handle_event(Event, small_blind, Data).
big_blind({?PP_CALL, Player, Amount}, Data) ->
Game = Data#data.game,
{ExpPlayer, Seat, ExpAmount} = Data#data.expected,
if
ExpPlayer /= Player ->
{next_state, big_blind, Data};
true ->
cancel_timer(Data),
InPlay = gen_server:call(Player, 'INPLAY'),
if
(ExpAmount /= Amount) and
(InPlay /= Amount) ->
timeout(Data, Player, big_blind);
true ->
SB = Data#data.small_blind_seat,
BB = Seat,
SBPlayer = gen_server:call(Game, {'PLAYER AT', SB}),
BBPlayer = Player,
gen_server:cast(Game, {'SET STATE', SBPlayer, ?PS_PLAY}),
gen_server:cast(Game, {'SET STATE', BBPlayer, ?PS_PLAY}),
Small = Data#data.small_blind_bet,
Big = Amount,
if
Data#data.no_small_blind ->
ok;
true ->
gen_server:cast(Game, {'ADD BET', SBPlayer, Small})
end,
gen_server:cast(Game, {'ADD BET', BBPlayer, Big}),
Seats = gen_server:call(Game, {'SEATS', ?PS_ACTIVE}),
if
(length(Seats) == 2) and (Data#data.type /= irc) ->
Button = SB;
true ->
Button = Data#data.button_seat
end,
Data1 = Data#data {
big_blind_seat = BB,
button_seat = Button,
expected = {none, none, 0}
},
gen_server:cast(Game, {'BROADCAST', {?PP_NOTIFY_SB, SB}}),
gen_server:cast(Game, {'BROADCAST', {?PP_NOTIFY_BB, BB}}),
gen_server:cast(Game, {'BROADCAST',
{?PP_NOTIFY_BET, SBPlayer, Small}}),
gen_server:cast(Game, {'BROADCAST',
{?PP_NOTIFY_BET, BBPlayer, Big}}),
Ctx = Data#data.context,
Ctx1 = Ctx#texas {
call = Amount,
small_blind_seat = SB,
big_blind_seat = BB,
button_seat = Button
},
{stop, {normal, Ctx1}, Data1}
end
end;
big_blind({?PP_FOLD, Player}, Data) ->
{ExpPlayer, _Seat, _ExpAmount} = Data#data.expected,
if
ExpPlayer /= Player ->
{next_state, big_blind, Data};
true ->
timeout(Data, Player, big_blind)
end;
big_blind({timeout, _Timer, Player}, Data) ->
cancel_timer(Data),
Game = Data#data.game,
GID = gen_server:call(Game, 'ID'),
Seat = gen_server:call(Game, {'WHAT SEAT', Player}),
error_logger:warning_report(
[{message, "Player timeout!"},
{module, ?MODULE},
{state, big_blind},
{player, Player},
{game, GID},
{seat, Seat},
{now, now()}]),
timeout(Data, Player, big_blind);
big_blind({?PP_JOIN, Player, SeatNum, BuyIn}, Data) ->
join(Data, Player, SeatNum, BuyIn, big_blind);
big_blind({?PP_LEAVE, Player}, Data) ->
leave(Data, Player, big_blind);
big_blind({?PP_SIT_OUT, Player}, Data) ->
sit_out(Data, Player, big_blind);
big_blind({?PP_COME_BACK, Player}, Data) ->
come_back(Data, Player, big_blind);
big_blind(Event, Data) ->
handle_event(Event, big_blind, Data).
handle_event(stop, _State, Data) ->
{stop, normal, Data};
handle_event(Event, State, Data) ->
error_logger:error_report([{module, ?MODULE},
{line, ?LINE},
{where, handle_event},
{message, Event},
{self, self()},
{game, Data#data.game},
{expected, Data#data.expected},
{sb, Data#data.small_blind_seat},
{bb, Data#data.big_blind_seat},
{b, Data#data.button_seat}]),
{next_state, State, Data}.
handle_sync_event(Event, From, State, Data) ->
error_logger:error_report([{module, ?MODULE},
{line, ?LINE},
{where, handle_sync_event},
{message, Event},
{from, From},
{self, self()},
{game, Data#data.game},
{expected, Data#data.expected},
{sb, Data#data.small_blind_seat},
{bb, Data#data.big_blind_seat},
{b, Data#data.button_seat}]),
{next_state, State, Data}.
handle_info(Info, State, Data) ->
error_logger:error_report([{module, ?MODULE},
{line, ?LINE},
{where, handle_info},
{message, Info},
{self, self()},
{game, Data#data.game},
{expected, Data#data.expected},
{sb, Data#data.small_blind_seat},
{bb, Data#data.big_blind_seat},
{b, Data#data.button_seat}]),
{next_state, State, Data}.
terminate(_Reason, _State, _Data) ->
ok.
code_change(_OldVsn, State, Data, _Extra) ->
{ok, State, Data}.
timeout(Data, Player, State) ->
cancel_timer(Data),
Game = Data#data.game,
Seat = gen_server:call(Game, {'WHAT SEAT', Player}),
case State of
small_blind ->
Players = gen_server:call(Game, {'SEATS', Seat, ?PS_ACTIVE}),
Amount = Data#data.small_blind_amount,
Expected = 2;
_ ->
Temp = gen_server:call(Game, {'SEATS', Seat, ?PS_BB_ACTIVE}),
Players = lists:delete(Data#data.small_blind_seat, Temp),
Amount = Data#data.big_blind_amount,
Expected = 1
end,
Players1 = lists:delete(Seat, Players),
gen_server:cast(Game, {'SET STATE', Player, ?PS_SIT_OUT}),
if
length(Players1) < Expected ->
{stop, {normal, restart}, Data};
true ->
Data1 = ask_for_blind(Data, hd(Players1), Amount),
{next_state, State, Data1}
end.
join(Data, Player, SeatNum, BuyIn, State) ->
Game = Data#data.game,
gen_server:cast(Game, {?PP_JOIN, Player, SeatNum, BuyIn, ?PS_MAKEUP_BB}),
{next_state, State, Data}.
leave(Data, Player, State) ->
Game = Data#data.game,
Seat = gen_server:call(Game, {'WHAT SEAT', Player}),
if
(State == big_blind) and
(Seat == Data#data.small_blind_seat) ->
oops;
true ->
gen_server:cast(Game, {?PP_LEAVE, Player})
end,
{next_state, State, Data}.
sit_out(Data, Player, State) ->
gen_server:cast(Data#data.game, {'SET STATE', Player, ?PS_SIT_OUT}),
{next_state, State, Data}.
come_back(Data, Player, State) ->
gen_server:cast(Data#data.game, {'SET STATE', Player, ?PS_PLAY}),
{next_state, State, Data}.
advance_button(Data) ->
Game = Data#data.game,
B = Data#data.button_seat,
if
B == none ->
start with the first player
Players = gen_server:call(Game, {'SEATS', ?PS_ANY}),
Button = lists:last(Players),
Bust = false;
true ->
start with the first
Players = gen_server:call(Game, {'SEATS', B, ?PS_ANY}),
Button = hd(Players),
BB = Data#data.big_blind_seat,
BBPlayer = gen_server:call(Game, {'PLAYER AT', BB}),
State = gen_server:call(Game, {'STATE', BBPlayer}),
Bust = ?PS_FOLD == State
end,
{Button, Bust}.
ask_for_blind(Data, Seat, Amount) ->
Game = Data#data.game,
FSM = gen_server:call(Game, 'FSM'),
Player = gen_server:call(Game, {'PLAYER AT', Seat}),
gen_server:cast(Player, {?PP_BET_REQ, FSM, Amount, 0, 0}),
Data1 = restart_timer(Data, Player),
Data1#data {
expected = {Player, Seat, Amount}
}.
cancel_timer(Data) ->
catch cardgame:cancel_timer(Data#data.timer).
restart_timer(Data, Msg) ->
Timeout = gen_server:call(Data#data.game, 'TIMEOUT'),
Data#data {
timer = cardgame:start_timer(Timeout, Msg)
}.
modules() ->
[ { delayed_start , [ 0 ] } ,
[{blinds, []}].
make_game_heads_up() ->
Players = test:make_players(2),
Ctx = #texas {
small_blind_seat = none,
big_blind_seat = none,
button_seat = none
},
Game = test:make_test_game(Players, Ctx, modules()),
{Game, Players}.
make_game_3_bust() ->
Players = test:make_players(3),
Ctx = #texas {
small_blind_seat = element(2, lists:nth(2, Players)),
big_blind_seat = element(2, lists:nth(3, Players)),
button_seat = element(2, lists:nth(1, Players))
},
Game = test:make_test_game(Players, Ctx, modules()),
{Game, Players}.
make_game_5_bust() ->
make_game_5_bust(1, 2, 3).
make_game_5_bust(Button_N, SB_N, BB_N) ->
A = test:make_player('A'),
B = test:make_player('B'),
C = test:make_player('C'),
D = test:make_player('D'),
E = test:make_player('E'),
Players = [{A, 2}, {B, 4}, {C, 6}, {D, 8}, {E, 9}],
Ctx = #texas {
small_blind_seat = element(2, lists:nth(SB_N, Players)),
big_blind_seat = element(2, lists:nth(BB_N, Players)),
button_seat = element(2, lists:nth(Button_N, Players))
},
Game = test:make_test_game(10, Players, Ctx, modules()),
{Game, Players}.
test() ->
test3(),
test4(),
test5(),
test6(),
test7(),
test8(),
test9(),
test10(),
test11(),
test12(),
ok.
post_blinds_trigger(Game, Event, Pid) ->
case Event of
{in, {'$gen_cast', {?PP_BET_REQ, Game, Amount, 0, 0}}} ->
cardgame:send_event(Game, {?PP_CALL, Pid, Amount});
_ ->
ok
end,
Game.
test3() ->
{Game, Players} = make_game_heads_up(),
[A, B] = Players,
test:install_trigger(fun post_blinds_trigger/3, Game, [A, B]),
Ctx = #texas {
button_seat = element(2, A),
small_blind_seat = element(2, A),
big_blind_seat = element(2, B),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
3 players , button is bust
test4() ->
{Game, Players} = make_game_3_bust(),
[A, B, C] = Players,
cardgame:cast(Game, {'SET STATE', element(1, A), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [A, B, C]),
Ctx = #texas {
button_seat = element(2, C),
small_blind_seat = element(2, C),
big_blind_seat = element(2, B),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
3 players , small blind is bust
test5() ->
{Game, Players} = make_game_3_bust(),
[A, B, C] = Players,
cardgame:cast(Game, {'SET STATE', element(1, B), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [A, B, C]),
Ctx = #texas {
button_seat = element(2, C),
small_blind_seat = element(2, C),
big_blind_seat = element(2, A),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
3 players , big blind is bust
test6() ->
{Game, Players} = make_game_3_bust(),
[A, B, C] = Players,
cardgame:cast(Game, {'SET STATE', element(1, C), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [A, B, C]),
Ctx = #texas {
button_seat = element(2, B),
small_blind_seat = element(2, B),
big_blind_seat = element(2, A),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
5 players , small blind is bust
test7() ->
{Game, Players} = make_game_5_bust(),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, B), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, B),
small_blind_seat = element(2, C),
big_blind_seat = element(2, D),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
test8() ->
{Game, Players} = make_game_5_bust(2, 3, 4),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, B), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, C),
small_blind_seat = element(2, D),
big_blind_seat = element(2, E),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
5 players , big blind is bust
test9() ->
{Game, Players} = make_game_5_bust(),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, C), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, B),
small_blind_seat = element(2, C),
big_blind_seat = element(2, D),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
test10() ->
{Game, Players} = make_game_5_bust(2, 3, 4),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, C), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, C),
small_blind_seat = element(2, D),
big_blind_seat = element(2, E),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
5 players , both blinds are bust
test11() ->
{Game, Players} = make_game_5_bust(),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, B), ?PS_FOLD}),
cardgame:cast(Game, {'SET STATE', element(1, C), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, B),
small_blind_seat = element(2, C),
big_blind_seat = element(2, D),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
test12() ->
{Game, Players} = make_game_5_bust(2, 3, 4),
[_, B, C, D, E] = Players,
cardgame:cast(Game, {'SET STATE', element(1, B), ?PS_FOLD}),
cardgame:cast(Game, {'SET STATE', element(1, C), ?PS_FOLD}),
test:install_trigger(fun post_blinds_trigger/3, Game, [B, C, D, E]),
Ctx = #texas {
button_seat = element(2, C),
small_blind_seat = element(2, D),
big_blind_seat = element(2, E),
call = 10
},
?match(success, ?waitmsg({'CARDGAME EXIT', Game, Ctx}, 1000)),
cardgame:stop(Game),
test:kill_players(Players).
|
7bd03d990db57e102613070ba3edd51451d1781024add22e1ebe9879070c2c4b | shortishly/pgmp | pgmp_pool_connection_sup.erl | Copyright ( c ) 2022 < >
%%
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.
-module(pgmp_pool_connection_sup).
-behaviour(supervisor).
-export([init/1]).
-export([start_link/1]).
-import(pgmp_sup, [worker/1]).
start_link(#{config := Config} = Arg) ->
supervisor:start_link(
?MODULE,
[Arg#{config := Config#{replication => fun replication/0,
group => interactive}}]).
replication() ->
<<"false">>.
init([Arg]) ->
{ok, configuration(children(Arg))}.
configuration(Children) ->
{maps:merge(
#{auto_shutdown => any_significant,
strategy => one_for_all},
pgmp_config:sup_flags(?MODULE)),
Children}.
children(Arg) ->
[worker(#{m => M,
restart => temporary,
significant => true,
args => [Arg#{supervisor => self()}]}) || M <- workers()].
workers() ->
[pgmp_socket, pgmp_mm].
| null | https://raw.githubusercontent.com/shortishly/pgmp/af2d815d187fde523654a01d0c8b6a77e29815d8/src/pgmp_pool_connection_sup.erl | erlang |
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. | Copyright ( c ) 2022 < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(pgmp_pool_connection_sup).
-behaviour(supervisor).
-export([init/1]).
-export([start_link/1]).
-import(pgmp_sup, [worker/1]).
start_link(#{config := Config} = Arg) ->
supervisor:start_link(
?MODULE,
[Arg#{config := Config#{replication => fun replication/0,
group => interactive}}]).
replication() ->
<<"false">>.
init([Arg]) ->
{ok, configuration(children(Arg))}.
configuration(Children) ->
{maps:merge(
#{auto_shutdown => any_significant,
strategy => one_for_all},
pgmp_config:sup_flags(?MODULE)),
Children}.
children(Arg) ->
[worker(#{m => M,
restart => temporary,
significant => true,
args => [Arg#{supervisor => self()}]}) || M <- workers()].
workers() ->
[pgmp_socket, pgmp_mm].
|
bd8519b7d3e5cbf8135cbbfacd27eae4e7eca49445b59bc63a1dc7ebb2857bfe | xavierleroy/camlidl | utils.mli | (***********************************************************************)
(* *)
(* CamlIDL *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1999 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 LGPL v2.1 *)
(* *)
(***********************************************************************)
$ I d : utils.mli , v 1.12 2004 - 01 - 09 21:12:12 doligez Exp $
(* Utility functions *)
val iprintf : out_channel -> ('a, out_channel, unit) format -> 'a
val increase_indent : unit -> unit
val decrease_indent : unit -> unit
val divert_output : unit -> out_channel
val end_diversion : out_channel -> unit
val module_name : string ref
val current_function : string ref
val error : string -> 'a
exception Error
val list_filter : ('a -> bool) -> 'a list -> 'a list
val list_partition : ('a -> bool) -> 'a list -> 'a list * 'a list
val map_index : (int -> 'a -> 'b) -> int -> 'a list -> 'b list
val iter_index : (int -> 'a -> unit) -> int -> 'a list -> unit
val find_in_path : string list -> string -> string
(*external ignore: 'a -> unit = "%identity"*)
val remove_file : string -> unit
| null | https://raw.githubusercontent.com/xavierleroy/camlidl/b192760875fe6e97b13004bd289720618e12ee22/compiler/utils.mli | ocaml | *********************************************************************
CamlIDL
under the terms of the GNU Lesser General Public License LGPL v2.1
*********************************************************************
Utility functions
external ignore: 'a -> unit = "%identity" | , projet Cristal , INRIA Rocquencourt
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
$ I d : utils.mli , v 1.12 2004 - 01 - 09 21:12:12 doligez Exp $
val iprintf : out_channel -> ('a, out_channel, unit) format -> 'a
val increase_indent : unit -> unit
val decrease_indent : unit -> unit
val divert_output : unit -> out_channel
val end_diversion : out_channel -> unit
val module_name : string ref
val current_function : string ref
val error : string -> 'a
exception Error
val list_filter : ('a -> bool) -> 'a list -> 'a list
val list_partition : ('a -> bool) -> 'a list -> 'a list * 'a list
val map_index : (int -> 'a -> 'b) -> int -> 'a list -> 'b list
val iter_index : (int -> 'a -> unit) -> int -> 'a list -> unit
val find_in_path : string list -> string -> string
val remove_file : string -> unit
|
b37ebf7e573bd364deb591f6c446fcea5a025e96216d396b8d6a07df17b20a7e | RyanGlScott/text-show-instances | TransSpec.hs | |
Module : Spec . Control . Applicative . TransSpec
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
@hspec@ tests for applicative functor transformers .
Module: Spec.Control.Applicative.TransSpec
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
@hspec@ tests for applicative functor transformers.
-}
module Spec.Control.Applicative.TransSpec (main, spec) where
import Control.Applicative.Backwards (Backwards)
import Control.Applicative.Lift (Lift)
import Data.Proxy (Proxy(..))
import Spec.Utils (matchesTextShowSpec)
import Test.Hspec (Spec, describe, hspec, parallel)
import Test.QuickCheck.Instances ()
import TextShow.Control.Applicative.Trans ()
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
describe "Backwards Maybe Int" $
matchesTextShowSpec (Proxy :: Proxy (Backwards Maybe Int))
describe "Lift Maybe Int" $
matchesTextShowSpec (Proxy :: Proxy (Lift Maybe Int))
| null | https://raw.githubusercontent.com/RyanGlScott/text-show-instances/a6eed4958b47016105d6a2417471c3e53c8d8b01/tests/Spec/Control/Applicative/TransSpec.hs | haskell | |
Module : Spec . Control . Applicative . TransSpec
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
@hspec@ tests for applicative functor transformers .
Module: Spec.Control.Applicative.TransSpec
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
@hspec@ tests for applicative functor transformers.
-}
module Spec.Control.Applicative.TransSpec (main, spec) where
import Control.Applicative.Backwards (Backwards)
import Control.Applicative.Lift (Lift)
import Data.Proxy (Proxy(..))
import Spec.Utils (matchesTextShowSpec)
import Test.Hspec (Spec, describe, hspec, parallel)
import Test.QuickCheck.Instances ()
import TextShow.Control.Applicative.Trans ()
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
describe "Backwards Maybe Int" $
matchesTextShowSpec (Proxy :: Proxy (Backwards Maybe Int))
describe "Lift Maybe Int" $
matchesTextShowSpec (Proxy :: Proxy (Lift Maybe Int))
| |
c810150666c9659ee7683a0a015424f7cf4a3d1fc7638986ee7172b84f6035a5 | lambdaisland/kaocha | repl_test.clj | (ns kaocha.repl-test
(:require [clojure.test :refer :all]
[kaocha.repl :as repl]
[kaocha.config :as config]))
(deftest config-test
(is (match?
'{:kaocha/tests [{:kaocha.testable/id :foo
:kaocha/test-paths ["test/foo"]}]
:kaocha/reporter [kaocha.report.progress/report]
:kaocha/color? false
:kaocha/fail-fast? true
:kaocha/plugins [:kaocha.plugin/randomize
:kaocha.plugin/filter
:kaocha.plugin/capture-output
:kaocha.plugin.alpha/xfail]}
(repl/config {:config-file "fixtures/custom_config.edn"}))))
(deftest extra-config-test
(is (match?
'{:kaocha/tests [{:kaocha.testable/id :foo
:kaocha/test-paths ["test/foo"]}]
:kaocha/reporter [kaocha.report.progress/report]
:kaocha/color? true
:kaocha/fail-fast? true
:kaocha/plugins [:kaocha.plugin/randomize
:kaocha.plugin/filter
:kaocha.plugin/capture-output
:kaocha.plugin.alpha/xfail]}
(repl/config {:color? true :config-file "fixtures/custom_config.edn"}))))
(deftest config-with-profile-test
(testing "specifying a profile"
(is (match?
'{:kaocha/tests [{:kaocha.testable/id :unit
:kaocha/test-paths ["test"]}]
:kaocha/reporter kaocha.report.progress/report }
(repl/config {:profile :test :config-file "test/unit/kaocha/config/loaded-test-profile.edn"}))))
(testing "not specifying a profile"
(is (match?
'{:kaocha/tests [{:kaocha.testable/id :unit
:kaocha/test-paths ["test"]}]
:kaocha/reporter kaocha.report/documentation }
(repl/config {:config-file "test/unit/kaocha/config/loaded-test-profile.edn"})))))
| null | https://raw.githubusercontent.com/lambdaisland/kaocha/8e9cf5f17673c5b58784eefe4aac1c5ea62ab127/test/unit/kaocha/repl_test.clj | clojure | (ns kaocha.repl-test
(:require [clojure.test :refer :all]
[kaocha.repl :as repl]
[kaocha.config :as config]))
(deftest config-test
(is (match?
'{:kaocha/tests [{:kaocha.testable/id :foo
:kaocha/test-paths ["test/foo"]}]
:kaocha/reporter [kaocha.report.progress/report]
:kaocha/color? false
:kaocha/fail-fast? true
:kaocha/plugins [:kaocha.plugin/randomize
:kaocha.plugin/filter
:kaocha.plugin/capture-output
:kaocha.plugin.alpha/xfail]}
(repl/config {:config-file "fixtures/custom_config.edn"}))))
(deftest extra-config-test
(is (match?
'{:kaocha/tests [{:kaocha.testable/id :foo
:kaocha/test-paths ["test/foo"]}]
:kaocha/reporter [kaocha.report.progress/report]
:kaocha/color? true
:kaocha/fail-fast? true
:kaocha/plugins [:kaocha.plugin/randomize
:kaocha.plugin/filter
:kaocha.plugin/capture-output
:kaocha.plugin.alpha/xfail]}
(repl/config {:color? true :config-file "fixtures/custom_config.edn"}))))
(deftest config-with-profile-test
(testing "specifying a profile"
(is (match?
'{:kaocha/tests [{:kaocha.testable/id :unit
:kaocha/test-paths ["test"]}]
:kaocha/reporter kaocha.report.progress/report }
(repl/config {:profile :test :config-file "test/unit/kaocha/config/loaded-test-profile.edn"}))))
(testing "not specifying a profile"
(is (match?
'{:kaocha/tests [{:kaocha.testable/id :unit
:kaocha/test-paths ["test"]}]
:kaocha/reporter kaocha.report/documentation }
(repl/config {:config-file "test/unit/kaocha/config/loaded-test-profile.edn"})))))
| |
5718f7821122d2a3f32095bd55c828860636bacdf826e654e5d41533128c5d61 | bennn/iPoe | bad-syllables.rkt | #lang ipoe/haiku
a line with five words
a line with five words
a line with five words
| null | https://raw.githubusercontent.com/bennn/iPoe/4a988f6537fb738b4fe842c404f9d78f658ab76f/examples/haiku/bad-syllables.rkt | racket | #lang ipoe/haiku
a line with five words
a line with five words
a line with five words
| |
bfb3daf5504a4cc89a7c38993c8d735bb1b33673cdc212e86e8680f250dfe3d7 | Julow/ocaml-java | unwrap.ml | open Parsetree
open Longident
open Asttypes
(** Decode a class declaration node
Raising a location error on syntax error
(see `class_` below) *)
(** Unwrap a method type
Returns the tuple (args core_type list, return core_type) *)
let rec method_type =
function
| [%type: [%t? lhs] -> [%t? rhs]] ->
let args, ret = method_type rhs in
lhs :: args, ret
| t -> [], t
* Unwrap a class field
Returns one of
` Method ( name , java_name , method_type )
` Method_static ..
` Field ( name , java_name , core_type )
` Field_static ..
` Constructor ( name , args core_type list )
Raises a location error on syntax errors
Returns one of
`Method (name, java_name, method_type)
`Method_static ..
`Field (name, java_name, core_type)
`Field_static ..
`Constructor (name, args core_type list)
Raises a location error on syntax errors *)
let class_field =
let rec is_static =
function
| ({ txt = "static"; _ }, PStr []) :: _ -> true
| [] -> false
| _ :: tl -> is_static tl
in
function
| { pcf_desc = Pcf_method ({ txt = name; _ }, visi, impl); pcf_loc = loc;
pcf_attributes } ->
begin match impl with
| _ when visi <> Public ->
Location.raise_errorf ~loc "Private method"
| Cfk_concrete (Fresh, { pexp_desc = Pexp_poly (
{ pexp_desc = Pexp_constant (Pconst_string (jname, None)); _ },
Some mtype); _ }) ->
let static = is_static pcf_attributes in
`Method (name, jname, method_type mtype, static)
| Cfk_concrete (Fresh, { pexp_desc = Pexp_poly (
{ pexp_loc = loc; _ }, _); _ }) ->
Location.raise_errorf ~loc "Expecting Java method name"
| Cfk_concrete (Fresh,
{ pexp_loc = loc; _ }) ->
Location.raise_errorf ~loc "Expecting method signature"
| Cfk_virtual _ ->
Location.raise_errorf ~loc "Virtual method"
| Cfk_concrete (Override, _) ->
Location.raise_errorf ~loc "Override method"
end
| { pcf_desc = Pcf_val ({ txt = name; _ }, mut, impl); pcf_loc = loc;
pcf_attributes } ->
begin match impl with
| Cfk_concrete (Fresh, { pexp_desc = Pexp_constraint (
{ pexp_desc = Pexp_constant (Pconst_string (jname, None)); _ },
ftype ); _ }) ->
let static = is_static pcf_attributes in
`Field (name, jname, ftype, mut = Mutable, static)
| Cfk_concrete (Fresh, { pexp_desc = Pexp_constraint (
{ pexp_loc = loc; _ }, _ ); _ }) ->
Location.raise_errorf ~loc "Expecting Java field name"
| Cfk_concrete (Fresh, { pexp_loc = loc; _ }) ->
Location.raise_errorf ~loc "Expecting field type"
| Cfk_virtual _ ->
Location.raise_errorf ~loc "Virtual field"
| Cfk_concrete (Override, _) ->
Location.raise_errorf ~loc "Override field"
end
| { pcf_desc = Pcf_initializer { pexp_desc =
Pexp_constraint ({ pexp_desc = Pexp_ident { txt = Lident name; _ };
pexp_loc = loc; _ }, ctype); _ }; _ } ->
begin match method_type ctype with
| args, { ptyp_desc = Ptyp_any; _ } ->
`Constructor (name, args)
| _ -> Location.raise_errorf ~loc "Constructor must returns `_'"
end
| { pcf_desc = Pcf_initializer { pexp_desc = Pexp_constraint (
{ pexp_loc = loc; _ }, _); _ }; _ } ->
Location.raise_errorf ~loc "Expecting constructor name"
| { pcf_desc = Pcf_initializer { pexp_loc = loc; _ }; _ } ->
Location.raise_errorf ~loc "Expecting constructor"
| { pcf_desc = Pcf_inherit (Fresh, { pcl_desc =
Pcl_constr ({ txt = id; _ }, []); _ }, None); _ } ->
`Inherit id
| { pcf_desc = Pcf_inherit (Fresh, { pcl_loc = loc; _ }, None); _ } ->
Location.raise_errorf ~loc "Expecting class name"
| { pcf_desc = Pcf_inherit (Fresh, _, Some { loc; _ }); _ } ->
Location.raise_errorf ~loc "Unsupported syntax"
| { pcf_desc = Pcf_inherit (Override, _, _); pcf_loc = loc; _ } ->
Location.raise_errorf ~loc "Override inherit"
| { pcf_loc = loc; _ } -> Location.raise_errorf ~loc "Unsupported"
* Unwrap the class_info node
Returns the tuple ( class_name , java_path , class_field list )
Raises a location error on syntax errors
Returns the tuple (class_name, java_path, class_field list)
Raises a location error on syntax errors *)
let class_ =
function
| { pci_name = { txt = class_name; _ };
pci_expr = { pcl_desc = Pcl_fun (Nolabel, None,
{ ppat_desc = Ppat_constant (Pconst_string (java_path, None)); _ },
{ pcl_desc = Pcl_structure {
pcstr_self = { ppat_desc = Ppat_any; _ };
pcstr_fields = fields }; _ }); _ }; _ } ->
let supers, fields = List.fold_right (fun field (s, f) ->
match class_field field with
| `Inherit s' -> s' :: s, f
| (`Method _ | `Field _ | `Constructor _) as f' ->
s, (f', field.pcf_loc) :: f
) fields ([], []) in
class_name, java_path, supers, fields
| { pci_expr = { pcl_desc = Pcl_fun (_, _, _, { pcl_desc = Pcl_structure {
pcstr_self = { ppat_desc; ppat_loc = loc; _ }; _
}; _}); _}; _ } when ppat_desc <> Ppat_any ->
Location.raise_errorf ~loc "self is not allowed"
| { pci_expr = { pcl_desc = Pcl_fun (_, _, { ppat_desc =
Ppat_constant (Pconst_string _); _ }, { pcl_loc = loc; _ }); _ }; _ } ->
Location.raise_errorf ~loc "Expecting object"
| { pci_loc = loc; _ } ->
Location.raise_errorf ~loc "Expecting Java class path"
| null | https://raw.githubusercontent.com/Julow/ocaml-java/5387eb7d85b3e1bbab35b7cc2c5a927193e8d299/ppx/unwrap.ml | ocaml | * Decode a class declaration node
Raising a location error on syntax error
(see `class_` below)
* Unwrap a method type
Returns the tuple (args core_type list, return core_type) | open Parsetree
open Longident
open Asttypes
let rec method_type =
function
| [%type: [%t? lhs] -> [%t? rhs]] ->
let args, ret = method_type rhs in
lhs :: args, ret
| t -> [], t
* Unwrap a class field
Returns one of
` Method ( name , java_name , method_type )
` Method_static ..
` Field ( name , java_name , core_type )
` Field_static ..
` Constructor ( name , args core_type list )
Raises a location error on syntax errors
Returns one of
`Method (name, java_name, method_type)
`Method_static ..
`Field (name, java_name, core_type)
`Field_static ..
`Constructor (name, args core_type list)
Raises a location error on syntax errors *)
let class_field =
let rec is_static =
function
| ({ txt = "static"; _ }, PStr []) :: _ -> true
| [] -> false
| _ :: tl -> is_static tl
in
function
| { pcf_desc = Pcf_method ({ txt = name; _ }, visi, impl); pcf_loc = loc;
pcf_attributes } ->
begin match impl with
| _ when visi <> Public ->
Location.raise_errorf ~loc "Private method"
| Cfk_concrete (Fresh, { pexp_desc = Pexp_poly (
{ pexp_desc = Pexp_constant (Pconst_string (jname, None)); _ },
Some mtype); _ }) ->
let static = is_static pcf_attributes in
`Method (name, jname, method_type mtype, static)
| Cfk_concrete (Fresh, { pexp_desc = Pexp_poly (
{ pexp_loc = loc; _ }, _); _ }) ->
Location.raise_errorf ~loc "Expecting Java method name"
| Cfk_concrete (Fresh,
{ pexp_loc = loc; _ }) ->
Location.raise_errorf ~loc "Expecting method signature"
| Cfk_virtual _ ->
Location.raise_errorf ~loc "Virtual method"
| Cfk_concrete (Override, _) ->
Location.raise_errorf ~loc "Override method"
end
| { pcf_desc = Pcf_val ({ txt = name; _ }, mut, impl); pcf_loc = loc;
pcf_attributes } ->
begin match impl with
| Cfk_concrete (Fresh, { pexp_desc = Pexp_constraint (
{ pexp_desc = Pexp_constant (Pconst_string (jname, None)); _ },
ftype ); _ }) ->
let static = is_static pcf_attributes in
`Field (name, jname, ftype, mut = Mutable, static)
| Cfk_concrete (Fresh, { pexp_desc = Pexp_constraint (
{ pexp_loc = loc; _ }, _ ); _ }) ->
Location.raise_errorf ~loc "Expecting Java field name"
| Cfk_concrete (Fresh, { pexp_loc = loc; _ }) ->
Location.raise_errorf ~loc "Expecting field type"
| Cfk_virtual _ ->
Location.raise_errorf ~loc "Virtual field"
| Cfk_concrete (Override, _) ->
Location.raise_errorf ~loc "Override field"
end
| { pcf_desc = Pcf_initializer { pexp_desc =
Pexp_constraint ({ pexp_desc = Pexp_ident { txt = Lident name; _ };
pexp_loc = loc; _ }, ctype); _ }; _ } ->
begin match method_type ctype with
| args, { ptyp_desc = Ptyp_any; _ } ->
`Constructor (name, args)
| _ -> Location.raise_errorf ~loc "Constructor must returns `_'"
end
| { pcf_desc = Pcf_initializer { pexp_desc = Pexp_constraint (
{ pexp_loc = loc; _ }, _); _ }; _ } ->
Location.raise_errorf ~loc "Expecting constructor name"
| { pcf_desc = Pcf_initializer { pexp_loc = loc; _ }; _ } ->
Location.raise_errorf ~loc "Expecting constructor"
| { pcf_desc = Pcf_inherit (Fresh, { pcl_desc =
Pcl_constr ({ txt = id; _ }, []); _ }, None); _ } ->
`Inherit id
| { pcf_desc = Pcf_inherit (Fresh, { pcl_loc = loc; _ }, None); _ } ->
Location.raise_errorf ~loc "Expecting class name"
| { pcf_desc = Pcf_inherit (Fresh, _, Some { loc; _ }); _ } ->
Location.raise_errorf ~loc "Unsupported syntax"
| { pcf_desc = Pcf_inherit (Override, _, _); pcf_loc = loc; _ } ->
Location.raise_errorf ~loc "Override inherit"
| { pcf_loc = loc; _ } -> Location.raise_errorf ~loc "Unsupported"
* Unwrap the class_info node
Returns the tuple ( class_name , java_path , class_field list )
Raises a location error on syntax errors
Returns the tuple (class_name, java_path, class_field list)
Raises a location error on syntax errors *)
let class_ =
function
| { pci_name = { txt = class_name; _ };
pci_expr = { pcl_desc = Pcl_fun (Nolabel, None,
{ ppat_desc = Ppat_constant (Pconst_string (java_path, None)); _ },
{ pcl_desc = Pcl_structure {
pcstr_self = { ppat_desc = Ppat_any; _ };
pcstr_fields = fields }; _ }); _ }; _ } ->
let supers, fields = List.fold_right (fun field (s, f) ->
match class_field field with
| `Inherit s' -> s' :: s, f
| (`Method _ | `Field _ | `Constructor _) as f' ->
s, (f', field.pcf_loc) :: f
) fields ([], []) in
class_name, java_path, supers, fields
| { pci_expr = { pcl_desc = Pcl_fun (_, _, _, { pcl_desc = Pcl_structure {
pcstr_self = { ppat_desc; ppat_loc = loc; _ }; _
}; _}); _}; _ } when ppat_desc <> Ppat_any ->
Location.raise_errorf ~loc "self is not allowed"
| { pci_expr = { pcl_desc = Pcl_fun (_, _, { ppat_desc =
Ppat_constant (Pconst_string _); _ }, { pcl_loc = loc; _ }); _ }; _ } ->
Location.raise_errorf ~loc "Expecting object"
| { pci_loc = loc; _ } ->
Location.raise_errorf ~loc "Expecting Java class path"
|
a00538afed5689752f45ccf73de807e7c77d64b99128985ef6f7758cecbe1d16 | ds-wizard/engine-backend | SubmissionDAO.hs | module Wizard.Database.DAO.Submission.SubmissionDAO where
import Control.Monad.Reader (asks, liftIO)
import Data.String
import Data.Time
import qualified Data.UUID as U
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
import GHC.Int
import Wizard.Database.DAO.Common
import Wizard.Database.Mapping.Submission.Submission ()
import Wizard.Model.Context.AppContext
import Wizard.Model.Context.ContextLenses ()
import Wizard.Model.Submission.Submission
entityName = "submission"
pageLabel = "submissions"
findSubmissions :: AppContextM [Submission]
findSubmissions = do
appUuid <- asks currentAppUuid
createFindEntitiesByFn entityName [appQueryUuid appUuid]
findSubmissionsFiltered :: [(String, String)] -> AppContextM [Submission]
findSubmissionsFiltered params = do
appUuid <- asks currentAppUuid
createFindEntitiesByFn entityName (appQueryUuid appUuid : params)
findSubmissionsByDocumentUuid :: U.UUID -> AppContextM [Submission]
findSubmissionsByDocumentUuid documentUuid = do
appUuid <- asks currentAppUuid
createFindEntitiesByFn entityName [appQueryUuid appUuid, ("document_uuid", U.toString documentUuid)]
findSubmissionById :: String -> AppContextM Submission
findSubmissionById uuid = do
appUuid <- asks currentAppUuid
createFindEntityByFn entityName [appQueryUuid appUuid, ("uuid", uuid)]
insertSubmission :: Submission -> AppContextM Int64
insertSubmission = createInsertFn entityName
updateSubmissionById :: Submission -> AppContextM Submission
updateSubmissionById sub = do
now <- liftIO getCurrentTime
appUuid <- asks currentAppUuid
let updatedSub = sub {updatedAt = now}
let sql =
fromString
"UPDATE submission SET uuid = ?, state = ?, location = ?, returned_data = ?, service_id = ?, document_uuid = ?, created_by = ?, created_at = ?, updated_at = ?, app_uuid = ? WHERE app_uuid = ? AND uuid = ?"
let params = toRow sub ++ [toField appUuid, toField updatedSub.uuid]
logQuery sql params
let action conn = execute conn sql params
runDB action
return updatedSub
deleteSubmissions :: AppContextM Int64
deleteSubmissions = createDeleteEntitiesFn entityName
deleteSubmissionsFiltered :: [(String, String)] -> AppContextM Int64
deleteSubmissionsFiltered params = do
appUuid <- asks currentAppUuid
createDeleteEntitiesByFn entityName (appQueryUuid appUuid : params)
deleteSubmissionById :: String -> AppContextM Int64
deleteSubmissionById uuid = do
appUuid <- asks currentAppUuid
createDeleteEntityByFn entityName [appQueryUuid appUuid, ("uuid", uuid)]
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/src/Wizard/Database/DAO/Submission/SubmissionDAO.hs | haskell | module Wizard.Database.DAO.Submission.SubmissionDAO where
import Control.Monad.Reader (asks, liftIO)
import Data.String
import Data.Time
import qualified Data.UUID as U
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.ToRow
import GHC.Int
import Wizard.Database.DAO.Common
import Wizard.Database.Mapping.Submission.Submission ()
import Wizard.Model.Context.AppContext
import Wizard.Model.Context.ContextLenses ()
import Wizard.Model.Submission.Submission
entityName = "submission"
pageLabel = "submissions"
findSubmissions :: AppContextM [Submission]
findSubmissions = do
appUuid <- asks currentAppUuid
createFindEntitiesByFn entityName [appQueryUuid appUuid]
findSubmissionsFiltered :: [(String, String)] -> AppContextM [Submission]
findSubmissionsFiltered params = do
appUuid <- asks currentAppUuid
createFindEntitiesByFn entityName (appQueryUuid appUuid : params)
findSubmissionsByDocumentUuid :: U.UUID -> AppContextM [Submission]
findSubmissionsByDocumentUuid documentUuid = do
appUuid <- asks currentAppUuid
createFindEntitiesByFn entityName [appQueryUuid appUuid, ("document_uuid", U.toString documentUuid)]
findSubmissionById :: String -> AppContextM Submission
findSubmissionById uuid = do
appUuid <- asks currentAppUuid
createFindEntityByFn entityName [appQueryUuid appUuid, ("uuid", uuid)]
insertSubmission :: Submission -> AppContextM Int64
insertSubmission = createInsertFn entityName
updateSubmissionById :: Submission -> AppContextM Submission
updateSubmissionById sub = do
now <- liftIO getCurrentTime
appUuid <- asks currentAppUuid
let updatedSub = sub {updatedAt = now}
let sql =
fromString
"UPDATE submission SET uuid = ?, state = ?, location = ?, returned_data = ?, service_id = ?, document_uuid = ?, created_by = ?, created_at = ?, updated_at = ?, app_uuid = ? WHERE app_uuid = ? AND uuid = ?"
let params = toRow sub ++ [toField appUuid, toField updatedSub.uuid]
logQuery sql params
let action conn = execute conn sql params
runDB action
return updatedSub
deleteSubmissions :: AppContextM Int64
deleteSubmissions = createDeleteEntitiesFn entityName
deleteSubmissionsFiltered :: [(String, String)] -> AppContextM Int64
deleteSubmissionsFiltered params = do
appUuid <- asks currentAppUuid
createDeleteEntitiesByFn entityName (appQueryUuid appUuid : params)
deleteSubmissionById :: String -> AppContextM Int64
deleteSubmissionById uuid = do
appUuid <- asks currentAppUuid
createDeleteEntityByFn entityName [appQueryUuid appUuid, ("uuid", uuid)]
| |
f78cc9bcdfbee82aebe69d103bc02e39271aba2e9d024160d6730a5578a0c439 | ryzhyk/cocoon | Statement.hs |
Copyrights ( c ) 2016 . Samsung Electronics Ltd. All right 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 .
Copyrights (c) 2016. Samsung Electronics Ltd. All right 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.
-}
module Statement( statFold
, statFuncsRec
, statIsDeterministic
, statIsMulticast
, statSendsTo
, statSendsToRoles) where
import Data.List
import Expr
import Syntax
statFold :: (a -> Statement -> a) -> a -> Statement -> a
statFold f acc s =
case s of
SSeq _ l r -> statFold f (statFold f acc' l) r
SPar _ l r -> statFold f (statFold f acc' l) r
SITE _ _ t e -> maybe (statFold f acc' t) (statFold f (statFold f acc' t)) e
STest _ _ -> acc'
SSet _ _ _ -> acc'
SSend _ _ -> acc'
SSendND _ _ _ -> acc'
SHavoc _ _ -> acc'
SAssume _ _ -> acc'
SLet _ _ _ _ -> acc'
SFork _ _ _ b -> statFold f acc' b
where acc' = f acc s
statFuncsRec :: Refine -> Statement -> [String]
statFuncsRec r s = nub $ statFold f [] s
where f fs (SITE _ c _ _) = fs ++ exprFuncsRec r c
f fs (STest _ c) = fs ++ exprFuncsRec r c
f fs (SSet _ lv rv) = fs ++ exprFuncsRec r lv ++ exprFuncsRec r rv
f fs (SSend _ d) = fs ++ exprFuncsRec r d
f fs (SSendND _ _ c) = fs ++ exprFuncsRec r c
f fs (SHavoc _ e) = fs ++ exprFuncsRec r e
f fs (SAssume _ c) = fs ++ exprFuncsRec r c
f fs (SLet _ _ _ v) = fs ++ exprFuncsRec r v
f fs (SFork _ _ c _) = fs ++ exprFuncsRec r c
f fs _ = fs
statIsDeterministic :: Statement -> Bool
statIsDeterministic (SSeq _ l r) = statIsDeterministic l && statIsDeterministic r
statIsDeterministic (SPar _ l r) = statIsDeterministic l && statIsDeterministic r
statIsDeterministic (SITE _ _ t e) = statIsDeterministic t && maybe True statIsDeterministic e
statIsDeterministic (STest _ _ ) = True
statIsDeterministic (SSet _ _ _) = True
statIsDeterministic (SSend _ _) = True
statIsDeterministic (SSendND _ _ _) = False
statIsDeterministic (SHavoc _ _) = False
statIsDeterministic (SAssume _ _) = False
statIsDeterministic (SLet _ _ _ _) = True
statIsDeterministic (SFork _ _ _ _) = True
statIsMulticast :: Statement -> Bool
statIsMulticast (SSeq _ l r) = statIsMulticast l || statIsMulticast r
statIsMulticast (SPar _ _ _) = True
statIsMulticast (SITE _ _ t e) = statIsMulticast t || maybe False statIsMulticast e
statIsMulticast (STest _ _ ) = False
statIsMulticast (SSet _ _ _) = False
statIsMulticast (SSend _ _) = False
statIsMulticast (SSendND _ _ _) = False
statIsMulticast (SHavoc _ _) = False
statIsMulticast (SAssume _ _) = False
statIsMulticast (SLet _ _ _ _) = False
statIsMulticast (SFork _ _ _ _) = True
statSendsToRoles :: Statement -> [String]
statSendsToRoles st = nub $ statSendsToRoles' st
statSendsToRoles' :: Statement -> [String]
statSendsToRoles' (SSeq _ s1 s2) = statSendsToRoles' s1 ++ statSendsToRoles' s2
statSendsToRoles' (SPar _ s1 s2) = statSendsToRoles' s1 ++ statSendsToRoles' s2
statSendsToRoles' (SITE _ _ s1 s2) = statSendsToRoles' s1 ++ (maybe [] statSendsToRoles' s2)
statSendsToRoles' (STest _ _) = []
statSendsToRoles' (SSet _ _ _) = []
statSendsToRoles' (SSend _ (ELocation _ rl _)) = [rl]
statSendsToRoles' (SSend _ e) = error $ "statSendsToRoles' SSend " ++ show e
statSendsToRoles' (SHavoc _ _) = []
statSendsToRoles' (SAssume _ _) = []
statSendsToRoles' (SLet _ _ _ _) = []
statSendsToRoles' (SSendND _ rl _) = [rl]
statSendsToRoles' (SFork _ _ _ b) = statSendsToRoles b
statSendsTo :: Statement -> [Expr]
statSendsTo st = nub $ statSendsTo' st
statSendsTo' :: Statement -> [Expr]
statSendsTo' (SSeq _ s1 s2) = statSendsTo' s1 ++ statSendsTo' s2
statSendsTo' (SPar _ s1 s2) = statSendsTo' s1 ++ statSendsTo' s2
statSendsTo' (SITE _ _ s1 s2) = statSendsTo' s1 ++ (maybe [] statSendsTo' s2)
statSendsTo' (STest _ _) = []
statSendsTo' (SSet _ _ _) = []
statSendsTo' (SSend _ loc) = [loc]
statSendsTo' (SHavoc _ _) = []
statSendsTo' (SAssume _ _) = []
statSendsTo' (SLet _ _ _ _) = []
statSendsTo' (SSendND _ _ _) = error "statSendsTo' SSendND"
statSendsTo' (SFork _ _ _ b) = statSendsTo' b
| null | https://raw.githubusercontent.com/ryzhyk/cocoon/409d10b848a4512e7cf653d5b6cf6ecf247eb794/cocoon/Statement.hs | haskell |
Copyrights ( c ) 2016 . Samsung Electronics Ltd. All right 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 .
Copyrights (c) 2016. Samsung Electronics Ltd. All right 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.
-}
module Statement( statFold
, statFuncsRec
, statIsDeterministic
, statIsMulticast
, statSendsTo
, statSendsToRoles) where
import Data.List
import Expr
import Syntax
statFold :: (a -> Statement -> a) -> a -> Statement -> a
statFold f acc s =
case s of
SSeq _ l r -> statFold f (statFold f acc' l) r
SPar _ l r -> statFold f (statFold f acc' l) r
SITE _ _ t e -> maybe (statFold f acc' t) (statFold f (statFold f acc' t)) e
STest _ _ -> acc'
SSet _ _ _ -> acc'
SSend _ _ -> acc'
SSendND _ _ _ -> acc'
SHavoc _ _ -> acc'
SAssume _ _ -> acc'
SLet _ _ _ _ -> acc'
SFork _ _ _ b -> statFold f acc' b
where acc' = f acc s
statFuncsRec :: Refine -> Statement -> [String]
statFuncsRec r s = nub $ statFold f [] s
where f fs (SITE _ c _ _) = fs ++ exprFuncsRec r c
f fs (STest _ c) = fs ++ exprFuncsRec r c
f fs (SSet _ lv rv) = fs ++ exprFuncsRec r lv ++ exprFuncsRec r rv
f fs (SSend _ d) = fs ++ exprFuncsRec r d
f fs (SSendND _ _ c) = fs ++ exprFuncsRec r c
f fs (SHavoc _ e) = fs ++ exprFuncsRec r e
f fs (SAssume _ c) = fs ++ exprFuncsRec r c
f fs (SLet _ _ _ v) = fs ++ exprFuncsRec r v
f fs (SFork _ _ c _) = fs ++ exprFuncsRec r c
f fs _ = fs
statIsDeterministic :: Statement -> Bool
statIsDeterministic (SSeq _ l r) = statIsDeterministic l && statIsDeterministic r
statIsDeterministic (SPar _ l r) = statIsDeterministic l && statIsDeterministic r
statIsDeterministic (SITE _ _ t e) = statIsDeterministic t && maybe True statIsDeterministic e
statIsDeterministic (STest _ _ ) = True
statIsDeterministic (SSet _ _ _) = True
statIsDeterministic (SSend _ _) = True
statIsDeterministic (SSendND _ _ _) = False
statIsDeterministic (SHavoc _ _) = False
statIsDeterministic (SAssume _ _) = False
statIsDeterministic (SLet _ _ _ _) = True
statIsDeterministic (SFork _ _ _ _) = True
statIsMulticast :: Statement -> Bool
statIsMulticast (SSeq _ l r) = statIsMulticast l || statIsMulticast r
statIsMulticast (SPar _ _ _) = True
statIsMulticast (SITE _ _ t e) = statIsMulticast t || maybe False statIsMulticast e
statIsMulticast (STest _ _ ) = False
statIsMulticast (SSet _ _ _) = False
statIsMulticast (SSend _ _) = False
statIsMulticast (SSendND _ _ _) = False
statIsMulticast (SHavoc _ _) = False
statIsMulticast (SAssume _ _) = False
statIsMulticast (SLet _ _ _ _) = False
statIsMulticast (SFork _ _ _ _) = True
statSendsToRoles :: Statement -> [String]
statSendsToRoles st = nub $ statSendsToRoles' st
statSendsToRoles' :: Statement -> [String]
statSendsToRoles' (SSeq _ s1 s2) = statSendsToRoles' s1 ++ statSendsToRoles' s2
statSendsToRoles' (SPar _ s1 s2) = statSendsToRoles' s1 ++ statSendsToRoles' s2
statSendsToRoles' (SITE _ _ s1 s2) = statSendsToRoles' s1 ++ (maybe [] statSendsToRoles' s2)
statSendsToRoles' (STest _ _) = []
statSendsToRoles' (SSet _ _ _) = []
statSendsToRoles' (SSend _ (ELocation _ rl _)) = [rl]
statSendsToRoles' (SSend _ e) = error $ "statSendsToRoles' SSend " ++ show e
statSendsToRoles' (SHavoc _ _) = []
statSendsToRoles' (SAssume _ _) = []
statSendsToRoles' (SLet _ _ _ _) = []
statSendsToRoles' (SSendND _ rl _) = [rl]
statSendsToRoles' (SFork _ _ _ b) = statSendsToRoles b
statSendsTo :: Statement -> [Expr]
statSendsTo st = nub $ statSendsTo' st
statSendsTo' :: Statement -> [Expr]
statSendsTo' (SSeq _ s1 s2) = statSendsTo' s1 ++ statSendsTo' s2
statSendsTo' (SPar _ s1 s2) = statSendsTo' s1 ++ statSendsTo' s2
statSendsTo' (SITE _ _ s1 s2) = statSendsTo' s1 ++ (maybe [] statSendsTo' s2)
statSendsTo' (STest _ _) = []
statSendsTo' (SSet _ _ _) = []
statSendsTo' (SSend _ loc) = [loc]
statSendsTo' (SHavoc _ _) = []
statSendsTo' (SAssume _ _) = []
statSendsTo' (SLet _ _ _ _) = []
statSendsTo' (SSendND _ _ _) = error "statSendsTo' SSendND"
statSendsTo' (SFork _ _ _ b) = statSendsTo' b
| |
422aae1c36a674223de765d55434d0b708f10d02b01ffb88b14bf5f11afc8c82 | amnh/PCG | FFI.hs | # LINE 1 " FFI.hsc " #
# LANGUAGE ForeignFunctionInterface , BangPatterns #
# LINE 2 " FFI.hsc " #
module Analysis.Parsimony.Binary.SequentialAlign.FFI where
import System.IO.Unsafe
import Foreign
import Foreign.Ptr
import Foreign.C.String
import Foreign.C.Types
# LINE 12 " FFI.hsc " #
-- Includes a struct (actually, a pointer thereto), and that struct, in turn, has a string
in it , so
Modified from code samples here : #Working_with_C_Structures
data AlignResult = AlignResult { val :: CInt
, seq1 :: CString
, seq2 :: CString
, seqLen :: CLong
}
This is the declaration of the wrapper for the C function we 're calling .
foreign import ccall unsafe "seqAlign_ffi.h aligner"
callExtAlignFn_c :: CString -> CString -> CInt -> CInt -> Ptr AlignResult -> CInt
-- Because we're using a struct we need to make a Storable instance
instance Storable AlignResult where
sizeOf _ = ((32))
# LINE 29 " FFI.hsc " #
alignment _ = alignment (undefined :: CDouble)
peek ptr = do
value <- ((\hsc_ptr -> peekByteOff hsc_ptr 0)) ptr
# LINE 32 " FFI.hsc " #
seq1Fin <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) ptr
# LINE 33 " FFI.hsc " #
seq2Fin <- ((\hsc_ptr -> peekByteOff hsc_ptr 16)) ptr
# LINE 34 " FFI.hsc " #
algnLen <- ((\hsc_ptr -> peekByteOff hsc_ptr 24)) ptr
# LINE 35 " FFI.hsc " #
return AlignResult { val = value, seq1 = seq1Fin, seq2 = seq2Fin, seqLen = algnLen }
------------- Don't need this part, but left in for completion ---------------
----- Will get compiler warning if left out, because of missing instances ----
poke ptr (AlignResult val seq1Fin seq2Fin alignLen) = do
((\hsc_ptr -> pokeByteOff hsc_ptr 0)) ptr val
# LINE 40 " FFI.hsc " #
((\hsc_ptr -> pokeByteOff hsc_ptr 8)) ptr seq1Fin
# LINE 41 " FFI.hsc " #
((\hsc_ptr -> pokeByteOff hsc_ptr 16)) ptr seq2Fin
# LINE 42 " FFI.hsc " #
((\hsc_ptr -> pokeByteOff hsc_ptr 24)) ptr alignLen -- need to be able to pass in length of alignment string
# LINE 43 " FFI.hsc " #
sequentialAlign :: Int -> Int -> String -> String -> Either String (Int, String, String)
sequentialAlign indelCst subCst inpStr1 inpStr2 = unsafePerformIO $
-- have to allocate memory. Note that we're allocating to a lambda fn. I
-- don't yet understand what exactly is going on here.
alloca $ \alignPtr -> do
This first part is similar to simple example , but now I need to pre - allocate the length of the String * inside * the retAlign struct
let len = length inpStr1 + length inpStr2 + 5 -- This is the total length of the alignment.
I padded each half by 2 , and there 's one more for NULL term .
-- This math will have to be rectified in C.
arg1 <- newCAString $ map removeAmbDNA inpStr1
arg2 <- newCAString $ map removeAmbDNA inpStr2
algnSeq1 <- newCAString $ replicate len ' ' -- to force allocation of space inside struct; will add NULL terminator in C.
algnSeq2 <- newCAString $ replicate len ' '
-- putting allocated aligned sequences and length of that string into return struct
poke alignPtr $ AlignResult 0 algnSeq1 algnSeq2 (CLong (fromIntegral (succ len) :: Int64))
-- Using strict here because of problems we had with simple example.
let !status = callExtAlignFn_c arg1 arg2 (CInt (fromIntegral indelCst :: Int32)) (CInt (fromIntegral subCst :: Int32)) alignPtr
free arg1
free arg2
if (fromIntegral status) == 0
then do
AlignResult val outSeq1 outSeq2 _ <- peek alignPtr
seq1Fin <- peekCAString algnSeq1
seq2Fin <- peekCAString outSeq2
free algnSeq1
free algnSeq2
pure $ Right (fromIntegral val, seq1Fin, seq2Fin)
else do
free algnSeq1
free algnSeq2
pure $ Left "Out of memory"
-- TODO: note I'm assuming all caps here.
removeAmbDNA :: Char -> Char
removeAmbDNA x = case x of
'B' -> 'C'
'D' -> 'A'
'H' -> 'A'
'K' -> 'G'
'M' -> 'A'
'N' -> 'A'
'R' -> 'A'
'S' -> 'C'
'V' -> 'A'
'W' -> 'A'
'X' -> 'A'
'Y' -> 'C'
_ -> x
-- Just for testing from CLI outside of ghci.
--main :: IO ()
--main =
show $ sequentialAlign 1 1 " CE " " GCT "
| null | https://raw.githubusercontent.com/amnh/PCG/3a1b6bdde273ed4dc09717623986e1144b006904/prototype/ffi_old_seq_align/Analysis/Parsimony/Binary/SequentialAlign/FFI.hs | haskell | Includes a struct (actually, a pointer thereto), and that struct, in turn, has a string
Because we're using a struct we need to make a Storable instance
----------- Don't need this part, but left in for completion ---------------
--- Will get compiler warning if left out, because of missing instances ----
need to be able to pass in length of alignment string
have to allocate memory. Note that we're allocating to a lambda fn. I
don't yet understand what exactly is going on here.
This is the total length of the alignment.
This math will have to be rectified in C.
to force allocation of space inside struct; will add NULL terminator in C.
putting allocated aligned sequences and length of that string into return struct
Using strict here because of problems we had with simple example.
TODO: note I'm assuming all caps here.
Just for testing from CLI outside of ghci.
main :: IO ()
main = | # LINE 1 " FFI.hsc " #
# LANGUAGE ForeignFunctionInterface , BangPatterns #
# LINE 2 " FFI.hsc " #
module Analysis.Parsimony.Binary.SequentialAlign.FFI where
import System.IO.Unsafe
import Foreign
import Foreign.Ptr
import Foreign.C.String
import Foreign.C.Types
# LINE 12 " FFI.hsc " #
in it , so
Modified from code samples here : #Working_with_C_Structures
data AlignResult = AlignResult { val :: CInt
, seq1 :: CString
, seq2 :: CString
, seqLen :: CLong
}
This is the declaration of the wrapper for the C function we 're calling .
foreign import ccall unsafe "seqAlign_ffi.h aligner"
callExtAlignFn_c :: CString -> CString -> CInt -> CInt -> Ptr AlignResult -> CInt
instance Storable AlignResult where
sizeOf _ = ((32))
# LINE 29 " FFI.hsc " #
alignment _ = alignment (undefined :: CDouble)
peek ptr = do
value <- ((\hsc_ptr -> peekByteOff hsc_ptr 0)) ptr
# LINE 32 " FFI.hsc " #
seq1Fin <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) ptr
# LINE 33 " FFI.hsc " #
seq2Fin <- ((\hsc_ptr -> peekByteOff hsc_ptr 16)) ptr
# LINE 34 " FFI.hsc " #
algnLen <- ((\hsc_ptr -> peekByteOff hsc_ptr 24)) ptr
# LINE 35 " FFI.hsc " #
return AlignResult { val = value, seq1 = seq1Fin, seq2 = seq2Fin, seqLen = algnLen }
poke ptr (AlignResult val seq1Fin seq2Fin alignLen) = do
((\hsc_ptr -> pokeByteOff hsc_ptr 0)) ptr val
# LINE 40 " FFI.hsc " #
((\hsc_ptr -> pokeByteOff hsc_ptr 8)) ptr seq1Fin
# LINE 41 " FFI.hsc " #
((\hsc_ptr -> pokeByteOff hsc_ptr 16)) ptr seq2Fin
# LINE 42 " FFI.hsc " #
# LINE 43 " FFI.hsc " #
sequentialAlign :: Int -> Int -> String -> String -> Either String (Int, String, String)
sequentialAlign indelCst subCst inpStr1 inpStr2 = unsafePerformIO $
alloca $ \alignPtr -> do
This first part is similar to simple example , but now I need to pre - allocate the length of the String * inside * the retAlign struct
I padded each half by 2 , and there 's one more for NULL term .
arg1 <- newCAString $ map removeAmbDNA inpStr1
arg2 <- newCAString $ map removeAmbDNA inpStr2
algnSeq2 <- newCAString $ replicate len ' '
poke alignPtr $ AlignResult 0 algnSeq1 algnSeq2 (CLong (fromIntegral (succ len) :: Int64))
let !status = callExtAlignFn_c arg1 arg2 (CInt (fromIntegral indelCst :: Int32)) (CInt (fromIntegral subCst :: Int32)) alignPtr
free arg1
free arg2
if (fromIntegral status) == 0
then do
AlignResult val outSeq1 outSeq2 _ <- peek alignPtr
seq1Fin <- peekCAString algnSeq1
seq2Fin <- peekCAString outSeq2
free algnSeq1
free algnSeq2
pure $ Right (fromIntegral val, seq1Fin, seq2Fin)
else do
free algnSeq1
free algnSeq2
pure $ Left "Out of memory"
removeAmbDNA :: Char -> Char
removeAmbDNA x = case x of
'B' -> 'C'
'D' -> 'A'
'H' -> 'A'
'K' -> 'G'
'M' -> 'A'
'N' -> 'A'
'R' -> 'A'
'S' -> 'C'
'V' -> 'A'
'W' -> 'A'
'X' -> 'A'
'Y' -> 'C'
_ -> x
show $ sequentialAlign 1 1 " CE " " GCT "
|
5e91d2d79e45839a531396eb9dbbb01e825dc94edc9d92464cb6d30922f91d71 | mcorbin/tour-of-clojure | let.clj | (ns tourofclojure.pages.let
(:require [hiccup.element :refer [link-to]]
[clojure.java.io :as io]
[tourofclojure.pages.util :refer [navigation-block]]))
(def code
(slurp (io/resource "public/pages/code/let.clj")))
(defn desc
[previous next lang]
(condp = lang
"fr" [:div
[:h2 "Let et variables locales"]
[:p "Nous avons vu précédemment " [:b "def"] " pour définir des variables"
" globales. Il est également possible de définir des variables localement"
" (dans une fonction par exemple) en utilisant " [:b "let"] "."]
[:p "Les variables se déclarent entre " [:b "[]"] ", et sont des paires"
" nom/valeur. Plus précisément, la syntaxe de " [:b "let"]
" peut être décrite comme "
[:b "[name1 value1 name2 value2 ...]"] "."]
[:pre [:code "(defn foo
[a]
(let [b (conj [10 20] 30)
c (conj b a)]
c))"]]
[:p "Dans l'exemple précédent, on déclare deux variables: " [:b "b"]
" et " [:b "c"] ", et on retourne " [:b "c"] "." " On remarque"
" que l'on utilise " [:b "b"] " dans la définition de "[:b "c"] "."]
[:p "Il est possible d'utiliser le symbole " [:b "_"] " à la place"
" du nom. Dans ce cas, la form suivante sera exécutée mais son résultat"
" ne sera assigné à aucune variable. Dans l'exemple de la fonction "
[:b "bar"] ", on voit que " [:b "println"] " est appelé."]
(navigation-block previous next)]
[:h2 "Language not supported."]))
(defn page
[previous next lang]
[(desc previous next lang)
code])
| null | https://raw.githubusercontent.com/mcorbin/tour-of-clojure/57f97b68ca1a8c96904bfb960f515217eeda24a6/src/tourofclojure/pages/let.clj | clojure | (ns tourofclojure.pages.let
(:require [hiccup.element :refer [link-to]]
[clojure.java.io :as io]
[tourofclojure.pages.util :refer [navigation-block]]))
(def code
(slurp (io/resource "public/pages/code/let.clj")))
(defn desc
[previous next lang]
(condp = lang
"fr" [:div
[:h2 "Let et variables locales"]
[:p "Nous avons vu précédemment " [:b "def"] " pour définir des variables"
" globales. Il est également possible de définir des variables localement"
" (dans une fonction par exemple) en utilisant " [:b "let"] "."]
[:p "Les variables se déclarent entre " [:b "[]"] ", et sont des paires"
" nom/valeur. Plus précisément, la syntaxe de " [:b "let"]
" peut être décrite comme "
[:b "[name1 value1 name2 value2 ...]"] "."]
[:pre [:code "(defn foo
[a]
(let [b (conj [10 20] 30)
c (conj b a)]
c))"]]
[:p "Dans l'exemple précédent, on déclare deux variables: " [:b "b"]
" et " [:b "c"] ", et on retourne " [:b "c"] "." " On remarque"
" que l'on utilise " [:b "b"] " dans la définition de "[:b "c"] "."]
[:p "Il est possible d'utiliser le symbole " [:b "_"] " à la place"
" du nom. Dans ce cas, la form suivante sera exécutée mais son résultat"
" ne sera assigné à aucune variable. Dans l'exemple de la fonction "
[:b "bar"] ", on voit que " [:b "println"] " est appelé."]
(navigation-block previous next)]
[:h2 "Language not supported."]))
(defn page
[previous next lang]
[(desc previous next lang)
code])
| |
3c196cf8ffc0896737bbacafa7ad2b09f0c4bacf7645da3a1f7b5a7aadbedd9e | pgj/mirage-kfreebsd | pcb.mli |
* Copyright ( c ) 2010 < >
*
* 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) 2010 Anil Madhavapeddy <>
*
* 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.
*)
open Nettypes
type t
type pcb
type listener
type connection = (pcb * unit Lwt.t)
val input: t -> src:ipv4_addr -> dst:ipv4_addr -> OS.Io_page.t -> unit Lwt.t
val connect: t -> dest_ip:ipv4_addr -> dest_port:int -> connection option Lwt.t
val listen: t -> int -> (connection Lwt_stream.t * listener)
val closelistener: listener -> unit
val close: pcb -> unit Lwt.t
val get_dest: pcb -> (ipv4_addr * int)
(* Blocking read for a segment *)
val read: pcb -> OS.Io_page.t option Lwt.t
(* Write a segment *)
val write_available : pcb -> int
val write_wait_for : pcb -> int -> unit Lwt.t
val write: pcb -> OS.Io_page.t -> unit Lwt.t
val writev: pcb -> OS.Io_page.t list -> unit Lwt.t
val create: Ipv4.t -> t * unit Lwt.t
val tcpstats : t - > unit
| null | https://raw.githubusercontent.com/pgj/mirage-kfreebsd/0ff5b2cd7ab0975e3f2ee1bd89f8e5dbf028b102/packages/mirage-net/lib/tcp/pcb.mli | ocaml | Blocking read for a segment
Write a segment |
* Copyright ( c ) 2010 < >
*
* 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) 2010 Anil Madhavapeddy <>
*
* 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.
*)
open Nettypes
type t
type pcb
type listener
type connection = (pcb * unit Lwt.t)
val input: t -> src:ipv4_addr -> dst:ipv4_addr -> OS.Io_page.t -> unit Lwt.t
val connect: t -> dest_ip:ipv4_addr -> dest_port:int -> connection option Lwt.t
val listen: t -> int -> (connection Lwt_stream.t * listener)
val closelistener: listener -> unit
val close: pcb -> unit Lwt.t
val get_dest: pcb -> (ipv4_addr * int)
val read: pcb -> OS.Io_page.t option Lwt.t
val write_available : pcb -> int
val write_wait_for : pcb -> int -> unit Lwt.t
val write: pcb -> OS.Io_page.t -> unit Lwt.t
val writev: pcb -> OS.Io_page.t list -> unit Lwt.t
val create: Ipv4.t -> t * unit Lwt.t
val tcpstats : t - > unit
|
d7cfc3075e219c8dfb4da79c80c178e367c96c93ddf38ae4a447b5cc5479ce06 | RefactoringTools/wrangler | utils_guards.erl | @private
@author < >
( C ) 2014 , ,
-module(utils_guards).
-export([guardsSuceed/3, guardsSuceed/4, rules/2, pos_to_node/2, evaluateGuardsExpression/2,get_variable/2,evaluateIsFun/1]).
%% Include files
-include("wrangler.hrl").
guardsSuceed(Arg1, Arg2, Arg3) ->
guardsSuceed(Arg1, Arg2, Arg3, []).
guardsSuceed(_,_,[],_) -> true;
guardsSuceed(Arg, ArgPatt, [[Guards | []] | []],Scope) ->
Type = api_refac:type(Guards),
if
Type == infix_expr orelse Type == prefix_expr orelse Type == application ->
NewGuards = utils_subst:subst(Guards, ArgPatt, Arg),
FinalGuards = utils_transform:transform_body(NewGuards, fun utils_guards:rules/2, Scope),
evaluateGuardsExpression(FinalGuards, Scope);
Type == atom ->
evaluateGuardsExpression(Guards, Scope);
true -> false
end;
guardsSuceed(_,_,_,_) ->
false.
rules(Args, FunDefInfo) -> core_arithmetics:rules(Args, FunDefInfo) ++ [core_funApp:length_rule()].
evaluateGuardsExpression(Node, Scope)->
NodeType = api_refac:type(Node),
if
NodeType == infix_expr ->
Cond = arithmetic_condition(Node),
if
Cond -> {expr, Node};
true ->
Match = findGuardInfixExpr(Node),
case Match of
{match,Operator, Left, Right} ->
LeftEvaluated = evaluateGuardsExpression(Left, Scope),
RightEvaluated = evaluateGuardsExpression(Right, Scope),
evaluateBooleanBinaryExp(Operator, LeftEvaluated, RightEvaluated);
_ -> maybe
end
end;
NodeType == prefix_expr orelse NodeType == application ->
LengthCall = NodeType == application andalso ?MATCH(?T("length(Exp@)"), Node),
if
LengthCall -> {expr, Node};
true ->
Match = findGuardApplication(Node, NodeType),
case Match of
negativeNum -> list_to_integer(?PP(Node));
{match, "is_function", Args@@} ->
evaluateIsFun(Args@@);
{match, Operator, Single} ->
SingleEvaluated = evaluateGuardsExpression(Single, Scope),
evaluateBooleanApplication(Operator, SingleEvaluated);
_ ->
maybe
end
end;
NodeType == variable ->
case get_variable(Node, Scope) of
{value, Expr@} -> evaluateGuardsExpression(Expr@, Scope);
Other -> Other
end;
true ->
Convert = utils_convert:convert_elem(Node),
case Convert of
error -> {expr, Node};
_ -> Convert
end
end.
findGuardApplication(Node, prefix_expr) ->
Match = ?MATCH(?T("not(Single@)"), Node),
if
Match -> {match, "not", Single@};
true ->
NegativeNum = ?MATCH(?T("-Num@"),Node),
if
NegativeNum -> negativeNum;
true -> noMatch
end
end;
findGuardApplication(Node, application) ->
Match = ?MATCH(?T("F@(Single@)"), Node),
if
Match ->
Name = ?PP(F@),
Cond = (Name == "is_list" orelse Name == "is_float" orelse
Name == "is_integer" orelse Name == "is_boolean" orelse
Name == "is_atom" orelse Name == "is_tuple" orelse Name == "is_number"),
if
Cond -> {match, Name, Single@};
true -> noMatch
end;
true ->
IsFun = ?MATCH(?T("is_function(Args@@)"), Node),
if
IsFun ->
{match, "is_function", Args@@};
true ->
noMatch
end
end.
findGuardInfixExpr(Node) ->
Match = findCompMatch(Node),
case Match of
noMatch -> findBooleanOpMatch(Node);
Result -> Result
end.
findCompMatch(Node) ->
Match = findSimpleCompMatch(Node),
case Match of
noMatch ->
GTMatch = findGTMatch(Node),
case GTMatch of
noMatch -> findLTMatch(Node);
Result -> Result
end;
Result -> Result
end.
findSimpleCompMatch(Node) ->
Match = findEqualComp(Node),
case Match of
noMatch -> findDiffComp(Node);
Result -> Result
end.
findBooleanOpMatch(Node) ->
ANDsMatch = findANDsMatch(Node),
case ANDsMatch of
noMatch ->
ORsMatch = findORsMatch(Node),
case ORsMatch of
noMatch ->
MatchXor = ?MATCH(?T("Left@ xor Right@"),Node),
if
MatchXor -> {match, "xor", Left@, Right@};
true -> noMatch
end;
Result -> Result
end;
Result -> Result
end.
findEqualComp(Node)->
MatchEquals = ?MATCH(?T("Left@ == Right@"),Node),
if
MatchEquals -> {match, "==", Left@, Right@};
true ->
MatchExacEquals = ?MATCH(?T("LeftDiff@ =:= RightDiff@"),Node),
if
MatchExacEquals -> {match, "=:=", LeftDiff@, RightDiff@};
true -> noMatch
end
end.
findDiffComp(Node) ->
MatchDiff = ?MATCH(?T("Left@ /= Right@"),Node),
if
MatchDiff -> {match, "/=", Left@, Right@};
true ->
MatchExacDiff = ?MATCH(?T("LeftDiff@ =/= RightDiff@"),Node),
if
MatchExacDiff -> {match, "=/=", LeftDiff@, RightDiff@};
true -> noMatch
end
end.
findGTMatch(Node) ->
MatchGTEquals = ?MATCH(?T("Left@ > Right@"),Node),
if
MatchGTEquals -> {match, ">", Left@, Right@};
true ->
MatchGT2Equals = ?MATCH(?T("Left2@ >= Right2@"),Node),
if
MatchGT2Equals -> {match, ">=", Left2@, Right2@};
true -> noMatch
end
end.
findLTMatch(Node) ->
MatchLTEquals = ?MATCH(?T("Left@ < Right@"),Node),
if
MatchLTEquals -> {match, "<", Left@, Right@};
true ->
MatchLT2Equals = ?MATCH(?T("Left2@ =< Right2@"),Node),
if
MatchLT2Equals -> {match, "=<", Left2@, Right2@};
true -> noMatch
end
end.
findANDsMatch(Node) ->
MatchAndEquals = ?MATCH(?T("Left@ and Right@"),Node),
if
MatchAndEquals -> {match, "and", Left@, Right@};
true ->
MatchAndAlsoEquals = ?MATCH(?T("Left2@ andalso Right2@"),Node),
if
MatchAndAlsoEquals -> {match, "andalso", Left2@, Right2@};
true -> noMatch
end
end.
findORsMatch(Node) ->
MatchOrEquals = ?MATCH(?T("Left@ or Right@"),Node),
if
MatchOrEquals -> {match, "or", Left@, Right@};
true ->
MatchOrElseEquals = ?MATCH(?T("Left2@ orelse Right2@"),Node),
if
MatchOrElseEquals -> {match, "orelse", Left2@, Right2@};
true -> noMatch
end
end.
evaluateBooleanBinaryExp(Operator, {expr, NodeLeft}, {expr, NodeRight}) ->
Equal = ?PP(NodeRight) == ?PP(NodeLeft),
if
Equal ->
evaluateBooleanBinaryExp(Operator, ?PP(NodeLeft), ?PP(NodeRight));
true ->
maybe
end;
evaluateBooleanBinaryExp(_Operator, {expr, _NodeLeft}, _A) -> maybe;
evaluateBooleanBinaryExp(_Operator, _, {expr, _NodeRight}) -> maybe;
evaluateBooleanBinaryExp(_Operator, maybe, _A) -> maybe;
evaluateBooleanBinaryExp(_Operator, _, maybe) -> maybe;
evaluateBooleanBinaryExp("==",Left,Right) -> Left == Right;
evaluateBooleanBinaryExp("=:=",Left,Right) -> Left =:= Right;
evaluateBooleanBinaryExp("/=",Left,Right) -> Left /= Right;
evaluateBooleanBinaryExp("=/=",Left,Right) -> Left =/= Right;
evaluateBooleanBinaryExp(">",Left,Right) -> Left > Right;
evaluateBooleanBinaryExp(">=",Left,Right) -> Left >= Right;
evaluateBooleanBinaryExp("<",Left,Right) -> Left < Right;
evaluateBooleanBinaryExp("=<",Left,Right) -> Left =< Right;
evaluateBooleanBinaryExp("andalso",Left,Right) when is_boolean(Left) andalso is_boolean(Right) ->
Left andalso Right;
evaluateBooleanBinaryExp("and",Left,Right) when is_boolean(Left) andalso is_boolean(Right) ->
Left and Right;
evaluateBooleanBinaryExp("orelse",Left,Right) when is_boolean(Left) andalso is_boolean(Right) ->
Left orelse Right;
evaluateBooleanBinaryExp("or",Left,Right) when is_boolean(Left) andalso is_boolean(Right) ->
Left or Right;
evaluateBooleanBinaryExp("xor",Left,Right) when is_boolean(Left) andalso is_boolean(Right) ->
Left xor Right;
evaluateBooleanBinaryExp(_,_,_) ->
false.
evaluateBooleanApplication(_Operator, {expr, _Node}) -> maybe;
evaluateBooleanApplication(_Operator, maybe) -> maybe;
evaluateBooleanApplication("not",Single) when is_boolean(Single) -> not (Single);
evaluateBooleanApplication("is_list",Single) -> is_list(Single);
evaluateBooleanApplication("is_integer",Single) -> is_integer(Single);
evaluateBooleanApplication("is_float",Single) -> is_float(Single);
evaluateBooleanApplication("is_number",Single) -> is_number(Single);
evaluateBooleanApplication("is_boolean",Single) -> is_boolean(Single);
evaluateBooleanApplication("is_atom",Single) -> is_atom(Single);
evaluateBooleanApplication("is_tuple",Single) -> is_tuple(Single);
evaluateBooleanApplication(_,_) -> false.
evaluateIsFun([]) -> false;
evaluateIsFun([F | []]) ->
Type = api_refac:type(F),
Type == fun_expr orelse Type == implicit_fun;
evaluateIsFun([F | [A | []]]) ->
MatchExpr = ?MATCH(?T("fun(Args@@) -> Body@@ end"), F),
if
MatchExpr ->
length(?PP(Args@@)) == list_to_integer(?PP(A));
true ->
api_refac:type(F) == implicit_fun andalso
begin
FunInfo = api_refac:fun_define_info(F),
case FunInfo of
{_M, _Fun, Ari} ->
Ari == list_to_integer(?PP(A));
_ -> false
end
end
end;
evaluateIsFun(_) -> false.
-spec(arithmetic_condition(Node::syntaxTree())->boolean()).
arithmetic_condition(Node) ->
NodeType = api_refac:type(Node),
if
NodeType == integer orelse NodeType == variable -> true;
NodeType == infix_expr ->
(?MATCH(?T("Sum1@ + Sum2@"),Node) andalso
arithmetic_condition(Sum1@) andalso
arithmetic_condition(Sum2@)) orelse
(?MATCH(?T("Sub1@ - Sub2@"),Node) andalso
arithmetic_condition(Sub1@) andalso
arithmetic_condition(Sub2@)) orelse
(?MATCH(?T("Mult1@ * Mult2@"),Node) andalso
arithmetic_condition(Mult1@) andalso
arithmetic_condition(Mult2@)) orelse
(?MATCH(?T("Div1@ div Div2@"), Node) andalso
arithmetic_condition(Div1@) andalso
arithmetic_condition(Div2@) andalso
begin
Result = do_arithmetic(Div2@),
Result /= error andalso
?PP(Result) /= "0"
end
) orelse
(?MATCH(?T("Num@ rem Rem@"), Node) andalso
arithmetic_condition(Num@) andalso
arithmetic_condition(Rem@)
);
true -> false
end.
-spec(do_arithmetic(Node::syntaxTree()) -> syntaxTree() | error).
do_arithmetic(Node) ->
case api_refac:type(Node) of
integer -> Node;
variable -> Node;
infix_expr ->
IsSum = ?MATCH(?T("Sum1@ + Sum2@"),Node),
if
IsSum -> core_arit_calc:do_operation('+',do_arithmetic(Sum1@),do_arithmetic(Sum2@));
true -> IsSub = ?MATCH(?T("Sub1@ - Sub2@"),Node),
if
IsSub -> core_arit_calc:do_operation('-',do_arithmetic(Sub1@),do_arithmetic(Sub2@));
true -> IsMult = ?MATCH(?T("Mult1@ * Mult2@"),Node),
if
IsMult -> core_arit_calc:do_operation('*',do_arithmetic(Mult1@) ,do_arithmetic(Mult2@));
true -> IsDiv = ?MATCH(?T("Div1@ div Div2@"),Node),
if
IsDiv -> core_arit_calc:do_operation('div',do_arithmetic(Div1@),do_arithmetic(Div2@));
true ->
IsRem = ?MATCH(?T("Num@ rem Rem@"), Node),
if
IsRem -> core_arit_calc:do_operation('rem',do_arithmetic(Num@), do_arithmetic(Rem@));
true -> error
end
end
end
end
end;
_ -> error
end.
get_variable(Var, VarsInfo) ->
case VarsInfo of
[] ->
{expr, Var};
_ ->
VarDefPos = api_refac:variable_define_pos(Var),
case VarDefPos of
[{0,0}] -> {expr, Var};
[_ | _] ->
Result = lists:keyfind(api_refac:free_vars(Var),1,VarsInfo),
case Result of
{_,Expr@} ->
{value,Expr@};
_ -> {expr, Var}
end;
_ -> {expr, Var}
end
end.
pos_to_node(Scope, Pos) ->
api_interface:pos_to_node(Scope, Pos, fun(Node) -> ?MATCH(?T("Var@ = Exp@"), Node) end).
| null | https://raw.githubusercontent.com/RefactoringTools/wrangler/1c33ad0e923bb7bcebb6fd75347638def91e50a8/src/symbolic_evaluation/utils/utils_guards.erl | erlang | Include files | @private
@author < >
( C ) 2014 , ,
-module(utils_guards).
-export([guardsSuceed/3, guardsSuceed/4, rules/2, pos_to_node/2, evaluateGuardsExpression/2,get_variable/2,evaluateIsFun/1]).
-include("wrangler.hrl").
guardsSuceed(Arg1, Arg2, Arg3) ->
guardsSuceed(Arg1, Arg2, Arg3, []).
guardsSuceed(_,_,[],_) -> true;
guardsSuceed(Arg, ArgPatt, [[Guards | []] | []],Scope) ->
Type = api_refac:type(Guards),
if
Type == infix_expr orelse Type == prefix_expr orelse Type == application ->
NewGuards = utils_subst:subst(Guards, ArgPatt, Arg),
FinalGuards = utils_transform:transform_body(NewGuards, fun utils_guards:rules/2, Scope),
evaluateGuardsExpression(FinalGuards, Scope);
Type == atom ->
evaluateGuardsExpression(Guards, Scope);
true -> false
end;
guardsSuceed(_,_,_,_) ->
false.
rules(Args, FunDefInfo) -> core_arithmetics:rules(Args, FunDefInfo) ++ [core_funApp:length_rule()].
evaluateGuardsExpression(Node, Scope)->
NodeType = api_refac:type(Node),
if
NodeType == infix_expr ->
Cond = arithmetic_condition(Node),
if
Cond -> {expr, Node};
true ->
Match = findGuardInfixExpr(Node),
case Match of
{match,Operator, Left, Right} ->
LeftEvaluated = evaluateGuardsExpression(Left, Scope),
RightEvaluated = evaluateGuardsExpression(Right, Scope),
evaluateBooleanBinaryExp(Operator, LeftEvaluated, RightEvaluated);
_ -> maybe
end
end;
NodeType == prefix_expr orelse NodeType == application ->
LengthCall = NodeType == application andalso ?MATCH(?T("length(Exp@)"), Node),
if
LengthCall -> {expr, Node};
true ->
Match = findGuardApplication(Node, NodeType),
case Match of
negativeNum -> list_to_integer(?PP(Node));
{match, "is_function", Args@@} ->
evaluateIsFun(Args@@);
{match, Operator, Single} ->
SingleEvaluated = evaluateGuardsExpression(Single, Scope),
evaluateBooleanApplication(Operator, SingleEvaluated);
_ ->
maybe
end
end;
NodeType == variable ->
case get_variable(Node, Scope) of
{value, Expr@} -> evaluateGuardsExpression(Expr@, Scope);
Other -> Other
end;
true ->
Convert = utils_convert:convert_elem(Node),
case Convert of
error -> {expr, Node};
_ -> Convert
end
end.
findGuardApplication(Node, prefix_expr) ->
Match = ?MATCH(?T("not(Single@)"), Node),
if
Match -> {match, "not", Single@};
true ->
NegativeNum = ?MATCH(?T("-Num@"),Node),
if
NegativeNum -> negativeNum;
true -> noMatch
end
end;
findGuardApplication(Node, application) ->
Match = ?MATCH(?T("F@(Single@)"), Node),
if
Match ->
Name = ?PP(F@),
Cond = (Name == "is_list" orelse Name == "is_float" orelse
Name == "is_integer" orelse Name == "is_boolean" orelse
Name == "is_atom" orelse Name == "is_tuple" orelse Name == "is_number"),
if
Cond -> {match, Name, Single@};
true -> noMatch
end;
true ->
IsFun = ?MATCH(?T("is_function(Args@@)"), Node),
if
IsFun ->
{match, "is_function", Args@@};
true ->
noMatch
end
end.
findGuardInfixExpr(Node) ->
Match = findCompMatch(Node),
case Match of
noMatch -> findBooleanOpMatch(Node);
Result -> Result
end.
findCompMatch(Node) ->
Match = findSimpleCompMatch(Node),
case Match of
noMatch ->
GTMatch = findGTMatch(Node),
case GTMatch of
noMatch -> findLTMatch(Node);
Result -> Result
end;
Result -> Result
end.
findSimpleCompMatch(Node) ->
Match = findEqualComp(Node),
case Match of
noMatch -> findDiffComp(Node);
Result -> Result
end.
findBooleanOpMatch(Node) ->
ANDsMatch = findANDsMatch(Node),
case ANDsMatch of
noMatch ->
ORsMatch = findORsMatch(Node),
case ORsMatch of
noMatch ->
MatchXor = ?MATCH(?T("Left@ xor Right@"),Node),
if
MatchXor -> {match, "xor", Left@, Right@};
true -> noMatch
end;
Result -> Result
end;
Result -> Result
end.
findEqualComp(Node)->
MatchEquals = ?MATCH(?T("Left@ == Right@"),Node),
if
MatchEquals -> {match, "==", Left@, Right@};
true ->
MatchExacEquals = ?MATCH(?T("LeftDiff@ =:= RightDiff@"),Node),
if
MatchExacEquals -> {match, "=:=", LeftDiff@, RightDiff@};
true -> noMatch
end
end.
findDiffComp(Node) ->
MatchDiff = ?MATCH(?T("Left@ /= Right@"),Node),
if
MatchDiff -> {match, "/=", Left@, Right@};
true ->
MatchExacDiff = ?MATCH(?T("LeftDiff@ =/= RightDiff@"),Node),
if
MatchExacDiff -> {match, "=/=", LeftDiff@, RightDiff@};
true -> noMatch
end
end.
findGTMatch(Node) ->
MatchGTEquals = ?MATCH(?T("Left@ > Right@"),Node),
if
MatchGTEquals -> {match, ">", Left@, Right@};
true ->
MatchGT2Equals = ?MATCH(?T("Left2@ >= Right2@"),Node),
if
MatchGT2Equals -> {match, ">=", Left2@, Right2@};
true -> noMatch
end
end.
findLTMatch(Node) ->
MatchLTEquals = ?MATCH(?T("Left@ < Right@"),Node),
if
MatchLTEquals -> {match, "<", Left@, Right@};
true ->
MatchLT2Equals = ?MATCH(?T("Left2@ =< Right2@"),Node),
if
MatchLT2Equals -> {match, "=<", Left2@, Right2@};
true -> noMatch
end
end.
findANDsMatch(Node) ->
MatchAndEquals = ?MATCH(?T("Left@ and Right@"),Node),
if
MatchAndEquals -> {match, "and", Left@, Right@};
true ->
MatchAndAlsoEquals = ?MATCH(?T("Left2@ andalso Right2@"),Node),
if
MatchAndAlsoEquals -> {match, "andalso", Left2@, Right2@};
true -> noMatch
end
end.
findORsMatch(Node) ->
MatchOrEquals = ?MATCH(?T("Left@ or Right@"),Node),
if
MatchOrEquals -> {match, "or", Left@, Right@};
true ->
MatchOrElseEquals = ?MATCH(?T("Left2@ orelse Right2@"),Node),
if
MatchOrElseEquals -> {match, "orelse", Left2@, Right2@};
true -> noMatch
end
end.
evaluateBooleanBinaryExp(Operator, {expr, NodeLeft}, {expr, NodeRight}) ->
Equal = ?PP(NodeRight) == ?PP(NodeLeft),
if
Equal ->
evaluateBooleanBinaryExp(Operator, ?PP(NodeLeft), ?PP(NodeRight));
true ->
maybe
end;
evaluateBooleanBinaryExp(_Operator, {expr, _NodeLeft}, _A) -> maybe;
evaluateBooleanBinaryExp(_Operator, _, {expr, _NodeRight}) -> maybe;
evaluateBooleanBinaryExp(_Operator, maybe, _A) -> maybe;
evaluateBooleanBinaryExp(_Operator, _, maybe) -> maybe;
evaluateBooleanBinaryExp("==",Left,Right) -> Left == Right;
evaluateBooleanBinaryExp("=:=",Left,Right) -> Left =:= Right;
evaluateBooleanBinaryExp("/=",Left,Right) -> Left /= Right;
evaluateBooleanBinaryExp("=/=",Left,Right) -> Left =/= Right;
evaluateBooleanBinaryExp(">",Left,Right) -> Left > Right;
evaluateBooleanBinaryExp(">=",Left,Right) -> Left >= Right;
evaluateBooleanBinaryExp("<",Left,Right) -> Left < Right;
evaluateBooleanBinaryExp("=<",Left,Right) -> Left =< Right;
evaluateBooleanBinaryExp("andalso",Left,Right) when is_boolean(Left) andalso is_boolean(Right) ->
Left andalso Right;
evaluateBooleanBinaryExp("and",Left,Right) when is_boolean(Left) andalso is_boolean(Right) ->
Left and Right;
evaluateBooleanBinaryExp("orelse",Left,Right) when is_boolean(Left) andalso is_boolean(Right) ->
Left orelse Right;
evaluateBooleanBinaryExp("or",Left,Right) when is_boolean(Left) andalso is_boolean(Right) ->
Left or Right;
evaluateBooleanBinaryExp("xor",Left,Right) when is_boolean(Left) andalso is_boolean(Right) ->
Left xor Right;
evaluateBooleanBinaryExp(_,_,_) ->
false.
evaluateBooleanApplication(_Operator, {expr, _Node}) -> maybe;
evaluateBooleanApplication(_Operator, maybe) -> maybe;
evaluateBooleanApplication("not",Single) when is_boolean(Single) -> not (Single);
evaluateBooleanApplication("is_list",Single) -> is_list(Single);
evaluateBooleanApplication("is_integer",Single) -> is_integer(Single);
evaluateBooleanApplication("is_float",Single) -> is_float(Single);
evaluateBooleanApplication("is_number",Single) -> is_number(Single);
evaluateBooleanApplication("is_boolean",Single) -> is_boolean(Single);
evaluateBooleanApplication("is_atom",Single) -> is_atom(Single);
evaluateBooleanApplication("is_tuple",Single) -> is_tuple(Single);
evaluateBooleanApplication(_,_) -> false.
evaluateIsFun([]) -> false;
evaluateIsFun([F | []]) ->
Type = api_refac:type(F),
Type == fun_expr orelse Type == implicit_fun;
evaluateIsFun([F | [A | []]]) ->
MatchExpr = ?MATCH(?T("fun(Args@@) -> Body@@ end"), F),
if
MatchExpr ->
length(?PP(Args@@)) == list_to_integer(?PP(A));
true ->
api_refac:type(F) == implicit_fun andalso
begin
FunInfo = api_refac:fun_define_info(F),
case FunInfo of
{_M, _Fun, Ari} ->
Ari == list_to_integer(?PP(A));
_ -> false
end
end
end;
evaluateIsFun(_) -> false.
-spec(arithmetic_condition(Node::syntaxTree())->boolean()).
arithmetic_condition(Node) ->
NodeType = api_refac:type(Node),
if
NodeType == integer orelse NodeType == variable -> true;
NodeType == infix_expr ->
(?MATCH(?T("Sum1@ + Sum2@"),Node) andalso
arithmetic_condition(Sum1@) andalso
arithmetic_condition(Sum2@)) orelse
(?MATCH(?T("Sub1@ - Sub2@"),Node) andalso
arithmetic_condition(Sub1@) andalso
arithmetic_condition(Sub2@)) orelse
(?MATCH(?T("Mult1@ * Mult2@"),Node) andalso
arithmetic_condition(Mult1@) andalso
arithmetic_condition(Mult2@)) orelse
(?MATCH(?T("Div1@ div Div2@"), Node) andalso
arithmetic_condition(Div1@) andalso
arithmetic_condition(Div2@) andalso
begin
Result = do_arithmetic(Div2@),
Result /= error andalso
?PP(Result) /= "0"
end
) orelse
(?MATCH(?T("Num@ rem Rem@"), Node) andalso
arithmetic_condition(Num@) andalso
arithmetic_condition(Rem@)
);
true -> false
end.
-spec(do_arithmetic(Node::syntaxTree()) -> syntaxTree() | error).
do_arithmetic(Node) ->
case api_refac:type(Node) of
integer -> Node;
variable -> Node;
infix_expr ->
IsSum = ?MATCH(?T("Sum1@ + Sum2@"),Node),
if
IsSum -> core_arit_calc:do_operation('+',do_arithmetic(Sum1@),do_arithmetic(Sum2@));
true -> IsSub = ?MATCH(?T("Sub1@ - Sub2@"),Node),
if
IsSub -> core_arit_calc:do_operation('-',do_arithmetic(Sub1@),do_arithmetic(Sub2@));
true -> IsMult = ?MATCH(?T("Mult1@ * Mult2@"),Node),
if
IsMult -> core_arit_calc:do_operation('*',do_arithmetic(Mult1@) ,do_arithmetic(Mult2@));
true -> IsDiv = ?MATCH(?T("Div1@ div Div2@"),Node),
if
IsDiv -> core_arit_calc:do_operation('div',do_arithmetic(Div1@),do_arithmetic(Div2@));
true ->
IsRem = ?MATCH(?T("Num@ rem Rem@"), Node),
if
IsRem -> core_arit_calc:do_operation('rem',do_arithmetic(Num@), do_arithmetic(Rem@));
true -> error
end
end
end
end
end;
_ -> error
end.
get_variable(Var, VarsInfo) ->
case VarsInfo of
[] ->
{expr, Var};
_ ->
VarDefPos = api_refac:variable_define_pos(Var),
case VarDefPos of
[{0,0}] -> {expr, Var};
[_ | _] ->
Result = lists:keyfind(api_refac:free_vars(Var),1,VarsInfo),
case Result of
{_,Expr@} ->
{value,Expr@};
_ -> {expr, Var}
end;
_ -> {expr, Var}
end
end.
pos_to_node(Scope, Pos) ->
api_interface:pos_to_node(Scope, Pos, fun(Node) -> ?MATCH(?T("Var@ = Exp@"), Node) end).
|
f84365fa9d26926a65d757a591d33a2f162f09563378167ec21c8ab795f4a53e | mwand/5010-examples | 10-7-callbacks.rkt | #lang racket
10 - 7 - callbacks : instead of registering ' this ' , the ball registers a
;; function to be called when it is notified. So we don't need a dedicated
;; update-pos method
(require rackunit)
(require 2htdp/universe)
(require 2htdp/image)
(require "extras.rkt")
start with ( run framerate ) . Typically : ( run 0.25 )
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; CONSTANTS
(define CANVAS-WIDTH 400)
(define CANVAS-HEIGHT 300)
(define EMPTY-CANVAS (empty-scene CANVAS-WIDTH CANVAS-HEIGHT))
(define INIT-BALL-X (/ CANVAS-HEIGHT 2))
(define INIT-BALL-Y (/ CANVAS-WIDTH 3))
(define INIT-BALL-SPEED 20)
(define INITIAL-WALL-POSITION 300)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Data Definitions
;; A Widget is an object whose class implements Widget<%>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; INTERFACES
The World implements the > interface
(define StatefulWorld<%>
(interface ()
; -> Void
; GIVEN: no arguments
; EFFECT: updates this world to its state after a tick
after-tick
; Integer Integer MouseEvent-> Void
; GIVEN: a location
; EFFECT: updates this world to the state that should follow the
; given mouse event at the given location.
after-mouse-event
KeyEvent : KeyEvent - > Void
; GIVEN: a key event
; EFFECT: updates this world to the state that should follow the
; given key event
after-key-event
; -> Scene
; GIVEN: a scene
; RETURNS: a scene that depicts this World
to-scene
; Widget -> Void
; GIVEN: A widget
; EFFECT: add the given widget to the world
add-widget
; SWidget -> Void
; GIVEN: A stateful widget
; EFFECT: add the given widget to the world
add-stateful-widget
))
;; Every functional object that lives in the world must implement the
;; Widget<%> interface.
(define Widget<%>
(interface ()
; -> Widget
; GIVEN: no arguments
; RETURNS: the state of this object that should follow at time t+1.
after-tick
Integer Integer - > Widget
; GIVEN: a location
; RETURNS: the state of this object that should follow the
; specified mouse event at the given location.
after-button-down
after-button-up
after-drag
KeyEvent : KeyEvent - > Widget
; GIVEN: a key event and a time
; RETURNS: the state of this object that should follow the
; given key event
after-key-event
; Scene -> Scene
; GIVEN: a scene
; RETURNS: a scene like the given one, but with this object
; painted on it.
add-to-scene
))
;; Every stable (stateful) object that lives in the world must implement the
;; SWidget<%> interface.
(define SWidget<%>
(interface ()
; -> Void
; GIVEN: no arguments
; EFFECT: updates this widget to the state it should have
; following a tick.
after-tick
Integer Integer - > Void
; GIVEN: a location
; EFFECT: updates this widget to the state it should have
; following the specified mouse event at the given location.
after-button-down
after-button-up
after-drag
KeyEvent : KeyEvent - > Void
; GIVEN: a key event
; EFFECT: updates this widget to the state it should have
; following the given key event
after-key-event
; Scene -> Scene
; GIVEN: a scene
; RETURNS: a scene like the given one, but with this object
; painted on it.
add-to-scene
))
;; Additional method for Ball:
(define SBall<%>
(interface (SWidget<%>)
;; ; Int -> Void
;; ; EFFECT: updates the ball's cached value of the wall's position
;; update-wall-pos
))
;; Additional method for Wall:
(define SWall<%>
(interface (SWidget<%>)
; (Int -> X) -> Int
; GIVEN: A function to be called whenever the wall position changes
; EFFECT: registers the function to receive position updates from this wall.
; RETURNS: the x-position of the wall
register
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; initial-world : -> WorldState
;; RETURNS: a world with a wall, a ball, and a factory
(define (initial-world)
(local
((define the-wall (new Wall%))
(define the-ball (new Ball% [w the-wall]))
(define the-world
(make-world-state
empty ; (list the-ball) -- the ball is now stateful
(list the-wall)))
(define the-factory
(new BallFactory% [wall the-wall][world the-world])))
(begin
;; put the factory in the world
(send the-world add-stateful-widget the-factory)
;; tell the factory to start a ball
(send the-factory after-key-event "b")
the-world)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; run : PosReal -> World
; GIVEN: a frame rate, in secs/tick
; EFFECT: runs an initial world at the given frame rate
; RETURNS: the world in its final state of the world
; Note: the (begin (send w ...) w) idiom
(define (run rate)
(big-bang (initial-world)
(on-tick
(lambda (w) (begin (send w after-tick) w))
rate)
(on-draw
(lambda (w) (send w to-scene)))
(on-key
(lambda (w kev)
(begin
(send w after-key-event kev)
w)))
(on-mouse
(lambda (w mx my mev)
(begin
(send w after-mouse-event mx my mev)
w)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The World% class
; ListOfWidget -> WorldState
(define (make-world-state objs sobjs)
(new WorldState% [objs objs][sobjs sobjs]))
(define WorldState%
(class* object% (StatefulWorld<%>)
(init-field objs) ; ListOfWidget
(init-field sobjs) ; ListOfSWidget
(super-new)
(define/public (add-widget w)
(set! objs (cons w objs)))
(define/public (add-stateful-widget w)
(set! sobjs (cons w sobjs)))
;; (Widget or SWidget -> Void) -> Void
(define (process-widgets fn)
(begin
(set! objs (map fn objs))
(for-each fn sobjs)))
;; after-tick : -> Void
Use map on the Widgets in this World ; use for - each on the
;; stateful widgets
(define/public (after-tick)
(process-widgets
(lambda (obj) (send obj after-tick))))
;; to-scene : -> Scene
;; Use HOFC foldr on the Widgets and SWidgets in this World
;; Note: the append is inefficient, but clear..
(define/public (to-scene)
(foldr
(lambda (obj scene)
(send obj add-to-scene scene))
EMPTY-CANVAS
(append objs sobjs)))
after - key - event : KeyEvent - > WorldState
STRATEGY : Pass the KeyEvents on to the objects in the world .
(define/public (after-key-event kev)
(process-widgets
(lambda (obj) (send obj after-key-event kev))))
world - after - mouse - event : WorldState
;; STRATGY: Cases on mev
(define/public (after-mouse-event mx my mev)
(cond
[(mouse=? mev "button-down")
(world-after-button-down mx my)]
[(mouse=? mev "drag")
(world-after-drag mx my)]
[(mouse=? mev "button-up")
(world-after-button-up mx my)]
[else this]))
;; the next few functions are local functions, not in the interface.
(define (world-after-button-down mx my)
(process-widgets
(lambda (obj) (send obj after-button-down mx my))))
(define (world-after-button-up mx my)
(process-widgets
(lambda (obj) (send obj after-button-up mx my))))
(define (world-after-drag mx my)
(process-widgets
(lambda (obj) (send obj after-drag mx my))))
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The BallFactory% class
;; accepts "b" key events and adds them to the world.
;; gets the world as an init-field
10 - 6 : in the push model , the ball is a stateful widget
(define BallFactory%
(class* object% (SWidget<%>)
(init-field world) ; the world to which the factory adds balls
(init-field wall) ; the wall that the new balls should bounce
; off of.
(super-new)
(define/public (after-key-event kev)
(cond
[(key=? kev "b")
(send world add-stateful-widget (new Ball% [w wall]))]))
the Ball Factory has no other behavior
(define/public (after-tick) this)
(define/public (after-button-down mx my) this)
(define/public (after-button-up mx my) this)
(define/public (after-drag mx my) this)
(define/public (add-to-scene s) s)
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
The class
A Ball is a ( new
;; [x Int][y Int][speed Int]
;; [saved-mx Integer][saved-my Integer][selected? Boolean]
;; [w Wall])
the Ball is now a stateful widget
(define Ball%
(class* object% (SWidget<%>)
the Wall that the ball should bounce off of
;; initial values of x, y (center of ball)
(init-field [x INIT-BALL-X])
(init-field [y INIT-BALL-Y])
(init-field [speed INIT-BALL-SPEED])
; is this selected? Default is false.
(init-field [selected? false])
;; if this is selected, the position of
;; the last button-down event inside this, relative to the
;; heli's center. Else any value.
(init-field [saved-mx 0] [saved-my 0])
(field [radius 20])
;; register this ball with the wall, and use the result as the
;; initial value of wall-pos
(field [wall-pos (send w register
; this
(lambda (n) (set! wall-pos n)))])
(super-new)
;; ;; Int -> Void
;; ;; EFFECT: updates the ball's idea of the wall's position to the
;; ;; given integer.
;; (define/public (update-wall-pos n)
( set ! ) )
;; after-tick : -> Void
;; state of this ball after a tick. A selected ball doesn't move.
(define/public (after-tick)
(if selected?
this
( new
;; [x (next-x-pos)]
;; [y y]
;; [speed (next-speed)]
;; [selected? selected?]
;; [saved-mx saved-mx]
;; [saved-my saved-my]
;; [w w])
(let ((x1 (next-x-pos))
(speed1 (next-speed)))
;; (next-speed) depends on x, and (next-x-pos) depends on
;; speed, so they have to be done independently before doing
;; any assignments.
(begin
(set! speed speed1)
(set! x x1)))))
;; -> Integer
;; position of the ball at the next tick
;; STRATEGY: use the ball's cached copy of the wall position to
;; set the upper limit of motion
(define (next-x-pos)
(limit-value
radius
(+ x speed)
(- wall-pos ; (send w get-pos)
radius)))
;; Number^3 -> Number
;; WHERE: lo <= hi
RETURNS : , but limited to the range [ lo , hi ]
(define (limit-value lo val hi)
(max lo (min val hi)))
;; -> Integer
;; RETURNS: the velocity of the ball at the next tick
;; STRATEGY: if the ball will be at its limit, negate the
;; velocity, otherwise return it unchanged
(define (next-speed)
(if (or
(= (next-x-pos) radius)
(= (next-x-pos) (- wall-pos ; (send w get-pos)
radius)))
(- speed)
speed))
(define/public (add-to-scene s)
(place-image
(circle radius
"outline"
"red")
x y s))
after - button - down : Integer Integer - > Void
; GIVEN: the location of a button-down event
; STRATEGY: Cases on whether the event is in this
(define/public (after-button-down mx my)
(if (in-this? mx my)
( new
;; [x x][y y][speed speed]
;; [selected? true]
;; [saved-mx (- mx x)]
;; [saved-my (- my y)]
;; [w w])
(begin
(set! selected? true)
(set! saved-mx (- mx x))
(set! saved-my (- my y)))
this))
in - this ? : Boolean
;; GIVEN: a location on the canvas
;; RETURNS: true iff the location is inside this.
(define (in-this? other-x other-y)
(<= (+ (sqr (- x other-x)) (sqr (- y other-y)))
(sqr radius)))
after - button - up : Integer Integer - > Void
; GIVEN: the location of a button-up event
; STRATEGY: Cases on whether the event is in this
; If this is selected, then unselect it.
(define/public (after-button-up mx my)
(if (in-this? mx my)
( new
;; [x x][y y][speed speed]
;; [selected? false]
;; [saved-mx 127]
[ saved - my 98 ] ; the invariant says that if selected ? is
;; ; false, you can put anything here.
;; [w w])
(set! selected? false)
this))
after - drag : Integer Integer - > Void
; GIVEN: the location of a drag event
; STRATEGY: Cases on whether the ball is selected.
; If it is selected, move it so that the vector from the center to
; the drag event is equal to (mx, my)
(define/public (after-drag mx my)
(if selected?
( new
;; [x (- mx saved-mx)]
;; [y (- my saved-my)]
;; [speed speed]
;; [selected? true]
;; [saved-mx saved-mx]
;; [saved-my saved-my]
;; [w w])
(begin
(set! x (- mx saved-mx))
(set! y (- my saved-my)))
this))
;; the ball ignores key events
(define/public (after-key-event kev) this)
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
The Wall% class
A Wall is ( new Wall% [ pos Integer ]
;; [saved-mx Integer]
;; [selected? Boolean])
;; all these fields have default values.
(define Wall%
(class* object% (SWall<%>)
(init-field [pos INITIAL-WALL-POSITION]) ; the x position of the wall
; is the wall selected? Default is false.
(init-field [selected? false])
;; if the wall is selected, the x position of
;; the last button-down event near the wall
(init-field [saved-mx 0])
;; the list of registered callbacks
ListOf(Int - > Void )
(field [callbacks empty])
(super-new)
;; the extra behavior for Wall<%>
;; (define/public (get-pos) pos)
;; (Int -> X) -> Int
;; EFFECT: registers the given callback
;; RETURNS: the current position of the wall
(define/public (register c)
(begin
(set! callbacks (cons c callbacks))
pos))
after - button - down : Integer Integer - > Void
; GIVEN: the (x, y) location of a button-down event
; EFFECT: if the event is near the wall, make the wall selected.
; STRATEGY: Cases on whether the event is near the wall
(if (near-wall? mx)
( new Wall%
;; [pos pos]
;; [selected? true]
;; [saved-mx (- mx pos)])
(begin
(set! selected? true)
(set! saved-mx (- mx pos)))
;; don't need to worry about returning this
this)) ;; but an if needs an else clause :-(
after - button - up : Integer Integer - > Void
; GIVEN: the (x,y) location of a button-up event
EFFECT : makes the Wall unselected
(define/public (after-button-up mx my)
( new Wall%
;; [pos pos]
;; [selected? false]
;; [saved-mx saved-mx])
(set! selected? false))
after - drag : Integer Integer - > Void
; GIVEN: the location of a drag event
; STRATEGY: Cases on whether the wall is selected.
; If it is selected, move it so that the vector from its position to
; the drag event is equal to saved-mx. Report the new position to
; the registered balls.
(define/public (after-drag mx my)
(if selected?
( new Wall%
;; [pos (- mx saved-mx)]
;; [selected? true]
;; [saved-mx saved-mx])
(begin
(set! pos (- mx saved-mx))
(for-each
(lambda (c)
; CHANGED in callback model
; (send b update-wall-pos pos)
(c pos))
callbacks))
this))
;; add-to-scene : Scene -> Scene
;; RETURNS: a scene like the given one, but with this wall painted
;; on it.
(define/public (add-to-scene scene)
(scene+line scene pos 0 pos CANVAS-HEIGHT "black"))
;; is mx near the wall? We arbitrarily say it's near if its
within 5 pixels .
(define (near-wall? mx)
(< (abs (- mx pos)) 5))
;; the wall has no other behaviors
(define/public (after-tick) this)
(define/public (after-key-event kev) this)
))
| null | https://raw.githubusercontent.com/mwand/5010-examples/ac24491ec2e533d048e11087ccc30ff1c087c218/10-7-callbacks.rkt | racket | function to be called when it is notified. So we don't need a dedicated
update-pos method
CONSTANTS
Data Definitions
A Widget is an object whose class implements Widget<%>
INTERFACES
-> Void
GIVEN: no arguments
EFFECT: updates this world to its state after a tick
Integer Integer MouseEvent-> Void
GIVEN: a location
EFFECT: updates this world to the state that should follow the
given mouse event at the given location.
GIVEN: a key event
EFFECT: updates this world to the state that should follow the
given key event
-> Scene
GIVEN: a scene
RETURNS: a scene that depicts this World
Widget -> Void
GIVEN: A widget
EFFECT: add the given widget to the world
SWidget -> Void
GIVEN: A stateful widget
EFFECT: add the given widget to the world
Every functional object that lives in the world must implement the
Widget<%> interface.
-> Widget
GIVEN: no arguments
RETURNS: the state of this object that should follow at time t+1.
GIVEN: a location
RETURNS: the state of this object that should follow the
specified mouse event at the given location.
GIVEN: a key event and a time
RETURNS: the state of this object that should follow the
given key event
Scene -> Scene
GIVEN: a scene
RETURNS: a scene like the given one, but with this object
painted on it.
Every stable (stateful) object that lives in the world must implement the
SWidget<%> interface.
-> Void
GIVEN: no arguments
EFFECT: updates this widget to the state it should have
following a tick.
GIVEN: a location
EFFECT: updates this widget to the state it should have
following the specified mouse event at the given location.
GIVEN: a key event
EFFECT: updates this widget to the state it should have
following the given key event
Scene -> Scene
GIVEN: a scene
RETURNS: a scene like the given one, but with this object
painted on it.
Additional method for Ball:
; Int -> Void
; EFFECT: updates the ball's cached value of the wall's position
update-wall-pos
Additional method for Wall:
(Int -> X) -> Int
GIVEN: A function to be called whenever the wall position changes
EFFECT: registers the function to receive position updates from this wall.
RETURNS: the x-position of the wall
initial-world : -> WorldState
RETURNS: a world with a wall, a ball, and a factory
(list the-ball) -- the ball is now stateful
put the factory in the world
tell the factory to start a ball
run : PosReal -> World
GIVEN: a frame rate, in secs/tick
EFFECT: runs an initial world at the given frame rate
RETURNS: the world in its final state of the world
Note: the (begin (send w ...) w) idiom
The World% class
ListOfWidget -> WorldState
ListOfWidget
ListOfSWidget
(Widget or SWidget -> Void) -> Void
after-tick : -> Void
use for - each on the
stateful widgets
to-scene : -> Scene
Use HOFC foldr on the Widgets and SWidgets in this World
Note: the append is inefficient, but clear..
STRATGY: Cases on mev
the next few functions are local functions, not in the interface.
The BallFactory% class
accepts "b" key events and adds them to the world.
gets the world as an init-field
the world to which the factory adds balls
the wall that the new balls should bounce
off of.
[x Int][y Int][speed Int]
[saved-mx Integer][saved-my Integer][selected? Boolean]
[w Wall])
initial values of x, y (center of ball)
is this selected? Default is false.
if this is selected, the position of
the last button-down event inside this, relative to the
heli's center. Else any value.
register this ball with the wall, and use the result as the
initial value of wall-pos
this
;; Int -> Void
;; EFFECT: updates the ball's idea of the wall's position to the
;; given integer.
(define/public (update-wall-pos n)
after-tick : -> Void
state of this ball after a tick. A selected ball doesn't move.
[x (next-x-pos)]
[y y]
[speed (next-speed)]
[selected? selected?]
[saved-mx saved-mx]
[saved-my saved-my]
[w w])
(next-speed) depends on x, and (next-x-pos) depends on
speed, so they have to be done independently before doing
any assignments.
-> Integer
position of the ball at the next tick
STRATEGY: use the ball's cached copy of the wall position to
set the upper limit of motion
(send w get-pos)
Number^3 -> Number
WHERE: lo <= hi
-> Integer
RETURNS: the velocity of the ball at the next tick
STRATEGY: if the ball will be at its limit, negate the
velocity, otherwise return it unchanged
(send w get-pos)
GIVEN: the location of a button-down event
STRATEGY: Cases on whether the event is in this
[x x][y y][speed speed]
[selected? true]
[saved-mx (- mx x)]
[saved-my (- my y)]
[w w])
GIVEN: a location on the canvas
RETURNS: true iff the location is inside this.
GIVEN: the location of a button-up event
STRATEGY: Cases on whether the event is in this
If this is selected, then unselect it.
[x x][y y][speed speed]
[selected? false]
[saved-mx 127]
the invariant says that if selected ? is
; false, you can put anything here.
[w w])
GIVEN: the location of a drag event
STRATEGY: Cases on whether the ball is selected.
If it is selected, move it so that the vector from the center to
the drag event is equal to (mx, my)
[x (- mx saved-mx)]
[y (- my saved-my)]
[speed speed]
[selected? true]
[saved-mx saved-mx]
[saved-my saved-my]
[w w])
the ball ignores key events
[saved-mx Integer]
[selected? Boolean])
all these fields have default values.
the x position of the wall
is the wall selected? Default is false.
if the wall is selected, the x position of
the last button-down event near the wall
the list of registered callbacks
the extra behavior for Wall<%>
(define/public (get-pos) pos)
(Int -> X) -> Int
EFFECT: registers the given callback
RETURNS: the current position of the wall
GIVEN: the (x, y) location of a button-down event
EFFECT: if the event is near the wall, make the wall selected.
STRATEGY: Cases on whether the event is near the wall
[pos pos]
[selected? true]
[saved-mx (- mx pos)])
don't need to worry about returning this
but an if needs an else clause :-(
GIVEN: the (x,y) location of a button-up event
[pos pos]
[selected? false]
[saved-mx saved-mx])
GIVEN: the location of a drag event
STRATEGY: Cases on whether the wall is selected.
If it is selected, move it so that the vector from its position to
the drag event is equal to saved-mx. Report the new position to
the registered balls.
[pos (- mx saved-mx)]
[selected? true]
[saved-mx saved-mx])
CHANGED in callback model
(send b update-wall-pos pos)
add-to-scene : Scene -> Scene
RETURNS: a scene like the given one, but with this wall painted
on it.
is mx near the wall? We arbitrarily say it's near if its
the wall has no other behaviors | #lang racket
10 - 7 - callbacks : instead of registering ' this ' , the ball registers a
(require rackunit)
(require 2htdp/universe)
(require 2htdp/image)
(require "extras.rkt")
start with ( run framerate ) . Typically : ( run 0.25 )
(define CANVAS-WIDTH 400)
(define CANVAS-HEIGHT 300)
(define EMPTY-CANVAS (empty-scene CANVAS-WIDTH CANVAS-HEIGHT))
(define INIT-BALL-X (/ CANVAS-HEIGHT 2))
(define INIT-BALL-Y (/ CANVAS-WIDTH 3))
(define INIT-BALL-SPEED 20)
(define INITIAL-WALL-POSITION 300)
The World implements the > interface
(define StatefulWorld<%>
(interface ()
after-tick
after-mouse-event
KeyEvent : KeyEvent - > Void
after-key-event
to-scene
add-widget
add-stateful-widget
))
(define Widget<%>
(interface ()
after-tick
Integer Integer - > Widget
after-button-down
after-button-up
after-drag
KeyEvent : KeyEvent - > Widget
after-key-event
add-to-scene
))
(define SWidget<%>
(interface ()
after-tick
Integer Integer - > Void
after-button-down
after-button-up
after-drag
KeyEvent : KeyEvent - > Void
after-key-event
add-to-scene
))
(define SBall<%>
(interface (SWidget<%>)
))
(define SWall<%>
(interface (SWidget<%>)
register
))
(define (initial-world)
(local
((define the-wall (new Wall%))
(define the-ball (new Ball% [w the-wall]))
(define the-world
(make-world-state
(list the-wall)))
(define the-factory
(new BallFactory% [wall the-wall][world the-world])))
(begin
(send the-world add-stateful-widget the-factory)
(send the-factory after-key-event "b")
the-world)))
(define (run rate)
(big-bang (initial-world)
(on-tick
(lambda (w) (begin (send w after-tick) w))
rate)
(on-draw
(lambda (w) (send w to-scene)))
(on-key
(lambda (w kev)
(begin
(send w after-key-event kev)
w)))
(on-mouse
(lambda (w mx my mev)
(begin
(send w after-mouse-event mx my mev)
w)))))
(define (make-world-state objs sobjs)
(new WorldState% [objs objs][sobjs sobjs]))
(define WorldState%
(class* object% (StatefulWorld<%>)
(super-new)
(define/public (add-widget w)
(set! objs (cons w objs)))
(define/public (add-stateful-widget w)
(set! sobjs (cons w sobjs)))
(define (process-widgets fn)
(begin
(set! objs (map fn objs))
(for-each fn sobjs)))
(define/public (after-tick)
(process-widgets
(lambda (obj) (send obj after-tick))))
(define/public (to-scene)
(foldr
(lambda (obj scene)
(send obj add-to-scene scene))
EMPTY-CANVAS
(append objs sobjs)))
after - key - event : KeyEvent - > WorldState
STRATEGY : Pass the KeyEvents on to the objects in the world .
(define/public (after-key-event kev)
(process-widgets
(lambda (obj) (send obj after-key-event kev))))
world - after - mouse - event : WorldState
(define/public (after-mouse-event mx my mev)
(cond
[(mouse=? mev "button-down")
(world-after-button-down mx my)]
[(mouse=? mev "drag")
(world-after-drag mx my)]
[(mouse=? mev "button-up")
(world-after-button-up mx my)]
[else this]))
(define (world-after-button-down mx my)
(process-widgets
(lambda (obj) (send obj after-button-down mx my))))
(define (world-after-button-up mx my)
(process-widgets
(lambda (obj) (send obj after-button-up mx my))))
(define (world-after-drag mx my)
(process-widgets
(lambda (obj) (send obj after-drag mx my))))
))
10 - 6 : in the push model , the ball is a stateful widget
(define BallFactory%
(class* object% (SWidget<%>)
(super-new)
(define/public (after-key-event kev)
(cond
[(key=? kev "b")
(send world add-stateful-widget (new Ball% [w wall]))]))
the Ball Factory has no other behavior
(define/public (after-tick) this)
(define/public (after-button-down mx my) this)
(define/public (after-button-up mx my) this)
(define/public (after-drag mx my) this)
(define/public (add-to-scene s) s)
))
The class
A Ball is a ( new
the Ball is now a stateful widget
(define Ball%
(class* object% (SWidget<%>)
the Wall that the ball should bounce off of
(init-field [x INIT-BALL-X])
(init-field [y INIT-BALL-Y])
(init-field [speed INIT-BALL-SPEED])
(init-field [selected? false])
(init-field [saved-mx 0] [saved-my 0])
(field [radius 20])
(field [wall-pos (send w register
(lambda (n) (set! wall-pos n)))])
(super-new)
( set ! ) )
(define/public (after-tick)
(if selected?
this
( new
(let ((x1 (next-x-pos))
(speed1 (next-speed)))
(begin
(set! speed speed1)
(set! x x1)))))
(define (next-x-pos)
(limit-value
radius
(+ x speed)
radius)))
RETURNS : , but limited to the range [ lo , hi ]
(define (limit-value lo val hi)
(max lo (min val hi)))
(define (next-speed)
(if (or
(= (next-x-pos) radius)
radius)))
(- speed)
speed))
(define/public (add-to-scene s)
(place-image
(circle radius
"outline"
"red")
x y s))
after - button - down : Integer Integer - > Void
(define/public (after-button-down mx my)
(if (in-this? mx my)
( new
(begin
(set! selected? true)
(set! saved-mx (- mx x))
(set! saved-my (- my y)))
this))
in - this ? : Boolean
(define (in-this? other-x other-y)
(<= (+ (sqr (- x other-x)) (sqr (- y other-y)))
(sqr radius)))
after - button - up : Integer Integer - > Void
(define/public (after-button-up mx my)
(if (in-this? mx my)
( new
(set! selected? false)
this))
after - drag : Integer Integer - > Void
(define/public (after-drag mx my)
(if selected?
( new
(begin
(set! x (- mx saved-mx))
(set! y (- my saved-my)))
this))
(define/public (after-key-event kev) this)
))
The Wall% class
A Wall is ( new Wall% [ pos Integer ]
(define Wall%
(class* object% (SWall<%>)
(init-field [selected? false])
(init-field [saved-mx 0])
ListOf(Int - > Void )
(field [callbacks empty])
(super-new)
(define/public (register c)
(begin
(set! callbacks (cons c callbacks))
pos))
after - button - down : Integer Integer - > Void
(if (near-wall? mx)
( new Wall%
(begin
(set! selected? true)
(set! saved-mx (- mx pos)))
after - button - up : Integer Integer - > Void
EFFECT : makes the Wall unselected
(define/public (after-button-up mx my)
( new Wall%
(set! selected? false))
after - drag : Integer Integer - > Void
(define/public (after-drag mx my)
(if selected?
( new Wall%
(begin
(set! pos (- mx saved-mx))
(for-each
(lambda (c)
(c pos))
callbacks))
this))
(define/public (add-to-scene scene)
(scene+line scene pos 0 pos CANVAS-HEIGHT "black"))
within 5 pixels .
(define (near-wall? mx)
(< (abs (- mx pos)) 5))
(define/public (after-tick) this)
(define/public (after-key-event kev) this)
))
|
321ef10e836f47abaa1cdb591987a541a9e9438bebfcd0de114876a41414b853 | nuvla/api-server | configuration_template_session_oidc.cljc | (ns sixsq.nuvla.server.resources.spec.configuration-template-session-oidc
(:require
[clojure.spec.alpha :as s]
[sixsq.nuvla.server.resources.spec.configuration-template :as ps]
[sixsq.nuvla.server.resources.spec.core :as cimi-core]
[sixsq.nuvla.server.util.spec :as su]
[spec-tools.core :as st]))
(s/def ::client-id
(-> (st/spec ::cimi-core/token)
(assoc :name "client-id"
:json-schema/displayName "client ID"
:json-schema/description "MITREid client ID"
:json-schema/group "body"
:json-schema/order 20
:json-schema/hidden false
:json-schema/sensitive false)))
(s/def ::client-secret
(-> (st/spec ::cimi-core/token)
(assoc :name "client-secret"
:json-schema/displayName "client secret"
:json-schema/description "OIDC client secret"
:json-schema/group "body"
:json-schema/order 21
:json-schema/hidden false
:json-schema/sensitive true)))
(s/def ::authorize-url
(-> (st/spec ::cimi-core/token)
(assoc :name "authorize-url"
:json-schema/displayName "authorization URL"
:json-schema/description "URL for the authorization phase of the OIDC protocol"
:json-schema/group "body"
:json-schema/order 22
:json-schema/hidden false
:json-schema/sensitive false)))
(s/def ::token-url
(-> (st/spec ::cimi-core/token)
(assoc :name "token-url"
:json-schema/displayName "token URL"
:json-schema/description "URL for the obtaining a token in the OIDC protocol"
:json-schema/group "body"
:json-schema/order 23
:json-schema/hidden false
:json-schema/sensitive false)))
; deprecated
(s/def ::public-key
(-> (st/spec ::cimi-core/nonblank-string) ;; allows jwk JSON representation
(assoc :name "public-key"
:json-schema/displayName "public key"
:json-schema/description "public key of the server in PEM or JWK JSON format"
:json-schema/group "body"
:json-schema/order 25
:json-schema/hidden false
:json-schema/sensitive false)))
(s/def ::jwks-url
(-> (st/spec ::cimi-core/token)
(assoc :name "jwks-url"
:json-schema/displayName "jwks url"
:json-schema/description "URL jwks to get public keys for signature"
:json-schema/group "body"
:json-schema/order 26
:json-schema/hidden false
:json-schema/sensitive false)))
; deprecated
(s/def ::redirect-url-resource
(-> (st/spec #{"hook", "callback"})
(assoc :name "redirect url resource"
:json-schema/type "string"
:json-schema/displayName "redirect url resource"
:json-schema/description "redirect url resource"
:json-schema/group "body"
:json-schema/order 27
:json-schema/hidden false
:json-schema/value-scope {:values ["hook", "callback"]
:default "callback"})))
(def configuration-template-keys-spec-req
{:req-un [::ps/instance ::client-id ::jwks-url
::authorize-url ::token-url]
:opt-un [::client-secret ::public-key ::redirect-url-resource]})
(def configuration-template-keys-spec-create
{:req-un [::ps/instance ::client-id ::jwks-url
::authorize-url ::token-url]
:opt-un [::client-secret ::redirect-url-resource]})
;; Defines the contents of the OIDC authentication configuration-template resource itself.
(s/def ::schema
(su/only-keys-maps ps/resource-keys-spec
configuration-template-keys-spec-req))
;; Defines the contents of the OIDC authentication template used in a create resource.
(s/def ::template
(su/only-keys-maps ps/template-keys-spec
configuration-template-keys-spec-create))
(s/def ::schema-create
(su/only-keys-maps ps/create-keys-spec
{:req-un [::template]}))
| null | https://raw.githubusercontent.com/nuvla/api-server/561b423c186ef7972aadc349ec270c2201a75b06/code/src/sixsq/nuvla/server/resources/spec/configuration_template_session_oidc.cljc | clojure | deprecated
allows jwk JSON representation
deprecated
Defines the contents of the OIDC authentication configuration-template resource itself.
Defines the contents of the OIDC authentication template used in a create resource. | (ns sixsq.nuvla.server.resources.spec.configuration-template-session-oidc
(:require
[clojure.spec.alpha :as s]
[sixsq.nuvla.server.resources.spec.configuration-template :as ps]
[sixsq.nuvla.server.resources.spec.core :as cimi-core]
[sixsq.nuvla.server.util.spec :as su]
[spec-tools.core :as st]))
(s/def ::client-id
(-> (st/spec ::cimi-core/token)
(assoc :name "client-id"
:json-schema/displayName "client ID"
:json-schema/description "MITREid client ID"
:json-schema/group "body"
:json-schema/order 20
:json-schema/hidden false
:json-schema/sensitive false)))
(s/def ::client-secret
(-> (st/spec ::cimi-core/token)
(assoc :name "client-secret"
:json-schema/displayName "client secret"
:json-schema/description "OIDC client secret"
:json-schema/group "body"
:json-schema/order 21
:json-schema/hidden false
:json-schema/sensitive true)))
(s/def ::authorize-url
(-> (st/spec ::cimi-core/token)
(assoc :name "authorize-url"
:json-schema/displayName "authorization URL"
:json-schema/description "URL for the authorization phase of the OIDC protocol"
:json-schema/group "body"
:json-schema/order 22
:json-schema/hidden false
:json-schema/sensitive false)))
(s/def ::token-url
(-> (st/spec ::cimi-core/token)
(assoc :name "token-url"
:json-schema/displayName "token URL"
:json-schema/description "URL for the obtaining a token in the OIDC protocol"
:json-schema/group "body"
:json-schema/order 23
:json-schema/hidden false
:json-schema/sensitive false)))
(s/def ::public-key
(assoc :name "public-key"
:json-schema/displayName "public key"
:json-schema/description "public key of the server in PEM or JWK JSON format"
:json-schema/group "body"
:json-schema/order 25
:json-schema/hidden false
:json-schema/sensitive false)))
(s/def ::jwks-url
(-> (st/spec ::cimi-core/token)
(assoc :name "jwks-url"
:json-schema/displayName "jwks url"
:json-schema/description "URL jwks to get public keys for signature"
:json-schema/group "body"
:json-schema/order 26
:json-schema/hidden false
:json-schema/sensitive false)))
(s/def ::redirect-url-resource
(-> (st/spec #{"hook", "callback"})
(assoc :name "redirect url resource"
:json-schema/type "string"
:json-schema/displayName "redirect url resource"
:json-schema/description "redirect url resource"
:json-schema/group "body"
:json-schema/order 27
:json-schema/hidden false
:json-schema/value-scope {:values ["hook", "callback"]
:default "callback"})))
(def configuration-template-keys-spec-req
{:req-un [::ps/instance ::client-id ::jwks-url
::authorize-url ::token-url]
:opt-un [::client-secret ::public-key ::redirect-url-resource]})
(def configuration-template-keys-spec-create
{:req-un [::ps/instance ::client-id ::jwks-url
::authorize-url ::token-url]
:opt-un [::client-secret ::redirect-url-resource]})
(s/def ::schema
(su/only-keys-maps ps/resource-keys-spec
configuration-template-keys-spec-req))
(s/def ::template
(su/only-keys-maps ps/template-keys-spec
configuration-template-keys-spec-create))
(s/def ::schema-create
(su/only-keys-maps ps/create-keys-spec
{:req-un [::template]}))
|
60fa4dc5ef87da0c37c6f1cac0335a4dce4195706af2d40ffdebef4d6026d3d1 | tommaisey/aeon | k2a.help.scm | (hear (k2a (mul (white-noise kr) 0.3)))
(hear (mce2 (k2a (mul (white-noise kr) 0.3))
(mul (white-noise ar) 0.3)))
(hear
(let* ((block-size (fdiv sample-rate control-rate))
(freq (mul (fdiv (mouse-x kr 0.1 40 1 0.1) block-size) sample-rate)))
(mul (mce2 (k2a (lf-noise0 kr freq))
(lf-noise0 ar freq))
0.3)))
| null | https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/controls/k2a.help.scm | scheme | (hear (k2a (mul (white-noise kr) 0.3)))
(hear (mce2 (k2a (mul (white-noise kr) 0.3))
(mul (white-noise ar) 0.3)))
(hear
(let* ((block-size (fdiv sample-rate control-rate))
(freq (mul (fdiv (mouse-x kr 0.1 40 1 0.1) block-size) sample-rate)))
(mul (mce2 (k2a (lf-noise0 kr freq))
(lf-noise0 ar freq))
0.3)))
| |
6d7936feaf45339d0c0206abb3ca9cd74afb6643934fb3f6142c2a4b573a1609 | backtracking/mlpost | spline_lib.mli | (**************************************************************************)
(* *)
Copyright ( C ) Johannes Kanig ,
, and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *)
(* *)
(**************************************************************************)
type point = Point_lib.t
type abscissa = Spline.abscissa
type path_ = { pl : Spline.t list; cycle : bool }
type path = Point of point | Path of path_
val is_closed : path -> bool
val is_a_point : path -> point option
val create : point -> point -> point -> point -> path
(** create a b c d return a path with :
- point a as the starting point,
- point b as its control point,
- point d as the ending point,
- point c as its control point *)
val create_point : point -> path
(** create a path consisting of a single point *)
val create_line : point -> point -> path
* create a straight line between two points
val create_lines : point list -> path
(** create a path consisting of straight lines connecting the points
in argument *)
val close : path -> path
(** close a path *)
val min_abscissa : path -> abscissa
val max_abscissa : path -> abscissa
val length : path -> int
(** number of vertex *)
val add_end : path -> point -> point -> path
* add_end p a b return the path p with one more spline at the end .
val add_end_line : path -> point -> path
val add_end_spline : path -> point -> point -> point -> path
val append : path -> point -> point -> path -> path
val reverse : path -> path
* reverse p return the path p reversed
union : path - > path - > path ( * * union p1 p2 return the union of
path p1 and p2 . [ ] are points of p1 ,
] max_abscissa p1;max_abscissa p1+max_abscissa p2 - min_abscissa p2 ]
are points of p2
path p1 and p2. [min_abscissa p1;max_abscissa p1] are points of p1,
]max_abscissa p1;max_abscissa p1+max_abscissa p2-min_abscissa p2]
are points of p2 *)
val union_conv : path -> path -> (abscissa -> abscissa)
*)
val one_intersection : path -> path -> abscissa * abscissa
val intersection : path -> path -> (abscissa * abscissa) list
* intersection p1 p2 return a list of pair of abscissa . In each
pairs ( a1,a2 ) , a1 ( resp . a2 ) is the abscissa in p1 ( resp . p2 ) of
one intersection point between p1 and p2 . Additionnal point of
intersection ( two point for only one real intersection ) can
appear in degenerate case .
pairs (a1,a2), a1 (resp. a2) is the abscissa in p1 (resp. p2) of
one intersection point between p1 and p2. Additionnal point of
intersection (two point for only one real intersection) can
appear in degenerate case. *)
val fold_left :
('a -> point -> point -> point -> point -> 'a) -> 'a -> path -> 'a
(** fold on all the splines of a path *)
val iter : (point -> point -> point -> point -> unit) -> path -> unit
(** iter on all the splines of a path *)
val cut_before : path -> path -> path
val cut_after : path -> path -> path
* remove the part of a path before the first intersection
or after the last
or after the last*)
val split : path -> abscissa -> path * path
val subpath : path -> abscissa -> abscissa -> path
val direction_of_abscissa : path -> abscissa -> point
val abscissa_to_point : path -> abscissa -> point
val bounding_box : path -> point * point
val unprecise_bounding_box : path -> point * point
val dist_min_point : path -> point -> float * abscissa
* [ dist_min_point p s ] computes the minimal distance of [ p ] to [ s ] ,
as well as the abscissa which corresponds to this minimal
distance ; the return value is [ distance , abscissa ] .
as well as the abscissa which corresponds to this minimal
distance; the return value is [distance, abscissa].
*)
val dist_min_path : path -> path -> float * (abscissa * abscissa)
* [ dist_min_path p1 p2 ] computes the minimal distance of [ p1 ] to
[ p2 ] , as well as the two abscissa which correspond to this minimal
distance ; the return value is [ distance , ( abscissa_on_p1 ,
abscissa_on_p2 ) ] .
[p2], as well as the two abscissa which correspond to this minimal
distance; the return value is [distance, (abscissa_on_p1,
abscissa_on_p2)].
*)
val translate : point -> path -> path
val transform : Matrix.t -> path -> path
val buildcycle : path -> path -> path
val of_bounding_box : point * point -> path
val print : Format.formatter -> path -> unit
val print_splines : Format.formatter -> Spline.t list -> unit
| null | https://raw.githubusercontent.com/backtracking/mlpost/bd4305289fd64d531b9f42d64dd641d72ab82fd5/src/spline_lib.mli | ocaml | ************************************************************************
This software is free software; you can redistribute it and/or
described in file LICENSE.
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
************************************************************************
* create a b c d return a path with :
- point a as the starting point,
- point b as its control point,
- point d as the ending point,
- point c as its control point
* create a path consisting of a single point
* create a path consisting of straight lines connecting the points
in argument
* close a path
* number of vertex
* fold on all the splines of a path
* iter on all the splines of a path | Copyright ( C ) Johannes Kanig ,
, and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
type point = Point_lib.t
type abscissa = Spline.abscissa
type path_ = { pl : Spline.t list; cycle : bool }
type path = Point of point | Path of path_
val is_closed : path -> bool
val is_a_point : path -> point option
val create : point -> point -> point -> point -> path
val create_point : point -> path
val create_line : point -> point -> path
* create a straight line between two points
val create_lines : point list -> path
val close : path -> path
val min_abscissa : path -> abscissa
val max_abscissa : path -> abscissa
val length : path -> int
val add_end : path -> point -> point -> path
* add_end p a b return the path p with one more spline at the end .
val add_end_line : path -> point -> path
val add_end_spline : path -> point -> point -> point -> path
val append : path -> point -> point -> path -> path
val reverse : path -> path
* reverse p return the path p reversed
union : path - > path - > path ( * * union p1 p2 return the union of
path p1 and p2 . [ ] are points of p1 ,
] max_abscissa p1;max_abscissa p1+max_abscissa p2 - min_abscissa p2 ]
are points of p2
path p1 and p2. [min_abscissa p1;max_abscissa p1] are points of p1,
]max_abscissa p1;max_abscissa p1+max_abscissa p2-min_abscissa p2]
are points of p2 *)
val union_conv : path -> path -> (abscissa -> abscissa)
*)
val one_intersection : path -> path -> abscissa * abscissa
val intersection : path -> path -> (abscissa * abscissa) list
* intersection p1 p2 return a list of pair of abscissa . In each
pairs ( a1,a2 ) , a1 ( resp . a2 ) is the abscissa in p1 ( resp . p2 ) of
one intersection point between p1 and p2 . Additionnal point of
intersection ( two point for only one real intersection ) can
appear in degenerate case .
pairs (a1,a2), a1 (resp. a2) is the abscissa in p1 (resp. p2) of
one intersection point between p1 and p2. Additionnal point of
intersection (two point for only one real intersection) can
appear in degenerate case. *)
val fold_left :
('a -> point -> point -> point -> point -> 'a) -> 'a -> path -> 'a
val iter : (point -> point -> point -> point -> unit) -> path -> unit
val cut_before : path -> path -> path
val cut_after : path -> path -> path
* remove the part of a path before the first intersection
or after the last
or after the last*)
val split : path -> abscissa -> path * path
val subpath : path -> abscissa -> abscissa -> path
val direction_of_abscissa : path -> abscissa -> point
val abscissa_to_point : path -> abscissa -> point
val bounding_box : path -> point * point
val unprecise_bounding_box : path -> point * point
val dist_min_point : path -> point -> float * abscissa
* [ dist_min_point p s ] computes the minimal distance of [ p ] to [ s ] ,
as well as the abscissa which corresponds to this minimal
distance ; the return value is [ distance , abscissa ] .
as well as the abscissa which corresponds to this minimal
distance; the return value is [distance, abscissa].
*)
val dist_min_path : path -> path -> float * (abscissa * abscissa)
* [ dist_min_path p1 p2 ] computes the minimal distance of [ p1 ] to
[ p2 ] , as well as the two abscissa which correspond to this minimal
distance ; the return value is [ distance , ( abscissa_on_p1 ,
abscissa_on_p2 ) ] .
[p2], as well as the two abscissa which correspond to this minimal
distance; the return value is [distance, (abscissa_on_p1,
abscissa_on_p2)].
*)
val translate : point -> path -> path
val transform : Matrix.t -> path -> path
val buildcycle : path -> path -> path
val of_bounding_box : point * point -> path
val print : Format.formatter -> path -> unit
val print_splines : Format.formatter -> Spline.t list -> unit
|
37b65f9f3a2468c0bb8a86fdc260e1e99e24f32f4c18992b1a896a9fd8889ca0 | realworldocaml/examples | follow_on_function.ml | let concat_and_print x y =
let v = x ^ y in
print_endline v;
v;
let add_and_print x y =
let v = x + y in
print_endline (string_of_int v);
v
let () =
let _x = add_and_print 1 2 in
let _y = concat_and_print "a" "b" in
()
| null | https://raw.githubusercontent.com/realworldocaml/examples/32ea926861a0b728813a29b0e4cf20dd15eb486e/code/front-end/follow_on_function.ml | ocaml | let concat_and_print x y =
let v = x ^ y in
print_endline v;
v;
let add_and_print x y =
let v = x + y in
print_endline (string_of_int v);
v
let () =
let _x = add_and_print 1 2 in
let _y = concat_and_print "a" "b" in
()
| |
dbf274d571b9e88bf9f45835fad201c6440a3f21e075ce305e86a7fe2b4b3a51 | seandepagnier/cruisingplot | sensor.scm | Copyright ( C ) 2010 < >
;;
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 file handles storing values (primarily from sensors)
;; values can be installed, queried, and callbacks can be installed as well
;; this should work even across a network
(declare (unit sensor))
(use srfi-69)
(define sensor-log-ports '())
(define (sensor-log-to-port port)
(set! sensor-log-ports (cons port sensor-log-ports)))
(define (sensor-log-to-file filename)
(sensor-log-to-port (open-output-file filename)))
(define sensors (make-hash-table))
; do we have all these sensors?
(define (sensor-contains? . name-keys)
(cond ((null? name-keys) #t)
((hash-table-exists? sensors (sensor-key (car name-keys)))
(apply sensor-contains? (cdr name-keys)))
(else #f)))
; a key is a list of (name index) or just name
(define (sensor-name name-key)
(if (list? name-key) (car name-key) name-key))
get the index out of they key , or use default index of 0
(define (sensor-index name-key)
(if (list? name-key) (cadr name-key) 0))
; get a list if indicies of of sensors by name
(define (sensor-indicies name)
(let each-value ((values (hash-table->alist sensors)))
(cond ((null? values) '())
((eq? (caar values) name)
(cons (cadar values)
(each-value (cdr values))))
(else
(each-value (cdr values))))))
; get the proper hash key for a name or key
(define (sensor-key name-key)
(list (sensor-name name-key) (sensor-index name-key)))
; query a sensor from the table directly, or #f if it is not there
(define (sensor-query name-key)
(let ((key (sensor-key name-key)))
(if (hash-table-exists? sensors key)
(hash-table-ref sensors key)
#f)))
(define (sensor-query-indexes name indexes)
(map (lambda (index) (sensor-query (list name index)))
indexes))
; Open a file and automatically update values from it
(define (sensor-replay-logfile arg)
(let ((options (create-options
(list (make-number-verifier 'rate "rate of replay" 1 .001 1000))
(string-append " Set input log file, and option\n")
#f)))
(let ((filename (parse-basic-arg-options-string options arg)))
(verbose "replaying data from log file '" filename "' at " (options 'rate) "x speed")
(create-task
(string-append "replay task for file: " filename)
(lambda ()
(with-input-from-file filename
(lambda ()
(let ((sensor-key-mapping (make-hash-table)))
(let each-line ()
(let ((line (read-line)))
(if (not (eof-object? line))
(let ((split (read-from-string line)))
(if (> (length split) 2)
(let ((time (car split))
(key (cadr split))
(value (caddr split)))
(task-sleep! (- (/ time (options 'rate)) (elapsed-seconds)))
(if (hash-table-exists? sensor-key-mapping key)
(sensor-update (hash-table-ref sensor-key-mapping key) value)
(let ((new-key `(,(sensor-name key)
,(sensor-new-index (sensor-name key)))))
(verbose "replay sensor from file '" filename "' " key " -> " new-key)
(hash-table-set! sensor-key-mapping key new-key))))))))
(each-line))
(verbose "log file '" filename "' complete")))))))))
(define (make-raw-sensor-computation name index)
; (print "make-raw-sensor-computation " name " " index)
(computation-register (string->symbol (string-append (symbol->string name)
"."
(number->string index)))
(string-append (symbol->string name) " " (number->string index))
`(,name)
(lambda () (sensor-query `(,name ,index)))))
; whenever a value needs to be updated, call this
; if the table did not have this value, it is now added
(define (sensor-update name-key value)
; (very-verbose "sensor update: " name-key " " value)
(set! sensor-log-ports
(let each-port ((ports sensor-log-ports))
(cond ((null? ports) '())
(else
(if (call/cc
(lambda (cont)
(with-exception-handler
(lambda _ (cont #f))
(lambda ()
(with-output-to-port (car ports)
(lambda () (print `(,(elapsed-seconds) ,name-key ,value))))
(cont #t)))))
(cons (car ports) (each-port (cdr ports)))
(each-port (cdr ports)))))))
; add computation for raw sensor data
(if (not (hash-table-exists? sensors (sensor-key name-key)))
(make-raw-sensor-computation (sensor-name name-key) (sensor-index name-key)))
; store value locally
(hash-table-set! sensors (sensor-key name-key) value))
(define (sensor-net-client address)
(net-add-client address
'(let ((port (current-output-port))) (sensor-log-to-port port) 'ok)
(lambda (data)
(if (not (eq? data 'ok))
(sensor-update (second data) (third data))))))
; return the number of entrees in the table with this name
(define (sensor-index-count name)
(let index-loop ((index 0))
(if (hash-table-exists? sensors (list name index))
(index-loop (+ index 1))
index)))
; register a new sensor index without updating it yet, return the index
(define (sensor-new-index name)
(let ((index (sensor-index-count name)))
(make-raw-sensor-computation name index)
(hash-table-set! sensors `(,name ,index) #f)
index))
; return a list of valid keys
(define (sensor-query-keys) (hash-table-keys sensors))
;;;; line reader used by various specific sensors
;; handles reading data from input sensors and executing callback functions
(define readers '())
(define (make-reader port proc end?)
(create-periodic-task
(string-append "reader for " (port->string port)) .05
(let ((cur ""))
(lambda ()
(if (char-ready? port)
(let ((c (read-char port)))
(call/cc
(lambda (flushed)
(cond ((end? c (lambda ()
(set! cur "")
(flushed #t)))
(proc cur)
(set! cur ""))
(else (set! cur (string-append cur (string c)))))))))))))
(define (make-line-reader port proc)
(create-periodic-task
(string-append "line reader for " (port->string port)) .02
(lambda ()
(let loop ()
(if (char-ready? port)
(let ((l (read-line port)))
(proc l)
(loop)))))))
(define (sensor-field-get name-key field)
(if (sensor-contains? name-key)
(type-field-get (sensor-name name-key) field
(sensor-query name-key)) #f))
(define (open-serial-device-with-handler device baud handler)
(call/cc (lambda (bail)
(verbose "Trying to open serial device at " device)
(let ((ret (with-exception-handler
(lambda _
(apply bail (handler _)))
(lambda ()
(if (not (eq? baud 'none))
(let ((cmd (string-append "stty -F " device " " (number->string baud))))
(verbose "executing shell command: " cmd)
(system cmd)))
(let ((cmd (string-append "stty -F " device
" ignbrk -icrnl -opost -onlcr -isig"
" -icanon -iexten -echo -echoe -echok"
" -echoctl -echoke min 1 time 5")))
(verbose "executing shell command: " cmd)
(system cmd))
(list (open-input-file device)
(open-output-file device))))))
(verbose "Success opening " device)
(apply values ret)))))
(define (open-serial-device device baud)
(open-serial-device-with-handler
device baud (lambda _
(print "device initialization failed on: " device ": " _)
(exit))))
(define (try-opening-serial-devices devices baud)
(if (null? devices)
(values #f #f)
(let-values (((i o) (open-serial-device-with-handler (car devices) baud
(lambda _ '(#f #f)))))
(if (and i o) (values i o)
(try-opening-serial-devices (cdr devices) baud)))))
(define (generic-serial-sensor-reader arg)
(define options
(create-options
`(,(make-string-verifier 'device "serial device" "/dev/ttyUSB0")
,(make-boolean-verifier 'windvane-control "control windvane with winch servo thru this device" #f)
,(make-baud-verifier 'baudrate "serial baud rate to use" 'none))
"no examples" #f))
(parse-basic-options-string options arg)
(let ((i #f) (o #f)
(possible-sensors '((accel 1333 #f)
(mag 50000 #f)
(windvane 1023 #f))))
(define (config)
(display "set /sensors/accel/outputrate " o)
(display rate o) (newline o)
(display "set /sensors/mag/outputrate " o)
(display rate o) (newline o))
(define (connect-serial-port)
(let-values (((ni no) (try-opening-serial-devices
`(,(options 'device) "/dev/ttyUSB0" "/dev/ttyUSB1"
"/dev/ttyACM0" "/dev/ttyACM1")
(options 'baudrate))))
(if (options 'windvane-control)
(set-windvane-control-port! no))
(set! i ni) (set! o no)))
(connect-serial-port)
(cond ((not (and i o))
(print "failed to initialize generic serial reader at " (options 'device)))
(else
; (config)
(make-line-reader
i
(lambda (line)
(cond ((eof-object? line)
(verbose "serial end of file: we will try to reconnect")
(connect-serial-port)
(cond ((not (and i o))
(for-each
(lambda (sensor)
(let ((sensor-indexes (third sensor)))
(if sensor-indexes
(for-each (lambda (sensor-index)
(sensor-update (list (first sensor)
sensor-index) #f))
sensor-indexes))))
possible-sensors)
(task-sleep 1))))
(else
(let ((words (string-split line)))
(if (> (length words) 1)
(let ((sensor (find (lambda (sensor)
; (print "lambda (sensor) " (car sensor) " " (car words))
(equal? (car sensor)
(string->symbol (remove-last-character (car words)))))
possible-sensors))
(sensor-values (map string->number (cdr words))))
(cond (sensor
(if (not (third sensor))
(set-car! (cddr sensor)
(let sensor-new-indexes ((local-index 0))
(if (< local-index (- (length words) 1))
(cons (sensor-new-index (first sensor))
(sensor-new-indexes (+ local-index 1)))
'()))))
(for-each (lambda (sensor-value sensor-index)
(sensor-update (list (first sensor) sensor-index)
(/ sensor-value (second sensor))))
sensor-values (third sensor)))
(else
(warning-once "unrecognized sensor: " words))))))))))))))
| null | https://raw.githubusercontent.com/seandepagnier/cruisingplot/d3d83e7372e2c5ce1a8e8071286e30c2028088cf/sensor.scm | scheme |
you can redistribute it and/or
modify it under the terms of the GNU General Public
either
This file handles storing values (primarily from sensors)
values can be installed, queried, and callbacks can be installed as well
this should work even across a network
do we have all these sensors?
a key is a list of (name index) or just name
get a list if indicies of of sensors by name
get the proper hash key for a name or key
query a sensor from the table directly, or #f if it is not there
Open a file and automatically update values from it
(print "make-raw-sensor-computation " name " " index)
whenever a value needs to be updated, call this
if the table did not have this value, it is now added
(very-verbose "sensor update: " name-key " " value)
add computation for raw sensor data
store value locally
return the number of entrees in the table with this name
register a new sensor index without updating it yet, return the index
return a list of valid keys
line reader used by various specific sensors
handles reading data from input sensors and executing callback functions
(config)
(print "lambda (sensor) " (car sensor) " " (car words)) | Copyright ( C ) 2010 < >
version 3 of the License , or ( at your option ) any later version .
(declare (unit sensor))
(use srfi-69)
(define sensor-log-ports '())
(define (sensor-log-to-port port)
(set! sensor-log-ports (cons port sensor-log-ports)))
(define (sensor-log-to-file filename)
(sensor-log-to-port (open-output-file filename)))
(define sensors (make-hash-table))
(define (sensor-contains? . name-keys)
(cond ((null? name-keys) #t)
((hash-table-exists? sensors (sensor-key (car name-keys)))
(apply sensor-contains? (cdr name-keys)))
(else #f)))
(define (sensor-name name-key)
(if (list? name-key) (car name-key) name-key))
get the index out of they key , or use default index of 0
(define (sensor-index name-key)
(if (list? name-key) (cadr name-key) 0))
(define (sensor-indicies name)
(let each-value ((values (hash-table->alist sensors)))
(cond ((null? values) '())
((eq? (caar values) name)
(cons (cadar values)
(each-value (cdr values))))
(else
(each-value (cdr values))))))
(define (sensor-key name-key)
(list (sensor-name name-key) (sensor-index name-key)))
(define (sensor-query name-key)
(let ((key (sensor-key name-key)))
(if (hash-table-exists? sensors key)
(hash-table-ref sensors key)
#f)))
(define (sensor-query-indexes name indexes)
(map (lambda (index) (sensor-query (list name index)))
indexes))
(define (sensor-replay-logfile arg)
(let ((options (create-options
(list (make-number-verifier 'rate "rate of replay" 1 .001 1000))
(string-append " Set input log file, and option\n")
#f)))
(let ((filename (parse-basic-arg-options-string options arg)))
(verbose "replaying data from log file '" filename "' at " (options 'rate) "x speed")
(create-task
(string-append "replay task for file: " filename)
(lambda ()
(with-input-from-file filename
(lambda ()
(let ((sensor-key-mapping (make-hash-table)))
(let each-line ()
(let ((line (read-line)))
(if (not (eof-object? line))
(let ((split (read-from-string line)))
(if (> (length split) 2)
(let ((time (car split))
(key (cadr split))
(value (caddr split)))
(task-sleep! (- (/ time (options 'rate)) (elapsed-seconds)))
(if (hash-table-exists? sensor-key-mapping key)
(sensor-update (hash-table-ref sensor-key-mapping key) value)
(let ((new-key `(,(sensor-name key)
,(sensor-new-index (sensor-name key)))))
(verbose "replay sensor from file '" filename "' " key " -> " new-key)
(hash-table-set! sensor-key-mapping key new-key))))))))
(each-line))
(verbose "log file '" filename "' complete")))))))))
(define (make-raw-sensor-computation name index)
(computation-register (string->symbol (string-append (symbol->string name)
"."
(number->string index)))
(string-append (symbol->string name) " " (number->string index))
`(,name)
(lambda () (sensor-query `(,name ,index)))))
(define (sensor-update name-key value)
(set! sensor-log-ports
(let each-port ((ports sensor-log-ports))
(cond ((null? ports) '())
(else
(if (call/cc
(lambda (cont)
(with-exception-handler
(lambda _ (cont #f))
(lambda ()
(with-output-to-port (car ports)
(lambda () (print `(,(elapsed-seconds) ,name-key ,value))))
(cont #t)))))
(cons (car ports) (each-port (cdr ports)))
(each-port (cdr ports)))))))
(if (not (hash-table-exists? sensors (sensor-key name-key)))
(make-raw-sensor-computation (sensor-name name-key) (sensor-index name-key)))
(hash-table-set! sensors (sensor-key name-key) value))
(define (sensor-net-client address)
(net-add-client address
'(let ((port (current-output-port))) (sensor-log-to-port port) 'ok)
(lambda (data)
(if (not (eq? data 'ok))
(sensor-update (second data) (third data))))))
(define (sensor-index-count name)
(let index-loop ((index 0))
(if (hash-table-exists? sensors (list name index))
(index-loop (+ index 1))
index)))
(define (sensor-new-index name)
(let ((index (sensor-index-count name)))
(make-raw-sensor-computation name index)
(hash-table-set! sensors `(,name ,index) #f)
index))
(define (sensor-query-keys) (hash-table-keys sensors))
(define readers '())
(define (make-reader port proc end?)
(create-periodic-task
(string-append "reader for " (port->string port)) .05
(let ((cur ""))
(lambda ()
(if (char-ready? port)
(let ((c (read-char port)))
(call/cc
(lambda (flushed)
(cond ((end? c (lambda ()
(set! cur "")
(flushed #t)))
(proc cur)
(set! cur ""))
(else (set! cur (string-append cur (string c)))))))))))))
(define (make-line-reader port proc)
(create-periodic-task
(string-append "line reader for " (port->string port)) .02
(lambda ()
(let loop ()
(if (char-ready? port)
(let ((l (read-line port)))
(proc l)
(loop)))))))
(define (sensor-field-get name-key field)
(if (sensor-contains? name-key)
(type-field-get (sensor-name name-key) field
(sensor-query name-key)) #f))
(define (open-serial-device-with-handler device baud handler)
(call/cc (lambda (bail)
(verbose "Trying to open serial device at " device)
(let ((ret (with-exception-handler
(lambda _
(apply bail (handler _)))
(lambda ()
(if (not (eq? baud 'none))
(let ((cmd (string-append "stty -F " device " " (number->string baud))))
(verbose "executing shell command: " cmd)
(system cmd)))
(let ((cmd (string-append "stty -F " device
" ignbrk -icrnl -opost -onlcr -isig"
" -icanon -iexten -echo -echoe -echok"
" -echoctl -echoke min 1 time 5")))
(verbose "executing shell command: " cmd)
(system cmd))
(list (open-input-file device)
(open-output-file device))))))
(verbose "Success opening " device)
(apply values ret)))))
(define (open-serial-device device baud)
(open-serial-device-with-handler
device baud (lambda _
(print "device initialization failed on: " device ": " _)
(exit))))
(define (try-opening-serial-devices devices baud)
(if (null? devices)
(values #f #f)
(let-values (((i o) (open-serial-device-with-handler (car devices) baud
(lambda _ '(#f #f)))))
(if (and i o) (values i o)
(try-opening-serial-devices (cdr devices) baud)))))
(define (generic-serial-sensor-reader arg)
(define options
(create-options
`(,(make-string-verifier 'device "serial device" "/dev/ttyUSB0")
,(make-boolean-verifier 'windvane-control "control windvane with winch servo thru this device" #f)
,(make-baud-verifier 'baudrate "serial baud rate to use" 'none))
"no examples" #f))
(parse-basic-options-string options arg)
(let ((i #f) (o #f)
(possible-sensors '((accel 1333 #f)
(mag 50000 #f)
(windvane 1023 #f))))
(define (config)
(display "set /sensors/accel/outputrate " o)
(display rate o) (newline o)
(display "set /sensors/mag/outputrate " o)
(display rate o) (newline o))
(define (connect-serial-port)
(let-values (((ni no) (try-opening-serial-devices
`(,(options 'device) "/dev/ttyUSB0" "/dev/ttyUSB1"
"/dev/ttyACM0" "/dev/ttyACM1")
(options 'baudrate))))
(if (options 'windvane-control)
(set-windvane-control-port! no))
(set! i ni) (set! o no)))
(connect-serial-port)
(cond ((not (and i o))
(print "failed to initialize generic serial reader at " (options 'device)))
(else
(make-line-reader
i
(lambda (line)
(cond ((eof-object? line)
(verbose "serial end of file: we will try to reconnect")
(connect-serial-port)
(cond ((not (and i o))
(for-each
(lambda (sensor)
(let ((sensor-indexes (third sensor)))
(if sensor-indexes
(for-each (lambda (sensor-index)
(sensor-update (list (first sensor)
sensor-index) #f))
sensor-indexes))))
possible-sensors)
(task-sleep 1))))
(else
(let ((words (string-split line)))
(if (> (length words) 1)
(let ((sensor (find (lambda (sensor)
(equal? (car sensor)
(string->symbol (remove-last-character (car words)))))
possible-sensors))
(sensor-values (map string->number (cdr words))))
(cond (sensor
(if (not (third sensor))
(set-car! (cddr sensor)
(let sensor-new-indexes ((local-index 0))
(if (< local-index (- (length words) 1))
(cons (sensor-new-index (first sensor))
(sensor-new-indexes (+ local-index 1)))
'()))))
(for-each (lambda (sensor-value sensor-index)
(sensor-update (list (first sensor) sensor-index)
(/ sensor-value (second sensor))))
sensor-values (third sensor)))
(else
(warning-once "unrecognized sensor: " words))))))))))))))
|
698f45233d190b12e94c8fd44b659a1dbbb2869ec9a95371298bc7cbc45c2041 | alyssa-p-hacker/SchemeBBS | patch-runtime_http-syntax.scm | diff -ur mit-scheme-9.2.orig/src/runtime/http-syntax.scm mit-scheme-9.2/src/runtime/http-syntax.scm
--- mit-scheme-9.2/src/runtime/http-syntax.scm.orig 2014-05-17 11:10:05.000000000 +0200
+++ mit-scheme-9.2/src/runtime/http-syntax.scm 2018-10-20 22:46:44.098379331 +0200
@@ -1310,8 +1310,13 @@
write-entity-tag)
(define-header "Location"
- (direct-parser parse-absolute-uri)
- absolute-uri?
+ (direct-parser
+ (*parser
+ (alt parse-absolute-uri
+ parse-relative-uri)))
+ (lambda (value)
+ (and (uri? value)
+ (not (uri-fragment value))))
write-uri)
#;
(define-header "Proxy-Authenticate"
| null | https://raw.githubusercontent.com/alyssa-p-hacker/SchemeBBS/7a5506e7fad22472e1e94671b4fabfce6432199a/patch-runtime_http-syntax.scm | scheme | diff -ur mit-scheme-9.2.orig/src/runtime/http-syntax.scm mit-scheme-9.2/src/runtime/http-syntax.scm
--- mit-scheme-9.2/src/runtime/http-syntax.scm.orig 2014-05-17 11:10:05.000000000 +0200
+++ mit-scheme-9.2/src/runtime/http-syntax.scm 2018-10-20 22:46:44.098379331 +0200
@@ -1310,8 +1310,13 @@
write-entity-tag)
(define-header "Location"
- (direct-parser parse-absolute-uri)
- absolute-uri?
+ (direct-parser
+ (*parser
+ (alt parse-absolute-uri
+ parse-relative-uri)))
+ (lambda (value)
+ (and (uri? value)
+ (not (uri-fragment value))))
write-uri)
(define-header "Proxy-Authenticate"
| |
d3f5197128edc0d81e4c1102c502041fe43f33ab8e3ba050760b80574c8e9d3c | input-output-hk/marlowe-cardano | MList.hs | -----------------------------------------------------------------------------
--
-- Module : $Headers
License : Apache 2.0
--
-- Stability : Experimental
Portability : Portable
--
| Compare the ` PlutusTx . AssocMap ` to 's ` MList ` .
--
-----------------------------------------------------------------------------
module Spec.Marlowe.Plutus.MList
( -- * Testing
tests
) where
import Data.Function (on)
import Data.List (nubBy, sortBy)
import Data.Maybe (fromMaybe, isJust)
import Prelude hiding (lookup)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (Assertion, assertBool, testCase)
import Test.Tasty.QuickCheck (Arbitrary(..), Gen, Property, elements, forAll, property, testProperty)
import qualified PlutusTx.AssocMap as AM
(Map, delete, empty, fromList, insert, lookup, member, null, singleton, toList, unionWith)
import qualified PlutusTx.Eq as P (Eq)
| An association list in Isabelle .
type MList a b = [(a, b)]
| Empty Isabelle ` MList ` .
--
-- @
definition empty : : " ( ' a::linorder \<times > ' b ) list " where
-- "empty = Nil"
-- @
empty :: MList a b
empty = []
# ANN insert " HLint : ignore Use guards " #
# ANN insert " HLint : ignore Use list literal " #
| Insert into Isabelle ` MList ` .
--
-- @
fun insert : : " ' a::linorder \<Rightarrow > ' b \<Rightarrow > ( ' a \<times > ' b ) list \<Rightarrow > ( ' a \<times > ' b ) list " where
-- "insert a b Nil = Cons (a, b) Nil" |
-- "insert a b (Cons (x, y) z) =
-- (if a < x
-- then (Cons (a, b) (Cons (x, y) z))
-- else (if a > x
-- then (Cons (x, y) (insert a b z))
-- else (Cons (x, b) z)))"
-- @
insert :: Ord a => a -> b -> MList a b -> MList a b
insert a b [] = (a, b) : []
insert a b ((x, y) : z) =
if a < x
then (a, b) : (x, y) : z
else if a > x
then (x, y) : insert a b z
else (x, b) : z
# ANN delete " HLint : ignore Use guards " #
| Delete from Isabelle ` MList ` .
--
-- @
-- fun delete :: "'a::linorder \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a \<times> 'b) list" where
" delete |
-- "delete a (Cons (x, y) z) =
-- (if a = x
-- then z
-- else (if a > x
-- then (Cons (x, y) (delete a z))
-- else (Cons (x, y) z)))"
-- @
delete :: Ord a => a -> MList a b -> MList a b
delete _a [] = []
delete a ((x, y) : z) =
if a == x
then z
else if a > x
then (x, y) : delete a z
else (x, y) : z
{-# ANN lookup "HLint: ignore Use guards" #-}
| Lookup in Isabelle ` MList ` .
--
-- @
-- fun lookup :: "'a::linorder \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> 'b option" where
-- "lookup a Nil = None" |
-- "lookup a (Cons (x, y) z) =
-- (if a = x
-- then Some y
-- else (if a > x
-- then lookup a z
-- else None))"
-- @
lookup :: Ord a => a -> MList a b -> Maybe b
lookup _a [] = Nothing
lookup a ((x, y) : z) =
if a == x
then Just y
else if a > x
then lookup a z
else Nothing
{-# ANN unionWith "HLint: ignore Use guards" #-}
| Union with Isabelle ` MList ` .
--
-- @
fun unionWith : : " ( ' b \<Rightarrow > ' b \<Rightarrow > ' b ) \<Rightarrow > ( ' a \<times > ' b ) list \<Rightarrow >
-- ('a \<times> 'b) list \<Rightarrow> (('a::linorder) \<times> 'b) list" where
-- "unionWith f (Cons (x, y) t) (Cons (x2, y2) t2) =
-- (if x < x2
-- then Cons (x, y) (unionWith f t (Cons (x2, y2) t2))
-- else (if x > x2
-- then Cons (x2, y2) (unionWith f (Cons (x, y) t) t2)
-- else Cons (x, f y y2) (unionWith f t t2)))" |
-- "unionWith f Nil l = l" |
-- "unionWith f l Nil = l"
-- @
unionWith :: Ord a => (b -> b -> b) -> MList a b -> MList a b -> MList a b
unionWith f ((x, y) : t) ((x2, y2) : t2) =
if x < x2
then (x, y) : unionWith f t ((x2, y2) : t2)
else if x > x2
then (x2, y2) : unionWith f ((x, y) : t) t2
else (x, f y y2) : unionWith f t t2
unionWith _f [] l = l
unionWith _f l [] = l
| Find with default for Isabelle ` MList ` .
--
-- @
-- fun findWithDefault :: "'b \<Rightarrow> 'a \<Rightarrow> (('a::linorder) \<times> 'b) list \<Rightarrow> 'b" where
-- "findWithDefault d k l = (case lookup k l of
-- None \<Rightarrow> d
-- | Some x \<Rightarrow> x)"
-- @
findWithDefault :: Ord a => b -> a -> MList a b -> b
findWithDefault d k l =
case lookup k l of
Nothing -> d
Just x -> x
-- | Run tests.
tests :: TestTree
tests =
testGroup "MList vs AssocMap"
[
testCase "`empty` is equivalent" checkEmpty
, testProperty "`null` is equivalent" checkNull
, testProperty "`singleton` is equivalent" checkSingleton
, testProperty "`insert` is equivalent" checkInsert
, testProperty "`delete` is equivalent" checkDelete
, testProperty "`lookup` is equivalent" checkLookup
, testProperty "`member` is equivalent" checkMember
, testProperty "`unionWith` is equivalent" checkUnionWith
, testProperty "`findWithDefault` is equivalent" checkFindWithDefault
]
-- | Key type for testing.
type Key = Integer
-- | Value type for testing.
type Value = [()]
| Generate a sorted ` MList ` with no duplicate keys .
arbitraryMList :: Gen (MList Key Value, AM.Map Key Value)
arbitraryMList =
do
items <- nubBy ((==) `on` fst) <$> arbitrary
pure (sortBy (compare `on` fst) items, AM.fromList items)
| Compare an ` MList ` to an ` AssocMap ` , ignoring ordering .
equivalent :: Ord a => P.Eq a => Eq b => MList a b -> AM.Map a b -> Bool
equivalent mlist assocmap =
mlist == sortBy (compare `on` fst) (AM.toList assocmap)
&& and [AM.lookup a assocmap == Just b | (a, b) <- mlist]
&& and [lookup a mlist == Just b | (a, b) <- AM.toList assocmap]
| Compare ` empty ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkEmpty :: Assertion
checkEmpty = assertBool "Empty MList and AssocMap" $ (empty :: MList Key Value) `equivalent` AM.empty
| Compare ` null ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkNull :: Property
checkNull = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
pure (mlist, assocmap)
forAll gen
$ \(mlist, assocmap) -> (== empty) mlist == AM.null assocmap
| Compare ` singleton ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkSingleton :: Property
checkSingleton = property $ do
let
gen = do
a <- arbitrary :: Gen Key
b <- arbitrary :: Gen Value
pure (a, b)
forAll gen
$ \(a, b) -> [(a, b)] `equivalent` AM.singleton a b
| Compare ` insert ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkInsert :: Property
checkInsert = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
a <- arbitrary
b <- arbitrary
pure (mlist, assocmap, a, b)
forAll gen
$ \(mlist, assocmap, a, b) -> insert a b mlist `equivalent` AM.insert a b assocmap
| Compare ` delete ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkDelete :: Property
checkDelete = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
a <- arbitrary
pure (mlist, assocmap, a)
forAll gen
$ \(mlist, assocmap, a) -> delete a mlist `equivalent` AM.delete a assocmap
| Compare ` lookup ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkLookup :: Property
checkLookup = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
a <- arbitrary
pure (mlist, assocmap, a)
forAll gen
$ \(mlist, assocmap, a) -> lookup a mlist == AM.lookup a assocmap
| Compare ` member ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkMember :: Property
checkMember = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
a <- arbitrary
pure (mlist, assocmap, a)
forAll gen
$ \(mlist, assocmap, a) -> isJust (lookup a mlist) == AM.member a assocmap
| Compare ` unionWith ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkUnionWith :: Property
checkUnionWith = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
(mlist', assocmap') <- arbitraryMList
function <- elements ["concat", "shortest", "longest", "first", "second"]
pure (mlist, assocmap, mlist', assocmap', function)
forAll gen
$ \(mlist, assocmap, mlist', assocmap', function) ->
let
f = case function of
"shortest" -> \x y -> if length x < length y then x else y
"longest" -> \x y -> if length x > length y then x else y
"first" -> const
"second" -> const id
_ -> (<>)
in
unionWith f mlist mlist' `equivalent` AM.unionWith f assocmap assocmap'
| Compare ` findWithDefault ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkFindWithDefault :: Property
checkFindWithDefault = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
a <- arbitrary
b <- arbitrary
pure (mlist, assocmap, a, b)
forAll gen
$ \(mlist, assocmap, a, b) -> findWithDefault b a mlist == fromMaybe b (AM.lookup a assocmap)
| null | https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/16a56284a9d53c71d4673abdb70fb5d97f1bbd69/marlowe-test/src/Spec/Marlowe/Plutus/MList.hs | haskell | ---------------------------------------------------------------------------
Module : $Headers
Stability : Experimental
---------------------------------------------------------------------------
* Testing
@
"empty = Nil"
@
@
"insert a b Nil = Cons (a, b) Nil" |
"insert a b (Cons (x, y) z) =
(if a < x
then (Cons (a, b) (Cons (x, y) z))
else (if a > x
then (Cons (x, y) (insert a b z))
else (Cons (x, b) z)))"
@
@
fun delete :: "'a::linorder \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a \<times> 'b) list" where
"delete a (Cons (x, y) z) =
(if a = x
then z
else (if a > x
then (Cons (x, y) (delete a z))
else (Cons (x, y) z)))"
@
# ANN lookup "HLint: ignore Use guards" #
@
fun lookup :: "'a::linorder \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> 'b option" where
"lookup a Nil = None" |
"lookup a (Cons (x, y) z) =
(if a = x
then Some y
else (if a > x
then lookup a z
else None))"
@
# ANN unionWith "HLint: ignore Use guards" #
@
('a \<times> 'b) list \<Rightarrow> (('a::linorder) \<times> 'b) list" where
"unionWith f (Cons (x, y) t) (Cons (x2, y2) t2) =
(if x < x2
then Cons (x, y) (unionWith f t (Cons (x2, y2) t2))
else (if x > x2
then Cons (x2, y2) (unionWith f (Cons (x, y) t) t2)
else Cons (x, f y y2) (unionWith f t t2)))" |
"unionWith f Nil l = l" |
"unionWith f l Nil = l"
@
@
fun findWithDefault :: "'b \<Rightarrow> 'a \<Rightarrow> (('a::linorder) \<times> 'b) list \<Rightarrow> 'b" where
"findWithDefault d k l = (case lookup k l of
None \<Rightarrow> d
| Some x \<Rightarrow> x)"
@
| Run tests.
| Key type for testing.
| Value type for testing. | License : Apache 2.0
Portability : Portable
| Compare the ` PlutusTx . AssocMap ` to 's ` MList ` .
module Spec.Marlowe.Plutus.MList
tests
) where
import Data.Function (on)
import Data.List (nubBy, sortBy)
import Data.Maybe (fromMaybe, isJust)
import Prelude hiding (lookup)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (Assertion, assertBool, testCase)
import Test.Tasty.QuickCheck (Arbitrary(..), Gen, Property, elements, forAll, property, testProperty)
import qualified PlutusTx.AssocMap as AM
(Map, delete, empty, fromList, insert, lookup, member, null, singleton, toList, unionWith)
import qualified PlutusTx.Eq as P (Eq)
| An association list in Isabelle .
type MList a b = [(a, b)]
| Empty Isabelle ` MList ` .
definition empty : : " ( ' a::linorder \<times > ' b ) list " where
empty :: MList a b
empty = []
# ANN insert " HLint : ignore Use guards " #
# ANN insert " HLint : ignore Use list literal " #
| Insert into Isabelle ` MList ` .
fun insert : : " ' a::linorder \<Rightarrow > ' b \<Rightarrow > ( ' a \<times > ' b ) list \<Rightarrow > ( ' a \<times > ' b ) list " where
insert :: Ord a => a -> b -> MList a b -> MList a b
insert a b [] = (a, b) : []
insert a b ((x, y) : z) =
if a < x
then (a, b) : (x, y) : z
else if a > x
then (x, y) : insert a b z
else (x, b) : z
# ANN delete " HLint : ignore Use guards " #
| Delete from Isabelle ` MList ` .
" delete |
delete :: Ord a => a -> MList a b -> MList a b
delete _a [] = []
delete a ((x, y) : z) =
if a == x
then z
else if a > x
then (x, y) : delete a z
else (x, y) : z
| Lookup in Isabelle ` MList ` .
lookup :: Ord a => a -> MList a b -> Maybe b
lookup _a [] = Nothing
lookup a ((x, y) : z) =
if a == x
then Just y
else if a > x
then lookup a z
else Nothing
| Union with Isabelle ` MList ` .
fun unionWith : : " ( ' b \<Rightarrow > ' b \<Rightarrow > ' b ) \<Rightarrow > ( ' a \<times > ' b ) list \<Rightarrow >
unionWith :: Ord a => (b -> b -> b) -> MList a b -> MList a b -> MList a b
unionWith f ((x, y) : t) ((x2, y2) : t2) =
if x < x2
then (x, y) : unionWith f t ((x2, y2) : t2)
else if x > x2
then (x2, y2) : unionWith f ((x, y) : t) t2
else (x, f y y2) : unionWith f t t2
unionWith _f [] l = l
unionWith _f l [] = l
| Find with default for Isabelle ` MList ` .
findWithDefault :: Ord a => b -> a -> MList a b -> b
findWithDefault d k l =
case lookup k l of
Nothing -> d
Just x -> x
tests :: TestTree
tests =
testGroup "MList vs AssocMap"
[
testCase "`empty` is equivalent" checkEmpty
, testProperty "`null` is equivalent" checkNull
, testProperty "`singleton` is equivalent" checkSingleton
, testProperty "`insert` is equivalent" checkInsert
, testProperty "`delete` is equivalent" checkDelete
, testProperty "`lookup` is equivalent" checkLookup
, testProperty "`member` is equivalent" checkMember
, testProperty "`unionWith` is equivalent" checkUnionWith
, testProperty "`findWithDefault` is equivalent" checkFindWithDefault
]
type Key = Integer
type Value = [()]
| Generate a sorted ` MList ` with no duplicate keys .
arbitraryMList :: Gen (MList Key Value, AM.Map Key Value)
arbitraryMList =
do
items <- nubBy ((==) `on` fst) <$> arbitrary
pure (sortBy (compare `on` fst) items, AM.fromList items)
| Compare an ` MList ` to an ` AssocMap ` , ignoring ordering .
equivalent :: Ord a => P.Eq a => Eq b => MList a b -> AM.Map a b -> Bool
equivalent mlist assocmap =
mlist == sortBy (compare `on` fst) (AM.toList assocmap)
&& and [AM.lookup a assocmap == Just b | (a, b) <- mlist]
&& and [lookup a mlist == Just b | (a, b) <- AM.toList assocmap]
| Compare ` empty ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkEmpty :: Assertion
checkEmpty = assertBool "Empty MList and AssocMap" $ (empty :: MList Key Value) `equivalent` AM.empty
| Compare ` null ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkNull :: Property
checkNull = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
pure (mlist, assocmap)
forAll gen
$ \(mlist, assocmap) -> (== empty) mlist == AM.null assocmap
| Compare ` singleton ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkSingleton :: Property
checkSingleton = property $ do
let
gen = do
a <- arbitrary :: Gen Key
b <- arbitrary :: Gen Value
pure (a, b)
forAll gen
$ \(a, b) -> [(a, b)] `equivalent` AM.singleton a b
| Compare ` insert ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkInsert :: Property
checkInsert = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
a <- arbitrary
b <- arbitrary
pure (mlist, assocmap, a, b)
forAll gen
$ \(mlist, assocmap, a, b) -> insert a b mlist `equivalent` AM.insert a b assocmap
| Compare ` delete ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkDelete :: Property
checkDelete = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
a <- arbitrary
pure (mlist, assocmap, a)
forAll gen
$ \(mlist, assocmap, a) -> delete a mlist `equivalent` AM.delete a assocmap
| Compare ` lookup ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkLookup :: Property
checkLookup = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
a <- arbitrary
pure (mlist, assocmap, a)
forAll gen
$ \(mlist, assocmap, a) -> lookup a mlist == AM.lookup a assocmap
| Compare ` member ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkMember :: Property
checkMember = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
a <- arbitrary
pure (mlist, assocmap, a)
forAll gen
$ \(mlist, assocmap, a) -> isJust (lookup a mlist) == AM.member a assocmap
| Compare ` unionWith ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkUnionWith :: Property
checkUnionWith = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
(mlist', assocmap') <- arbitraryMList
function <- elements ["concat", "shortest", "longest", "first", "second"]
pure (mlist, assocmap, mlist', assocmap', function)
forAll gen
$ \(mlist, assocmap, mlist', assocmap', function) ->
let
f = case function of
"shortest" -> \x y -> if length x < length y then x else y
"longest" -> \x y -> if length x > length y then x else y
"first" -> const
"second" -> const id
_ -> (<>)
in
unionWith f mlist mlist' `equivalent` AM.unionWith f assocmap assocmap'
| Compare ` findWithDefault ` for ` MList ` and ` AssocMap ` , provided the ` MList ` is sorted and neither contains duplicate keys .
checkFindWithDefault :: Property
checkFindWithDefault = property $ do
let
gen = do
(mlist, assocmap) <- arbitraryMList
a <- arbitrary
b <- arbitrary
pure (mlist, assocmap, a, b)
forAll gen
$ \(mlist, assocmap, a, b) -> findWithDefault b a mlist == fromMaybe b (AM.lookup a assocmap)
|
32e95e9a18e2987f54e2f5ef9176ba230cfef217f453452d0caddd274d990534 | sharplispers/linedit | command-functions.lisp | Copyright ( c ) 2003 , 2004 , 2012 Nikodemus Siivola ,
;;;;
;;;; Permission is hereby granted, free of charge, to any person obtaining
;;;; a copy of this software and associated documentation files (the
" Software " ) , to deal in the Software without restriction , including
;;;; without limitation the rights to use, copy, modify, merge, publish,
distribute , sublicense , and/or sell copies of the Software , and to
permit persons to whom the Software is furnished to do so , subject to
;;;; the following conditions:
;;;;
;;;; The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software .
;;;;
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT .
;;;; IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT ,
;;;; TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
;;;; SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(in-package :linedit)
;;; These functions are meant to be call throught the command table
;;; of an editor. These functions should not explicitly call refresh, etc:
;;; that is the responsibility of the editor -- but beeping is ok.
;;;
;;; The arguments passed are: CHORD EDITOR
;;; BASIC EDITING
(defun add-char (char editor)
(with-editor-point-and-string ((point string) editor)
(setf (get-string editor)
(concat (subseq string 0 point)
(string char)
(if (editor-insert-mode editor)
(subseq string point)
(when (> (length string) (1+ point))
(subseq string (1+ point))))))
(incf (get-point editor))))
(defun delete-char-backwards (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
Ca n't delegate to editor because of the SUBSEQ index calc .
(unless (zerop point)
(setf (get-string editor) (concat (subseq string 0 (1- point))
(subseq string point))
(get-point editor) (1- point)))))
(defun delete-char-forwards (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(setf (get-string editor) (concat (subseq string 0 point)
(subseq string (min (1+ point) (length string)))))))
(defun delete-char-forwards-or-eof (chord editor)
(if (equal "" (get-string editor))
(error 'end-of-file :stream *standard-input*)
(delete-char-forwards chord editor)))
(defun delete-word-forwards (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(let ((i (get-point editor))
(j (editor-next-word-end editor)))
(setf (get-string editor)
(concat (subseq string 0 i) (subseq string j))))))
(defun delete-word-backwards (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(let ((i (editor-previous-word-start editor)))
(setf (get-string editor) (concat (subseq string 0 i)
(subseq string point))
(get-point editor) i))))
(defun finish-input (chord editor)
(declare (ignore chord editor))
(throw 'linedit-done t))
;;; CASE CHANGES
(flet ((frob-case (frob editor)
(with-editor-point-and-string ((point string) editor)
(let ((end (editor-next-word-end editor)))
(setf (get-string editor) (concat
(subseq string 0 point)
(funcall frob
(subseq string point end))
(subseq string end))
(get-point editor) end)))))
(defun upcase-word (chord editor)
(declare (ignore chord))
(funcall #'frob-case #'string-upcase editor))
(defun downcase-word (chord editor)
(declare (ignore chord))
(funcall #'frob-case #'string-downcase editor)))
;;; MOVEMENT
(defun move-to-bol (chord editor)
(declare (ignore chord))
(setf (get-point editor) 0))
(defun move-to-eol (chord editor)
(declare (ignore chord))
(setf (get-point editor) (length (get-string editor))))
(defun move-char-right (chord editor)
(declare (ignore chord))
(incf (get-point editor)))
(defun move-char-left (chord editor)
(declare (ignore chord))
(decf (get-point editor)))
(defun move-word-backwards (chord editor)
(declare (ignore chord))
(setf (get-point editor) (editor-previous-word-start editor)))
(defun move-word-forwards (chord editor)
(declare (ignore chord))
(setf (get-point editor) (editor-next-word-end editor)))
;;; UNDO
(defun undo (chord editor)
(declare (ignore chord))
(rewind-state editor)
(throw 'linedit-loop t))
;;; HISTORY
(defun history-previous (chord editor)
(declare (ignore chord))
(aif (buffer-previous (get-string editor) (editor-history editor))
(setf (get-string editor) it)
(beep editor)))
(defun history-next (chord editor)
(declare (ignore chord))
(aif (buffer-next (get-string editor) (editor-history editor))
(setf (get-string editor) it)
(beep editor)))
(defvar *history-search* nil)
(defvar *history-needle* nil)
(defun history-search-needle (editor &key direction)
(let ((text (if *history-search*
(cond ((and *history-needle*
(member *last-command* '(search-history-backwards
search-history-forwards)))
*history-needle*)
(t
(setf *history-needle* (get-string editor))))
(let* ((*history-search* t)
(*aux-prompt* nil))
(linedit :prompt "Search History: ")))))
(when *history-search*
(setf *aux-prompt* (concat "[" text "] ")))
text))
(defun history-search (editor direction)
(let* ((text (history-search-needle editor))
(history (editor-history editor))
(test (lambda (old) (search text old)))
(match (unless (equal "" text)
(ecase direction
(:backwards
(buffer-find-previous-if test history))
(:forwards
(buffer-find-next-if test history))))))
(unless match
(beep editor)
(setf match text))
(setf (get-string editor) match
(get-point editor) (length match))))
(defun search-history-backwards (chord editor)
(declare (ignore chord))
(history-search editor :backwards))
(defun search-history-forwards (chord editor)
(declare (ignore chord))
(history-search editor :forwards))
;;; KILLING & YANKING
(defun %yank (editor)
(aif (buffer-peek (editor-killring editor))
(with-editor-point-and-string ((point string) editor)
(setf (get-string editor)
(concat (subseq string 0 (editor-yank editor))
it
(subseq string point))
(get-point editor) (+ (editor-yank editor) (length it))))
(beep editor)))
(defun yank (chord editor)
(declare (ignore chord))
(remember-yank editor)
(%yank editor))
(defun yank-cycle (chord editor)
(declare (ignore chord))
(if (try-yank editor)
(progn
(buffer-cycle (editor-killring editor))
(%yank editor))
(beep editor)))
(defun kill-to-eol (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(buffer-push (subseq string point) (editor-killring editor))
(setf (get-string editor) (subseq string 0 point))))
(defun kill-to-bol (chord editor)
Thanks to
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(buffer-push (subseq string 0 point) (editor-killring editor))
(setf (get-string editor) (subseq string point)
(get-point editor) 0)))
(defun copy-region (chord editor)
(declare (ignore chord))
(awhen (editor-mark editor)
(with-editor-point-and-string ((point string) editor)
(let ((start (min it point))
(end (max it point)))
(buffer-push (subseq string start end) (editor-killring editor))
(setf (editor-mark editor) nil)))))
(defun cut-region (chord editor)
(declare (ignore chord))
(awhen (editor-mark editor)
(with-editor-point-and-string ((point string) editor)
(let ((start (min it point))
(end (max it point)))
(copy-region t editor)
(setf (get-string editor) (concat (subseq string 0 start)
(subseq string end))
(get-point editor) start)))))
(defun set-mark (chord editor)
(declare (ignore chord))
FIXME : this was ( setf mark ( unless mark point ) ) -- modulo correct
;; accessors. Why? Was I not thinking, or am I not thinking now?
(setf (editor-mark editor) (get-point editor)))
SEXP MOTION
(defun forward-sexp (chord editor)
(declare (ignore chord))
(setf (get-point editor) (editor-sexp-end editor)))
(defun backward-sexp (chord editor)
(declare (ignore chord))
(setf (get-point editor) (editor-sexp-start editor)))
FIXME : KILL - SEXP is fairly broken , but works for enough of my
;; common use cases. Most of its flaws lie in how the EDITOR-SEXP-
;; functions deal with objects other than lists and strings.
(defun kill-sexp (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(let ((start (editor-sexp-start editor))
(end (min (1+ (editor-sexp-end editor)) (length string))))
(buffer-push (subseq string start end) (editor-killring editor))
(setf (get-string editor) (concat (subseq string 0 start)
(subseq string end))
(get-point editor) start))))
(defun close-all-sexp (chord editor)
(move-to-eol chord editor)
(do ((string (get-string editor) (get-string editor)))
((not (find-open-paren string (length string))))
(add-char (case (schar string (find-open-paren string (length string)))
(#\( #\))
(#\[ #\])
(#\{ #\}))
editor)))
;;; SIGNALS
(defun interrupt-lisp (chord editor)
(declare (ignore chord))
(editor-interrupt editor))
(defun stop-lisp (chord editor)
(declare (ignore chord))
(editor-stop editor))
MISCELLANY
(defun help (chord editor)
(declare (ignore chord))
(let ((pairs nil)
(max-id 0)
(max-f 0))
(maphash (lambda (id function)
(let ((f (string-downcase (symbol-name function))))
(push (list id f) pairs)
(setf max-id (max max-id (length id))
max-f (max max-f (length f)))))
(editor-commands editor))
(print-in-columns editor
(mapcar (lambda (pair)
(destructuring-bind (id f) pair
(with-output-to-string (s)
(write-string id s)
(loop repeat (- (1+ max-id) (length id))
do (write-char #\Space s))
(write-string f s))))
(nreverse pairs))
:width (+ max-id max-f 2))))
(defun unknown-command (chord editor)
(newline editor)
(format *standard-output* "Unknown command ~S." chord)
(newline editor))
(defun complete (chord editor)
(declare (ignore chord))
(multiple-value-bind (completions max-len) (editor-complete editor)
(if completions
(if (not (cdr completions))
(editor-replace-word editor (car completions))
(print-in-columns editor completions :width (+ max-len 2)))
(beep editor))))
(defun apropos-word (chord editor)
(declare (ignore chord))
(let* ((word (editor-word editor))
(apropi (apropos-list word)))
(if (null apropi)
(beep editor)
(let* ((longest 0)
(strings (mapcar (lambda (symbol)
(declare (symbol symbol))
(let ((str (prin1-to-string symbol)))
(setf longest (max longest (length str)))
(string-downcase str)))
apropi)))
(print-in-columns editor strings :width (+ longest 2))))))
(defun describe-word (chord editor)
(declare (ignore chord))
(print-in-lines editor
(with-output-to-string (s)
(describe (read-from-string (editor-word editor)) s))))
(defun toggle-insert (chord editor)
(declare (ignore chord))
(setf (editor-insert-mode editor) (not (editor-insert-mode editor))))
| null | https://raw.githubusercontent.com/sharplispers/linedit/0561c97dfca2f5854fcc66558a567a9875ddcb8f/command-functions.lisp | lisp |
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
without limitation the rights to use, copy, modify, merge, publish,
the following conditions:
The above copyright notice and this permission notice shall be included
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
These functions are meant to be call throught the command table
of an editor. These functions should not explicitly call refresh, etc:
that is the responsibility of the editor -- but beeping is ok.
The arguments passed are: CHORD EDITOR
BASIC EDITING
CASE CHANGES
MOVEMENT
UNDO
HISTORY
KILLING & YANKING
accessors. Why? Was I not thinking, or am I not thinking now?
common use cases. Most of its flaws lie in how the EDITOR-SEXP-
functions deal with objects other than lists and strings.
SIGNALS | Copyright ( c ) 2003 , 2004 , 2012 Nikodemus Siivola ,
" Software " ) , to deal in the Software without restriction , including
distribute , sublicense , and/or sell copies of the Software , and to
permit persons to whom the Software is furnished to do so , subject to
in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT .
CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT ,
(in-package :linedit)
(defun add-char (char editor)
(with-editor-point-and-string ((point string) editor)
(setf (get-string editor)
(concat (subseq string 0 point)
(string char)
(if (editor-insert-mode editor)
(subseq string point)
(when (> (length string) (1+ point))
(subseq string (1+ point))))))
(incf (get-point editor))))
(defun delete-char-backwards (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
Ca n't delegate to editor because of the SUBSEQ index calc .
(unless (zerop point)
(setf (get-string editor) (concat (subseq string 0 (1- point))
(subseq string point))
(get-point editor) (1- point)))))
(defun delete-char-forwards (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(setf (get-string editor) (concat (subseq string 0 point)
(subseq string (min (1+ point) (length string)))))))
(defun delete-char-forwards-or-eof (chord editor)
(if (equal "" (get-string editor))
(error 'end-of-file :stream *standard-input*)
(delete-char-forwards chord editor)))
(defun delete-word-forwards (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(let ((i (get-point editor))
(j (editor-next-word-end editor)))
(setf (get-string editor)
(concat (subseq string 0 i) (subseq string j))))))
(defun delete-word-backwards (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(let ((i (editor-previous-word-start editor)))
(setf (get-string editor) (concat (subseq string 0 i)
(subseq string point))
(get-point editor) i))))
(defun finish-input (chord editor)
(declare (ignore chord editor))
(throw 'linedit-done t))
(flet ((frob-case (frob editor)
(with-editor-point-and-string ((point string) editor)
(let ((end (editor-next-word-end editor)))
(setf (get-string editor) (concat
(subseq string 0 point)
(funcall frob
(subseq string point end))
(subseq string end))
(get-point editor) end)))))
(defun upcase-word (chord editor)
(declare (ignore chord))
(funcall #'frob-case #'string-upcase editor))
(defun downcase-word (chord editor)
(declare (ignore chord))
(funcall #'frob-case #'string-downcase editor)))
(defun move-to-bol (chord editor)
(declare (ignore chord))
(setf (get-point editor) 0))
(defun move-to-eol (chord editor)
(declare (ignore chord))
(setf (get-point editor) (length (get-string editor))))
(defun move-char-right (chord editor)
(declare (ignore chord))
(incf (get-point editor)))
(defun move-char-left (chord editor)
(declare (ignore chord))
(decf (get-point editor)))
(defun move-word-backwards (chord editor)
(declare (ignore chord))
(setf (get-point editor) (editor-previous-word-start editor)))
(defun move-word-forwards (chord editor)
(declare (ignore chord))
(setf (get-point editor) (editor-next-word-end editor)))
(defun undo (chord editor)
(declare (ignore chord))
(rewind-state editor)
(throw 'linedit-loop t))
(defun history-previous (chord editor)
(declare (ignore chord))
(aif (buffer-previous (get-string editor) (editor-history editor))
(setf (get-string editor) it)
(beep editor)))
(defun history-next (chord editor)
(declare (ignore chord))
(aif (buffer-next (get-string editor) (editor-history editor))
(setf (get-string editor) it)
(beep editor)))
(defvar *history-search* nil)
(defvar *history-needle* nil)
(defun history-search-needle (editor &key direction)
(let ((text (if *history-search*
(cond ((and *history-needle*
(member *last-command* '(search-history-backwards
search-history-forwards)))
*history-needle*)
(t
(setf *history-needle* (get-string editor))))
(let* ((*history-search* t)
(*aux-prompt* nil))
(linedit :prompt "Search History: ")))))
(when *history-search*
(setf *aux-prompt* (concat "[" text "] ")))
text))
(defun history-search (editor direction)
(let* ((text (history-search-needle editor))
(history (editor-history editor))
(test (lambda (old) (search text old)))
(match (unless (equal "" text)
(ecase direction
(:backwards
(buffer-find-previous-if test history))
(:forwards
(buffer-find-next-if test history))))))
(unless match
(beep editor)
(setf match text))
(setf (get-string editor) match
(get-point editor) (length match))))
(defun search-history-backwards (chord editor)
(declare (ignore chord))
(history-search editor :backwards))
(defun search-history-forwards (chord editor)
(declare (ignore chord))
(history-search editor :forwards))
(defun %yank (editor)
(aif (buffer-peek (editor-killring editor))
(with-editor-point-and-string ((point string) editor)
(setf (get-string editor)
(concat (subseq string 0 (editor-yank editor))
it
(subseq string point))
(get-point editor) (+ (editor-yank editor) (length it))))
(beep editor)))
(defun yank (chord editor)
(declare (ignore chord))
(remember-yank editor)
(%yank editor))
(defun yank-cycle (chord editor)
(declare (ignore chord))
(if (try-yank editor)
(progn
(buffer-cycle (editor-killring editor))
(%yank editor))
(beep editor)))
(defun kill-to-eol (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(buffer-push (subseq string point) (editor-killring editor))
(setf (get-string editor) (subseq string 0 point))))
(defun kill-to-bol (chord editor)
Thanks to
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(buffer-push (subseq string 0 point) (editor-killring editor))
(setf (get-string editor) (subseq string point)
(get-point editor) 0)))
(defun copy-region (chord editor)
(declare (ignore chord))
(awhen (editor-mark editor)
(with-editor-point-and-string ((point string) editor)
(let ((start (min it point))
(end (max it point)))
(buffer-push (subseq string start end) (editor-killring editor))
(setf (editor-mark editor) nil)))))
(defun cut-region (chord editor)
(declare (ignore chord))
(awhen (editor-mark editor)
(with-editor-point-and-string ((point string) editor)
(let ((start (min it point))
(end (max it point)))
(copy-region t editor)
(setf (get-string editor) (concat (subseq string 0 start)
(subseq string end))
(get-point editor) start)))))
(defun set-mark (chord editor)
(declare (ignore chord))
FIXME : this was ( setf mark ( unless mark point ) ) -- modulo correct
(setf (editor-mark editor) (get-point editor)))
SEXP MOTION
(defun forward-sexp (chord editor)
(declare (ignore chord))
(setf (get-point editor) (editor-sexp-end editor)))
(defun backward-sexp (chord editor)
(declare (ignore chord))
(setf (get-point editor) (editor-sexp-start editor)))
FIXME : KILL - SEXP is fairly broken , but works for enough of my
(defun kill-sexp (chord editor)
(declare (ignore chord))
(with-editor-point-and-string ((point string) editor)
(let ((start (editor-sexp-start editor))
(end (min (1+ (editor-sexp-end editor)) (length string))))
(buffer-push (subseq string start end) (editor-killring editor))
(setf (get-string editor) (concat (subseq string 0 start)
(subseq string end))
(get-point editor) start))))
(defun close-all-sexp (chord editor)
(move-to-eol chord editor)
(do ((string (get-string editor) (get-string editor)))
((not (find-open-paren string (length string))))
(add-char (case (schar string (find-open-paren string (length string)))
(#\( #\))
(#\[ #\])
(#\{ #\}))
editor)))
(defun interrupt-lisp (chord editor)
(declare (ignore chord))
(editor-interrupt editor))
(defun stop-lisp (chord editor)
(declare (ignore chord))
(editor-stop editor))
MISCELLANY
(defun help (chord editor)
(declare (ignore chord))
(let ((pairs nil)
(max-id 0)
(max-f 0))
(maphash (lambda (id function)
(let ((f (string-downcase (symbol-name function))))
(push (list id f) pairs)
(setf max-id (max max-id (length id))
max-f (max max-f (length f)))))
(editor-commands editor))
(print-in-columns editor
(mapcar (lambda (pair)
(destructuring-bind (id f) pair
(with-output-to-string (s)
(write-string id s)
(loop repeat (- (1+ max-id) (length id))
do (write-char #\Space s))
(write-string f s))))
(nreverse pairs))
:width (+ max-id max-f 2))))
(defun unknown-command (chord editor)
(newline editor)
(format *standard-output* "Unknown command ~S." chord)
(newline editor))
(defun complete (chord editor)
(declare (ignore chord))
(multiple-value-bind (completions max-len) (editor-complete editor)
(if completions
(if (not (cdr completions))
(editor-replace-word editor (car completions))
(print-in-columns editor completions :width (+ max-len 2)))
(beep editor))))
(defun apropos-word (chord editor)
(declare (ignore chord))
(let* ((word (editor-word editor))
(apropi (apropos-list word)))
(if (null apropi)
(beep editor)
(let* ((longest 0)
(strings (mapcar (lambda (symbol)
(declare (symbol symbol))
(let ((str (prin1-to-string symbol)))
(setf longest (max longest (length str)))
(string-downcase str)))
apropi)))
(print-in-columns editor strings :width (+ longest 2))))))
(defun describe-word (chord editor)
(declare (ignore chord))
(print-in-lines editor
(with-output-to-string (s)
(describe (read-from-string (editor-word editor)) s))))
(defun toggle-insert (chord editor)
(declare (ignore chord))
(setf (editor-insert-mode editor) (not (editor-insert-mode editor))))
|
3ed9d8c73cb919d9c20a34f02cfb6caa330684348f3eb5a0d423066d4cb4ff52 | fredfeng/CS162 | ast.ml | (** Binary operators *)
type binop = Add | Sub | Mul | Gt | Lt | And | Or | Eq
(** Types *)
type typ =
| TInt
| TFun of typ * typ
| TList of typ
(** AST of Lambda+ expressions *)
type expr =
| NumLit of int
| Var of string
| Binop of expr * binop * expr
| IfThenElse of expr * expr * expr
| LetBind of string * typ option * expr * expr
| Lambda of string * typ option * expr
| App of expr * expr
| ListNil of typ option
| ListCons of expr * expr
| ListHead of expr
| ListTail of expr
| ListIsNil of expr
| Fix of expr
(** Pretty print binop as string *)
let string_of_binop (op: binop) : string =
match op with
| Add -> "+" | Sub -> "-" | Mul -> "*" | Lt -> "<" | Gt -> ">"
| Or -> "||" | And -> "&&" | Eq -> "="
let rec string_of_typ : typ -> string =
let is_complex = function
| TFun _ -> true
| _ -> false
in
let pp_nested t =
let s = string_of_typ t in if is_complex t then "(" ^ s ^ ")" else s
in
function
| TInt -> "Int"
| TFun (t1, t2) -> pp_nested t1 ^ " -> " ^ string_of_typ t2
| TList t -> Format.sprintf "List[%s]" (pp_nested t)
(** Pretty print expr as string *)
let rec string_of_expr : expr -> string =
let is_complex = function
| (NumLit _ | Var _ | ListNil _) -> false
| _ -> true
in
let parens e = "(" ^ string_of_expr e ^ ")" in
let pp_nested e = if is_complex e then parens e else string_of_expr e in
let pp_topt topt = Option.fold ~none:"" ~some:(fun t -> ": " ^ string_of_typ t) topt in
function
| NumLit n -> string_of_int n
| Var x -> x
| Binop (e1, op, e2) -> pp_nested e1 ^ " " ^ string_of_binop op ^ " " ^ pp_nested e2
| IfThenElse (e1, e2, e3) ->
Format.sprintf "if %s then %s else %s"
(string_of_expr e1) (string_of_expr e2) (string_of_expr e3)
| Lambda (x, topt, e) -> Format.sprintf "lambda %s%s. %s" x (pp_topt topt) (string_of_expr e)
| LetBind (x, topt, e1, e2) ->
Format.sprintf "let %s%s = %s in %s"
x (pp_topt topt) (string_of_expr e1) (string_of_expr e2)
| App (e1, e2) -> pp_nested e1 ^ " " ^ pp_nested e2
| ListNil topt ->
"Nil" ^ Option.fold ~none:"" ~some:(fun t -> Format.sprintf "[%s]" (string_of_typ t)) topt
| ListCons (e1, e2) ->
let p2 = match e2 with
| ListCons _ -> string_of_expr e2
| _ -> pp_nested e2
in
pp_nested e1 ^ " @ " ^ p2
| ListHead e -> "!" ^ pp_nested e
| ListTail e -> "#" ^ pp_nested e
| ListIsNil e -> "isnil " ^ pp_nested e
| Fix e -> "fix " ^ pp_nested e
(** Returns true iff the given expr is a value *)
let rec is_value : expr -> bool = function
| NumLit _ -> true
| Lambda _ -> true
| ListNil _ -> true
| ListCons (e1, e2) -> is_value e1 && is_value e2
| _ -> false
module Dsl = struct
let lam x ?t:(t=None) e = Lambda(x, t, e)
let v x = Var x
let i n = NumLit n
let (+:) e1 e2 = Binop (e1, Add, e2)
let (-:) e1 e2 = Binop (e1, Sub, e2)
let ( *:) e1 e2 = Binop (e1, Mul, e2)
let (>:) e1 e2 = Binop (e1, Gt, e2)
let (<:) e1 e2 = Binop (e1, Lt, e2)
let (&&:) e1 e2 = Binop (e1, And, e2)
let (||:) e1 e2 = Binop (e1, Or, e2)
let (=:) e1 e2 = Binop (e1, Eq, e2)
let ite e1 e2 e3 = IfThenElse (e1, e2, e3)
let let_ x ?t:(t=None) e1 e2 = LetBind (x, t, e1, e2)
let app e1 e2 = App (e1, e2)
let nil = ListNil None
let nil' t = ListNil t
let cons e1 e2 = ListCons (e1, e2)
let list ?t:(t=None) es = List.fold_right cons es (nil' t)
let tail e = ListTail e
let head e = ListHead e
let isnil e = ListIsNil e
let tint = TInt
let tlist t = TList t
let tfun t1 t2 = TFun (t1, t2)
end
| null | https://raw.githubusercontent.com/fredfeng/CS162/65bd324dc8a8c1406ee45548780ca417e35d35e3/homework/hw6/ast.ml | ocaml | * Binary operators
* Types
* AST of Lambda+ expressions
* Pretty print binop as string
* Pretty print expr as string
* Returns true iff the given expr is a value | type binop = Add | Sub | Mul | Gt | Lt | And | Or | Eq
type typ =
| TInt
| TFun of typ * typ
| TList of typ
type expr =
| NumLit of int
| Var of string
| Binop of expr * binop * expr
| IfThenElse of expr * expr * expr
| LetBind of string * typ option * expr * expr
| Lambda of string * typ option * expr
| App of expr * expr
| ListNil of typ option
| ListCons of expr * expr
| ListHead of expr
| ListTail of expr
| ListIsNil of expr
| Fix of expr
let string_of_binop (op: binop) : string =
match op with
| Add -> "+" | Sub -> "-" | Mul -> "*" | Lt -> "<" | Gt -> ">"
| Or -> "||" | And -> "&&" | Eq -> "="
let rec string_of_typ : typ -> string =
let is_complex = function
| TFun _ -> true
| _ -> false
in
let pp_nested t =
let s = string_of_typ t in if is_complex t then "(" ^ s ^ ")" else s
in
function
| TInt -> "Int"
| TFun (t1, t2) -> pp_nested t1 ^ " -> " ^ string_of_typ t2
| TList t -> Format.sprintf "List[%s]" (pp_nested t)
let rec string_of_expr : expr -> string =
let is_complex = function
| (NumLit _ | Var _ | ListNil _) -> false
| _ -> true
in
let parens e = "(" ^ string_of_expr e ^ ")" in
let pp_nested e = if is_complex e then parens e else string_of_expr e in
let pp_topt topt = Option.fold ~none:"" ~some:(fun t -> ": " ^ string_of_typ t) topt in
function
| NumLit n -> string_of_int n
| Var x -> x
| Binop (e1, op, e2) -> pp_nested e1 ^ " " ^ string_of_binop op ^ " " ^ pp_nested e2
| IfThenElse (e1, e2, e3) ->
Format.sprintf "if %s then %s else %s"
(string_of_expr e1) (string_of_expr e2) (string_of_expr e3)
| Lambda (x, topt, e) -> Format.sprintf "lambda %s%s. %s" x (pp_topt topt) (string_of_expr e)
| LetBind (x, topt, e1, e2) ->
Format.sprintf "let %s%s = %s in %s"
x (pp_topt topt) (string_of_expr e1) (string_of_expr e2)
| App (e1, e2) -> pp_nested e1 ^ " " ^ pp_nested e2
| ListNil topt ->
"Nil" ^ Option.fold ~none:"" ~some:(fun t -> Format.sprintf "[%s]" (string_of_typ t)) topt
| ListCons (e1, e2) ->
let p2 = match e2 with
| ListCons _ -> string_of_expr e2
| _ -> pp_nested e2
in
pp_nested e1 ^ " @ " ^ p2
| ListHead e -> "!" ^ pp_nested e
| ListTail e -> "#" ^ pp_nested e
| ListIsNil e -> "isnil " ^ pp_nested e
| Fix e -> "fix " ^ pp_nested e
let rec is_value : expr -> bool = function
| NumLit _ -> true
| Lambda _ -> true
| ListNil _ -> true
| ListCons (e1, e2) -> is_value e1 && is_value e2
| _ -> false
module Dsl = struct
let lam x ?t:(t=None) e = Lambda(x, t, e)
let v x = Var x
let i n = NumLit n
let (+:) e1 e2 = Binop (e1, Add, e2)
let (-:) e1 e2 = Binop (e1, Sub, e2)
let ( *:) e1 e2 = Binop (e1, Mul, e2)
let (>:) e1 e2 = Binop (e1, Gt, e2)
let (<:) e1 e2 = Binop (e1, Lt, e2)
let (&&:) e1 e2 = Binop (e1, And, e2)
let (||:) e1 e2 = Binop (e1, Or, e2)
let (=:) e1 e2 = Binop (e1, Eq, e2)
let ite e1 e2 e3 = IfThenElse (e1, e2, e3)
let let_ x ?t:(t=None) e1 e2 = LetBind (x, t, e1, e2)
let app e1 e2 = App (e1, e2)
let nil = ListNil None
let nil' t = ListNil t
let cons e1 e2 = ListCons (e1, e2)
let list ?t:(t=None) es = List.fold_right cons es (nil' t)
let tail e = ListTail e
let head e = ListHead e
let isnil e = ListIsNil e
let tint = TInt
let tlist t = TList t
let tfun t1 t2 = TFun (t1, t2)
end
|
4318dc4dabfa48a9e3393f29fd0d03c185bf0b6c482ce6b656ca717c2c3ef46c | arachne-framework/valuehash | api_test.clj | (ns valuehash.api-test
(:require [clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test.check.clojure-test :refer [defspec]]
[valuehash.api :as api]
))
(defprotocol Perturbable
"A value that can be converted to a value of a different type, but stil be equal"
(perturb [obj] "Convert an object to a different but equal object"))
(defn select
"Deterministically select one of the options (based on the hash of the key)"
[key & options]
(nth options (mod (hash key) (count options))))
(extend-protocol Perturbable
Object
(perturb [obj] obj)
Long
(perturb [l]
(select l
(if (< Byte/MIN_VALUE l Byte/MAX_VALUE) (byte l) l)
(if (< Integer/MIN_VALUE l Integer/MAX_VALUE) (int l) l)))
Double
(perturb [d]
(if (= d (unchecked-float d))
(unchecked-float d)
d))
java.util.Map
(perturb [obj]
(let [keyvals (interleave (reverse (keys obj))
(reverse (map perturb (vals obj))))]
(select obj
(apply array-map keyvals)
(apply hash-map keyvals)
(java.util.HashMap. (apply array-map keyvals)))))
java.util.List
(perturb [obj]
(let [l (map perturb obj)]
(select obj
(lazy-seq l)
(apply vector l)
(apply list l)
(java.util.ArrayList. l)
(java.util.LinkedList. l))))
java.util.Set
(perturb [obj]
(let [s (reverse (map perturb obj))]
(select obj
(apply hash-set s)
(java.util.HashSet. s)
(java.util.LinkedHashSet. s)))))
(defspec value-semantics-hold 150
(prop/for-all [o gen/any-printable]
(let [p (perturb o)]
(= (api/md5-str o) (api/md5-str p))
(= (api/sha-1-str o) (api/sha-1-str p))
(= (api/sha-256-str o) (api/sha-256-str p)))))
| null | https://raw.githubusercontent.com/arachne-framework/valuehash/ff1d4b7f1260daf41c786a61cb45d02871b7baf9/test/valuehash/api_test.clj | clojure | (ns valuehash.api-test
(:require [clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test.check.clojure-test :refer [defspec]]
[valuehash.api :as api]
))
(defprotocol Perturbable
"A value that can be converted to a value of a different type, but stil be equal"
(perturb [obj] "Convert an object to a different but equal object"))
(defn select
"Deterministically select one of the options (based on the hash of the key)"
[key & options]
(nth options (mod (hash key) (count options))))
(extend-protocol Perturbable
Object
(perturb [obj] obj)
Long
(perturb [l]
(select l
(if (< Byte/MIN_VALUE l Byte/MAX_VALUE) (byte l) l)
(if (< Integer/MIN_VALUE l Integer/MAX_VALUE) (int l) l)))
Double
(perturb [d]
(if (= d (unchecked-float d))
(unchecked-float d)
d))
java.util.Map
(perturb [obj]
(let [keyvals (interleave (reverse (keys obj))
(reverse (map perturb (vals obj))))]
(select obj
(apply array-map keyvals)
(apply hash-map keyvals)
(java.util.HashMap. (apply array-map keyvals)))))
java.util.List
(perturb [obj]
(let [l (map perturb obj)]
(select obj
(lazy-seq l)
(apply vector l)
(apply list l)
(java.util.ArrayList. l)
(java.util.LinkedList. l))))
java.util.Set
(perturb [obj]
(let [s (reverse (map perturb obj))]
(select obj
(apply hash-set s)
(java.util.HashSet. s)
(java.util.LinkedHashSet. s)))))
(defspec value-semantics-hold 150
(prop/for-all [o gen/any-printable]
(let [p (perturb o)]
(= (api/md5-str o) (api/md5-str p))
(= (api/sha-1-str o) (api/sha-1-str p))
(= (api/sha-256-str o) (api/sha-256-str p)))))
| |
ec08e600038a5b51345cdc7fe8a41af4da1b984a2ccfb0332a03571829aefb4b | c-cube/ocaml-containers | containers_testlib.mli | type 'a eq = 'a -> 'a -> bool
type 'a print = 'a -> string
module Test : sig
type t
end
module type S = sig
module Q = QCheck
val t : ?name:string -> (unit -> bool) -> unit
val eq : ?name:string -> ?cmp:'a eq -> ?printer:'a print -> 'a -> 'a -> unit
val q :
?name:string ->
?count:int ->
?long_factor:int ->
?max_gen:int ->
?max_fail:int ->
?if_assumptions_fail:[ `Fatal | `Warning ] * float ->
'a Q.arbitrary ->
('a -> bool) ->
unit
val assert_equal :
?printer:('a -> string) -> ?cmp:('a -> 'a -> bool) -> 'a -> 'a -> unit
val assert_bool : string -> bool -> unit
val assert_failure : string -> 'a
val assert_raises : (exn -> bool) -> (unit -> 'b) -> unit
val get : unit -> Test.t list
end
val make : __FILE__:string -> unit -> (module S)
val run_all :
?seed:string -> ?long:bool -> descr:string -> Test.t list list -> unit
| null | https://raw.githubusercontent.com/c-cube/ocaml-containers/484aa3a1e75e29b3576f8b0fc7ea6073f3021e6e/src/testlib/containers_testlib.mli | ocaml | type 'a eq = 'a -> 'a -> bool
type 'a print = 'a -> string
module Test : sig
type t
end
module type S = sig
module Q = QCheck
val t : ?name:string -> (unit -> bool) -> unit
val eq : ?name:string -> ?cmp:'a eq -> ?printer:'a print -> 'a -> 'a -> unit
val q :
?name:string ->
?count:int ->
?long_factor:int ->
?max_gen:int ->
?max_fail:int ->
?if_assumptions_fail:[ `Fatal | `Warning ] * float ->
'a Q.arbitrary ->
('a -> bool) ->
unit
val assert_equal :
?printer:('a -> string) -> ?cmp:('a -> 'a -> bool) -> 'a -> 'a -> unit
val assert_bool : string -> bool -> unit
val assert_failure : string -> 'a
val assert_raises : (exn -> bool) -> (unit -> 'b) -> unit
val get : unit -> Test.t list
end
val make : __FILE__:string -> unit -> (module S)
val run_all :
?seed:string -> ?long:bool -> descr:string -> Test.t list list -> unit
| |
2aee4b61022bfe027e9be9e1cacc4768a89ef355a9ce65fd85ae54d44db2f915 | fpco/ide-backend | Text.hs | -----------------------------------------------------------------------------
-- |
-- Module : Distribution.Text
Copyright : 2007
--
-- Maintainer :
-- Portability : portable
--
-- This defines a 'Text' class which is a bit like the 'Read' and 'Show'
-- classes. The difference is that is uses a modern pretty printer and parser
system and the format is not expected to be concrete syntax but
rather the external human readable representation used by Cabal .
--
module Distribution.Text (
Text(..),
display,
simpleParse,
) where
import qualified Distribution.Compat.ReadP as Parse
import qualified Text.PrettyPrint as Disp
import Data.Version (Version(Version))
import qualified Data.Char as Char (isDigit, isAlphaNum, isSpace)
class Text a where
disp :: a -> Disp.Doc
parse :: Parse.ReadP r a
display :: Text a => a -> String
display = Disp.renderStyle style . disp
where style = Disp.Style {
Disp.mode = Disp.PageMode,
Disp.lineLength = 79,
Disp.ribbonsPerLine = 1.0
}
simpleParse :: Text a => String -> Maybe a
simpleParse str = case [ p | (p, s) <- Parse.readP_to_S parse str
, all Char.isSpace s ] of
[] -> Nothing
(p:_) -> Just p
-- -----------------------------------------------------------------------------
-- Instances for types from the base package
instance Text Bool where
disp = Disp.text . show
parse = Parse.choice [ (Parse.string "True" Parse.+++
Parse.string "true") >> return True
, (Parse.string "False" Parse.+++
Parse.string "false") >> return False ]
instance Text Version where
disp (Version branch _tags) -- Death to version tags!!
= Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int branch))
parse = do
branch <- Parse.sepBy1 digits (Parse.char '.')
tags <- Parse.many (Parse.char '-' >> Parse.munch1 Char.isAlphaNum)
return (Version branch tags) --TODO: should we ignore the tags?
where
digits = do
first <- Parse.satisfy Char.isDigit
if first == '0'
then return 0
else do rest <- Parse.munch Char.isDigit
return (read (first : rest))
| null | https://raw.githubusercontent.com/fpco/ide-backend/860636f2d0e872e9481569236bce690637e0016e/ide-backend/TestSuite/inputs/Cabal-1.18.1.5/Distribution/Text.hs | haskell | ---------------------------------------------------------------------------
|
Module : Distribution.Text
Maintainer :
Portability : portable
This defines a 'Text' class which is a bit like the 'Read' and 'Show'
classes. The difference is that is uses a modern pretty printer and parser
-----------------------------------------------------------------------------
Instances for types from the base package
Death to version tags!!
TODO: should we ignore the tags? | Copyright : 2007
system and the format is not expected to be concrete syntax but
rather the external human readable representation used by Cabal .
module Distribution.Text (
Text(..),
display,
simpleParse,
) where
import qualified Distribution.Compat.ReadP as Parse
import qualified Text.PrettyPrint as Disp
import Data.Version (Version(Version))
import qualified Data.Char as Char (isDigit, isAlphaNum, isSpace)
class Text a where
disp :: a -> Disp.Doc
parse :: Parse.ReadP r a
display :: Text a => a -> String
display = Disp.renderStyle style . disp
where style = Disp.Style {
Disp.mode = Disp.PageMode,
Disp.lineLength = 79,
Disp.ribbonsPerLine = 1.0
}
simpleParse :: Text a => String -> Maybe a
simpleParse str = case [ p | (p, s) <- Parse.readP_to_S parse str
, all Char.isSpace s ] of
[] -> Nothing
(p:_) -> Just p
instance Text Bool where
disp = Disp.text . show
parse = Parse.choice [ (Parse.string "True" Parse.+++
Parse.string "true") >> return True
, (Parse.string "False" Parse.+++
Parse.string "false") >> return False ]
instance Text Version where
= Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int branch))
parse = do
branch <- Parse.sepBy1 digits (Parse.char '.')
tags <- Parse.many (Parse.char '-' >> Parse.munch1 Char.isAlphaNum)
where
digits = do
first <- Parse.satisfy Char.isDigit
if first == '0'
then return 0
else do rest <- Parse.munch Char.isDigit
return (read (first : rest))
|
354154e3447a5fb28c6619745cfc3919190e66d18059f7b3d55d33fd9337841b | dgiot/dgiot_dlink | dgiot_dlink_app.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. 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.
%%--------------------------------------------------------------------
%% @doc
%%
%% dgiot_mqtt_app:
%%
%%
%%
%% @end
-module(dgiot_dlink_app).
-emqx_plugin(auth).
-behaviour(application).
%% Application callbacks
-export([start/2,
prep_stop/1,
stop/1]).
%% ===================================================================
%% Application callbacks
%% ===================================================================
start(_StartType, _StartArgs) ->
{ok, Sup} = dgiot_dlink_sup:start_link(),
_ = load_auth_hook(),
_ = load_acl_hook(),
_ = load_publish_hook(),
{ok, Sup}.
stop(_State) ->
ok.
prep_stop(State) ->
emqx:unhook('client.authenticate', fun dgiot_mqtt_auth:check/3),
emqx:unhook('client.check_acl', fun dgiot_mqtt_acl:check_acl/5),
State.
load_auth_hook() ->
emqx:hook('client.authenticate', fun dgiot_mqtt_auth:check/3, [#{hash_type => plain}]).
load_acl_hook() ->
emqx:hook('client.check_acl', fun dgiot_mqtt_acl:check_acl/5, [#{}]).
load_publish_hook() ->
emqx:hook('message.publish', fun dgiot_mqtt_message:on_message_publish/2, [#{}]).
| null | https://raw.githubusercontent.com/dgiot/dgiot_dlink/3c6fae502d53ad73488b0203d20286cdfc2df163/src/dgiot_dlink_app.erl | erlang | --------------------------------------------------------------------
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.
--------------------------------------------------------------------
@doc
dgiot_mqtt_app:
@end
Application callbacks
===================================================================
Application callbacks
=================================================================== | Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. 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(dgiot_dlink_app).
-emqx_plugin(auth).
-behaviour(application).
-export([start/2,
prep_stop/1,
stop/1]).
start(_StartType, _StartArgs) ->
{ok, Sup} = dgiot_dlink_sup:start_link(),
_ = load_auth_hook(),
_ = load_acl_hook(),
_ = load_publish_hook(),
{ok, Sup}.
stop(_State) ->
ok.
prep_stop(State) ->
emqx:unhook('client.authenticate', fun dgiot_mqtt_auth:check/3),
emqx:unhook('client.check_acl', fun dgiot_mqtt_acl:check_acl/5),
State.
load_auth_hook() ->
emqx:hook('client.authenticate', fun dgiot_mqtt_auth:check/3, [#{hash_type => plain}]).
load_acl_hook() ->
emqx:hook('client.check_acl', fun dgiot_mqtt_acl:check_acl/5, [#{}]).
load_publish_hook() ->
emqx:hook('message.publish', fun dgiot_mqtt_message:on_message_publish/2, [#{}]).
|
28a547346192ff2c1044bdc78d42bdc60eba1ea94d97ff50d3769cf38e1f648b | erlang/otp | diameter_codec_SUITE.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2010 - 2022 . 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%
%%
%%
%% Test encode/decode of dictionary-related modules. Each test case
%% runs multiple tests in parallel since many of the tests are just
%% the same code with different in-data: implementing each test as a
%% single testcase would make for much duplication with ct's current
requirement of one function per testcase .
%%
-module(diameter_codec_SUITE).
%% testcases, no common_test dependency
-export([run/0,
run/1]).
%% common_test wrapping
-export([suite/0,
all/0,
base/1,
gen/1,
lib/1,
unknown/1,
recode/1]).
-include("diameter.hrl").
-define(util, diameter_util).
-define(L, atom_to_list).
%% ===========================================================================
suite() ->
[{timetrap, {seconds, 15}}].
all() ->
[base, gen, lib, unknown, recode].
base(_Config) ->
run(base).
gen(_Config) ->
run(gen).
lib(_Config) ->
run(lib).
unknown(Config) ->
Priv = proplists:get_value(priv_dir, Config),
Data = proplists:get_value(data_dir, Config),
unknown(Priv, Data).
recode(_Config) ->
run(recode).
%% ===========================================================================
%% run/0
run() ->
run(all()).
run/1
run(base) ->
diameter_codec_test:base();
run(gen) ->
[{application, diameter, App}] = diameter_util:consult(diameter, app),
{modules, Ms} = lists:keyfind(modules, 1, App),
[_|_] = Gs = lists:filter(fun(M) ->
lists:prefix("diameter_gen_", ?L(M))
end,
Ms),
lists:foreach(fun diameter_codec_test:gen/1, Gs);
run(lib) ->
diameter_codec_test:lib();
Have a separate AVP dictionary just to exercise more code .
run(unknown) ->
PD = ?util:mktemp("diameter_codec"),
DD = filename:join([code:lib_dir(diameter),
"test",
"diameter_codec_SUITE_data"]),
try
unknown(PD, DD)
after
file:del_dir_r(PD)
end;
run(success) ->
success();
run(grouped_error) ->
grouped_error();
run(failed_error) ->
failed_error();
run(recode) ->
ok = diameter:start(),
try
?util:run([{?MODULE, run, [F]} || F <- [success,
grouped_error,
failed_error]])
after
ok = diameter:stop()
end;
run(List) ->
?util:run([{{?MODULE, run, [F]}, 10000} || F <- List]).
%% ===========================================================================
unknown(Priv, Data) ->
ok = make(Data, "recv.dia", Priv),
ok = make(Data, "avps.dia", Priv),
{ok, _, _} = compile(Priv, "diameter_test_avps.erl"),
ok = make(Data, "send.dia", Priv),
{ok, _, _} = compile(Priv, "diameter_test_send.erl"),
{ok, _, _} = compile(Priv, "diameter_test_recv.erl"),
{ok, _, _} = compile(Priv,
filename:join([Data, "diameter_test_unknown.erl"]),
[{i, Priv}]),
diameter_test_unknown:run().
make(Dir, File, Out) ->
diameter_make:codec(filename:join(Dir, File), [{outdir, Out}]).
compile(Dir, File) ->
compile(Dir, File, []).
compile(Dir, File, Opts) ->
compile:file(filename:join(Dir, File), [return | Opts]).
%% ===========================================================================
%% Ensure a Grouped AVP is represented by a list in the avps field.
success() ->
Avps = [{295, <<1:32>>}, %% Termination-Cause
{284, [{280, "Proxy-Host"}, %% Proxy-Info
{33, "Proxy-State"}, %%
{295, <<2:32>>}]}], %% Termination-Cause
#diameter_packet{avps = [#diameter_avp{code = 295,
value = 1,
data = <<1:32>>},
[#diameter_avp{code = 284},
#diameter_avp{code = 280},
#diameter_avp{code = 33},
#diameter_avp{code = 295,
value = 2,
data = <<2:32>>}]],
errors = []}
= str(repkg(str(Avps))).
%% ===========================================================================
Ensure a Grouped AVP is represented by a list in the avps field
even in the case of a decode error on a component AVP .
grouped_error() ->
Avps = [{295, <<1:32>>}, %% Termination-Cause
{284, [{295, <<0:32>>}, %% Proxy-Info, Termination-Cause
{280, "Proxy-Host"},
{33, "Proxy-State"}]}],
#diameter_packet{avps = [#diameter_avp{code = 295,
value = 1,
data = <<1:32>>},
[#diameter_avp{code = 284},
#diameter_avp{code = 295,
value = undefined,
data = <<0:32>>},
#diameter_avp{code = 280},
#diameter_avp{code = 33}]],
errors = [{5004, #diameter_avp{code = 284}}]}
= str(repkg(str(Avps))).
%% ===========================================================================
%% Ensure that a failed decode in Failed-AVP is acceptable, and that
%% the component AVPs are decoded if possible.
failed_error() ->
Avps = [{279, [{295, <<0:32>>}, %% Failed-AVP, Termination-Cause
Auth - Application - Id
{284, [{280, "Proxy-Host"}, %% Proxy-Info
{33, "Proxy-State"},
{295, <<0:32>>}, %% Termination-Cause, invalid
Auth - Application - Id
#diameter_packet{avps = [[#diameter_avp{code = 279},
#diameter_avp{code = 295,
value = undefined,
data = <<0:32>>},
#diameter_avp{code = 258,
value = 1,
data = <<1:32>>},
[#diameter_avp{code = 284},
#diameter_avp{code = 280},
#diameter_avp{code = 33},
#diameter_avp{code = 295,
value = undefined},
#diameter_avp{code = 258,
value = 2,
data = <<2:32>>}]]],
errors = []}
= sta(repkg(sta(Avps))).
%% ===========================================================================
%% str/1
str(#diameter_packet{avps = [#diameter_avp{code = 263},
#diameter_avp{code = 264},
#diameter_avp{code = 296},
#diameter_avp{code = 283},
#diameter_avp{code = 258,
value = 0}
| T]}
= Pkt) ->
Pkt#diameter_packet{avps = T};
str(Avps) ->
OH = "diameter.erlang.org",
OR = "erlang.org",
DR = "example.com",
Sid = "diameter.erlang.org;123;456",
[#diameter_header{version = 1,
STR
is_request = true,
application_id = 0,
hop_by_hop_id = 17,
end_to_end_id = 42,
is_proxiable = false,
is_error = false,
is_retransmitted = false}
| avp([{263, Sid}, %% Session-Id
{264, OH}, %% Origin-Host
{296, OR}, %% Origin-Realm
Destination - Realm
Auth - Application - Id
++ Avps)].
sta/1
sta(#diameter_packet{avps = [#diameter_avp{code = 263},
#diameter_avp{code = 268},
#diameter_avp{code = 264},
#diameter_avp{code = 296},
#diameter_avp{code = 278,
value = 4}
| T]}
= Pkt) ->
Pkt#diameter_packet{avps = T};
sta(Avps) ->
OH = "diameter.erlang.org",
OR = "erlang.org",
Sid = "diameter.erlang.org;123;456",
[#diameter_header{version = 1,
STA
is_request = false,
application_id = 0,
hop_by_hop_id = 17,
end_to_end_id = 42,
is_proxiable = false,
is_error = false,
is_retransmitted = false}
| avp([{263, Sid}, %% Session-Id
{268, <<2002:32>>}, %% Result-Code
{264, OH}, %% Origin-Host
{296, OR}, %% Origin-Realm
{278, <<4:32>>}] %% Origin-State-Id
++ Avps)].
avp({Code, Data}) ->
#diameter_avp{code = Code,
data = avp(Data)};
avp(#diameter_avp{} = A) ->
A;
avp([{_,_} | _] = Avps) ->
lists:map(fun avp/1, Avps);
avp(V) ->
V.
%% repkg/1
repkg(Msg) ->
recode(Msg, diameter_gen_base_rfc6733).
recode(#diameter_packet{} = Pkt, Dict) ->
diameter_codec:decode(Dict, opts(Dict), diameter_codec:encode(Dict, Pkt));
recode(Msg, Dict) ->
recode(#diameter_packet{msg = Msg}, Dict).
opts(Mod) ->
#{app_dictionary => Mod,
decode_format => record,
string_decode => false,
strict_mbit => true,
rfc => 6733,
failed_avp => false}.
| null | https://raw.githubusercontent.com/erlang/otp/c4d2c952fec0c4ab4ac7ff34c1a153e740fac9a6/lib/diameter/test/diameter_codec_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%
Test encode/decode of dictionary-related modules. Each test case
runs multiple tests in parallel since many of the tests are just
the same code with different in-data: implementing each test as a
single testcase would make for much duplication with ct's current
testcases, no common_test dependency
common_test wrapping
===========================================================================
===========================================================================
run/0
===========================================================================
===========================================================================
Ensure a Grouped AVP is represented by a list in the avps field.
Termination-Cause
Proxy-Info
Termination-Cause
===========================================================================
Termination-Cause
Proxy-Info, Termination-Cause
===========================================================================
Ensure that a failed decode in Failed-AVP is acceptable, and that
the component AVPs are decoded if possible.
Failed-AVP, Termination-Cause
Proxy-Info
Termination-Cause, invalid
===========================================================================
str/1
Session-Id
Origin-Host
Origin-Realm
Session-Id
Result-Code
Origin-Host
Origin-Realm
Origin-State-Id
repkg/1 | Copyright Ericsson AB 2010 - 2022 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
requirement of one function per testcase .
-module(diameter_codec_SUITE).
-export([run/0,
run/1]).
-export([suite/0,
all/0,
base/1,
gen/1,
lib/1,
unknown/1,
recode/1]).
-include("diameter.hrl").
-define(util, diameter_util).
-define(L, atom_to_list).
suite() ->
[{timetrap, {seconds, 15}}].
all() ->
[base, gen, lib, unknown, recode].
base(_Config) ->
run(base).
gen(_Config) ->
run(gen).
lib(_Config) ->
run(lib).
unknown(Config) ->
Priv = proplists:get_value(priv_dir, Config),
Data = proplists:get_value(data_dir, Config),
unknown(Priv, Data).
recode(_Config) ->
run(recode).
run() ->
run(all()).
run/1
run(base) ->
diameter_codec_test:base();
run(gen) ->
[{application, diameter, App}] = diameter_util:consult(diameter, app),
{modules, Ms} = lists:keyfind(modules, 1, App),
[_|_] = Gs = lists:filter(fun(M) ->
lists:prefix("diameter_gen_", ?L(M))
end,
Ms),
lists:foreach(fun diameter_codec_test:gen/1, Gs);
run(lib) ->
diameter_codec_test:lib();
Have a separate AVP dictionary just to exercise more code .
run(unknown) ->
PD = ?util:mktemp("diameter_codec"),
DD = filename:join([code:lib_dir(diameter),
"test",
"diameter_codec_SUITE_data"]),
try
unknown(PD, DD)
after
file:del_dir_r(PD)
end;
run(success) ->
success();
run(grouped_error) ->
grouped_error();
run(failed_error) ->
failed_error();
run(recode) ->
ok = diameter:start(),
try
?util:run([{?MODULE, run, [F]} || F <- [success,
grouped_error,
failed_error]])
after
ok = diameter:stop()
end;
run(List) ->
?util:run([{{?MODULE, run, [F]}, 10000} || F <- List]).
unknown(Priv, Data) ->
ok = make(Data, "recv.dia", Priv),
ok = make(Data, "avps.dia", Priv),
{ok, _, _} = compile(Priv, "diameter_test_avps.erl"),
ok = make(Data, "send.dia", Priv),
{ok, _, _} = compile(Priv, "diameter_test_send.erl"),
{ok, _, _} = compile(Priv, "diameter_test_recv.erl"),
{ok, _, _} = compile(Priv,
filename:join([Data, "diameter_test_unknown.erl"]),
[{i, Priv}]),
diameter_test_unknown:run().
make(Dir, File, Out) ->
diameter_make:codec(filename:join(Dir, File), [{outdir, Out}]).
compile(Dir, File) ->
compile(Dir, File, []).
compile(Dir, File, Opts) ->
compile:file(filename:join(Dir, File), [return | Opts]).
success() ->
#diameter_packet{avps = [#diameter_avp{code = 295,
value = 1,
data = <<1:32>>},
[#diameter_avp{code = 284},
#diameter_avp{code = 280},
#diameter_avp{code = 33},
#diameter_avp{code = 295,
value = 2,
data = <<2:32>>}]],
errors = []}
= str(repkg(str(Avps))).
Ensure a Grouped AVP is represented by a list in the avps field
even in the case of a decode error on a component AVP .
grouped_error() ->
{280, "Proxy-Host"},
{33, "Proxy-State"}]}],
#diameter_packet{avps = [#diameter_avp{code = 295,
value = 1,
data = <<1:32>>},
[#diameter_avp{code = 284},
#diameter_avp{code = 295,
value = undefined,
data = <<0:32>>},
#diameter_avp{code = 280},
#diameter_avp{code = 33}]],
errors = [{5004, #diameter_avp{code = 284}}]}
= str(repkg(str(Avps))).
failed_error() ->
Auth - Application - Id
{33, "Proxy-State"},
Auth - Application - Id
#diameter_packet{avps = [[#diameter_avp{code = 279},
#diameter_avp{code = 295,
value = undefined,
data = <<0:32>>},
#diameter_avp{code = 258,
value = 1,
data = <<1:32>>},
[#diameter_avp{code = 284},
#diameter_avp{code = 280},
#diameter_avp{code = 33},
#diameter_avp{code = 295,
value = undefined},
#diameter_avp{code = 258,
value = 2,
data = <<2:32>>}]]],
errors = []}
= sta(repkg(sta(Avps))).
str(#diameter_packet{avps = [#diameter_avp{code = 263},
#diameter_avp{code = 264},
#diameter_avp{code = 296},
#diameter_avp{code = 283},
#diameter_avp{code = 258,
value = 0}
| T]}
= Pkt) ->
Pkt#diameter_packet{avps = T};
str(Avps) ->
OH = "diameter.erlang.org",
OR = "erlang.org",
DR = "example.com",
Sid = "diameter.erlang.org;123;456",
[#diameter_header{version = 1,
STR
is_request = true,
application_id = 0,
hop_by_hop_id = 17,
end_to_end_id = 42,
is_proxiable = false,
is_error = false,
is_retransmitted = false}
Destination - Realm
Auth - Application - Id
++ Avps)].
sta/1
sta(#diameter_packet{avps = [#diameter_avp{code = 263},
#diameter_avp{code = 268},
#diameter_avp{code = 264},
#diameter_avp{code = 296},
#diameter_avp{code = 278,
value = 4}
| T]}
= Pkt) ->
Pkt#diameter_packet{avps = T};
sta(Avps) ->
OH = "diameter.erlang.org",
OR = "erlang.org",
Sid = "diameter.erlang.org;123;456",
[#diameter_header{version = 1,
STA
is_request = false,
application_id = 0,
hop_by_hop_id = 17,
end_to_end_id = 42,
is_proxiable = false,
is_error = false,
is_retransmitted = false}
++ Avps)].
avp({Code, Data}) ->
#diameter_avp{code = Code,
data = avp(Data)};
avp(#diameter_avp{} = A) ->
A;
avp([{_,_} | _] = Avps) ->
lists:map(fun avp/1, Avps);
avp(V) ->
V.
repkg(Msg) ->
recode(Msg, diameter_gen_base_rfc6733).
recode(#diameter_packet{} = Pkt, Dict) ->
diameter_codec:decode(Dict, opts(Dict), diameter_codec:encode(Dict, Pkt));
recode(Msg, Dict) ->
recode(#diameter_packet{msg = Msg}, Dict).
opts(Mod) ->
#{app_dictionary => Mod,
decode_format => record,
string_decode => false,
strict_mbit => true,
rfc => 6733,
failed_avp => false}.
|
df34a4ca82615147711a5b6ed938a3a7a104c4ef13cb44fa0c8ed1e0de99aedf | CorticalComputer/Book_NeuroevolutionThroughErlang | morphology.erl | This source code and work is provided and developed by DXNN Research Group WWW.DXNNResearch . COM
%%
Copyright ( C ) 2012 by , DXNN Research Group ,
%All rights reserved.
%
This code is licensed under the version 3 of the GNU General Public License . Please see the LICENSE file that accompanies this project for the terms of use .
-module(morphology).
-compile(export_all).
-include("records.hrl").
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Get Init Standard Actuators/Sensors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
get_InitSensors(Morphology)->
Sensors = morphology:Morphology(sensors),
[lists:nth(1,Sensors)].
get_InitActuators(Morphology)->
Actuators = morphology:Morphology(actuators),
[lists:nth(1,Actuators)].
get_Sensors(Morphology)->
morphology:Morphology(sensors).
get_Actuators(Morphology)->
morphology:Morphology(actuators).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Get Init Substrate_CPPs/Substrate_CEPs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
get_InitSubstrateCPPs(Dimensions,Plasticity)->
Substrate_CPPs = get_SubstrateCPPs(Dimensions,Plasticity),
[lists:nth(1,Substrate_CPPs)].
get_InitSubstrateCEPs(Dimensions,Plasticity)->
Substrate_CEPs = get_SubstrateCEPs(Dimensions,Plasticity),
[lists:nth(1,Substrate_CEPs)].
get_SubstrateCPPs(Dimensions,Plasticity)->
io:format("Dimensions:~p, Plasticity:~p~n",[Dimensions,Plasticity]),
if
(Plasticity == iterative) or (Plasticity == abcn) ->
Std=[
#sensor{name=cartesian,type=substrate,vl=Dimensions*2+3},%{cartesian,Dimensions*2+3},
#sensor{name=centripital_distances,type=substrate,vl=2+3},%{centripital_distances,2+3},
#sensor{name=cartesian_distance,type=substrate,vl=1+3},%{cartesian_distance,1+3},
#sensor{name=cartesian_CoordDiffs,type=substrate,vl=Dimensions+3},%{cartesian_CoordDiffs,Dimensions+3}
, Dimensions+3 }
#sensor{name=iow,type=substrate,vl=3}%{iow,3}
],
Adt=case Dimensions of
2 ->
[#sensor{name=polar,type=substrate,vl=Dimensions*2+3}];%[{polar,Dimensions*2+3}];
3 ->
[#sensor{name=spherical,type=substrate,vl=Dimensions*2+3}];%[{spherical,Dimensions*2+3}]
_ ->
[]
end,
lists:append(Std,Adt);
(Plasticity == none) or (Plasticity == modular_none)->
Std=[
#sensor{name=cartesian,type=substrate,vl=Dimensions*2},%{cartesian,Dimensions*2},
#sensor{name=centripital_distances,type=substrate,vl=2},%{centripital_distances,2},
#sensor{name=cartesian_distance,type=substrate,vl=1},%{cartesian_distance,1},
#sensor{name=cartesian_CoordDiffs,type=substrate,vl=Dimensions},%{cartesian_CoordDiffs,Dimensions+3}
, Dimensions+3 }
],
Adt=case Dimensions of
2 ->
[#sensor{name=polar,type=substrate,vl=Dimensions*2}];%[{polar,Dimensions*2}];
3 ->
[#sensor{name=spherical,type=substrate,vl=Dimensions*2}];%[{spherical,Dimensions*2}]
_ ->
[]
end,
lists:append(Std,Adt)
end.
get_SubstrateCEPs(Dimensions,Plasticity)->
case Plasticity of
iterative ->
[#actuator{name=delta_weight,type=substrate,vl=1}]; %[{delta_weight,1}];
abcn ->
[ { abcn,4 } ] ;
none ->
[#actuator{name=set_weight,type=substrate,vl=1}]; %[{weight,1}]
modular_none ->
[#actuator{name=weight_expression,type=substrate,vl=2}] %[{weight_conexpr,2}]
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MORPHOLOGIES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xor_mimic(sensors)->
[
#sensor{name=xor_GetInput,type=standard,scape={private,xor_sim},vl=2}
];
xor_mimic(actuators)->
[
#actuator{name=xor_SendOutput,type=standard,scape={private,xor_sim},vl=1}
].
* Every sensor and actuator uses some kind of function associated with it . A function that either polls the environment for sensory signals ( in the case of a sensor ) or acts upon the environment ( in the case of an actuator ) . It is a function that we need to define and program before it is used , and the name of the function is the same as the name of the sensor or actuator it self . For example , the create_Sensor/1 has specified only the rng sensor , because that is the only sensor function we 've finished developing . The rng function has its own vl specification , which will determine the number of weights that a neuron will need to allocate if it is to accept this sensor 's output vector . The same principles apply to the create_Actuator function . Both , create_Sensor and create_Actuator function , given the name of the sensor or actuator , will return a record with all the specifications of that element , each with its own unique Id.
pole_balancing(sensors)->
[
#sensor{name=pb_GetInput,type=standard,scape={private,pb_sim},vl=3,parameters=[3]}
];
pole_balancing(actuators)->
[
#actuator{name=pb_SendOutput,type=standard,scape={private,pb_sim},vl=1,parameters=[with_damping,1]}
].
Both , the pole balancing sensor and actuator , interface with the pole balancing simulation , a private scape . The type of problem the pole balancing simulation is used as depends on the sensor and acutuator parameters . The sensor 's vl and parameters specify that the sensor will request the private scape for the cart 's and pole 's position and angular position respectively . The actuator 's parameters specify that the scape should use without_damping type of fitness , and that since only a single pole is being used , that the termination condition associated with the second pole will be zeroed out , by being multiplied by the specified 0 value . When instead of using 0 , we use 1 , the private scape would use the angular position of the second pole as an element in calculating the fitness score of the interfacing agent , and using that angular position for the purpose of calculating whether termination condition has been reached by the problem .
discrete_tmaze(sensors)->
[
#sensor{name=dtm_GetInput,type=standard,scape={private,dtm_sim},vl=4,parameters=[all]}
];
discrete_tmaze(actuators)->
[
#actuator{name=dtm_SendOutput,type=standard,scape={private,dtm_sim},vl=1,parameters=[]}
].
predator(actuators)->
prey(actuators);
predator(sensors)->
prey(sensors).
prey(actuators)->
Movement = [#actuator{name=differential_drive,type=standard,scape={public,flatland}, vl=2, parameters=[2]}],
Movement;
prey(sensors)->
Pi = math:pi(),
Color_Scanners = [#sensor{name=color_scanner,type=standard,scape={public,flatland},vl=Density, parameters=[Spread,Density,ROffset]} || Spread <-[Pi/2], Density <-[5], ROffset<-[Pi*0/2]],
Range_Scanners = [#sensor{name=range_scanner,type=standard,scape={public,flatland},vl=Density, parameters=[Spread,Density,ROffset]} || Spread <-[Pi/2], Density <-[5], ROffset<-[Pi*0/2]],
Color_Scanners++Range_Scanners.
forex_trader(actuators)->
[
#actuator{name=fx_Trade,type=standard,scape={private,fx_sim},format=no_geo,vl=1,parameters=[]}
];
forex_trader(sensors)->
PLI_Sensors=[#sensor{name=fx_PLI,type=standard,scape={private,fx_sim},format=no_geo,vl=HRes,parameters=[HRes,close]} || HRes<-[10]],
PCI_Sensors = [#sensor{name=fx_PCI,type=standard,scape={private,fx_sim},format={symmetric,[HRes,VRes]},vl=HRes*VRes,parameters=[HRes,VRes]} || HRes <-[50], VRes<-[20]],
[ Long|Short|Void],Value
PCI_Sensors.%++InternalSensors.
generate_id() ->
{MegaSeconds,Seconds,MicroSeconds} = now(),
1/(MegaSeconds*1000000 + Seconds + MicroSeconds/1000000).
| null | https://raw.githubusercontent.com/CorticalComputer/Book_NeuroevolutionThroughErlang/81b96e3d7985624a6183cb313a7f9bff0a7e14c5/Ch_19/morphology.erl | erlang |
All rights reserved.
Get Init Standard Actuators/Sensors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Get Init Substrate_CPPs/Substrate_CEPs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
{cartesian,Dimensions*2+3},
{centripital_distances,2+3},
{cartesian_distance,1+3},
{cartesian_CoordDiffs,Dimensions+3}
{iow,3}
[{polar,Dimensions*2+3}];
[{spherical,Dimensions*2+3}]
{cartesian,Dimensions*2},
{centripital_distances,2},
{cartesian_distance,1},
{cartesian_CoordDiffs,Dimensions+3}
[{polar,Dimensions*2}];
[{spherical,Dimensions*2}]
[{delta_weight,1}];
[{weight,1}]
[{weight_conexpr,2}]
MORPHOLOGIES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
++InternalSensors. | This source code and work is provided and developed by DXNN Research Group WWW.DXNNResearch . COM
Copyright ( C ) 2012 by , DXNN Research Group ,
This code is licensed under the version 3 of the GNU General Public License . Please see the LICENSE file that accompanies this project for the terms of use .
-module(morphology).
-compile(export_all).
-include("records.hrl").
get_InitSensors(Morphology)->
Sensors = morphology:Morphology(sensors),
[lists:nth(1,Sensors)].
get_InitActuators(Morphology)->
Actuators = morphology:Morphology(actuators),
[lists:nth(1,Actuators)].
get_Sensors(Morphology)->
morphology:Morphology(sensors).
get_Actuators(Morphology)->
morphology:Morphology(actuators).
get_InitSubstrateCPPs(Dimensions,Plasticity)->
Substrate_CPPs = get_SubstrateCPPs(Dimensions,Plasticity),
[lists:nth(1,Substrate_CPPs)].
get_InitSubstrateCEPs(Dimensions,Plasticity)->
Substrate_CEPs = get_SubstrateCEPs(Dimensions,Plasticity),
[lists:nth(1,Substrate_CEPs)].
get_SubstrateCPPs(Dimensions,Plasticity)->
io:format("Dimensions:~p, Plasticity:~p~n",[Dimensions,Plasticity]),
if
(Plasticity == iterative) or (Plasticity == abcn) ->
Std=[
, Dimensions+3 }
],
Adt=case Dimensions of
2 ->
3 ->
_ ->
[]
end,
lists:append(Std,Adt);
(Plasticity == none) or (Plasticity == modular_none)->
Std=[
, Dimensions+3 }
],
Adt=case Dimensions of
2 ->
3 ->
_ ->
[]
end,
lists:append(Std,Adt)
end.
get_SubstrateCEPs(Dimensions,Plasticity)->
case Plasticity of
iterative ->
abcn ->
[ { abcn,4 } ] ;
none ->
modular_none ->
end.
xor_mimic(sensors)->
[
#sensor{name=xor_GetInput,type=standard,scape={private,xor_sim},vl=2}
];
xor_mimic(actuators)->
[
#actuator{name=xor_SendOutput,type=standard,scape={private,xor_sim},vl=1}
].
* Every sensor and actuator uses some kind of function associated with it . A function that either polls the environment for sensory signals ( in the case of a sensor ) or acts upon the environment ( in the case of an actuator ) . It is a function that we need to define and program before it is used , and the name of the function is the same as the name of the sensor or actuator it self . For example , the create_Sensor/1 has specified only the rng sensor , because that is the only sensor function we 've finished developing . The rng function has its own vl specification , which will determine the number of weights that a neuron will need to allocate if it is to accept this sensor 's output vector . The same principles apply to the create_Actuator function . Both , create_Sensor and create_Actuator function , given the name of the sensor or actuator , will return a record with all the specifications of that element , each with its own unique Id.
pole_balancing(sensors)->
[
#sensor{name=pb_GetInput,type=standard,scape={private,pb_sim},vl=3,parameters=[3]}
];
pole_balancing(actuators)->
[
#actuator{name=pb_SendOutput,type=standard,scape={private,pb_sim},vl=1,parameters=[with_damping,1]}
].
Both , the pole balancing sensor and actuator , interface with the pole balancing simulation , a private scape . The type of problem the pole balancing simulation is used as depends on the sensor and acutuator parameters . The sensor 's vl and parameters specify that the sensor will request the private scape for the cart 's and pole 's position and angular position respectively . The actuator 's parameters specify that the scape should use without_damping type of fitness , and that since only a single pole is being used , that the termination condition associated with the second pole will be zeroed out , by being multiplied by the specified 0 value . When instead of using 0 , we use 1 , the private scape would use the angular position of the second pole as an element in calculating the fitness score of the interfacing agent , and using that angular position for the purpose of calculating whether termination condition has been reached by the problem .
discrete_tmaze(sensors)->
[
#sensor{name=dtm_GetInput,type=standard,scape={private,dtm_sim},vl=4,parameters=[all]}
];
discrete_tmaze(actuators)->
[
#actuator{name=dtm_SendOutput,type=standard,scape={private,dtm_sim},vl=1,parameters=[]}
].
predator(actuators)->
prey(actuators);
predator(sensors)->
prey(sensors).
prey(actuators)->
Movement = [#actuator{name=differential_drive,type=standard,scape={public,flatland}, vl=2, parameters=[2]}],
Movement;
prey(sensors)->
Pi = math:pi(),
Color_Scanners = [#sensor{name=color_scanner,type=standard,scape={public,flatland},vl=Density, parameters=[Spread,Density,ROffset]} || Spread <-[Pi/2], Density <-[5], ROffset<-[Pi*0/2]],
Range_Scanners = [#sensor{name=range_scanner,type=standard,scape={public,flatland},vl=Density, parameters=[Spread,Density,ROffset]} || Spread <-[Pi/2], Density <-[5], ROffset<-[Pi*0/2]],
Color_Scanners++Range_Scanners.
forex_trader(actuators)->
[
#actuator{name=fx_Trade,type=standard,scape={private,fx_sim},format=no_geo,vl=1,parameters=[]}
];
forex_trader(sensors)->
PLI_Sensors=[#sensor{name=fx_PLI,type=standard,scape={private,fx_sim},format=no_geo,vl=HRes,parameters=[HRes,close]} || HRes<-[10]],
PCI_Sensors = [#sensor{name=fx_PCI,type=standard,scape={private,fx_sim},format={symmetric,[HRes,VRes]},vl=HRes*VRes,parameters=[HRes,VRes]} || HRes <-[50], VRes<-[20]],
[ Long|Short|Void],Value
generate_id() ->
{MegaSeconds,Seconds,MicroSeconds} = now(),
1/(MegaSeconds*1000000 + Seconds + MicroSeconds/1000000).
|
2e38fc104ebe581f7959e87a2d57dab7273d49be6721461f09b285060fbae6df | haskell-servant/servant | HasClient.hs | {-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE PolyKinds #
# LANGUAGE QuantifiedConstraints #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
module Servant.Client.Core.HasClient (
clientIn,
HasClient (..),
EmptyClient (..),
AsClientT,
(//),
(/:),
foldMapUnion,
matchUnion,
) where
import Prelude ()
import Prelude.Compat
import Control.Arrow
(left, (+++))
import Control.Monad
(unless)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import Data.Either
(partitionEithers)
import Data.Constraint (Dict(..))
import Data.Foldable
(toList)
import Data.List
(foldl')
import Data.Sequence
(fromList)
import qualified Data.Text as T
import Network.HTTP.Media
(MediaType, matches, parseAccept)
import qualified Network.HTTP.Media as Media
import qualified Data.Sequence as Seq
import Data.SOP.BasicFunctors
(I (I), (:.:) (Comp))
import Data.SOP.Constraint
(All)
import Data.SOP.NP
(NP (..), cpure_NP)
import Data.SOP.NS
(NS (S))
import Data.String
(fromString)
import Data.Text
(Text, pack)
import Data.Proxy
(Proxy (Proxy))
import GHC.TypeLits
(KnownNat, KnownSymbol, TypeError, symbolVal)
import Network.HTTP.Types
(Status)
import qualified Network.HTTP.Types as H
import Servant.API
((:<|>) ((:<|>)), (:>), AuthProtect, BasicAuth, BasicAuthData,
BuildHeadersTo (..), Capture', CaptureAll, Description,
EmptyAPI, Fragment, FramingRender (..), FramingUnrender (..),
FromSourceIO (..), Header', Headers (..), HttpVersion,
IsSecure, MimeRender (mimeRender),
MimeUnrender (mimeUnrender), NoContent (NoContent),
NoContentVerb, QueryFlag, QueryParam', QueryParams, Raw, RawM,
ReflectMethod (..), RemoteHost, ReqBody', SBoolI, Stream,
StreamBody', Summary, ToHttpApiData, ToSourceIO (..), Vault,
Verb, WithNamedContext, WithResource, WithStatus (..), contentType, getHeadersHList,
getResponse, toEncodedUrlPiece, toUrlPiece, NamedRoutes)
import Servant.API.Generic
(GenericMode(..), ToServant, ToServantApi
, GenericServant, toServant, fromServant)
import Servant.API.ContentTypes
(contentTypes, AllMime (allMime), AllMimeUnrender (allMimeUnrender))
import Servant.API.Status
(statusFromNat)
import Servant.API.TypeLevel (FragmentUnique, AtLeastOneFragment)
import Servant.API.Modifiers
(FoldRequired, RequiredArgument, foldRequiredArgument)
import Servant.API.TypeErrors
import Servant.API.UVerb
(HasStatus, HasStatuses (Statuses, statuses), UVerb, Union, Unique, inject, statusOf, foldMapUnion, matchUnion)
import Servant.Client.Core.Auth
import Servant.Client.Core.BasicAuth
import Servant.Client.Core.ClientError
import Servant.Client.Core.Request
import Servant.Client.Core.Response
import Servant.Client.Core.RunClient
-- * Accessing APIs as a Client
| ' clientIn ' allows you to produce operations to query an API from a client
within a ' ' monad .
--
> type MyApi = " books " :> Get ' [ JSON ] [ Book ] -- GET /books
-- > :<|> "books" :> ReqBody '[JSON] Book :> Post '[JSON] Book -- POST /books
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
> clientM : : Proxy ClientM
-- > clientM = Proxy
-- >
-- > getAllBooks :: ClientM [Book]
-- > postNewBook :: Book -> ClientM Book
> ( getAllBooks : < | > postNewBook ) = myApi ` clientIn ` clientM
clientIn :: HasClient m api => Proxy api -> Proxy m -> Client m api
clientIn p pm = clientWithRoute pm p defaultRequest
-- | This class lets us define how each API combinator influences the creation
-- of an HTTP request.
--
Unless you are writing a new backend for @servant - client - core@ or new
-- combinators that you want to support client-generation, you can ignore this
-- class.
class RunClient m => HasClient m api where
type Client (m :: * -> *) (api :: *) :: *
clientWithRoute :: Proxy m -> Proxy api -> Request -> Client m api
hoistClientMonad
:: Proxy m
-> Proxy api
-> (forall x. mon x -> mon' x)
-> Client mon api
-> Client mon' api
| A client querying function for @a ' : < | > ' b@ will actually hand you
one function for querying @a@ and another one for querying @b@ ,
-- stitching them together with ':<|>', which really is just like a pair.
--
> type MyApi = " books " :> Get ' [ JSON ] [ Book ] -- GET /books
-- > :<|> "books" :> ReqBody '[JSON] Book :> Post Book -- POST /books
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
-- > getAllBooks :: ClientM [Book]
-- > postNewBook :: Book -> ClientM Book
> ( getAllBooks : < | > postNewBook ) = client myApi
instance (HasClient m a, HasClient m b) => HasClient m (a :<|> b) where
type Client m (a :<|> b) = Client m a :<|> Client m b
clientWithRoute pm Proxy req =
clientWithRoute pm (Proxy :: Proxy a) req :<|>
clientWithRoute pm (Proxy :: Proxy b) req
hoistClientMonad pm _ f (ca :<|> cb) =
hoistClientMonad pm (Proxy :: Proxy a) f ca :<|>
hoistClientMonad pm (Proxy :: Proxy b) f cb
-- | Singleton type representing a client for an empty API.
data EmptyClient = EmptyClient deriving (Eq, Show, Bounded, Enum)
| The client for ' EmptyAPI ' is simply ' EmptyClient ' .
--
> type MyAPI = " books " :> Get ' [ JSON ] [ Book ] -- GET /books
> : < | > " nothing " :> EmptyAPI
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
-- > getAllBooks :: ClientM [Book]
> ( getAllBooks : < | > EmptyClient ) = client myApi
instance RunClient m => HasClient m EmptyAPI where
type Client m EmptyAPI = EmptyClient
clientWithRoute _pm Proxy _ = EmptyClient
hoistClientMonad _ _ _ EmptyClient = EmptyClient
-- | If you use a 'Capture' in one of your endpoints in your API,
-- the corresponding querying function will automatically take
-- an additional argument of the type specified by your 'Capture'.
-- That function will take care of inserting a textual representation
-- of this value at the right place in the request path.
--
-- You can control how values for this type are turned into
text by specifying a ' ToHttpApiData ' instance for your type .
--
-- Example:
--
> type MyApi = " books " :> Capture " isbn " Text :> Get ' [ JSON ] Book
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
-- > getBook :: Text -> ClientM Book
> getBook = client myApi
-- > -- then you can just use "getBook" to query that endpoint
instance (KnownSymbol capture, ToHttpApiData a, HasClient m api)
=> HasClient m (Capture' mods capture a :> api) where
type Client m (Capture' mods capture a :> api) =
a -> Client m api
clientWithRoute pm Proxy req val =
clientWithRoute pm (Proxy :: Proxy api)
(appendToPath p req)
where p = toEncodedUrlPiece val
hoistClientMonad pm _ f cl = \a ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl a)
| If you use a ' CaptureAll ' in one of your endpoints in your API ,
-- the corresponding querying function will automatically take an
-- additional argument of a list of the type specified by your
' CaptureAll ' . That function will take care of inserting a textual
-- representation of this value at the right place in the request
-- path.
--
-- You can control how these values are turned into text by specifying
a ' ToHttpApiData ' instance of your type .
--
-- Example:
--
> type MyAPI = " src " :> CaptureAll Text - > Get ' [ JSON ] SourceFile
-- >
-- > myApi :: Proxy
-- > myApi = Proxy
--
-- > getSourceFile :: [Text] -> ClientM SourceFile
> getSourceFile = client myApi
-- > -- then you can use "getSourceFile" to query that endpoint
instance (KnownSymbol capture, ToHttpApiData a, HasClient m sublayout)
=> HasClient m (CaptureAll capture a :> sublayout) where
type Client m (CaptureAll capture a :> sublayout) =
[a] -> Client m sublayout
clientWithRoute pm Proxy req vals =
clientWithRoute pm (Proxy :: Proxy sublayout)
(foldl' (flip appendToPath) req ps)
where ps = map toEncodedUrlPiece vals
hoistClientMonad pm _ f cl = \as ->
hoistClientMonad pm (Proxy :: Proxy sublayout) f (cl as)
instance {-# OVERLAPPABLE #-}
-- Note [Non-Empty Content Types]
( RunClient m, MimeUnrender ct a, ReflectMethod method, cts' ~ (ct ': cts)
, KnownNat status
) => HasClient m (Verb method status cts' a) where
type Client m (Verb method status cts' a) = m a
clientWithRoute _pm Proxy req = do
response <- runRequestAcceptStatus (Just [status]) req
{ requestAccept = fromList $ toList accept
, requestMethod = method
}
response `decodedAs` (Proxy :: Proxy ct)
where
accept = contentTypes (Proxy :: Proxy ct)
method = reflectMethod (Proxy :: Proxy method)
status = statusFromNat (Proxy :: Proxy status)
hoistClientMonad _ _ f ma = f ma
instance {-# OVERLAPPING #-}
( RunClient m, ReflectMethod method, KnownNat status
) => HasClient m (Verb method status cts NoContent) where
type Client m (Verb method status cts NoContent)
= m NoContent
clientWithRoute _pm Proxy req = do
_response <- runRequestAcceptStatus (Just [status]) req { requestMethod = method }
return NoContent
where method = reflectMethod (Proxy :: Proxy method)
status = statusFromNat (Proxy :: Proxy status)
hoistClientMonad _ _ f ma = f ma
instance (RunClient m, ReflectMethod method) =>
HasClient m (NoContentVerb method) where
type Client m (NoContentVerb method)
= m NoContent
clientWithRoute _pm Proxy req = do
_response <- runRequest req { requestMethod = method }
return NoContent
where method = reflectMethod (Proxy :: Proxy method)
hoistClientMonad _ _ f ma = f ma
instance {-# OVERLAPPING #-}
-- Note [Non-Empty Content Types]
( RunClient m, MimeUnrender ct a, BuildHeadersTo ls, KnownNat status
, ReflectMethod method, cts' ~ (ct ': cts)
) => HasClient m (Verb method status cts' (Headers ls a)) where
type Client m (Verb method status cts' (Headers ls a))
= m (Headers ls a)
clientWithRoute _pm Proxy req = do
response <- runRequestAcceptStatus (Just [status]) req
{ requestMethod = method
, requestAccept = fromList $ toList accept
}
val <- response `decodedAs` (Proxy :: Proxy ct)
return $ Headers { getResponse = val
, getHeadersHList = buildHeadersTo . toList $ responseHeaders response
}
where
method = reflectMethod (Proxy :: Proxy method)
accept = contentTypes (Proxy :: Proxy ct)
status = statusFromNat (Proxy :: Proxy status)
hoistClientMonad _ _ f ma = f ma
instance {-# OVERLAPPING #-}
( RunClient m, BuildHeadersTo ls, ReflectMethod method, KnownNat status
) => HasClient m (Verb method status cts (Headers ls NoContent)) where
type Client m (Verb method status cts (Headers ls NoContent))
= m (Headers ls NoContent)
clientWithRoute _pm Proxy req = do
response <- runRequestAcceptStatus (Just [status]) req { requestMethod = method }
return $ Headers { getResponse = NoContent
, getHeadersHList = buildHeadersTo . toList $ responseHeaders response
}
where
method = reflectMethod (Proxy :: Proxy method)
status = statusFromNat (Proxy :: Proxy status)
hoistClientMonad _ _ f ma = f ma
data ClientParseError = ClientParseError MediaType String | ClientStatusMismatch | ClientNoMatchingStatus
deriving (Eq, Show)
class UnrenderResponse (cts :: [*]) (a :: *) where
unrenderResponse :: Seq.Seq H.Header -> BL.ByteString -> Proxy cts
-> [Either (MediaType, String) a]
instance {-# OVERLAPPABLE #-} AllMimeUnrender cts a => UnrenderResponse cts a where
unrenderResponse _ body = map parse . allMimeUnrender
where parse (mediaType, parser) = left ((,) mediaType) (parser body)
instance {-# OVERLAPPING #-} forall cts a h . (UnrenderResponse cts a, BuildHeadersTo h)
=> UnrenderResponse cts (Headers h a) where
unrenderResponse hs body = (map . fmap) setHeaders . unrenderResponse hs body
where
setHeaders :: a -> Headers h a
setHeaders x = Headers x (buildHeadersTo (toList hs))
instance {-# OVERLAPPING #-} UnrenderResponse cts a
=> UnrenderResponse cts (WithStatus n a) where
unrenderResponse hs body = (map . fmap) WithStatus . unrenderResponse hs body
instance {-# OVERLAPPING #-}
( RunClient m,
contentTypes ~ (contentType ': otherContentTypes),
-- ('otherContentTypes' should be '_', but even -XPartialTypeSignatures does not seem
-- allow this in instance types as of 8.8.3.)
as ~ (a ': as'),
AllMime contentTypes,
ReflectMethod method,
All (UnrenderResponse contentTypes) as,
All HasStatus as, HasStatuses as',
Unique (Statuses as)
) =>
HasClient m (UVerb method contentTypes as)
where
type Client m (UVerb method contentTypes as) = m (Union as)
clientWithRoute _ _ request = do
let accept = Seq.fromList . allMime $ Proxy @contentTypes
-- offering to accept all mime types listed in the api gives best compatibility. eg.,
-- we might not own the server implementation, and the server may choose to support
-- only part of the api.
method = reflectMethod $ Proxy @method
acceptStatus = statuses (Proxy @as)
response <- runRequestAcceptStatus (Just acceptStatus) request {requestMethod = method, requestAccept = accept}
responseContentType <- checkContentTypeHeader response
unless (any (matches responseContentType) accept) $ do
throwClientError $ UnsupportedContentType responseContentType response
let status = responseStatusCode response
body = responseBody response
headers = responseHeaders response
res = tryParsers status $ mimeUnrenders (Proxy @contentTypes) headers body
case res of
Left errors -> throwClientError $ DecodeFailure (T.pack (show errors)) response
Right x -> return x
where
| Given a list of parsers of ' mkres ' , returns the first one that succeeds and all the
-- failures it encountered along the way
TODO ; better name , rewrite .
tryParsers :: forall xs. All HasStatus xs => Status -> NP ([] :.: Either (MediaType, String)) xs -> Either [ClientParseError] (Union xs)
tryParsers _ Nil = Left [ClientNoMatchingStatus]
tryParsers status (Comp x :* xs)
| status == statusOf (Comp x) =
case partitionEithers x of
(err', []) -> (map (uncurry ClientParseError) err' ++) +++ S $ tryParsers status xs
(_, (res : _)) -> Right . inject . I $ res
no reason to parse in the first place . This ai n't the one we 're looking for
(ClientStatusMismatch :) +++ S $ tryParsers status xs
-- | Given a list of types, parses the given response body as each type
mimeUnrenders ::
forall cts xs.
All (UnrenderResponse cts) xs =>
Proxy cts ->
Seq.Seq H.Header ->
BL.ByteString ->
NP ([] :.: Either (MediaType, String)) xs
mimeUnrenders ctp headers body = cpure_NP
(Proxy @(UnrenderResponse cts))
(Comp . unrenderResponse headers body $ ctp)
hoistClientMonad _ _ nt s = nt s
instance {-# OVERLAPPABLE #-}
( RunStreamingClient m, MimeUnrender ct chunk, ReflectMethod method,
FramingUnrender framing, FromSourceIO chunk a
) => HasClient m (Stream method status framing ct a) where
type Client m (Stream method status framing ct a) = m a
hoistClientMonad _ _ f ma = f ma
clientWithRoute _pm Proxy req = withStreamingRequest req' $ \gres -> do
let mimeUnrender' = mimeUnrender (Proxy :: Proxy ct) :: BL.ByteString -> Either String chunk
framingUnrender' = framingUnrender (Proxy :: Proxy framing) mimeUnrender'
return $ fromSourceIO $ framingUnrender' $ responseBody gres
where
req' = req
{ requestAccept = fromList [contentType (Proxy :: Proxy ct)]
, requestMethod = reflectMethod (Proxy :: Proxy method)
}
instance {-# OVERLAPPING #-}
( RunStreamingClient m, MimeUnrender ct chunk, ReflectMethod method,
FramingUnrender framing, FromSourceIO chunk a,
BuildHeadersTo hs
) => HasClient m (Stream method status framing ct (Headers hs a)) where
type Client m (Stream method status framing ct (Headers hs a)) = m (Headers hs a)
hoistClientMonad _ _ f ma = f ma
clientWithRoute _pm Proxy req = withStreamingRequest req' $ \gres -> do
let mimeUnrender' = mimeUnrender (Proxy :: Proxy ct) :: BL.ByteString -> Either String chunk
framingUnrender' = framingUnrender (Proxy :: Proxy framing) mimeUnrender'
val = fromSourceIO $ framingUnrender' $ responseBody gres
return $ Headers
{ getResponse = val
, getHeadersHList = buildHeadersTo . toList $ responseHeaders gres
}
where
req' = req
{ requestAccept = fromList [contentType (Proxy :: Proxy ct)]
, requestMethod = reflectMethod (Proxy :: Proxy method)
}
-- | If you use a 'Header' in one of your endpoints in your API,
-- the corresponding querying function will automatically take
-- an additional argument of the type specified by your 'Header',
-- wrapped in Maybe.
--
-- That function will take care of encoding this argument as Text
-- in the request headers.
--
All you need is for your type to have a ' ToHttpApiData ' instance .
--
-- Example:
--
> newtype referrer : : Text }
> deriving ( Eq , Show , Generic , ToHttpApiData )
-- >
-- > -- GET /view-my-referer
> type MyApi = " view - my - referer " :> Header " Referer " Referer :> Get ' [ JSON ]
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
> viewReferer : : Maybe ClientM Book
> = client myApi
> -- then you can just use " viewRefer " to query that endpoint
-- > -- specifying Nothing or e.g Just "/" as arguments
instance (KnownSymbol sym, ToHttpApiData a, HasClient m api, SBoolI (FoldRequired mods))
=> HasClient m (Header' mods sym a :> api) where
type Client m (Header' mods sym a :> api) =
RequiredArgument mods a -> Client m api
clientWithRoute pm Proxy req mval =
clientWithRoute pm (Proxy :: Proxy api) $ foldRequiredArgument
(Proxy :: Proxy mods) add (maybe req add) mval
where
hname = fromString $ symbolVal (Proxy :: Proxy sym)
add :: a -> Request
add value = addHeader hname value req
hoistClientMonad pm _ f cl = \arg ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl arg)
| Using a ' HttpVersion ' combinator in your API does n't affect the client
-- functions.
instance HasClient m api
=> HasClient m (HttpVersion :> api) where
type Client m (HttpVersion :> api) =
Client m api
clientWithRoute pm Proxy =
clientWithRoute pm (Proxy :: Proxy api)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
-- | Ignore @'Summary'@ in client functions.
instance HasClient m api => HasClient m (Summary desc :> api) where
type Client m (Summary desc :> api) = Client m api
clientWithRoute pm _ = clientWithRoute pm (Proxy :: Proxy api)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
-- | Ignore @'Description'@ in client functions.
instance HasClient m api => HasClient m (Description desc :> api) where
type Client m (Description desc :> api) = Client m api
clientWithRoute pm _ = clientWithRoute pm (Proxy :: Proxy api)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
| If you use a ' QueryParam ' in one of your endpoints in your API ,
-- the corresponding querying function will automatically take
an additional argument of the type specified by your ' QueryParam ' ,
-- enclosed in Maybe.
--
-- If you give Nothing, nothing will be added to the query string.
--
-- If you give a non-'Nothing' value, this function will take care
-- of inserting a textual representation of this value in the query string.
--
-- You can control how values for your type are turned into
text by specifying a ' ToHttpApiData ' instance for your type .
--
-- Example:
--
> type MyApi = " books " :> QueryParam " author " Text :> Get ' [ JSON ] [ Book ]
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
-- > getBooksBy :: Maybe Text -> ClientM [Book]
> getBooksBy = client myApi
-- > -- then you can just use "getBooksBy" to query that endpoint.
-- > -- 'getBooksBy Nothing' for all books
> -- ' getBooksBy ( Just " " ) ' to get all books by
instance (KnownSymbol sym, ToHttpApiData a, HasClient m api, SBoolI (FoldRequired mods))
=> HasClient m (QueryParam' mods sym a :> api) where
type Client m (QueryParam' mods sym a :> api) =
RequiredArgument mods a -> Client m api
-- if mparam = Nothing, we don't add it to the query string
clientWithRoute pm Proxy req mparam =
clientWithRoute pm (Proxy :: Proxy api) $ foldRequiredArgument
(Proxy :: Proxy mods) add (maybe req add) mparam
where
add :: a -> Request
add param = appendToQueryString pname (Just $ encodeQueryParamValue param) req
pname :: Text
pname = pack $ symbolVal (Proxy :: Proxy sym)
hoistClientMonad pm _ f cl = \arg ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl arg)
-- | If you use a 'QueryParams' in one of your endpoints in your API,
-- the corresponding querying function will automatically take
-- an additional argument, a list of values of the type specified
-- by your 'QueryParams'.
--
-- If you give an empty list, nothing will be added to the query string.
--
-- Otherwise, this function will take care
-- of inserting a textual representation of your values in the query string,
-- under the same query string parameter name.
--
-- You can control how values for your type are turned into
text by specifying a ' ToHttpApiData ' instance for your type .
--
-- Example:
--
> type MyApi = " books " :> QueryParams " authors " Text :> Get ' [ JSON ] [ Book ]
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
-- > getBooksBy :: [Text] -> ClientM [Book]
> getBooksBy = client myApi
-- > -- then you can just use "getBooksBy" to query that endpoint.
-- > -- 'getBooksBy []' for all books
> -- ' getBooksBy [ " " , " " ] '
> -- to get all books by and
instance (KnownSymbol sym, ToHttpApiData a, HasClient m api)
=> HasClient m (QueryParams sym a :> api) where
type Client m (QueryParams sym a :> api) =
[a] -> Client m api
clientWithRoute pm Proxy req paramlist =
clientWithRoute pm (Proxy :: Proxy api)
(foldl' (\ req' -> maybe req' (flip (appendToQueryString pname) req' . Just))
req
paramlist'
)
where pname = pack $ symbolVal (Proxy :: Proxy sym)
paramlist' = map (Just . encodeQueryParamValue) paramlist
hoistClientMonad pm _ f cl = \as ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl as)
| If you use a ' QueryFlag ' in one of your endpoints in your API ,
-- the corresponding querying function will automatically take
an additional ' ' argument .
--
-- If you give 'False', nothing will be added to the query string.
--
-- Otherwise, this function will insert a value-less query string
parameter under the name associated to your ' QueryFlag ' .
--
-- Example:
--
> type MyApi = " books " :> QueryFlag " published " :> Get ' [ JSON ] [ Book ]
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
-- > getBooks :: Bool -> ClientM [Book]
> getBooks = client myApi
> -- then you can just use " getBooks " to query that endpoint .
-- > -- 'getBooksBy False' for all books
-- > -- 'getBooksBy True' to only get _already published_ books
instance (KnownSymbol sym, HasClient m api)
=> HasClient m (QueryFlag sym :> api) where
type Client m (QueryFlag sym :> api) =
Bool -> Client m api
clientWithRoute pm Proxy req flag =
clientWithRoute pm (Proxy :: Proxy api)
(if flag
then appendToQueryString paramname Nothing req
else req
)
where paramname = pack $ symbolVal (Proxy :: Proxy sym)
hoistClientMonad pm _ f cl = \b ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl b)
-- | Pick a 'Method' and specify where the server you want to query is. You get
-- back the full `Response`.
instance RunClient m => HasClient m Raw where
type Client m Raw
= H.Method -> m Response
clientWithRoute :: Proxy m -> Proxy Raw -> Request -> Client m Raw
clientWithRoute _pm Proxy req httpMethod = do
runRequest req { requestMethod = httpMethod }
hoistClientMonad _ _ f cl = \meth -> f (cl meth)
instance RunClient m => HasClient m RawM where
type Client m RawM
= H.Method -> m Response
clientWithRoute :: Proxy m -> Proxy RawM -> Request -> Client m RawM
clientWithRoute _pm Proxy req httpMethod = do
runRequest req { requestMethod = httpMethod }
hoistClientMonad _ _ f cl = \meth -> f (cl meth)
-- | If you use a 'ReqBody' in one of your endpoints in your API,
-- the corresponding querying function will automatically take
-- an additional argument of the type specified by your 'ReqBody'.
-- That function will take care of encoding this argument as JSON and
-- of using it as the request body.
--
All you need is for your type to have a ' ToJSON ' instance .
--
-- Example:
--
> type MyApi = " books " :> ReqBody ' [ JSON ] Book :> Post ' [ JSON ] Book
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
-- > addBook :: Book -> ClientM Book
> addBook = client myApi
-- > -- then you can just use "addBook" to query that endpoint
instance (MimeRender ct a, HasClient m api)
=> HasClient m (ReqBody' mods (ct ': cts) a :> api) where
type Client m (ReqBody' mods (ct ': cts) a :> api) =
a -> Client m api
clientWithRoute pm Proxy req body =
clientWithRoute pm (Proxy :: Proxy api)
(let ctProxy = Proxy :: Proxy ct
in setRequestBodyLBS (mimeRender ctProxy body)
-- We use first contentType from the Accept list
(contentType ctProxy)
req
)
hoistClientMonad pm _ f cl = \a ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl a)
instance
( HasClient m api, MimeRender ctype chunk, FramingRender framing, ToSourceIO chunk a
) => HasClient m (StreamBody' mods framing ctype a :> api)
where
type Client m (StreamBody' mods framing ctype a :> api) = a -> Client m api
hoistClientMonad pm _ f cl = \a ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl a)
clientWithRoute pm Proxy req body
= clientWithRoute pm (Proxy :: Proxy api)
$ setRequestBody (RequestBodySource sourceIO) (contentType ctypeP) req
where
ctypeP = Proxy :: Proxy ctype
framingP = Proxy :: Proxy framing
sourceIO = framingRender
framingP
(mimeRender ctypeP :: chunk -> BL.ByteString)
(toSourceIO body)
-- | Make the querying function append @path@ to the request path.
instance (KnownSymbol path, HasClient m api) => HasClient m (path :> api) where
type Client m (path :> api) = Client m api
clientWithRoute pm Proxy req =
clientWithRoute pm (Proxy :: Proxy api)
(appendToPath p req)
where p = toEncodedUrlPiece $ pack $ symbolVal (Proxy :: Proxy path)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
instance HasClient m api => HasClient m (Vault :> api) where
type Client m (Vault :> api) = Client m api
clientWithRoute pm Proxy req =
clientWithRoute pm (Proxy :: Proxy api) req
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
instance HasClient m api => HasClient m (RemoteHost :> api) where
type Client m (RemoteHost :> api) = Client m api
clientWithRoute pm Proxy req =
clientWithRoute pm (Proxy :: Proxy api) req
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
instance HasClient m api => HasClient m (IsSecure :> api) where
type Client m (IsSecure :> api) = Client m api
clientWithRoute pm Proxy req =
clientWithRoute pm (Proxy :: Proxy api) req
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
instance HasClient m subapi =>
HasClient m (WithNamedContext name context subapi) where
type Client m (WithNamedContext name context subapi) = Client m subapi
clientWithRoute pm Proxy = clientWithRoute pm (Proxy :: Proxy subapi)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy subapi) f cl
instance HasClient m subapi =>
HasClient m (WithResource res :> subapi) where
type Client m (WithResource res :> subapi) = Client m subapi
clientWithRoute pm Proxy = clientWithRoute pm (Proxy :: Proxy subapi)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy subapi) f cl
instance ( HasClient m api
) => HasClient m (AuthProtect tag :> api) where
type Client m (AuthProtect tag :> api)
= AuthenticatedRequest (AuthProtect tag) -> Client m api
clientWithRoute pm Proxy req (AuthenticatedRequest (val,func)) =
clientWithRoute pm (Proxy :: Proxy api) (func val req)
hoistClientMonad pm _ f cl = \authreq ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl authreq)
-- | Ignore @'Fragment'@ in client functions.
-- See <#section-15.1.3> for more details.
--
-- Example:
--
> type MyApi = " books " :> Fragment Text :> Get ' [ JSON ] [ Book ]
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
-- > getBooks :: ClientM [Book]
> getBooks = client myApi
-- > -- then you can just use "getBooksBy" to query that endpoint.
> -- ' getBooks ' for all books .
instance (AtLeastOneFragment api, FragmentUnique (Fragment a :> api), HasClient m api
) => HasClient m (Fragment a :> api) where
type Client m (Fragment a :> api) = Client m api
clientWithRoute pm _ = clientWithRoute pm (Proxy :: Proxy api)
hoistClientMonad pm _ = hoistClientMonad pm (Proxy :: Proxy api)
-- * Basic Authentication
instance HasClient m api => HasClient m (BasicAuth realm usr :> api) where
type Client m (BasicAuth realm usr :> api) = BasicAuthData -> Client m api
clientWithRoute pm Proxy req val =
clientWithRoute pm (Proxy :: Proxy api) (basicAuthReq val req)
hoistClientMonad pm _ f cl = \bauth ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl bauth)
-- | A type that specifies that an API record contains a client implementation.
data AsClientT (m :: * -> *)
instance GenericMode (AsClientT m) where
type AsClientT m :- api = Client m api
type GClientConstraints api m =
( GenericServant api (AsClientT m)
, Client m (ToServantApi api) ~ ToServant api (AsClientT m)
)
class GClient (api :: * -> *) m where
gClientProof :: Dict (GClientConstraints api m)
instance GClientConstraints api m => GClient api m where
gClientProof = Dict
instance
( forall n. GClient api n
, HasClient m (ToServantApi api)
, RunClient m
)
=> HasClient m (NamedRoutes api) where
type Client m (NamedRoutes api) = api (AsClientT m)
clientWithRoute :: Proxy m -> Proxy (NamedRoutes api) -> Request -> Client m (NamedRoutes api)
clientWithRoute pm _ request =
case gClientProof @api @m of
Dict -> fromServant $ clientWithRoute pm (Proxy @(ToServantApi api)) request
hoistClientMonad
:: forall ma mb.
Proxy m
-> Proxy (NamedRoutes api)
-> (forall x. ma x -> mb x)
-> Client ma (NamedRoutes api)
-> Client mb (NamedRoutes api)
hoistClientMonad _ _ nat clientA =
case (gClientProof @api @ma, gClientProof @api @mb) of
(Dict, Dict) ->
fromServant @api @(AsClientT mb) $
hoistClientMonad @m @(ToServantApi api) @ma @mb Proxy Proxy nat $
toServant @api @(AsClientT ma) clientA
infixl 1 //
infixl 2 /:
-- | Helper to make code using records of clients more readable.
--
-- Can be mixed with (/:) for supplying arguments.
--
-- Example:
--
-- @
type Api = NamedRoutes RootApi
--
-- data RootApi mode = RootApi
-- { subApi :: mode :- NamedRoutes SubApi
-- , …
} deriving Generic
--
data SubApi mode = SubApi
-- { endpoint :: mode :- Get '[JSON] Person
-- , …
} deriving Generic
--
-- api :: Proxy API
-- api = Proxy
--
rootClient : : ( AsClientT ClientM )
-- rootClient = client api
--
-- endpointClient :: ClientM Person
-- endpointClient = client \/\/ subApi \/\/ endpoint
-- @
(//) :: a -> (a -> b) -> b
x // f = f x
-- | Convenience function for supplying arguments to client functions when
-- working with records of clients.
--
-- Intended to be used in conjunction with '(//)'.
--
-- Example:
--
-- @
type Api = NamedRoutes RootApi
--
-- data RootApi mode = RootApi
-- { subApi :: mode :- Capture "token" String :> NamedRoutes SubApi
, hello : : mode : - Capture " name " String :> Get ' [ JSON ] String
-- , …
} deriving Generic
--
data SubApi mode = SubApi
-- { endpoint :: mode :- Get '[JSON] Person
-- , …
} deriving Generic
--
-- api :: Proxy API
-- api = Proxy
--
rootClient : : ( AsClientT ClientM )
-- rootClient = client api
--
-- hello :: String -> ClientM String
hello name = rootClient \/\/ hello \/ : name
--
-- endpointClient :: ClientM Person
endpointClient = client \/\/ subApi \/ : " foobar123 " \/\/ endpoint
-- @
(/:) :: (a -> b -> c) -> b -> a -> c
(/:) = flip
Note [ Non - Empty Content Types ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Rather than have
instance ( ... , cts ' ~ ( ct ' : cts ) ) = > ... cts ' ...
It may seem to make more sense to have :
instance ( ... ) = > ... ( ct ' : cts ) ...
But this means that if another instance exists that does * not * require
non - empty lists , but is otherwise more specific , no instance will be overall
more specific . This in turn generally means adding yet another instance ( one
for empty and one for non - empty lists ) .
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Rather than have
instance (..., cts' ~ (ct ': cts)) => ... cts' ...
It may seem to make more sense to have:
instance (...) => ... (ct ': cts) ...
But this means that if another instance exists that does *not* require
non-empty lists, but is otherwise more specific, no instance will be overall
more specific. This in turn generally means adding yet another instance (one
for empty and one for non-empty lists).
-}
-------------------------------------------------------------------------------
-- helpers
-------------------------------------------------------------------------------
checkContentTypeHeader :: RunClient m => Response -> m MediaType
checkContentTypeHeader response =
case lookup "Content-Type" $ toList $ responseHeaders response of
Nothing -> return $ "application" Media.// "octet-stream"
Just t -> case parseAccept t of
Nothing -> throwClientError $ InvalidContentTypeHeader response
Just t' -> return t'
decodedAs :: forall ct a m. (MimeUnrender ct a, RunClient m)
=> Response -> Proxy ct -> m a
decodedAs response ct = do
responseContentType <- checkContentTypeHeader response
unless (any (matches responseContentType) accept) $
throwClientError $ UnsupportedContentType responseContentType response
case mimeUnrender ct $ responseBody response of
Left err -> throwClientError $ DecodeFailure (T.pack err) response
Right val -> return val
where
accept = toList $ contentTypes ct
-------------------------------------------------------------------------------
-- Custom type errors
-------------------------------------------------------------------------------
Erroring instance for ' when a combinator is not fully applied
instance (RunClient m, TypeError (PartialApplication HasClient arr)) => HasClient m ((arr :: a -> b) :> sub)
where
type Client m (arr :> sub) = TypeError (PartialApplication HasClient arr)
clientWithRoute _ _ _ = error "unreachable"
hoistClientMonad _ _ _ _ = error "unreachable"
Erroring instances for ' ' for unknown API combinators
instance {-# OVERLAPPABLE #-} (RunClient m, TypeError (NoInstanceForSub (HasClient m) ty)) => HasClient m (ty :> sub)
instance {-# OVERLAPPABLE #-} (RunClient m, TypeError (NoInstanceFor (HasClient m api))) => HasClient m api
| null | https://raw.githubusercontent.com/haskell-servant/servant/ea87e9780847561ad7c082165a1c8b89ea830a32/servant-client-core/src/Servant/Client/Core/HasClient.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
* Accessing APIs as a Client
GET /books
> :<|> "books" :> ReqBody '[JSON] Book :> Post '[JSON] Book -- POST /books
>
> myApi :: Proxy MyApi
> myApi = Proxy
>
> clientM = Proxy
>
> getAllBooks :: ClientM [Book]
> postNewBook :: Book -> ClientM Book
| This class lets us define how each API combinator influences the creation
of an HTTP request.
combinators that you want to support client-generation, you can ignore this
class.
stitching them together with ':<|>', which really is just like a pair.
GET /books
> :<|> "books" :> ReqBody '[JSON] Book :> Post Book -- POST /books
>
> myApi :: Proxy MyApi
> myApi = Proxy
>
> getAllBooks :: ClientM [Book]
> postNewBook :: Book -> ClientM Book
| Singleton type representing a client for an empty API.
GET /books
>
> myApi :: Proxy MyApi
> myApi = Proxy
>
> getAllBooks :: ClientM [Book]
| If you use a 'Capture' in one of your endpoints in your API,
the corresponding querying function will automatically take
an additional argument of the type specified by your 'Capture'.
That function will take care of inserting a textual representation
of this value at the right place in the request path.
You can control how values for this type are turned into
Example:
>
> myApi :: Proxy MyApi
> myApi = Proxy
>
> getBook :: Text -> ClientM Book
> -- then you can just use "getBook" to query that endpoint
the corresponding querying function will automatically take an
additional argument of a list of the type specified by your
representation of this value at the right place in the request
path.
You can control how these values are turned into text by specifying
Example:
>
> myApi :: Proxy
> myApi = Proxy
> getSourceFile :: [Text] -> ClientM SourceFile
> -- then you can use "getSourceFile" to query that endpoint
# OVERLAPPABLE #
Note [Non-Empty Content Types]
# OVERLAPPING #
# OVERLAPPING #
Note [Non-Empty Content Types]
# OVERLAPPING #
# OVERLAPPABLE #
# OVERLAPPING #
# OVERLAPPING #
# OVERLAPPING #
('otherContentTypes' should be '_', but even -XPartialTypeSignatures does not seem
allow this in instance types as of 8.8.3.)
offering to accept all mime types listed in the api gives best compatibility. eg.,
we might not own the server implementation, and the server may choose to support
only part of the api.
failures it encountered along the way
| Given a list of types, parses the given response body as each type
# OVERLAPPABLE #
# OVERLAPPING #
| If you use a 'Header' in one of your endpoints in your API,
the corresponding querying function will automatically take
an additional argument of the type specified by your 'Header',
wrapped in Maybe.
That function will take care of encoding this argument as Text
in the request headers.
Example:
>
> -- GET /view-my-referer
>
> myApi :: Proxy MyApi
> myApi = Proxy
>
then you can just use " viewRefer " to query that endpoint
> -- specifying Nothing or e.g Just "/" as arguments
functions.
| Ignore @'Summary'@ in client functions.
| Ignore @'Description'@ in client functions.
the corresponding querying function will automatically take
enclosed in Maybe.
If you give Nothing, nothing will be added to the query string.
If you give a non-'Nothing' value, this function will take care
of inserting a textual representation of this value in the query string.
You can control how values for your type are turned into
Example:
>
> myApi :: Proxy MyApi
> myApi = Proxy
>
> getBooksBy :: Maybe Text -> ClientM [Book]
> -- then you can just use "getBooksBy" to query that endpoint.
> -- 'getBooksBy Nothing' for all books
' getBooksBy ( Just " " ) ' to get all books by
if mparam = Nothing, we don't add it to the query string
| If you use a 'QueryParams' in one of your endpoints in your API,
the corresponding querying function will automatically take
an additional argument, a list of values of the type specified
by your 'QueryParams'.
If you give an empty list, nothing will be added to the query string.
Otherwise, this function will take care
of inserting a textual representation of your values in the query string,
under the same query string parameter name.
You can control how values for your type are turned into
Example:
>
> myApi :: Proxy MyApi
> myApi = Proxy
>
> getBooksBy :: [Text] -> ClientM [Book]
> -- then you can just use "getBooksBy" to query that endpoint.
> -- 'getBooksBy []' for all books
' getBooksBy [ " " , " " ] '
to get all books by and
the corresponding querying function will automatically take
If you give 'False', nothing will be added to the query string.
Otherwise, this function will insert a value-less query string
Example:
>
> myApi :: Proxy MyApi
> myApi = Proxy
>
> getBooks :: Bool -> ClientM [Book]
then you can just use " getBooks " to query that endpoint .
> -- 'getBooksBy False' for all books
> -- 'getBooksBy True' to only get _already published_ books
| Pick a 'Method' and specify where the server you want to query is. You get
back the full `Response`.
| If you use a 'ReqBody' in one of your endpoints in your API,
the corresponding querying function will automatically take
an additional argument of the type specified by your 'ReqBody'.
That function will take care of encoding this argument as JSON and
of using it as the request body.
Example:
>
> myApi :: Proxy MyApi
> myApi = Proxy
>
> addBook :: Book -> ClientM Book
> -- then you can just use "addBook" to query that endpoint
We use first contentType from the Accept list
| Make the querying function append @path@ to the request path.
| Ignore @'Fragment'@ in client functions.
See <#section-15.1.3> for more details.
Example:
>
> myApi :: Proxy MyApi
> myApi = Proxy
>
> getBooks :: ClientM [Book]
> -- then you can just use "getBooksBy" to query that endpoint.
' getBooks ' for all books .
* Basic Authentication
| A type that specifies that an API record contains a client implementation.
| Helper to make code using records of clients more readable.
Can be mixed with (/:) for supplying arguments.
Example:
@
data RootApi mode = RootApi
{ subApi :: mode :- NamedRoutes SubApi
, …
{ endpoint :: mode :- Get '[JSON] Person
, …
api :: Proxy API
api = Proxy
rootClient = client api
endpointClient :: ClientM Person
endpointClient = client \/\/ subApi \/\/ endpoint
@
| Convenience function for supplying arguments to client functions when
working with records of clients.
Intended to be used in conjunction with '(//)'.
Example:
@
data RootApi mode = RootApi
{ subApi :: mode :- Capture "token" String :> NamedRoutes SubApi
, …
{ endpoint :: mode :- Get '[JSON] Person
, …
api :: Proxy API
api = Proxy
rootClient = client api
hello :: String -> ClientM String
endpointClient :: ClientM Person
@
-----------------------------------------------------------------------------
helpers
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Custom type errors
-----------------------------------------------------------------------------
# OVERLAPPABLE #
# OVERLAPPABLE # | # LANGUAGE FlexibleInstances #
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE PolyKinds #
# LANGUAGE QuantifiedConstraints #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Servant.Client.Core.HasClient (
clientIn,
HasClient (..),
EmptyClient (..),
AsClientT,
(//),
(/:),
foldMapUnion,
matchUnion,
) where
import Prelude ()
import Prelude.Compat
import Control.Arrow
(left, (+++))
import Control.Monad
(unless)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import Data.Either
(partitionEithers)
import Data.Constraint (Dict(..))
import Data.Foldable
(toList)
import Data.List
(foldl')
import Data.Sequence
(fromList)
import qualified Data.Text as T
import Network.HTTP.Media
(MediaType, matches, parseAccept)
import qualified Network.HTTP.Media as Media
import qualified Data.Sequence as Seq
import Data.SOP.BasicFunctors
(I (I), (:.:) (Comp))
import Data.SOP.Constraint
(All)
import Data.SOP.NP
(NP (..), cpure_NP)
import Data.SOP.NS
(NS (S))
import Data.String
(fromString)
import Data.Text
(Text, pack)
import Data.Proxy
(Proxy (Proxy))
import GHC.TypeLits
(KnownNat, KnownSymbol, TypeError, symbolVal)
import Network.HTTP.Types
(Status)
import qualified Network.HTTP.Types as H
import Servant.API
((:<|>) ((:<|>)), (:>), AuthProtect, BasicAuth, BasicAuthData,
BuildHeadersTo (..), Capture', CaptureAll, Description,
EmptyAPI, Fragment, FramingRender (..), FramingUnrender (..),
FromSourceIO (..), Header', Headers (..), HttpVersion,
IsSecure, MimeRender (mimeRender),
MimeUnrender (mimeUnrender), NoContent (NoContent),
NoContentVerb, QueryFlag, QueryParam', QueryParams, Raw, RawM,
ReflectMethod (..), RemoteHost, ReqBody', SBoolI, Stream,
StreamBody', Summary, ToHttpApiData, ToSourceIO (..), Vault,
Verb, WithNamedContext, WithResource, WithStatus (..), contentType, getHeadersHList,
getResponse, toEncodedUrlPiece, toUrlPiece, NamedRoutes)
import Servant.API.Generic
(GenericMode(..), ToServant, ToServantApi
, GenericServant, toServant, fromServant)
import Servant.API.ContentTypes
(contentTypes, AllMime (allMime), AllMimeUnrender (allMimeUnrender))
import Servant.API.Status
(statusFromNat)
import Servant.API.TypeLevel (FragmentUnique, AtLeastOneFragment)
import Servant.API.Modifiers
(FoldRequired, RequiredArgument, foldRequiredArgument)
import Servant.API.TypeErrors
import Servant.API.UVerb
(HasStatus, HasStatuses (Statuses, statuses), UVerb, Union, Unique, inject, statusOf, foldMapUnion, matchUnion)
import Servant.Client.Core.Auth
import Servant.Client.Core.BasicAuth
import Servant.Client.Core.ClientError
import Servant.Client.Core.Request
import Servant.Client.Core.Response
import Servant.Client.Core.RunClient
| ' clientIn ' allows you to produce operations to query an API from a client
within a ' ' monad .
> clientM : : Proxy ClientM
> ( getAllBooks : < | > postNewBook ) = myApi ` clientIn ` clientM
clientIn :: HasClient m api => Proxy api -> Proxy m -> Client m api
clientIn p pm = clientWithRoute pm p defaultRequest
Unless you are writing a new backend for @servant - client - core@ or new
class RunClient m => HasClient m api where
type Client (m :: * -> *) (api :: *) :: *
clientWithRoute :: Proxy m -> Proxy api -> Request -> Client m api
hoistClientMonad
:: Proxy m
-> Proxy api
-> (forall x. mon x -> mon' x)
-> Client mon api
-> Client mon' api
| A client querying function for @a ' : < | > ' b@ will actually hand you
one function for querying @a@ and another one for querying @b@ ,
> ( getAllBooks : < | > postNewBook ) = client myApi
instance (HasClient m a, HasClient m b) => HasClient m (a :<|> b) where
type Client m (a :<|> b) = Client m a :<|> Client m b
clientWithRoute pm Proxy req =
clientWithRoute pm (Proxy :: Proxy a) req :<|>
clientWithRoute pm (Proxy :: Proxy b) req
hoistClientMonad pm _ f (ca :<|> cb) =
hoistClientMonad pm (Proxy :: Proxy a) f ca :<|>
hoistClientMonad pm (Proxy :: Proxy b) f cb
data EmptyClient = EmptyClient deriving (Eq, Show, Bounded, Enum)
| The client for ' EmptyAPI ' is simply ' EmptyClient ' .
> : < | > " nothing " :> EmptyAPI
> ( getAllBooks : < | > EmptyClient ) = client myApi
instance RunClient m => HasClient m EmptyAPI where
type Client m EmptyAPI = EmptyClient
clientWithRoute _pm Proxy _ = EmptyClient
hoistClientMonad _ _ _ EmptyClient = EmptyClient
text by specifying a ' ToHttpApiData ' instance for your type .
> type MyApi = " books " :> Capture " isbn " Text :> Get ' [ JSON ] Book
> getBook = client myApi
instance (KnownSymbol capture, ToHttpApiData a, HasClient m api)
=> HasClient m (Capture' mods capture a :> api) where
type Client m (Capture' mods capture a :> api) =
a -> Client m api
clientWithRoute pm Proxy req val =
clientWithRoute pm (Proxy :: Proxy api)
(appendToPath p req)
where p = toEncodedUrlPiece val
hoistClientMonad pm _ f cl = \a ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl a)
| If you use a ' CaptureAll ' in one of your endpoints in your API ,
' CaptureAll ' . That function will take care of inserting a textual
a ' ToHttpApiData ' instance of your type .
> type MyAPI = " src " :> CaptureAll Text - > Get ' [ JSON ] SourceFile
> getSourceFile = client myApi
instance (KnownSymbol capture, ToHttpApiData a, HasClient m sublayout)
=> HasClient m (CaptureAll capture a :> sublayout) where
type Client m (CaptureAll capture a :> sublayout) =
[a] -> Client m sublayout
clientWithRoute pm Proxy req vals =
clientWithRoute pm (Proxy :: Proxy sublayout)
(foldl' (flip appendToPath) req ps)
where ps = map toEncodedUrlPiece vals
hoistClientMonad pm _ f cl = \as ->
hoistClientMonad pm (Proxy :: Proxy sublayout) f (cl as)
( RunClient m, MimeUnrender ct a, ReflectMethod method, cts' ~ (ct ': cts)
, KnownNat status
) => HasClient m (Verb method status cts' a) where
type Client m (Verb method status cts' a) = m a
clientWithRoute _pm Proxy req = do
response <- runRequestAcceptStatus (Just [status]) req
{ requestAccept = fromList $ toList accept
, requestMethod = method
}
response `decodedAs` (Proxy :: Proxy ct)
where
accept = contentTypes (Proxy :: Proxy ct)
method = reflectMethod (Proxy :: Proxy method)
status = statusFromNat (Proxy :: Proxy status)
hoistClientMonad _ _ f ma = f ma
( RunClient m, ReflectMethod method, KnownNat status
) => HasClient m (Verb method status cts NoContent) where
type Client m (Verb method status cts NoContent)
= m NoContent
clientWithRoute _pm Proxy req = do
_response <- runRequestAcceptStatus (Just [status]) req { requestMethod = method }
return NoContent
where method = reflectMethod (Proxy :: Proxy method)
status = statusFromNat (Proxy :: Proxy status)
hoistClientMonad _ _ f ma = f ma
instance (RunClient m, ReflectMethod method) =>
HasClient m (NoContentVerb method) where
type Client m (NoContentVerb method)
= m NoContent
clientWithRoute _pm Proxy req = do
_response <- runRequest req { requestMethod = method }
return NoContent
where method = reflectMethod (Proxy :: Proxy method)
hoistClientMonad _ _ f ma = f ma
( RunClient m, MimeUnrender ct a, BuildHeadersTo ls, KnownNat status
, ReflectMethod method, cts' ~ (ct ': cts)
) => HasClient m (Verb method status cts' (Headers ls a)) where
type Client m (Verb method status cts' (Headers ls a))
= m (Headers ls a)
clientWithRoute _pm Proxy req = do
response <- runRequestAcceptStatus (Just [status]) req
{ requestMethod = method
, requestAccept = fromList $ toList accept
}
val <- response `decodedAs` (Proxy :: Proxy ct)
return $ Headers { getResponse = val
, getHeadersHList = buildHeadersTo . toList $ responseHeaders response
}
where
method = reflectMethod (Proxy :: Proxy method)
accept = contentTypes (Proxy :: Proxy ct)
status = statusFromNat (Proxy :: Proxy status)
hoistClientMonad _ _ f ma = f ma
( RunClient m, BuildHeadersTo ls, ReflectMethod method, KnownNat status
) => HasClient m (Verb method status cts (Headers ls NoContent)) where
type Client m (Verb method status cts (Headers ls NoContent))
= m (Headers ls NoContent)
clientWithRoute _pm Proxy req = do
response <- runRequestAcceptStatus (Just [status]) req { requestMethod = method }
return $ Headers { getResponse = NoContent
, getHeadersHList = buildHeadersTo . toList $ responseHeaders response
}
where
method = reflectMethod (Proxy :: Proxy method)
status = statusFromNat (Proxy :: Proxy status)
hoistClientMonad _ _ f ma = f ma
data ClientParseError = ClientParseError MediaType String | ClientStatusMismatch | ClientNoMatchingStatus
deriving (Eq, Show)
class UnrenderResponse (cts :: [*]) (a :: *) where
unrenderResponse :: Seq.Seq H.Header -> BL.ByteString -> Proxy cts
-> [Either (MediaType, String) a]
unrenderResponse _ body = map parse . allMimeUnrender
where parse (mediaType, parser) = left ((,) mediaType) (parser body)
=> UnrenderResponse cts (Headers h a) where
unrenderResponse hs body = (map . fmap) setHeaders . unrenderResponse hs body
where
setHeaders :: a -> Headers h a
setHeaders x = Headers x (buildHeadersTo (toList hs))
=> UnrenderResponse cts (WithStatus n a) where
unrenderResponse hs body = (map . fmap) WithStatus . unrenderResponse hs body
( RunClient m,
contentTypes ~ (contentType ': otherContentTypes),
as ~ (a ': as'),
AllMime contentTypes,
ReflectMethod method,
All (UnrenderResponse contentTypes) as,
All HasStatus as, HasStatuses as',
Unique (Statuses as)
) =>
HasClient m (UVerb method contentTypes as)
where
type Client m (UVerb method contentTypes as) = m (Union as)
clientWithRoute _ _ request = do
let accept = Seq.fromList . allMime $ Proxy @contentTypes
method = reflectMethod $ Proxy @method
acceptStatus = statuses (Proxy @as)
response <- runRequestAcceptStatus (Just acceptStatus) request {requestMethod = method, requestAccept = accept}
responseContentType <- checkContentTypeHeader response
unless (any (matches responseContentType) accept) $ do
throwClientError $ UnsupportedContentType responseContentType response
let status = responseStatusCode response
body = responseBody response
headers = responseHeaders response
res = tryParsers status $ mimeUnrenders (Proxy @contentTypes) headers body
case res of
Left errors -> throwClientError $ DecodeFailure (T.pack (show errors)) response
Right x -> return x
where
| Given a list of parsers of ' mkres ' , returns the first one that succeeds and all the
TODO ; better name , rewrite .
tryParsers :: forall xs. All HasStatus xs => Status -> NP ([] :.: Either (MediaType, String)) xs -> Either [ClientParseError] (Union xs)
tryParsers _ Nil = Left [ClientNoMatchingStatus]
tryParsers status (Comp x :* xs)
| status == statusOf (Comp x) =
case partitionEithers x of
(err', []) -> (map (uncurry ClientParseError) err' ++) +++ S $ tryParsers status xs
(_, (res : _)) -> Right . inject . I $ res
no reason to parse in the first place . This ai n't the one we 're looking for
(ClientStatusMismatch :) +++ S $ tryParsers status xs
mimeUnrenders ::
forall cts xs.
All (UnrenderResponse cts) xs =>
Proxy cts ->
Seq.Seq H.Header ->
BL.ByteString ->
NP ([] :.: Either (MediaType, String)) xs
mimeUnrenders ctp headers body = cpure_NP
(Proxy @(UnrenderResponse cts))
(Comp . unrenderResponse headers body $ ctp)
hoistClientMonad _ _ nt s = nt s
( RunStreamingClient m, MimeUnrender ct chunk, ReflectMethod method,
FramingUnrender framing, FromSourceIO chunk a
) => HasClient m (Stream method status framing ct a) where
type Client m (Stream method status framing ct a) = m a
hoistClientMonad _ _ f ma = f ma
clientWithRoute _pm Proxy req = withStreamingRequest req' $ \gres -> do
let mimeUnrender' = mimeUnrender (Proxy :: Proxy ct) :: BL.ByteString -> Either String chunk
framingUnrender' = framingUnrender (Proxy :: Proxy framing) mimeUnrender'
return $ fromSourceIO $ framingUnrender' $ responseBody gres
where
req' = req
{ requestAccept = fromList [contentType (Proxy :: Proxy ct)]
, requestMethod = reflectMethod (Proxy :: Proxy method)
}
( RunStreamingClient m, MimeUnrender ct chunk, ReflectMethod method,
FramingUnrender framing, FromSourceIO chunk a,
BuildHeadersTo hs
) => HasClient m (Stream method status framing ct (Headers hs a)) where
type Client m (Stream method status framing ct (Headers hs a)) = m (Headers hs a)
hoistClientMonad _ _ f ma = f ma
clientWithRoute _pm Proxy req = withStreamingRequest req' $ \gres -> do
let mimeUnrender' = mimeUnrender (Proxy :: Proxy ct) :: BL.ByteString -> Either String chunk
framingUnrender' = framingUnrender (Proxy :: Proxy framing) mimeUnrender'
val = fromSourceIO $ framingUnrender' $ responseBody gres
return $ Headers
{ getResponse = val
, getHeadersHList = buildHeadersTo . toList $ responseHeaders gres
}
where
req' = req
{ requestAccept = fromList [contentType (Proxy :: Proxy ct)]
, requestMethod = reflectMethod (Proxy :: Proxy method)
}
All you need is for your type to have a ' ToHttpApiData ' instance .
> newtype referrer : : Text }
> deriving ( Eq , Show , Generic , ToHttpApiData )
> type MyApi = " view - my - referer " :> Header " Referer " Referer :> Get ' [ JSON ]
> viewReferer : : Maybe ClientM Book
> = client myApi
instance (KnownSymbol sym, ToHttpApiData a, HasClient m api, SBoolI (FoldRequired mods))
=> HasClient m (Header' mods sym a :> api) where
type Client m (Header' mods sym a :> api) =
RequiredArgument mods a -> Client m api
clientWithRoute pm Proxy req mval =
clientWithRoute pm (Proxy :: Proxy api) $ foldRequiredArgument
(Proxy :: Proxy mods) add (maybe req add) mval
where
hname = fromString $ symbolVal (Proxy :: Proxy sym)
add :: a -> Request
add value = addHeader hname value req
hoistClientMonad pm _ f cl = \arg ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl arg)
| Using a ' HttpVersion ' combinator in your API does n't affect the client
instance HasClient m api
=> HasClient m (HttpVersion :> api) where
type Client m (HttpVersion :> api) =
Client m api
clientWithRoute pm Proxy =
clientWithRoute pm (Proxy :: Proxy api)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
instance HasClient m api => HasClient m (Summary desc :> api) where
type Client m (Summary desc :> api) = Client m api
clientWithRoute pm _ = clientWithRoute pm (Proxy :: Proxy api)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
instance HasClient m api => HasClient m (Description desc :> api) where
type Client m (Description desc :> api) = Client m api
clientWithRoute pm _ = clientWithRoute pm (Proxy :: Proxy api)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
| If you use a ' QueryParam ' in one of your endpoints in your API ,
an additional argument of the type specified by your ' QueryParam ' ,
text by specifying a ' ToHttpApiData ' instance for your type .
> type MyApi = " books " :> QueryParam " author " Text :> Get ' [ JSON ] [ Book ]
> getBooksBy = client myApi
instance (KnownSymbol sym, ToHttpApiData a, HasClient m api, SBoolI (FoldRequired mods))
=> HasClient m (QueryParam' mods sym a :> api) where
type Client m (QueryParam' mods sym a :> api) =
RequiredArgument mods a -> Client m api
clientWithRoute pm Proxy req mparam =
clientWithRoute pm (Proxy :: Proxy api) $ foldRequiredArgument
(Proxy :: Proxy mods) add (maybe req add) mparam
where
add :: a -> Request
add param = appendToQueryString pname (Just $ encodeQueryParamValue param) req
pname :: Text
pname = pack $ symbolVal (Proxy :: Proxy sym)
hoistClientMonad pm _ f cl = \arg ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl arg)
text by specifying a ' ToHttpApiData ' instance for your type .
> type MyApi = " books " :> QueryParams " authors " Text :> Get ' [ JSON ] [ Book ]
> getBooksBy = client myApi
instance (KnownSymbol sym, ToHttpApiData a, HasClient m api)
=> HasClient m (QueryParams sym a :> api) where
type Client m (QueryParams sym a :> api) =
[a] -> Client m api
clientWithRoute pm Proxy req paramlist =
clientWithRoute pm (Proxy :: Proxy api)
(foldl' (\ req' -> maybe req' (flip (appendToQueryString pname) req' . Just))
req
paramlist'
)
where pname = pack $ symbolVal (Proxy :: Proxy sym)
paramlist' = map (Just . encodeQueryParamValue) paramlist
hoistClientMonad pm _ f cl = \as ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl as)
| If you use a ' QueryFlag ' in one of your endpoints in your API ,
an additional ' ' argument .
parameter under the name associated to your ' QueryFlag ' .
> type MyApi = " books " :> QueryFlag " published " :> Get ' [ JSON ] [ Book ]
> getBooks = client myApi
instance (KnownSymbol sym, HasClient m api)
=> HasClient m (QueryFlag sym :> api) where
type Client m (QueryFlag sym :> api) =
Bool -> Client m api
clientWithRoute pm Proxy req flag =
clientWithRoute pm (Proxy :: Proxy api)
(if flag
then appendToQueryString paramname Nothing req
else req
)
where paramname = pack $ symbolVal (Proxy :: Proxy sym)
hoistClientMonad pm _ f cl = \b ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl b)
instance RunClient m => HasClient m Raw where
type Client m Raw
= H.Method -> m Response
clientWithRoute :: Proxy m -> Proxy Raw -> Request -> Client m Raw
clientWithRoute _pm Proxy req httpMethod = do
runRequest req { requestMethod = httpMethod }
hoistClientMonad _ _ f cl = \meth -> f (cl meth)
instance RunClient m => HasClient m RawM where
type Client m RawM
= H.Method -> m Response
clientWithRoute :: Proxy m -> Proxy RawM -> Request -> Client m RawM
clientWithRoute _pm Proxy req httpMethod = do
runRequest req { requestMethod = httpMethod }
hoistClientMonad _ _ f cl = \meth -> f (cl meth)
All you need is for your type to have a ' ToJSON ' instance .
> type MyApi = " books " :> ReqBody ' [ JSON ] Book :> Post ' [ JSON ] Book
> addBook = client myApi
instance (MimeRender ct a, HasClient m api)
=> HasClient m (ReqBody' mods (ct ': cts) a :> api) where
type Client m (ReqBody' mods (ct ': cts) a :> api) =
a -> Client m api
clientWithRoute pm Proxy req body =
clientWithRoute pm (Proxy :: Proxy api)
(let ctProxy = Proxy :: Proxy ct
in setRequestBodyLBS (mimeRender ctProxy body)
(contentType ctProxy)
req
)
hoistClientMonad pm _ f cl = \a ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl a)
instance
( HasClient m api, MimeRender ctype chunk, FramingRender framing, ToSourceIO chunk a
) => HasClient m (StreamBody' mods framing ctype a :> api)
where
type Client m (StreamBody' mods framing ctype a :> api) = a -> Client m api
hoistClientMonad pm _ f cl = \a ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl a)
clientWithRoute pm Proxy req body
= clientWithRoute pm (Proxy :: Proxy api)
$ setRequestBody (RequestBodySource sourceIO) (contentType ctypeP) req
where
ctypeP = Proxy :: Proxy ctype
framingP = Proxy :: Proxy framing
sourceIO = framingRender
framingP
(mimeRender ctypeP :: chunk -> BL.ByteString)
(toSourceIO body)
instance (KnownSymbol path, HasClient m api) => HasClient m (path :> api) where
type Client m (path :> api) = Client m api
clientWithRoute pm Proxy req =
clientWithRoute pm (Proxy :: Proxy api)
(appendToPath p req)
where p = toEncodedUrlPiece $ pack $ symbolVal (Proxy :: Proxy path)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
instance HasClient m api => HasClient m (Vault :> api) where
type Client m (Vault :> api) = Client m api
clientWithRoute pm Proxy req =
clientWithRoute pm (Proxy :: Proxy api) req
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
instance HasClient m api => HasClient m (RemoteHost :> api) where
type Client m (RemoteHost :> api) = Client m api
clientWithRoute pm Proxy req =
clientWithRoute pm (Proxy :: Proxy api) req
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
instance HasClient m api => HasClient m (IsSecure :> api) where
type Client m (IsSecure :> api) = Client m api
clientWithRoute pm Proxy req =
clientWithRoute pm (Proxy :: Proxy api) req
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy api) f cl
instance HasClient m subapi =>
HasClient m (WithNamedContext name context subapi) where
type Client m (WithNamedContext name context subapi) = Client m subapi
clientWithRoute pm Proxy = clientWithRoute pm (Proxy :: Proxy subapi)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy subapi) f cl
instance HasClient m subapi =>
HasClient m (WithResource res :> subapi) where
type Client m (WithResource res :> subapi) = Client m subapi
clientWithRoute pm Proxy = clientWithRoute pm (Proxy :: Proxy subapi)
hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy :: Proxy subapi) f cl
instance ( HasClient m api
) => HasClient m (AuthProtect tag :> api) where
type Client m (AuthProtect tag :> api)
= AuthenticatedRequest (AuthProtect tag) -> Client m api
clientWithRoute pm Proxy req (AuthenticatedRequest (val,func)) =
clientWithRoute pm (Proxy :: Proxy api) (func val req)
hoistClientMonad pm _ f cl = \authreq ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl authreq)
> type MyApi = " books " :> Fragment Text :> Get ' [ JSON ] [ Book ]
> getBooks = client myApi
instance (AtLeastOneFragment api, FragmentUnique (Fragment a :> api), HasClient m api
) => HasClient m (Fragment a :> api) where
type Client m (Fragment a :> api) = Client m api
clientWithRoute pm _ = clientWithRoute pm (Proxy :: Proxy api)
hoistClientMonad pm _ = hoistClientMonad pm (Proxy :: Proxy api)
instance HasClient m api => HasClient m (BasicAuth realm usr :> api) where
type Client m (BasicAuth realm usr :> api) = BasicAuthData -> Client m api
clientWithRoute pm Proxy req val =
clientWithRoute pm (Proxy :: Proxy api) (basicAuthReq val req)
hoistClientMonad pm _ f cl = \bauth ->
hoistClientMonad pm (Proxy :: Proxy api) f (cl bauth)
data AsClientT (m :: * -> *)
instance GenericMode (AsClientT m) where
type AsClientT m :- api = Client m api
type GClientConstraints api m =
( GenericServant api (AsClientT m)
, Client m (ToServantApi api) ~ ToServant api (AsClientT m)
)
class GClient (api :: * -> *) m where
gClientProof :: Dict (GClientConstraints api m)
instance GClientConstraints api m => GClient api m where
gClientProof = Dict
instance
( forall n. GClient api n
, HasClient m (ToServantApi api)
, RunClient m
)
=> HasClient m (NamedRoutes api) where
type Client m (NamedRoutes api) = api (AsClientT m)
clientWithRoute :: Proxy m -> Proxy (NamedRoutes api) -> Request -> Client m (NamedRoutes api)
clientWithRoute pm _ request =
case gClientProof @api @m of
Dict -> fromServant $ clientWithRoute pm (Proxy @(ToServantApi api)) request
hoistClientMonad
:: forall ma mb.
Proxy m
-> Proxy (NamedRoutes api)
-> (forall x. ma x -> mb x)
-> Client ma (NamedRoutes api)
-> Client mb (NamedRoutes api)
hoistClientMonad _ _ nat clientA =
case (gClientProof @api @ma, gClientProof @api @mb) of
(Dict, Dict) ->
fromServant @api @(AsClientT mb) $
hoistClientMonad @m @(ToServantApi api) @ma @mb Proxy Proxy nat $
toServant @api @(AsClientT ma) clientA
infixl 1 //
infixl 2 /:
type Api = NamedRoutes RootApi
} deriving Generic
data SubApi mode = SubApi
} deriving Generic
rootClient : : ( AsClientT ClientM )
(//) :: a -> (a -> b) -> b
x // f = f x
type Api = NamedRoutes RootApi
, hello : : mode : - Capture " name " String :> Get ' [ JSON ] String
} deriving Generic
data SubApi mode = SubApi
} deriving Generic
rootClient : : ( AsClientT ClientM )
hello name = rootClient \/\/ hello \/ : name
endpointClient = client \/\/ subApi \/ : " foobar123 " \/\/ endpoint
(/:) :: (a -> b -> c) -> b -> a -> c
(/:) = flip
Note [ Non - Empty Content Types ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Rather than have
instance ( ... , cts ' ~ ( ct ' : cts ) ) = > ... cts ' ...
It may seem to make more sense to have :
instance ( ... ) = > ... ( ct ' : cts ) ...
But this means that if another instance exists that does * not * require
non - empty lists , but is otherwise more specific , no instance will be overall
more specific . This in turn generally means adding yet another instance ( one
for empty and one for non - empty lists ) .
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Rather than have
instance (..., cts' ~ (ct ': cts)) => ... cts' ...
It may seem to make more sense to have:
instance (...) => ... (ct ': cts) ...
But this means that if another instance exists that does *not* require
non-empty lists, but is otherwise more specific, no instance will be overall
more specific. This in turn generally means adding yet another instance (one
for empty and one for non-empty lists).
-}
checkContentTypeHeader :: RunClient m => Response -> m MediaType
checkContentTypeHeader response =
case lookup "Content-Type" $ toList $ responseHeaders response of
Nothing -> return $ "application" Media.// "octet-stream"
Just t -> case parseAccept t of
Nothing -> throwClientError $ InvalidContentTypeHeader response
Just t' -> return t'
decodedAs :: forall ct a m. (MimeUnrender ct a, RunClient m)
=> Response -> Proxy ct -> m a
decodedAs response ct = do
responseContentType <- checkContentTypeHeader response
unless (any (matches responseContentType) accept) $
throwClientError $ UnsupportedContentType responseContentType response
case mimeUnrender ct $ responseBody response of
Left err -> throwClientError $ DecodeFailure (T.pack err) response
Right val -> return val
where
accept = toList $ contentTypes ct
Erroring instance for ' when a combinator is not fully applied
instance (RunClient m, TypeError (PartialApplication HasClient arr)) => HasClient m ((arr :: a -> b) :> sub)
where
type Client m (arr :> sub) = TypeError (PartialApplication HasClient arr)
clientWithRoute _ _ _ = error "unreachable"
hoistClientMonad _ _ _ _ = error "unreachable"
Erroring instances for ' ' for unknown API combinators
|
78771f503618a328edd697da34baf59fbf0cc60bc2ccc8a4bbb2240af4461b25 | footprintanalytics/footprint-web | util.clj | (ns metabase.test.mock.util)
(def table-defaults
{:description nil
:entity_type nil
:caveats nil
:points_of_interest nil
:show_in_getting_started false
:schema nil
:fields []
:rows nil
:updated_at true
:active true
:id true
:db_id true
:visibility_type nil
:created_at true})
(def field-defaults
{:description nil
:table_id true
:caveats nil
:points_of_interest nil
:fk_target_field_id false
:updated_at true
:active true
:nfc_path nil
:parent_id false
:semantic_type nil
:id true
:last_analyzed true
:position 0
:visibility_type :normal
:preview_display true
:created_at true})
(def pulse-channel-defaults
{:schedule_frame nil
:schedule_hour nil
:schedule_day nil
:entity_id true
:enabled true})
(defn mock-execute-reducible-query [query respond]
(respond
{}
(let [fields-count (count (get-in query [:query :fields]))]
(for [i (range 500)]
(repeat fields-count i)))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/test/mock/util.clj | clojure | (ns metabase.test.mock.util)
(def table-defaults
{:description nil
:entity_type nil
:caveats nil
:points_of_interest nil
:show_in_getting_started false
:schema nil
:fields []
:rows nil
:updated_at true
:active true
:id true
:db_id true
:visibility_type nil
:created_at true})
(def field-defaults
{:description nil
:table_id true
:caveats nil
:points_of_interest nil
:fk_target_field_id false
:updated_at true
:active true
:nfc_path nil
:parent_id false
:semantic_type nil
:id true
:last_analyzed true
:position 0
:visibility_type :normal
:preview_display true
:created_at true})
(def pulse-channel-defaults
{:schedule_frame nil
:schedule_hour nil
:schedule_day nil
:entity_id true
:enabled true})
(defn mock-execute-reducible-query [query respond]
(respond
{}
(let [fields-count (count (get-in query [:query :fields]))]
(for [i (range 500)]
(repeat fields-count i)))))
| |
6b8bd1edabc21f0d68c4d1accb642515f4164562a48bf848f3334f20e396e0db | etnt/polish | polish_common.erl | @author
YYYY Torbjorn Tornkvist .
-module(polish_common).
-include("polish.hrl").
-export([header/1
, footer/0
, right/0
, left/0
]).
-import(polish, [all_custom_lcs/0, l2a/1]).
right() ->
#panel { class=menu, body=["RIGHT"] }.
left() ->
#panel { class=menu, body=["LEFT"] }.
header(Selected) ->
#panel { class=menu, body=[
#list{body=[build_dropdown_menu(Selected),
#listitem{ body=[#link { text = " - "}]},
#listitem{ body=[#link { class=search, url='#search_form', text="Search"}]},
#listitem{ body=[#link { class=statsbutton, url='#stats', text="Status"}]},
#listitem{ body=[#link { class=statsbutton, url='#help', text="Help"}]},
#listitem{ body=[#link { id=logout, url='/logout', text="Logout"}]}]}
]}.
build_dropdown_menu(Selected0) ->
Selected = case Selected0 of
[] -> "Languages";
_ -> Selected0
end,
#listitem{body = [#link{text=Selected}, #list{body = lang_links()}]}.
lang_links() ->
[#listitem { body = [#link{id=?l2a(string:to_lower(gettext_iso639:lc2lang(LC))),
url="/?po="++LC,
text=gettext_iso639:lc2lang(LC) }]}
|| LC <- all_custom_lcs()].
footer() ->
[#br{},
#panel { class=credits, body=[
""
Copyright & copy ; 2010 < a href=''>Torbjorn > .
Released under the MIT License .
]}].
| null | https://raw.githubusercontent.com/etnt/polish/857f6adeca7ae205f5b5d5f8c9b59fd5fe5d95b4/src/polish_common.erl | erlang | @author
YYYY Torbjorn Tornkvist .
-module(polish_common).
-include("polish.hrl").
-export([header/1
, footer/0
, right/0
, left/0
]).
-import(polish, [all_custom_lcs/0, l2a/1]).
right() ->
#panel { class=menu, body=["RIGHT"] }.
left() ->
#panel { class=menu, body=["LEFT"] }.
header(Selected) ->
#panel { class=menu, body=[
#list{body=[build_dropdown_menu(Selected),
#listitem{ body=[#link { text = " - "}]},
#listitem{ body=[#link { class=search, url='#search_form', text="Search"}]},
#listitem{ body=[#link { class=statsbutton, url='#stats', text="Status"}]},
#listitem{ body=[#link { class=statsbutton, url='#help', text="Help"}]},
#listitem{ body=[#link { id=logout, url='/logout', text="Logout"}]}]}
]}.
build_dropdown_menu(Selected0) ->
Selected = case Selected0 of
[] -> "Languages";
_ -> Selected0
end,
#listitem{body = [#link{text=Selected}, #list{body = lang_links()}]}.
lang_links() ->
[#listitem { body = [#link{id=?l2a(string:to_lower(gettext_iso639:lc2lang(LC))),
url="/?po="++LC,
text=gettext_iso639:lc2lang(LC) }]}
|| LC <- all_custom_lcs()].
footer() ->
[#br{},
#panel { class=credits, body=[
""
Copyright & copy ; 2010 < a href=''>Torbjorn > .
Released under the MIT License .
]}].
| |
95291b3456c3e879592d1b2eb12b9cb49d275de81d63f48f43b7ed48a9398a03 | jarohen/phoenix | loader.clj | (ns phoenix.loader
(:require [phoenix.location :as l]
[phoenix.merge :refer [deep-merge]]
[phoenix.references :as pr]
[clojure.tools.logging :as log]
[clojure.tools.reader.edn :as edn]))
(defn try-slurp [slurpable]
(try
(slurp slurpable)
(catch Exception e
(log/warnf "Can't read config-file: '%s', ignoring..." slurpable)
::invalid-include)))
(defn parse-config [s]
(when (string? s)
(edn/read-string {:readers *data-readers*}
s)))
(defn load-config-source [config-source location]
(some-> (try-slurp config-source)
parse-config
(l/select-location location)))
(defn includes [config]
(->> config
((juxt :general :environment :host :user))
(mapcat :phoenix/includes)))
(defn load-config-sources [initial-source location]
(loop [[config-source & more-sources :as config-sources] [initial-source]
loaded-sources #{}
configs []]
(if (empty? config-sources)
configs
(if-not config-source
(recur more-sources loaded-sources configs)
(let [new-config (load-config-source config-source location)]
(recur (concat more-sources (->> (includes new-config)
(remove #(contains? loaded-sources %))
(remove #{::invalid-include})))
(conj loaded-sources config-source)
(conj configs new-config)))))))
(defn load-config [{:keys [config-source location]}]
(-> (load-config-sources config-source location)
deep-merge
((juxt :general :host :user :environment))
deep-merge
(dissoc :phoenix/includes)
pr/resolve-references))
| null | https://raw.githubusercontent.com/jarohen/phoenix/f828bf144154f110f0a73f54645f5696e2c8bdab/runtime/src/phoenix/loader.clj | clojure | (ns phoenix.loader
(:require [phoenix.location :as l]
[phoenix.merge :refer [deep-merge]]
[phoenix.references :as pr]
[clojure.tools.logging :as log]
[clojure.tools.reader.edn :as edn]))
(defn try-slurp [slurpable]
(try
(slurp slurpable)
(catch Exception e
(log/warnf "Can't read config-file: '%s', ignoring..." slurpable)
::invalid-include)))
(defn parse-config [s]
(when (string? s)
(edn/read-string {:readers *data-readers*}
s)))
(defn load-config-source [config-source location]
(some-> (try-slurp config-source)
parse-config
(l/select-location location)))
(defn includes [config]
(->> config
((juxt :general :environment :host :user))
(mapcat :phoenix/includes)))
(defn load-config-sources [initial-source location]
(loop [[config-source & more-sources :as config-sources] [initial-source]
loaded-sources #{}
configs []]
(if (empty? config-sources)
configs
(if-not config-source
(recur more-sources loaded-sources configs)
(let [new-config (load-config-source config-source location)]
(recur (concat more-sources (->> (includes new-config)
(remove #(contains? loaded-sources %))
(remove #{::invalid-include})))
(conj loaded-sources config-source)
(conj configs new-config)))))))
(defn load-config [{:keys [config-source location]}]
(-> (load-config-sources config-source location)
deep-merge
((juxt :general :host :user :environment))
deep-merge
(dissoc :phoenix/includes)
pr/resolve-references))
| |
03ee21cd41aad4e0aa61216c505fb1f65f4adbe1508d43ddbe355b08e9aff24f | thicksteadTHpp/Obvius | types-tutorial.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; File: types-tutorial.lisp
Author :
;;; Description: Introduction to LISP and its data types
Creation Date : 6/93
;;; ----------------------------------------------------------------
Object - Based Vision and Image Understanding System ( OBVIUS ) ,
Copyright 1988 , Vision Science Group , Media Laboratory ,
Massachusetts Institute of Technology .
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; LISP is most commonly known for its lists but it also has
;;; a rich variety of data types which includes complex numbers,
;;; multidimensional arrays, strings and hash tables.
;;; Numbers in LISP come in many different varieties. The 'simplest'
form is the INTEGER . After performing a division , LISP attempts to
maintain a form known as RATIONALS . If the rationals become too unwieldy
to handle it converts it to . If a negative square root is
;;; encountered, it promotes the number type to a COMPLEX type if necessary.
;;; All this is done automatically and you need not be concerned with
;;; it under normal circumstances.
adds 1 and 2 = > 3
adds 1 , 2 , 3 and 4 = > 10
divides 22 by 7 = > 22/7 , a rational
(asin (/ 1 (sqrt 2))) ;; takes the arc sine of 1/sqrt(2) => 0.785398, a float
(sqrt -1) ;; takes the square root of minus one
(+ 1.0 2) ;; coerces a floating point addition
;;; The following is a list of arithmetic operations that are commonly used:-
;;;
;;; (+ <num-1> <num-2> ...) -- adds all the arguments
;;; (- <num-1> <num-2> ...) -- subtracts <num-2> ... from <num-1>
;;; (* <num-1> <num-2> ...) -- multiplies all the arguments together
;;; (/ <num-1> <num-2> ...) -- divides <num-1> by (<num-2> ...)
;;; (rem <number> <divisor>) -- returns the remainder of <number>/<divisor>
;;; (min <num-1> <num-2> ...) -- returns the minimum of all the arguments
;;; (max <num-1> <num-2> ...) -- returns the maximum of all the arguments
;;; (1+ <num>) -- returns <num>+1
;;; (1- <num>) -- returns <num>-1
;;; (floor <num>) -- rounds down the number
;;; (ceiling <num>) -- rounds up the number
;;; (round <num>) -- rounds off the number
;;; (exp <power>) -- raises e to the power <power>
;;; (expt <base> <power>) -- raises <base> to the power <power>
( log < number > & optional < base > ) -- takes the log of < number > to the base < base >
;;; which defaults to e.
;;; (sqrt <number>) -- takes the square root of <number>
( < number > ) -- takes the integer square root of < number > ( rounds down )
;;; (abs <number>) -- returns the absolute of <number>
;;; (sin <radians>) -- returns the sine of <radians>
;;; (cos <radians>) -- returns the cosine of <radians>
;;; (tan <radians>) -- returns the tangent of <radians>
;;; (asin <number>) -- returns the arc sine of <number>
( < number > ) -- returns the arc cosine of < number >
( atan < number > ) -- returns the arc tangent of < number >
( atan < y > & optional < x > ) -- returns the arc tangent of < y>/<x >
;;; the signs of y/x are used to derive the
;;; quadrant information.
;;; (random <num> &optional <state>) -- returns a random number [0, <num)
pi -- evaluates to the value of PI .
;;;
;;; The simplest data type in LISP is a symbol which can be
;;; used to name variables. The following are examples of
;;; symbols :-
;;;
;;; psych-267
;;; gabor-filter
;;; destroy!
3x3 - filter
;;;
;;; LISP allows a wider range of characters that can be used to
;;; specify symbols than C. At the top level of the LISP interpretor,
;;; symbols evaluate to their symbol-value (i.e. the value bound to
;;; the symbol). Later, we'll see that symbols can also have functions
;;; bound to them in addition to regular values.
;;;
;;; We assign values to symbols with (setq).
a = 1
b = 2
These do the same thing in this example but ( setf )
(setf b 2) ;; is more general as we will see later.
;;; The most glaring data type in LISP is the list and is the
;;; reason for all the parentheses. A list is a sequence of elements
;;; separated by spaces within parenthesis. Each element may be
;;; of a different data type.
;; '(1 2 3 4 5) ;; list of numbers
;; '(a b c d e) ;; list of symbols
;; '("a" "b" "c") ;; list of symbols
;; '(a 1 b 2) ;; mixed list of symbols and numbers
' ( 1 ( 2 ( 3 4 ) ) 5 ) ; ; nested lists
;;; Why do we have the quote in front of the list? In general, lists are
evaluated by the interpretor in a very special way . The first element
;;; is taken to be the name of the function and the rest of the elements as
;;; arguments to be passed to this function. Hence, (1 2 3 4 5)
would result in apply 2 3 4 5 to the function 1 which does n't make
;;; sense. On the other hand, '(1 2 3 4 5) is a synonym for
;;; (quote (1 2 3 4 5)). This results in the list (1 2 3 4 5) being passed
;;; to the function quote which simply returns it. Although LISP usually
evaluates its arguments first in which case we would have still
;;; had to evaluate (1 2 3 4 5), the (quote) function is a special-form
;;; in that LISP doesn't evaluate its arguments prior to calling the function.
;;; Lists are widely used in LISP programs as data structures so we'll
;;; devote quite a bit of time to exploring them.
First , let 's make a list of numbers
(setq numbers '(1 2 4 3 6 5 6))
;;; Verify that it's actually there by typing numbers (you'll need to type
;;; this in yourself).
;;;
;;; numbers
;;; (cons <element> <list>) => (<element> . <list>)
;;; cons takes an element and adds it to the front of the list.
(cons 9 numbers)
;;; Now take a look at numbers again by typing it.
What happened to number 9 ? Actually , the ( cons ) operator
;;; creates a new list (not quite but let's consider it to be that way
for now ) . So , if we want ' numbers ' to have that 9 in front ,
;;; we need to assign it. (cons) is a non-destructive operator.
;;; In "pure" LISP, all operators "should" be non-destructive.
;;; However, it's inefficient to always do this and LISP has
;;; destructive operations which actually modifies the list
;;; passed.
Now , if we look at numbers again , it 'll have number 9
(setq numbers (cons 9 numbers))
;;; Type numbers to verify this.
;;; Reverses the list. (reverse) is non-destructive, so we
;;; would have to (setq) it to numbers if we wanted to modify
;;; numbers.
(reverse numbers)
;;; Appends one list to another (non-destructive).
(append numbers numbers)
Tests if 2 is an element of the list numbers . Note that
( ) does n't check recursively , i.e. if you have nested
;;; lists, this wouldn't work. Returns the list with the element
as the first element of that list if the element can be found ;
otherwise returns NIL .
(member 2 numbers)
(member 20 numbers)
;;; Returns the length of the list
(length numbers)
;;;; Makes a list containing all its arguments
(list 1 2 3 4 5 6)
;;; Now, try this:-
(setq list-1 (list 2 (+ 2 7) (* 3 4)))
(setq list-2 '(2 (+ 2 7) (* 3 4)))
;;; (list) makes a list containing all of its arguments.
;;; However, all the arguments are evaluated prior to
being sent to ( list ) . In the second example , the quote
;;; operator inhibits evaluation of its argument.
;;; Nil, () and '().
As far as lisp is concerned , the following three are
;;; identical. Nil is also used to mean false
;;; in boolean operations as we shall se later.
;;;
;;; Type them in for yourself and see.
;;; Nil
;;; ()
;;; '()
;;;
car , cdr , first , second , nth ...
;;;
( car ) returns the first element of the list . By definition ,
;;; if numbers is nil, a nil is returned as well.
(car numbers)
( cdr ) returns a list of all the elements except the first .
(cdr numbers)
Returns the second element of the list . Actually ,
( cdr numbers ) returns a list whose first element
is the second element of the original list and
( car < of - that - result > ) returns that first element .
(car (cdr numbers))
;;; Synonyms and shorthands.
;;; This is the same as the previous expression.
(cadr numbers)
;;; In general, we can cascade as many as we like but gets quite
;;; unreadable.
Returns the fourth element of the list .
(car (cdr (cdr (cdr numbers))))
(cadddr numbers)
;;; We could also have used:-
(fourth numbers)
;;; Dependending on the implementation of LISP that you're using, you may
have fifth , sixth , .... The general and more useful
;;; form is:-
( nth ) returns the fourth number ( zero is the first element ) .
(nth 3 numbers)
;;;
;;; The Cons Cell
;;;
;;; CONS cells are the only time you'll hear about pointers
;;; in LISP.
;;; We have mentioned what lists are but it's useful to
;;; understand what really goes on behind the scene.
;;; Lists are made up of CONS cells (also known as dotted pairs).
Each cons cell is a 2 - tuple represented as ( a . b ) ( note the
dot ) where a is the first element and b the second . In most
;;; cases, b is a pointer to another CONS cell. Graphically,
;;;
;;; +---+---+
;;; | a | b |
;;; +---+---+
;;;
;;; So, what are lists? We will illustrate with an example.
(setq short-list '(1 (2 (3) 4)))
;;; is equivalent to :-
;;;
' ( 1 . ( ( 2 . ( ( 3 . NIL ) . ( 4 . NIL ) ) ) . NIL ) )
;;;
;;; and
;;;
( cons 1 ( cons ( cons 2 ( cons ( cons 3 nil ) ( cons 4 nil ) ) ) nil ) )
;;;
;;; (You can evaluate both of these expressions in LISP and they'll
;;; give the same expression.)
;;;
;;; Graphically, we have,
;;;
;;; +---+---+ +---+---+
;;; | 1 | X +-->| X | X-+-->NIL
;;; +---+---+ +-+-+---+
;;; |
;;; | +---+---+
;;; +-->| 2 | X |
;;; +---+-+-+
;;; |
;;; | +---+---+
;;; +--->| X | X |
;;; +-+-+-+-+
;;; | |
;;; | | +---+---+
| + --->| 4 | X-+-->NIL
;;; | +---+---+
;;; |
;;; | +---+---+
;;; +------->| 3 | X-+-->NIL
;;; +---+---+
;;;
;;; So, why do we need to know all this? Well, remember
;;; when we learnt about cons and the result of
evaluating ( cons 9 numbers ) ?
;;;
;;; What actually happened was a new cons cell was created
which has as its first element the number 9 and the
second element , a pointer to the original list .
;;;
;;; +---+---+
;;; | 9 | X-+--> numbers
;;; +---+---+
;;;
;;; For you C hackers out there, you'd probably be saying
;;; that we can really do some neat stuff here (and also
;;; mess up badly). Consider the following example.
(setq a '(2 3 4))
(setq b (cons 4 a))
The following sets the value of the first element in
;;; the CONS cell. This is a destructive operation! Similarly,
( setf ( cdr a ) something ) sets the second element of the cell .
(setf (car a) 'two)
;;; Take a look at the list a.
;;; Now, take a guess what 'b' is.
;;; Lo-and-behold! What happened? Well, as we said, what really
;;; happened was we only created a new cons cell with a pointer to
;;; the old. A new list is not created.
;;; Now, try this:-
(setf a '(4 5 6))
;;; What do you think 'b' is?
;;; 'b" remains the same. Why? What happened was we created a new
list ' ( 4 5 6 ) and bounded that to the symbol ' a ' . ' b ' continues to
;;; point to the old list that 'a' used to point to.
;;; If you're thinking about it already, the answer is "yes," you can
;;; create circular lists but be careful there is no way to
;;; print it out as the printing will go on forever!
;;; So far, we have only worked with lists of numbers and nested lists
;;; of numbers. We can also have lists of strings or symbols or other
;;; data types. We could have lists with different data types.
;;;
;;; Property Lists and Association Lists
;;;
;;; A common use of lists is as PROPERTY LISTS.
;;; Property lists are lists of the form:-
;;; (symbol-1 value-1 symbol-2 value-2 symbol-3 value-3 ...)
;;;
;;; For example, a simple property list could be a name-telephone number
;;; list.
;;;
(setq *phone-book*
'(patrick "7-1234"
ivan "7-4321"
jean "7-2332"))
The following returns the value of the symbol ' ' .
( getf ) returns the value if successful and NIL otherwise .
(getf *phone-book* 'ivan)
;;; The following changes the value of the symbol 'patrick'.
(setf (getf *phone-book* 'patrick) "7-4559")
;;; The following removes the symbol-value pair from the list.
;;; (remf) returns T if successful and NIL otherwise. It is
;;; a destructive operation.
(remf *phone-book* 'jean)
;;; A similar idea can be implemented as ASSOCIATION LISTS.
;;; Association lists are lists of the form:-
;;; ((symbol-1 . value-1) (symbol-2 . value-2) ...)
;;;
;;; Let's try out the previous example:-
;;;
;;; (Note: we are using dot operators -- this is not *really* necessary
;;; though but is generally the way people do it.)
(setq *phone-book*
'((patrick . "7-1234")
(ivan . "7-4321")
(jean . "7-2332")))
;;; The following returns the (symbol . value) pair associated with the
;;; symbol 'patrick.
(assoc 'patrick *phone-book*)
;;; The following modifies the value associated with the returned
;;; (symbol . value) pair.
(setf (cdr (assoc 'patrick *phone-book*)) "7-5723")
;;; See what *phone-book* is.
;;; The following returns the (symbol . value) pair associated with the value
;;; "7-4321". Note we had to include :test #'string=. This tells rassoc to use
the ( string= ) function to test between the given value and the values
;;; in the list. We could have given any function including ones that we
;;; write.
(rassoc "7-4321" *phone-book* :test #'string=)
;;; The following adds a (symbol . value) pair to *phone-book*. Since (acons)
;;; is non-destructive, we need to set our original list to itself.
(setf *phone-book*
(acons 'alison "7-9876" *phone-book*))
;;; The following removes the (symbol . value) pair from the list.
(setf *phone-book*
(remove (assoc 'patrick *phone-book*) *phone-book*))
;;;
;;; Arrays
;;;
;;; Another useful data type is the array data type. Again, the array
;;; data structure is also very extensive, we will introduce the more common
uses of it and refer you to for more details .
;;;
;;;
The following creates an 2D array of size 20x30 of type float
and initializes it to 0.0 .
;;;
(setq my-array (make-array '(20 30)
:element-type 'float
:initial-element 0.0))
;;;
;;; The following creates a 3D array initialized to the given contents.
;;;
(make-array '(4 2 3)
:initial-contents
'(((a b c) (1 2 3))
((d e f) (3 1 2))
((g h i) (2 3 1))
((j k l) (0 0 0))))
( aref ) reads element ( 2,10 ) of my - array .
(aref my-array 2 10)
Sets element ( 5,3 ) of my - array to 1.0 .
(setf (aref my-array 5 3) 1.0)
;;; (array-rank) returns the number of dimensions of my-array.
(array-rank my-array)
;;; (array-dimension) returns the size of a given dimension.
(array-dimension my-array 0)
(array-dimension my-array 1)
;;; (array-dimensions) returns a list whose elements are the
;;; dimensions of the array.
(array-dimensions my-array)
;;; (array-total-size) returns the total number of elements.
;;; in the array.
(array-total-size my-array)
;;; (array-in-bounds-p) returns T if the index is within
;;; the bounds of the array and NIL otherwise.
(array-in-bounds-p my-array 10 10)
(array-in-bounds-p my-array 10 30)
;;;
Boolean datatype
;;;
;;; There is no real boolean data type in LISP. Most LISP predicates
consider NIL to be false and any non - NIL value to be true .
;;; The following is a series of LISP predicates operating on
;;; symbols, numbers and lists.
;;;
;;;
;;; Simple Predicates
;;;
( ) returns T if the argument is a list , NIL otherwise .
(listp nil)
(listp '(1 2 3))
(listp 1)
;;; Sometimes it's useful to see if it's a list that contains
at least one element ( i.e. not a NIL list ) . The ( consp )
;;; operator does just that.
(consp nil)
(consp 1)
(consp '(1 2 3))
;;; (symbolp) returns T if the argument is a symbol, NIL otherwise.
(symbolp 1)
(symbolp 'a)
(symbolp '(1 2 3))
;;; (atom) returns T if the argument is an atom, NIL otherwise.
(atom 1)
(atom 'a)
(atom '(1 2 3))
( null ) returns T if the argument is NIL , NIL otherwise .
(null 'a)
(null '(1 2 3))
(null nil)
Boolean NOT operator . Returns T if the argument is NIL , NIL otherwise .
(not '(1 2 3))
(not nil)
(not t)
;;;
;;; equal/eq/eql/=
;;;
Lisp has three different notions of equality and causes confusion
for many people . ( The last two are equivalent and the most intuitive
;;; is equal.)
;;;
;;; (equal) returns T if the printed outputs "look" the same.
;;; (eq) checks if the memory locations of the pointers are the
;;; same. This can be used for numbers, symbols and other atoms.
;;; Lastly, (eql) and (=) operates only on numbers.
(setq a '(1 2 3))
(setq b '(1 2 3))
(setq c b)
(equal a b)
;;; 'a' and 'b' are not (eq) because they point to different structures
;;; while 'b' and 'c' point to the same CONS cell.
(eq a b)
(eq b c)
;;; Clearly, (eq) is the most efficient and should be used when possible.
;;; However, it can often lead to bugs as you might expect. So, be
;;; absolutely certain that you know what you are doing. Otherwise, (equal)
;;; is the safest to use (but unfortunately, the most inefficient). (eql)
;;; is the most efficient for numbers.
;;;
;;; Logical Operators
;;;
;;; Some of the common logical operators include (and), (or) and (not). We've
;;; already seen (not) in the previous section. The operation for (and) and
;;; (or) are almost identical.
;;; The (and) operator takes any number of arguments and returns the last argument
;;; if there are no NIL elements or returns a NIL otherwise.
(and (> 1 2) (< 2 3) (> 4 5))
(and "a" "b" "c")
(and "a" (> 2 3) "c")
( and ) performs short - circuit ( lazy ) evaluation . So , if a NIL is encountered
;;; before the end of the list, (and) will not evaluate its other arguments.
;;; Similarly, the (or) operator takes any number of arguments and returns the
first non - NIL argument or returns NIL otherwise .
(or (> 1 2) (< 2 3) (> 4 5))
(or (> 1 2) "b" "c")
(or (> 1 2) (> 3 4))
;;; (or) also performs short-circuit evaluation, i.e. if it encounters
;;; a non-NIL argument it doesn't evaluate the other arguments.
;;; Because of this feature, (or) can be used in place of (if). It's
;;; entirely a matter of style.
;;;
;;; Predicates on Numbers
;;;
( zerop < number > ) - returns T if < number > is zero , NIL otherwise .
( plusp < number > ) - returns T if < number > is strictly greater than zero , NIL otherwise .
( minusp < number > ) - returns T if < number > is strictly less than zero , NIL otherwise .
;;; (oddp <number>) - returns T if <number> is odd, NIL otherwise.
( evenp < number > ) - returns T if < number > is even ( or zero ) , NIL otherwise .
;;;
;;;
;;; Comparisons on Numbers
;;;
;;; (= number &rest <more-numbers>) - returns T if all the numbers are the same.
;;; (/= number &rest <more-numbers>) - returns T if all the numbers are different.
;;; (< number &rest <more-numbers>) - returns T if the numbers are monotonically increasing.
;;; (> number &rest <more-numbers>) - returns T if the numbers are monotonically decreasing.
;;; (<= number &rest <more-numbers>) - returns T if the numbers are monotonically non-decreasing.
;;; (>= number &rest <more-numbers>) - returns T if the numbers are monotonically non-increasing.
;;;
;;;
;;; Aggregate structures
;;;
;;; Aggregate structures can be created by (defstruct) which
is very similar to C 's structs and 's records . However ,
we will not go over them as CLOS ( Common Lisp Object System ) is
;;; more useful.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Local Variables:
;;; buffer-read-only: t
fill - column : 79
;;; End:
| null | https://raw.githubusercontent.com/thicksteadTHpp/Obvius/9a91673609def033539c9ebaf098e8f11eb0df6e/tutorials/lisp/types-tutorial.lisp | lisp |
File: types-tutorial.lisp
Description: Introduction to LISP and its data types
----------------------------------------------------------------
LISP is most commonly known for its lists but it also has
a rich variety of data types which includes complex numbers,
multidimensional arrays, strings and hash tables.
Numbers in LISP come in many different varieties. The 'simplest'
encountered, it promotes the number type to a COMPLEX type if necessary.
All this is done automatically and you need not be concerned with
it under normal circumstances.
takes the arc sine of 1/sqrt(2) => 0.785398, a float
takes the square root of minus one
coerces a floating point addition
The following is a list of arithmetic operations that are commonly used:-
(+ <num-1> <num-2> ...) -- adds all the arguments
(- <num-1> <num-2> ...) -- subtracts <num-2> ... from <num-1>
(* <num-1> <num-2> ...) -- multiplies all the arguments together
(/ <num-1> <num-2> ...) -- divides <num-1> by (<num-2> ...)
(rem <number> <divisor>) -- returns the remainder of <number>/<divisor>
(min <num-1> <num-2> ...) -- returns the minimum of all the arguments
(max <num-1> <num-2> ...) -- returns the maximum of all the arguments
(1+ <num>) -- returns <num>+1
(1- <num>) -- returns <num>-1
(floor <num>) -- rounds down the number
(ceiling <num>) -- rounds up the number
(round <num>) -- rounds off the number
(exp <power>) -- raises e to the power <power>
(expt <base> <power>) -- raises <base> to the power <power>
which defaults to e.
(sqrt <number>) -- takes the square root of <number>
(abs <number>) -- returns the absolute of <number>
(sin <radians>) -- returns the sine of <radians>
(cos <radians>) -- returns the cosine of <radians>
(tan <radians>) -- returns the tangent of <radians>
(asin <number>) -- returns the arc sine of <number>
the signs of y/x are used to derive the
quadrant information.
(random <num> &optional <state>) -- returns a random number [0, <num)
The simplest data type in LISP is a symbol which can be
used to name variables. The following are examples of
symbols :-
psych-267
gabor-filter
destroy!
LISP allows a wider range of characters that can be used to
specify symbols than C. At the top level of the LISP interpretor,
symbols evaluate to their symbol-value (i.e. the value bound to
the symbol). Later, we'll see that symbols can also have functions
bound to them in addition to regular values.
We assign values to symbols with (setq).
is more general as we will see later.
The most glaring data type in LISP is the list and is the
reason for all the parentheses. A list is a sequence of elements
separated by spaces within parenthesis. Each element may be
of a different data type.
'(1 2 3 4 5) ;; list of numbers
'(a b c d e) ;; list of symbols
'("a" "b" "c") ;; list of symbols
'(a 1 b 2) ;; mixed list of symbols and numbers
; nested lists
Why do we have the quote in front of the list? In general, lists are
is taken to be the name of the function and the rest of the elements as
arguments to be passed to this function. Hence, (1 2 3 4 5)
sense. On the other hand, '(1 2 3 4 5) is a synonym for
(quote (1 2 3 4 5)). This results in the list (1 2 3 4 5) being passed
to the function quote which simply returns it. Although LISP usually
had to evaluate (1 2 3 4 5), the (quote) function is a special-form
in that LISP doesn't evaluate its arguments prior to calling the function.
Lists are widely used in LISP programs as data structures so we'll
devote quite a bit of time to exploring them.
Verify that it's actually there by typing numbers (you'll need to type
this in yourself).
numbers
(cons <element> <list>) => (<element> . <list>)
cons takes an element and adds it to the front of the list.
Now take a look at numbers again by typing it.
creates a new list (not quite but let's consider it to be that way
we need to assign it. (cons) is a non-destructive operator.
In "pure" LISP, all operators "should" be non-destructive.
However, it's inefficient to always do this and LISP has
destructive operations which actually modifies the list
passed.
Type numbers to verify this.
Reverses the list. (reverse) is non-destructive, so we
would have to (setq) it to numbers if we wanted to modify
numbers.
Appends one list to another (non-destructive).
lists, this wouldn't work. Returns the list with the element
Returns the length of the list
Makes a list containing all its arguments
Now, try this:-
(list) makes a list containing all of its arguments.
However, all the arguments are evaluated prior to
operator inhibits evaluation of its argument.
Nil, () and '().
identical. Nil is also used to mean false
in boolean operations as we shall se later.
Type them in for yourself and see.
Nil
()
'()
if numbers is nil, a nil is returned as well.
Synonyms and shorthands.
This is the same as the previous expression.
In general, we can cascade as many as we like but gets quite
unreadable.
We could also have used:-
Dependending on the implementation of LISP that you're using, you may
form is:-
The Cons Cell
CONS cells are the only time you'll hear about pointers
in LISP.
We have mentioned what lists are but it's useful to
understand what really goes on behind the scene.
Lists are made up of CONS cells (also known as dotted pairs).
cases, b is a pointer to another CONS cell. Graphically,
+---+---+
| a | b |
+---+---+
So, what are lists? We will illustrate with an example.
is equivalent to :-
and
(You can evaluate both of these expressions in LISP and they'll
give the same expression.)
Graphically, we have,
+---+---+ +---+---+
| 1 | X +-->| X | X-+-->NIL
+---+---+ +-+-+---+
|
| +---+---+
+-->| 2 | X |
+---+-+-+
|
| +---+---+
+--->| X | X |
+-+-+-+-+
| |
| | +---+---+
| +---+---+
|
| +---+---+
+------->| 3 | X-+-->NIL
+---+---+
So, why do we need to know all this? Well, remember
when we learnt about cons and the result of
What actually happened was a new cons cell was created
+---+---+
| 9 | X-+--> numbers
+---+---+
For you C hackers out there, you'd probably be saying
that we can really do some neat stuff here (and also
mess up badly). Consider the following example.
the CONS cell. This is a destructive operation! Similarly,
Take a look at the list a.
Now, take a guess what 'b' is.
Lo-and-behold! What happened? Well, as we said, what really
happened was we only created a new cons cell with a pointer to
the old. A new list is not created.
Now, try this:-
What do you think 'b' is?
'b" remains the same. Why? What happened was we created a new
point to the old list that 'a' used to point to.
If you're thinking about it already, the answer is "yes," you can
create circular lists but be careful there is no way to
print it out as the printing will go on forever!
So far, we have only worked with lists of numbers and nested lists
of numbers. We can also have lists of strings or symbols or other
data types. We could have lists with different data types.
Property Lists and Association Lists
A common use of lists is as PROPERTY LISTS.
Property lists are lists of the form:-
(symbol-1 value-1 symbol-2 value-2 symbol-3 value-3 ...)
For example, a simple property list could be a name-telephone number
list.
The following changes the value of the symbol 'patrick'.
The following removes the symbol-value pair from the list.
(remf) returns T if successful and NIL otherwise. It is
a destructive operation.
A similar idea can be implemented as ASSOCIATION LISTS.
Association lists are lists of the form:-
((symbol-1 . value-1) (symbol-2 . value-2) ...)
Let's try out the previous example:-
(Note: we are using dot operators -- this is not *really* necessary
though but is generally the way people do it.)
The following returns the (symbol . value) pair associated with the
symbol 'patrick.
The following modifies the value associated with the returned
(symbol . value) pair.
See what *phone-book* is.
The following returns the (symbol . value) pair associated with the value
"7-4321". Note we had to include :test #'string=. This tells rassoc to use
in the list. We could have given any function including ones that we
write.
The following adds a (symbol . value) pair to *phone-book*. Since (acons)
is non-destructive, we need to set our original list to itself.
The following removes the (symbol . value) pair from the list.
Arrays
Another useful data type is the array data type. Again, the array
data structure is also very extensive, we will introduce the more common
The following creates a 3D array initialized to the given contents.
(array-rank) returns the number of dimensions of my-array.
(array-dimension) returns the size of a given dimension.
(array-dimensions) returns a list whose elements are the
dimensions of the array.
(array-total-size) returns the total number of elements.
in the array.
(array-in-bounds-p) returns T if the index is within
the bounds of the array and NIL otherwise.
There is no real boolean data type in LISP. Most LISP predicates
The following is a series of LISP predicates operating on
symbols, numbers and lists.
Simple Predicates
Sometimes it's useful to see if it's a list that contains
operator does just that.
(symbolp) returns T if the argument is a symbol, NIL otherwise.
(atom) returns T if the argument is an atom, NIL otherwise.
equal/eq/eql/=
is equal.)
(equal) returns T if the printed outputs "look" the same.
(eq) checks if the memory locations of the pointers are the
same. This can be used for numbers, symbols and other atoms.
Lastly, (eql) and (=) operates only on numbers.
'a' and 'b' are not (eq) because they point to different structures
while 'b' and 'c' point to the same CONS cell.
Clearly, (eq) is the most efficient and should be used when possible.
However, it can often lead to bugs as you might expect. So, be
absolutely certain that you know what you are doing. Otherwise, (equal)
is the safest to use (but unfortunately, the most inefficient). (eql)
is the most efficient for numbers.
Logical Operators
Some of the common logical operators include (and), (or) and (not). We've
already seen (not) in the previous section. The operation for (and) and
(or) are almost identical.
The (and) operator takes any number of arguments and returns the last argument
if there are no NIL elements or returns a NIL otherwise.
before the end of the list, (and) will not evaluate its other arguments.
Similarly, the (or) operator takes any number of arguments and returns the
(or) also performs short-circuit evaluation, i.e. if it encounters
a non-NIL argument it doesn't evaluate the other arguments.
Because of this feature, (or) can be used in place of (if). It's
entirely a matter of style.
Predicates on Numbers
(oddp <number>) - returns T if <number> is odd, NIL otherwise.
Comparisons on Numbers
(= number &rest <more-numbers>) - returns T if all the numbers are the same.
(/= number &rest <more-numbers>) - returns T if all the numbers are different.
(< number &rest <more-numbers>) - returns T if the numbers are monotonically increasing.
(> number &rest <more-numbers>) - returns T if the numbers are monotonically decreasing.
(<= number &rest <more-numbers>) - returns T if the numbers are monotonically non-decreasing.
(>= number &rest <more-numbers>) - returns T if the numbers are monotonically non-increasing.
Aggregate structures
Aggregate structures can be created by (defstruct) which
more useful.
Local Variables:
buffer-read-only: t
End: | Author :
Creation Date : 6/93
Object - Based Vision and Image Understanding System ( OBVIUS ) ,
Copyright 1988 , Vision Science Group , Media Laboratory ,
Massachusetts Institute of Technology .
form is the INTEGER . After performing a division , LISP attempts to
maintain a form known as RATIONALS . If the rationals become too unwieldy
to handle it converts it to . If a negative square root is
adds 1 and 2 = > 3
adds 1 , 2 , 3 and 4 = > 10
divides 22 by 7 = > 22/7 , a rational
( log < number > & optional < base > ) -- takes the log of < number > to the base < base >
( < number > ) -- takes the integer square root of < number > ( rounds down )
( < number > ) -- returns the arc cosine of < number >
( atan < number > ) -- returns the arc tangent of < number >
( atan < y > & optional < x > ) -- returns the arc tangent of < y>/<x >
pi -- evaluates to the value of PI .
3x3 - filter
a = 1
b = 2
These do the same thing in this example but ( setf )
evaluated by the interpretor in a very special way . The first element
would result in apply 2 3 4 5 to the function 1 which does n't make
evaluates its arguments first in which case we would have still
First , let 's make a list of numbers
(setq numbers '(1 2 4 3 6 5 6))
(cons 9 numbers)
What happened to number 9 ? Actually , the ( cons ) operator
for now ) . So , if we want ' numbers ' to have that 9 in front ,
Now , if we look at numbers again , it 'll have number 9
(setq numbers (cons 9 numbers))
(reverse numbers)
(append numbers numbers)
Tests if 2 is an element of the list numbers . Note that
( ) does n't check recursively , i.e. if you have nested
otherwise returns NIL .
(member 2 numbers)
(member 20 numbers)
(length numbers)
(list 1 2 3 4 5 6)
(setq list-1 (list 2 (+ 2 7) (* 3 4)))
(setq list-2 '(2 (+ 2 7) (* 3 4)))
being sent to ( list ) . In the second example , the quote
As far as lisp is concerned , the following three are
car , cdr , first , second , nth ...
( car ) returns the first element of the list . By definition ,
(car numbers)
( cdr ) returns a list of all the elements except the first .
(cdr numbers)
Returns the second element of the list . Actually ,
( cdr numbers ) returns a list whose first element
is the second element of the original list and
( car < of - that - result > ) returns that first element .
(car (cdr numbers))
(cadr numbers)
Returns the fourth element of the list .
(car (cdr (cdr (cdr numbers))))
(cadddr numbers)
(fourth numbers)
have fifth , sixth , .... The general and more useful
( nth ) returns the fourth number ( zero is the first element ) .
(nth 3 numbers)
Each cons cell is a 2 - tuple represented as ( a . b ) ( note the
dot ) where a is the first element and b the second . In most
(setq short-list '(1 (2 (3) 4)))
' ( 1 . ( ( 2 . ( ( 3 . NIL ) . ( 4 . NIL ) ) ) . NIL ) )
( cons 1 ( cons ( cons 2 ( cons ( cons 3 nil ) ( cons 4 nil ) ) ) nil ) )
| + --->| 4 | X-+-->NIL
evaluating ( cons 9 numbers ) ?
which has as its first element the number 9 and the
second element , a pointer to the original list .
(setq a '(2 3 4))
(setq b (cons 4 a))
The following sets the value of the first element in
( setf ( cdr a ) something ) sets the second element of the cell .
(setf (car a) 'two)
(setf a '(4 5 6))
list ' ( 4 5 6 ) and bounded that to the symbol ' a ' . ' b ' continues to
(setq *phone-book*
'(patrick "7-1234"
ivan "7-4321"
jean "7-2332"))
The following returns the value of the symbol ' ' .
( getf ) returns the value if successful and NIL otherwise .
(getf *phone-book* 'ivan)
(setf (getf *phone-book* 'patrick) "7-4559")
(remf *phone-book* 'jean)
(setq *phone-book*
'((patrick . "7-1234")
(ivan . "7-4321")
(jean . "7-2332")))
(assoc 'patrick *phone-book*)
(setf (cdr (assoc 'patrick *phone-book*)) "7-5723")
the ( string= ) function to test between the given value and the values
(rassoc "7-4321" *phone-book* :test #'string=)
(setf *phone-book*
(acons 'alison "7-9876" *phone-book*))
(setf *phone-book*
(remove (assoc 'patrick *phone-book*) *phone-book*))
uses of it and refer you to for more details .
The following creates an 2D array of size 20x30 of type float
and initializes it to 0.0 .
(setq my-array (make-array '(20 30)
:element-type 'float
:initial-element 0.0))
(make-array '(4 2 3)
:initial-contents
'(((a b c) (1 2 3))
((d e f) (3 1 2))
((g h i) (2 3 1))
((j k l) (0 0 0))))
( aref ) reads element ( 2,10 ) of my - array .
(aref my-array 2 10)
Sets element ( 5,3 ) of my - array to 1.0 .
(setf (aref my-array 5 3) 1.0)
(array-rank my-array)
(array-dimension my-array 0)
(array-dimension my-array 1)
(array-dimensions my-array)
(array-total-size my-array)
(array-in-bounds-p my-array 10 10)
(array-in-bounds-p my-array 10 30)
Boolean datatype
consider NIL to be false and any non - NIL value to be true .
( ) returns T if the argument is a list , NIL otherwise .
(listp nil)
(listp '(1 2 3))
(listp 1)
at least one element ( i.e. not a NIL list ) . The ( consp )
(consp nil)
(consp 1)
(consp '(1 2 3))
(symbolp 1)
(symbolp 'a)
(symbolp '(1 2 3))
(atom 1)
(atom 'a)
(atom '(1 2 3))
( null ) returns T if the argument is NIL , NIL otherwise .
(null 'a)
(null '(1 2 3))
(null nil)
Boolean NOT operator . Returns T if the argument is NIL , NIL otherwise .
(not '(1 2 3))
(not nil)
(not t)
Lisp has three different notions of equality and causes confusion
for many people . ( The last two are equivalent and the most intuitive
(setq a '(1 2 3))
(setq b '(1 2 3))
(setq c b)
(equal a b)
(eq a b)
(eq b c)
(and (> 1 2) (< 2 3) (> 4 5))
(and "a" "b" "c")
(and "a" (> 2 3) "c")
( and ) performs short - circuit ( lazy ) evaluation . So , if a NIL is encountered
first non - NIL argument or returns NIL otherwise .
(or (> 1 2) (< 2 3) (> 4 5))
(or (> 1 2) "b" "c")
(or (> 1 2) (> 3 4))
( zerop < number > ) - returns T if < number > is zero , NIL otherwise .
( plusp < number > ) - returns T if < number > is strictly greater than zero , NIL otherwise .
( minusp < number > ) - returns T if < number > is strictly less than zero , NIL otherwise .
( evenp < number > ) - returns T if < number > is even ( or zero ) , NIL otherwise .
is very similar to C 's structs and 's records . However ,
we will not go over them as CLOS ( Common Lisp Object System ) is
fill - column : 79
|
831a668b6d1a25fea281dae0ec2c87f2b64a702967e23726ad78cfd529457145 | metosin/malli | generator.cljc | (ns malli.experimental.time.generator
(:require [clojure.test.check.generators :as gen]
[clojure.spec.gen.alpha :as ga]
[malli.core :as m]
[malli.generator :as mg]
#?(:clj [malli.experimental.time :as time]
:cljs [malli.experimental.time :as time
:refer [Duration LocalDate LocalDateTime LocalTime Instant OffsetTime ZonedDateTime OffsetDateTime ZoneId ZoneOffset]]))
#?(:clj (:import (java.time Duration LocalDate LocalDateTime LocalTime Instant OffsetTime ZonedDateTime OffsetDateTime ZoneId ZoneOffset))))
#?(:clj (set! *warn-on-reflection* true))
(def zone-id-gen
(mg/generator (into [:enum] (map #(. ZoneId of ^String %)) (. ZoneId getAvailableZoneIds))))
(defmethod mg/-schema-generator :time/zone-id [_schema _options] zone-id-gen)
#?(:clj (def ^:const ^:private seconds-in-day 86400)
:cljs (def ^:private seconds-in-day 86400))
(defn -to-long ^long [o]
(cond
(instance? Instant o) (.toEpochMilli ^Instant o)
(instance? LocalDate o) (.toEpochDay ^LocalDate o)
(instance? LocalTime o) (.toSecondOfDay ^LocalTime o)
(instance? ZoneOffset o) #?(:clj (.getTotalSeconds ^ZoneOffset o)
:cljs (.totalSeconds ^ZoneOffset o))
(instance? LocalDateTime o)
(unchecked-add
(unchecked-multiply (.toEpochDay (.toLocalDate ^LocalDateTime o)) seconds-in-day)
(-to-long (.toLocalTime ^LocalDateTime o)))
(instance? OffsetDateTime o) (.toEpochMilli (.toInstant ^OffsetDateTime o))
(instance? ZonedDateTime o) (.toEpochMilli (.toInstant ^ZonedDateTime o))
(instance? Duration o) (.toNanos ^Duration o)
(int? o) (long o)))
(defn to-long [o] (when o (-to-long o)))
(defn -min-max [schema options]
(let [{:keys [min max] gen-min :gen/min gen-max :gen/max}
(merge
(m/type-properties schema options)
(m/properties schema options))
{:keys [accessor] :or {accessor identity}} options
as-long #(when % (to-long (accessor %)))
min (as-long min) max (as-long max) gen-min (as-long gen-min) gen-max (as-long gen-max)]
(when (and min gen-min (< gen-min min))
(m/-fail! ::mg/invalid-property {:key :gen/min, :value gen-min, :min min}))
(when (and max gen-max (> gen-max max))
(m/-fail! ::mg/invalid-property {:key :gen/max, :value gen-min, :max min}))
{:min (or gen-min min)
:max (or gen-max max)}))
(defn -zone-offset-gen [schema options]
(ga/fmap #(. ZoneOffset ofTotalSeconds %) (gen/large-integer* (-min-max schema options))))
(defmethod mg/-schema-generator :time/zone-offset [schema options]
(-zone-offset-gen schema options))
(defn -instant-gen [schema options]
(ga/fmap #(. Instant ofEpochMilli %) (gen/large-integer* (-min-max schema options))))
(defmethod mg/-schema-generator :time/instant [schema options]
(-instant-gen schema options))
(comment
(gen/sample (mg/-schema-generator (time/-instant-schema) nil)))
(defmethod mg/-schema-generator :time/local-date [schema options]
(ga/fmap #(. LocalDate ofEpochDay %) (gen/large-integer* (-min-max schema options))))
(defn -local-time-gen [schema options]
(ga/fmap #(. LocalTime ofSecondOfDay %) (gen/large-integer* (-min-max schema options))))
(defmethod mg/-schema-generator :time/local-time [schema options]
(-local-time-gen schema options))
(comment
(gen/sample (mg/-schema-generator (time/-local-time-schema) nil)))
(defn -offset-time-gen [schema options]
(let [local-opts (assoc options :accessor #(.toLocalTime ^OffsetTime %))
zone-opts #?(:clj (assoc options :accessor #(- (.getTotalSeconds (.getOffset ^OffsetTime %))))
:cljs (assoc options :accessor #(- (.totalSeconds (.offset ^js %)))))
offset-gen (-zone-offset-gen schema zone-opts)]
(ga/bind
(-local-time-gen schema local-opts)
(fn [local-time]
(ga/fmap #(. OffsetTime of local-time %) offset-gen)))))
(defmethod mg/-schema-generator :time/offset-time [schema options]
(-offset-time-gen schema options))
(comment
(gen/sample (mg/-schema-generator (time/-offset-time-schema) nil)))
(defmethod mg/-schema-generator :time/local-date-time [schema options]
(gen/fmap
(fn [n]
(. LocalDateTime of
(. LocalDate ofEpochDay (quot n seconds-in-day))
(. LocalTime ofSecondOfDay (mod n seconds-in-day))))
(gen/large-integer* (-min-max schema options))))
(comment
(gen/sample (mg/-schema-generator (time/-local-date-time-schema) nil) 1000))
(defn -zoned-date-time-gen [schema options]
(gen/bind
(-instant-gen schema options)
(fn [instant]
(gen/fmap #(. ZonedDateTime ofInstant instant %) zone-id-gen))))
(defmethod mg/-schema-generator :time/zoned-date-time [schema options]
(-zoned-date-time-gen schema options))
(comment
(gen/sample (mg/-schema-generator (time/-zoned-date-time-schema) nil) 100))
(defn -offset-date-time-gen [schema options]
(gen/fmap #(. OffsetDateTime from %) (-zoned-date-time-gen schema options)))
(defmethod mg/-schema-generator :time/offset-date-time [schema options]
(-offset-date-time-gen schema options))
(defmethod mg/-schema-generator :time/duration [schema options]
(gen/fmap #(. Duration ofNanos %) (gen/large-integer* (-min-max schema options))))
| null | https://raw.githubusercontent.com/metosin/malli/372ad8119300d1ed054a383e184c431b8494c697/src/malli/experimental/time/generator.cljc | clojure | (ns malli.experimental.time.generator
(:require [clojure.test.check.generators :as gen]
[clojure.spec.gen.alpha :as ga]
[malli.core :as m]
[malli.generator :as mg]
#?(:clj [malli.experimental.time :as time]
:cljs [malli.experimental.time :as time
:refer [Duration LocalDate LocalDateTime LocalTime Instant OffsetTime ZonedDateTime OffsetDateTime ZoneId ZoneOffset]]))
#?(:clj (:import (java.time Duration LocalDate LocalDateTime LocalTime Instant OffsetTime ZonedDateTime OffsetDateTime ZoneId ZoneOffset))))
#?(:clj (set! *warn-on-reflection* true))
(def zone-id-gen
(mg/generator (into [:enum] (map #(. ZoneId of ^String %)) (. ZoneId getAvailableZoneIds))))
(defmethod mg/-schema-generator :time/zone-id [_schema _options] zone-id-gen)
#?(:clj (def ^:const ^:private seconds-in-day 86400)
:cljs (def ^:private seconds-in-day 86400))
(defn -to-long ^long [o]
(cond
(instance? Instant o) (.toEpochMilli ^Instant o)
(instance? LocalDate o) (.toEpochDay ^LocalDate o)
(instance? LocalTime o) (.toSecondOfDay ^LocalTime o)
(instance? ZoneOffset o) #?(:clj (.getTotalSeconds ^ZoneOffset o)
:cljs (.totalSeconds ^ZoneOffset o))
(instance? LocalDateTime o)
(unchecked-add
(unchecked-multiply (.toEpochDay (.toLocalDate ^LocalDateTime o)) seconds-in-day)
(-to-long (.toLocalTime ^LocalDateTime o)))
(instance? OffsetDateTime o) (.toEpochMilli (.toInstant ^OffsetDateTime o))
(instance? ZonedDateTime o) (.toEpochMilli (.toInstant ^ZonedDateTime o))
(instance? Duration o) (.toNanos ^Duration o)
(int? o) (long o)))
(defn to-long [o] (when o (-to-long o)))
(defn -min-max [schema options]
(let [{:keys [min max] gen-min :gen/min gen-max :gen/max}
(merge
(m/type-properties schema options)
(m/properties schema options))
{:keys [accessor] :or {accessor identity}} options
as-long #(when % (to-long (accessor %)))
min (as-long min) max (as-long max) gen-min (as-long gen-min) gen-max (as-long gen-max)]
(when (and min gen-min (< gen-min min))
(m/-fail! ::mg/invalid-property {:key :gen/min, :value gen-min, :min min}))
(when (and max gen-max (> gen-max max))
(m/-fail! ::mg/invalid-property {:key :gen/max, :value gen-min, :max min}))
{:min (or gen-min min)
:max (or gen-max max)}))
(defn -zone-offset-gen [schema options]
(ga/fmap #(. ZoneOffset ofTotalSeconds %) (gen/large-integer* (-min-max schema options))))
(defmethod mg/-schema-generator :time/zone-offset [schema options]
(-zone-offset-gen schema options))
(defn -instant-gen [schema options]
(ga/fmap #(. Instant ofEpochMilli %) (gen/large-integer* (-min-max schema options))))
(defmethod mg/-schema-generator :time/instant [schema options]
(-instant-gen schema options))
(comment
(gen/sample (mg/-schema-generator (time/-instant-schema) nil)))
(defmethod mg/-schema-generator :time/local-date [schema options]
(ga/fmap #(. LocalDate ofEpochDay %) (gen/large-integer* (-min-max schema options))))
(defn -local-time-gen [schema options]
(ga/fmap #(. LocalTime ofSecondOfDay %) (gen/large-integer* (-min-max schema options))))
(defmethod mg/-schema-generator :time/local-time [schema options]
(-local-time-gen schema options))
(comment
(gen/sample (mg/-schema-generator (time/-local-time-schema) nil)))
(defn -offset-time-gen [schema options]
(let [local-opts (assoc options :accessor #(.toLocalTime ^OffsetTime %))
zone-opts #?(:clj (assoc options :accessor #(- (.getTotalSeconds (.getOffset ^OffsetTime %))))
:cljs (assoc options :accessor #(- (.totalSeconds (.offset ^js %)))))
offset-gen (-zone-offset-gen schema zone-opts)]
(ga/bind
(-local-time-gen schema local-opts)
(fn [local-time]
(ga/fmap #(. OffsetTime of local-time %) offset-gen)))))
(defmethod mg/-schema-generator :time/offset-time [schema options]
(-offset-time-gen schema options))
(comment
(gen/sample (mg/-schema-generator (time/-offset-time-schema) nil)))
(defmethod mg/-schema-generator :time/local-date-time [schema options]
(gen/fmap
(fn [n]
(. LocalDateTime of
(. LocalDate ofEpochDay (quot n seconds-in-day))
(. LocalTime ofSecondOfDay (mod n seconds-in-day))))
(gen/large-integer* (-min-max schema options))))
(comment
(gen/sample (mg/-schema-generator (time/-local-date-time-schema) nil) 1000))
(defn -zoned-date-time-gen [schema options]
(gen/bind
(-instant-gen schema options)
(fn [instant]
(gen/fmap #(. ZonedDateTime ofInstant instant %) zone-id-gen))))
(defmethod mg/-schema-generator :time/zoned-date-time [schema options]
(-zoned-date-time-gen schema options))
(comment
(gen/sample (mg/-schema-generator (time/-zoned-date-time-schema) nil) 100))
(defn -offset-date-time-gen [schema options]
(gen/fmap #(. OffsetDateTime from %) (-zoned-date-time-gen schema options)))
(defmethod mg/-schema-generator :time/offset-date-time [schema options]
(-offset-date-time-gen schema options))
(defmethod mg/-schema-generator :time/duration [schema options]
(gen/fmap #(. Duration ofNanos %) (gen/large-integer* (-min-max schema options))))
| |
8f5b5120280214a2c60b34a7b802c9fcabdd37c960b4c799d61b9a0912c4ccba | mmottl/gsl-ocaml | poly.ml | gsl - ocaml - OCaml interface to GSL
Copyright ( © ) 2002 - 2012 - Olivier Andrieu
Distributed under the terms of the GPL version 3
let () = Error.init ()
open Gsl_complex
type poly = float array
external eval : poly -> float -> float
= "ml_gsl_poly_eval"
type quad_sol =
| Quad_0
| Quad_2 of float * float
external solve_quadratic : a:float -> b:float -> c:float -> quad_sol
= "ml_gsl_poly_solve_quadratic"
external complex_solve_quadratic : a:float -> b:float -> c:float -> complex * complex
= "ml_gsl_poly_complex_solve_quadratic"
type cubic_sol =
| Cubic_0
| Cubic_1 of float
| Cubic_3 of float * float * float
external solve_cubic : a:float -> b:float -> c:float -> cubic_sol
= "ml_gsl_poly_solve_cubic"
external complex_solve_cubic : a:float -> b:float -> c:float -> complex * complex * complex
= "ml_gsl_poly_complex_solve_cubic"
type ws
external _alloc_ws : int -> ws = "ml_gsl_poly_complex_workspace_alloc"
external _free_ws : ws -> unit= "ml_gsl_poly_complex_workspace_free"
external _solve : poly -> ws -> complex_array -> unit
= "ml_gsl_poly_complex_solve"
let solve poly =
let n = Array.length poly in
let ws = _alloc_ws n in
try
let sol = Array.make (2*(n-1)) 0. in
_solve poly ws sol ;
_free_ws ws ;
sol
with exn ->
_free_ws ws ; raise exn
| null | https://raw.githubusercontent.com/mmottl/gsl-ocaml/76f8d93cccc1f23084f4a33d3e0a8f1289450580/src/poly.ml | ocaml | gsl - ocaml - OCaml interface to GSL
Copyright ( © ) 2002 - 2012 - Olivier Andrieu
Distributed under the terms of the GPL version 3
let () = Error.init ()
open Gsl_complex
type poly = float array
external eval : poly -> float -> float
= "ml_gsl_poly_eval"
type quad_sol =
| Quad_0
| Quad_2 of float * float
external solve_quadratic : a:float -> b:float -> c:float -> quad_sol
= "ml_gsl_poly_solve_quadratic"
external complex_solve_quadratic : a:float -> b:float -> c:float -> complex * complex
= "ml_gsl_poly_complex_solve_quadratic"
type cubic_sol =
| Cubic_0
| Cubic_1 of float
| Cubic_3 of float * float * float
external solve_cubic : a:float -> b:float -> c:float -> cubic_sol
= "ml_gsl_poly_solve_cubic"
external complex_solve_cubic : a:float -> b:float -> c:float -> complex * complex * complex
= "ml_gsl_poly_complex_solve_cubic"
type ws
external _alloc_ws : int -> ws = "ml_gsl_poly_complex_workspace_alloc"
external _free_ws : ws -> unit= "ml_gsl_poly_complex_workspace_free"
external _solve : poly -> ws -> complex_array -> unit
= "ml_gsl_poly_complex_solve"
let solve poly =
let n = Array.length poly in
let ws = _alloc_ws n in
try
let sol = Array.make (2*(n-1)) 0. in
_solve poly ws sol ;
_free_ws ws ;
sol
with exn ->
_free_ws ws ; raise exn
| |
1d6f6cfb7d1fdef7221b9da021aca2a6c65ff1a6808eebcb758b1957f3ea0d31 | MinaProtocol/mina | deferred.mli | open Core_kernel
open Async_kernel
include module type of Deferred with module Result := Deferred.Result
module List : sig
include module type of Deferred.List
end
module Result : sig
include module type of Deferred.Result
module List : sig
val fold :
'a list
-> init:'b
-> f:('b -> 'a -> ('b, 'e) Deferred.Result.t)
-> ('b, 'e) Deferred.Result.t
val map :
'a list
-> f:('a -> ('b, 'e) Deferred.Result.t)
-> ('b list, 'e) Deferred.Result.t
val iter :
'a list
-> f:('a -> (unit, 'e) Deferred.Result.t)
-> (unit, 'e) Deferred.Result.t
end
end
| null | https://raw.githubusercontent.com/MinaProtocol/mina/57e2ea1b87fe1a24517e1c62f51cc59fe9bc87cd/src/lib/mina_stdlib/deferred.mli | ocaml | open Core_kernel
open Async_kernel
include module type of Deferred with module Result := Deferred.Result
module List : sig
include module type of Deferred.List
end
module Result : sig
include module type of Deferred.Result
module List : sig
val fold :
'a list
-> init:'b
-> f:('b -> 'a -> ('b, 'e) Deferred.Result.t)
-> ('b, 'e) Deferred.Result.t
val map :
'a list
-> f:('a -> ('b, 'e) Deferred.Result.t)
-> ('b list, 'e) Deferred.Result.t
val iter :
'a list
-> f:('a -> (unit, 'e) Deferred.Result.t)
-> (unit, 'e) Deferred.Result.t
end
end
| |
4eaf7fa8022ba7836b8b8338363f130282b7e99f727f0602cd4c6f21862ef463 | naoiwata/sicp | ex3.23.scm | ;;
;; @author naoiwata
SICP Chapter3
Exercise 3.23 .
;;
; queue
(define (make-queue)
(cons '() '()))
(define (empty-queue? queue)
(null? (front-ptr queue)))
(define (front-queue queue)
(if (empty-queue? queue)
(error "no queue")
(value-node (front-ptr queue))))
(define (rear-queue queue)
(if (empty-queue? queue)
(error "no queue")
(value-node (rear-ptr queue))))
; ptr
(define (front-ptr queue)
(car queue))
(define (rear-ptr queue)
(cdr queue))
(define (set-front-ptr! queue node)
(set-car! queue node))
(define (set-rear-ptr! queue node)
(set-cdr! queue node))
; node
(define (make-node value)
(list value '() '()))
(define (value-node node)
(car node))
(define (next-node node)
(cddr node))
(define (prev-node node)
(cadr node))
(define (set-next-node! node next)
(set-cdr! (cdr node) next))
(define (set-prev-node! node prev)
(set-car! (cdr node) prev))
; insert
(define (front-insert-queue! queue value)
(let
((new-node (make-node value)))
(cond
((empty-queue? queue)
(set-front-ptr! queue new-node)
(set-rear-ptr! queue new-node)
queue)
(else
(set-next-node! new-node (front-ptr queue))
(set-rear-ptr! queue new-node)
queue))))
(define (rear-insert-queue! queue value)
(let
((new-node (make-node value)))
(cond
((empty-queue? queue)
(set-front-ptr! queue new-node)
(set-rear-ptr! queue new-node)
queue)
(else
(set-prev-node! new-node (rear-ptr queue))
(set-next-node! (rear-ptr queue) new-node)
(set-rear-ptr! queue new-node)
queue))))
; delete
(define (front-delete-queue! queue)
(cond
((empty-queue? queue)
(error "no queue"))
(else
(set-front-ptr! queue (next-node (front-ptr queue))))))
(define (rear-delete-queue! queue)
(cond
((empty-queue? queue)
(error "no queue"))
(else
(set-rear-ptr! queue (prev-node (rear-ptr queue))))))
; display
(define (display-queue queue)
(define (display-queue-internal q)
(cond ((eq? q (rear-ptr queue))
(display " ")
(display (value-node q)))
(else
(begin (display " ")
(display (value-node q))
(display-queue-internal (next-node q))))))
(if (empty-queue? queue)
(display "empty queue\n")
(begin
(display "(")
(display-queue-internal (front-ptr queue))
(display ")\n"))))
; test
(define q (make-queue))
(display-queue q) ; empty queue
(front-insert-queue! q 'a)
(display-queue q) ; (a)
(rear-insert-queue! q 'b)
(display-queue q) ; (a b)
(front-delete-queue! q)
(display-queue q) ; (b)
(rear-insert-queue! q 'c)
(front-delete-queue! q)
(display-queue q) ; (c)
; END | null | https://raw.githubusercontent.com/naoiwata/sicp/7314136c5892de402015acfe4b9148a3558b1211/chapter3/ex3.23.scm | scheme |
@author naoiwata
queue
ptr
node
insert
delete
display
test
empty queue
(a)
(a b)
(b)
(c)
END | SICP Chapter3
Exercise 3.23 .
(define (make-queue)
(cons '() '()))
(define (empty-queue? queue)
(null? (front-ptr queue)))
(define (front-queue queue)
(if (empty-queue? queue)
(error "no queue")
(value-node (front-ptr queue))))
(define (rear-queue queue)
(if (empty-queue? queue)
(error "no queue")
(value-node (rear-ptr queue))))
(define (front-ptr queue)
(car queue))
(define (rear-ptr queue)
(cdr queue))
(define (set-front-ptr! queue node)
(set-car! queue node))
(define (set-rear-ptr! queue node)
(set-cdr! queue node))
(define (make-node value)
(list value '() '()))
(define (value-node node)
(car node))
(define (next-node node)
(cddr node))
(define (prev-node node)
(cadr node))
(define (set-next-node! node next)
(set-cdr! (cdr node) next))
(define (set-prev-node! node prev)
(set-car! (cdr node) prev))
(define (front-insert-queue! queue value)
(let
((new-node (make-node value)))
(cond
((empty-queue? queue)
(set-front-ptr! queue new-node)
(set-rear-ptr! queue new-node)
queue)
(else
(set-next-node! new-node (front-ptr queue))
(set-rear-ptr! queue new-node)
queue))))
(define (rear-insert-queue! queue value)
(let
((new-node (make-node value)))
(cond
((empty-queue? queue)
(set-front-ptr! queue new-node)
(set-rear-ptr! queue new-node)
queue)
(else
(set-prev-node! new-node (rear-ptr queue))
(set-next-node! (rear-ptr queue) new-node)
(set-rear-ptr! queue new-node)
queue))))
(define (front-delete-queue! queue)
(cond
((empty-queue? queue)
(error "no queue"))
(else
(set-front-ptr! queue (next-node (front-ptr queue))))))
(define (rear-delete-queue! queue)
(cond
((empty-queue? queue)
(error "no queue"))
(else
(set-rear-ptr! queue (prev-node (rear-ptr queue))))))
(define (display-queue queue)
(define (display-queue-internal q)
(cond ((eq? q (rear-ptr queue))
(display " ")
(display (value-node q)))
(else
(begin (display " ")
(display (value-node q))
(display-queue-internal (next-node q))))))
(if (empty-queue? queue)
(display "empty queue\n")
(begin
(display "(")
(display-queue-internal (front-ptr queue))
(display ")\n"))))
(define q (make-queue))
(front-insert-queue! q 'a)
(rear-insert-queue! q 'b)
(front-delete-queue! q)
(rear-insert-queue! q 'c)
(front-delete-queue! q)
|
3b8955f7154456571b53065fb6ac620f6840b0acf81610f13913ea454df0e784 | haskell-tls/hs-certificate | Fingerprint.hs | -- |
-- Module : Data.X509.Validation.Fingerprint
-- License : BSD-style
Maintainer : < >
-- Stability : experimental
-- Portability : unknown
--
# LANGUAGE GeneralizedNewtypeDeriving #
module Data.X509.Validation.Fingerprint
( Fingerprint(..)
, getFingerprint
) where
import Crypto.Hash
import Data.X509
import Data.ASN1.Types
import Data.ByteArray (convert, ByteArrayAccess)
import Data.ByteString (ByteString)
-- | Fingerprint of a certificate
newtype Fingerprint = Fingerprint ByteString
deriving (Show,Eq,ByteArrayAccess)
-- | Get the fingerprint of the whole signed object
-- using the hashing algorithm specified
getFingerprint :: (Show a, Eq a, ASN1Object a)
=> SignedExact a -- ^ object to fingerprint
-> HashALG -- ^ algorithm to compute the fingerprint
-> Fingerprint -- ^ fingerprint in binary form
getFingerprint sobj halg = Fingerprint $ mkHash halg $ encodeSignedObject sobj
where
mkHash HashMD2 = convert . hashWith MD2
mkHash HashMD5 = convert . hashWith MD5
mkHash HashSHA1 = convert . hashWith SHA1
mkHash HashSHA224 = convert . hashWith SHA224
mkHash HashSHA256 = convert . hashWith SHA256
mkHash HashSHA384 = convert . hashWith SHA384
mkHash HashSHA512 = convert . hashWith SHA512
| null | https://raw.githubusercontent.com/haskell-tls/hs-certificate/4a0a2ce292ea46c0c5f72e1d31eca2001079cdd2/x509-validation/Data/X509/Validation/Fingerprint.hs | haskell | |
Module : Data.X509.Validation.Fingerprint
License : BSD-style
Stability : experimental
Portability : unknown
| Fingerprint of a certificate
| Get the fingerprint of the whole signed object
using the hashing algorithm specified
^ object to fingerprint
^ algorithm to compute the fingerprint
^ fingerprint in binary form | Maintainer : < >
# LANGUAGE GeneralizedNewtypeDeriving #
module Data.X509.Validation.Fingerprint
( Fingerprint(..)
, getFingerprint
) where
import Crypto.Hash
import Data.X509
import Data.ASN1.Types
import Data.ByteArray (convert, ByteArrayAccess)
import Data.ByteString (ByteString)
newtype Fingerprint = Fingerprint ByteString
deriving (Show,Eq,ByteArrayAccess)
getFingerprint :: (Show a, Eq a, ASN1Object a)
getFingerprint sobj halg = Fingerprint $ mkHash halg $ encodeSignedObject sobj
where
mkHash HashMD2 = convert . hashWith MD2
mkHash HashMD5 = convert . hashWith MD5
mkHash HashSHA1 = convert . hashWith SHA1
mkHash HashSHA224 = convert . hashWith SHA224
mkHash HashSHA256 = convert . hashWith SHA256
mkHash HashSHA384 = convert . hashWith SHA384
mkHash HashSHA512 = convert . hashWith SHA512
|
e7bca43e9de6ff5722493942b58e9ef0874b44dee495662ee6a70c149d60beb9 | jackfirth/lens | flatten.rkt | #lang racket/base
(provide append*-lens flatten/depth-lens flatten/depth unflatten/depth)
(require fancy-app lens/common racket/list racket/match)
(module+ test
(require rackunit syntax/parse lens/private/test-util/test-lens))
( define - type ( * A n )
( cond [ ( zero ? n ) A ]
[ else ( * ( A ) ( sub1 n ) ) ] ) )
flatten / depth - lens : ( Lens ( Listof * Any n ) ( Any ) )
;; where the only valid views are lists with the same length as the
;; result of (flatten/depth n target)
(define (flatten/depth-lens n)
(make-lens
(flatten/depth n _)
(unflatten/depth n _ _)))
append*-lens : ( Lens ( ( Any ) ) ( Any ) )
;; where the only valid views are lists with the same length as the
;; result of applying append* to the target.
;; Viewing is equivalent to using append*
;; Setting restores the structure of the original nested list
(define append*-lens
(flatten/depth-lens 2))
flatten / depth : n ( * A n ) - > ( A )
(define (flatten/depth n structure)
(check-structure-depth! n structure)
(cond [(zero? n) (list structure)]
[else (append*n (sub1 n) structure)]))
unflatten / depth : n ( * A n ) ( B ) - > ( * B n )
(define (unflatten/depth n structure flattened)
(check-structure-depth! n structure)
(check-flattened-length! n structure flattened)
(cond [(zero? n) (first flattened)]
[else (unappend*n (sub1 n) structure flattened)]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
restore - structure : ( ( A ) ) ( B ) - > ( ( B ) )
Takes a list of lists and a list and un - flattens the flattened
;; argument according to the structure of the structure arguement.
;; The length of the flattened list must be the same as the length
;; of (append* structure).
(define (restore-structure structure flattened)
(restore-structure/acc structure flattened (list)))
restore - structure / acc : ( ( A ) ) ( B ) ( ( B ) ) - > ( ( B ) )
;; Accumulates a reversed version of the result of restore-structure,
then returns an un - reversed version .
(define (restore-structure/acc structure flattened acc)
(match structure
[(list)
(reverse acc)]
[(cons s-lst s-rst)
(define-values [f-lst f-rst]
(split-at flattened (length s-lst)))
(restore-structure/acc s-rst f-rst (cons f-lst acc))]))
append*n : n ( ( * A n ) ) - > ( A )
(define (append*n n structure)
(cond [(zero? n) structure]
[else (append*n (sub1 n) (append* structure))]))
unappend*n : n ( ( * A n ) ) ( B ) - > ( ( * B n ) )
(define (unappend*n n structure flattened)
(cond [(zero? n) flattened]
[else (restore-structure
structure
(unappend*n (sub1 n) (append* structure) flattened))]))
;; list/depth? : Natural Any -> Boolean
(define (list/depth? n structure)
(cond [(zero? n) #true]
[else (and (list? structure)
(andmap (list/depth? (sub1 n) _) structure))]))
check - structure - depth ! : n ( * A n ) - > Void
(define (check-structure-depth! depth structure)
(unless (list/depth? depth structure)
(raise-argument-error 'flatten/depth-lens
(format "a nested list of depth ~v" depth)
structure)))
check - flattened - length ! : n ( * A n ) ( B ) - > Void
(define (check-flattened-length! depth structure flattened)
(unless (= (length (flatten/depth depth structure)) (length flattened))
(raise-argument-error 'flatten/depth-lens
(format "a list of length ~v"
(length (flatten/depth depth structure)))
1
structure
flattened)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(module+ test
(test-case "append*-lens"
(check-equal? (lens-view append*-lens (list (list 1) (list 2 3) (list)))
(list 1 2 3))
(check-equal? (lens-set append*-lens
(list (list 1) (list 2 3) (list))
(list 'a 'b 'c))
(list (list 'a) (list 'b 'c) (list)))
(check-equal? (lens-transform append*-lens
(list (list 1) (list 2 3) (list))
reverse) ; any length-preserving computation
(list (list 3) (list 2 1) (list)))
(check-exn #rx"expected: a nested list of depth 2\n given: '\\(5\\)"
(λ () (lens-view append*-lens (list 5))))
(check-exn #rx"expected: a nested list of depth 2\n given: '\\(5\\)"
(λ () (lens-set append*-lens (list 5) (list 'a))))
(check-exn #rx"expected: a list of length 3\n given: '\\(a b\\)"
(λ () (lens-set append*-lens (list (list 1) (list 2 3) (list)) (list 'a 'b))))
(test-lens-laws append*-lens
(list (list 1) (list 2 3) (list))
(list 'a 'b 'c)
(list "a" "b" "c"))
)
(test-case "(flatten/depth-lens 0) adds a list layer"
(define flat0-lens (flatten/depth-lens 0))
(check-equal? (lens-view flat0-lens 42) (list 42))
(check-equal? (lens-set flat0-lens 42 (list 'a)) 'a)
(check-equal? (lens-transform flat0-lens 42 reverse) 42)
(test-lens-laws flat0-lens
42
(list 'a)
(list "a")))
(test-case "(flatten/depth-lens 1) copies the list"
(define flat1-lens (flatten/depth-lens 1))
(check-equal? (lens-view flat1-lens (list 1 2 3)) (list 1 2 3))
(check-equal? (lens-set flat1-lens (list 1 2 3) (list 'a 'b 'c)) (list 'a 'b 'c))
(check-equal? (lens-transform flat1-lens (list 1 2 3) reverse) (list 3 2 1))
(test-lens-laws flat1-lens
(list 1 2 3)
(list 'a 'b 'c)
(list "a" "b" "c")))
(test-case "(flatten/depth-lens 2) should be equivalent to append*-lens"
(define flat2-lens (flatten/depth-lens 2))
(check-equal? (lens-view flat2-lens
(list (list 1) (list 2 3) (list)))
(list 1 2 3))
(check-equal? (lens-set flat2-lens
(list (list 1) (list 2 3) (list))
(list 'a 'b 'c))
(list (list 'a) (list 'b 'c) (list)))
(check-equal? (lens-transform flat2-lens
(list (list 1) (list 2 3) (list))
reverse)
(list (list 3) (list 2 1) (list)))
(test-lens-laws flat2-lens
(list (list 1) (list 2 3) (list))
(list 'a 'b 'c)
(list "a" "b" "c")))
(test-case "(flatten/depth-lens 3) deals with lists of depth 3"
(define flat3-lens (flatten/depth-lens 3))
(check-equal? (lens-view flat3-lens
(list (list (list) (list 1))
(list (list 2 3))
(list)
(list (list 4) (list) (list 5 6))))
(list 1 2 3 4 5 6))
(check-equal? (lens-set flat3-lens
(list (list (list) (list 1))
(list (list 2 3))
(list)
(list (list 4) (list) (list 5 6)))
(list 'a 'b 'c 'd 'e 'f))
(list (list (list) (list 'a))
(list (list 'b 'c))
(list)
(list (list 'd) (list) (list 'e 'f))))
(check-equal? (lens-transform flat3-lens
(list (list (list) (list 1))
(list (list 2 3))
(list)
(list (list 4) (list) (list 5 6)))
reverse)
(list (list (list) (list 6))
(list (list 5 4))
(list)
(list (list 3) (list) (list 2 1))))
(check-exn #rx"expected: a nested list of depth 3\n *given: '\\(5\\)"
(λ () (lens-view flat3-lens (list 5))))
(check-exn #rx"expected: a nested list of depth 3\n given: '\\(5\\)"
(λ () (lens-set flat3-lens (list 5) (list 'a))))
(check-exn #rx"expected: a list of length 6\n given: '\\(a b\\)"
(λ () (lens-set flat3-lens
(list (list (list) (list 1))
(list (list 2 3))
(list)
(list (list 4) (list) (list 5 6)))
(list 'a 'b))))
(test-lens-laws flat3-lens
(list (list (list) (list 1))
(list (list 2 3))
(list)
(list (list 4) (list) (list 5 6)))
(list 'a 'b 'c 'd 'e 'f)
(list "a" "b" "c" "d" "e" "f")))
)
| null | https://raw.githubusercontent.com/jackfirth/lens/733db7744921409b69ddc78ae5b23ffaa6b91e37/lens-data/lens/private/list/flatten.rkt | racket | where the only valid views are lists with the same length as the
result of (flatten/depth n target)
where the only valid views are lists with the same length as the
result of applying append* to the target.
Viewing is equivalent to using append*
Setting restores the structure of the original nested list
argument according to the structure of the structure arguement.
The length of the flattened list must be the same as the length
of (append* structure).
Accumulates a reversed version of the result of restore-structure,
list/depth? : Natural Any -> Boolean
any length-preserving computation | #lang racket/base
(provide append*-lens flatten/depth-lens flatten/depth unflatten/depth)
(require fancy-app lens/common racket/list racket/match)
(module+ test
(require rackunit syntax/parse lens/private/test-util/test-lens))
( define - type ( * A n )
( cond [ ( zero ? n ) A ]
[ else ( * ( A ) ( sub1 n ) ) ] ) )
flatten / depth - lens : ( Lens ( Listof * Any n ) ( Any ) )
(define (flatten/depth-lens n)
(make-lens
(flatten/depth n _)
(unflatten/depth n _ _)))
append*-lens : ( Lens ( ( Any ) ) ( Any ) )
(define append*-lens
(flatten/depth-lens 2))
flatten / depth : n ( * A n ) - > ( A )
(define (flatten/depth n structure)
(check-structure-depth! n structure)
(cond [(zero? n) (list structure)]
[else (append*n (sub1 n) structure)]))
unflatten / depth : n ( * A n ) ( B ) - > ( * B n )
(define (unflatten/depth n structure flattened)
(check-structure-depth! n structure)
(check-flattened-length! n structure flattened)
(cond [(zero? n) (first flattened)]
[else (unappend*n (sub1 n) structure flattened)]))
restore - structure : ( ( A ) ) ( B ) - > ( ( B ) )
Takes a list of lists and a list and un - flattens the flattened
(define (restore-structure structure flattened)
(restore-structure/acc structure flattened (list)))
restore - structure / acc : ( ( A ) ) ( B ) ( ( B ) ) - > ( ( B ) )
then returns an un - reversed version .
(define (restore-structure/acc structure flattened acc)
(match structure
[(list)
(reverse acc)]
[(cons s-lst s-rst)
(define-values [f-lst f-rst]
(split-at flattened (length s-lst)))
(restore-structure/acc s-rst f-rst (cons f-lst acc))]))
append*n : n ( ( * A n ) ) - > ( A )
(define (append*n n structure)
(cond [(zero? n) structure]
[else (append*n (sub1 n) (append* structure))]))
unappend*n : n ( ( * A n ) ) ( B ) - > ( ( * B n ) )
(define (unappend*n n structure flattened)
(cond [(zero? n) flattened]
[else (restore-structure
structure
(unappend*n (sub1 n) (append* structure) flattened))]))
(define (list/depth? n structure)
(cond [(zero? n) #true]
[else (and (list? structure)
(andmap (list/depth? (sub1 n) _) structure))]))
check - structure - depth ! : n ( * A n ) - > Void
(define (check-structure-depth! depth structure)
(unless (list/depth? depth structure)
(raise-argument-error 'flatten/depth-lens
(format "a nested list of depth ~v" depth)
structure)))
check - flattened - length ! : n ( * A n ) ( B ) - > Void
(define (check-flattened-length! depth structure flattened)
(unless (= (length (flatten/depth depth structure)) (length flattened))
(raise-argument-error 'flatten/depth-lens
(format "a list of length ~v"
(length (flatten/depth depth structure)))
1
structure
flattened)))
(module+ test
(test-case "append*-lens"
(check-equal? (lens-view append*-lens (list (list 1) (list 2 3) (list)))
(list 1 2 3))
(check-equal? (lens-set append*-lens
(list (list 1) (list 2 3) (list))
(list 'a 'b 'c))
(list (list 'a) (list 'b 'c) (list)))
(check-equal? (lens-transform append*-lens
(list (list 1) (list 2 3) (list))
(list (list 3) (list 2 1) (list)))
(check-exn #rx"expected: a nested list of depth 2\n given: '\\(5\\)"
(λ () (lens-view append*-lens (list 5))))
(check-exn #rx"expected: a nested list of depth 2\n given: '\\(5\\)"
(λ () (lens-set append*-lens (list 5) (list 'a))))
(check-exn #rx"expected: a list of length 3\n given: '\\(a b\\)"
(λ () (lens-set append*-lens (list (list 1) (list 2 3) (list)) (list 'a 'b))))
(test-lens-laws append*-lens
(list (list 1) (list 2 3) (list))
(list 'a 'b 'c)
(list "a" "b" "c"))
)
(test-case "(flatten/depth-lens 0) adds a list layer"
(define flat0-lens (flatten/depth-lens 0))
(check-equal? (lens-view flat0-lens 42) (list 42))
(check-equal? (lens-set flat0-lens 42 (list 'a)) 'a)
(check-equal? (lens-transform flat0-lens 42 reverse) 42)
(test-lens-laws flat0-lens
42
(list 'a)
(list "a")))
(test-case "(flatten/depth-lens 1) copies the list"
(define flat1-lens (flatten/depth-lens 1))
(check-equal? (lens-view flat1-lens (list 1 2 3)) (list 1 2 3))
(check-equal? (lens-set flat1-lens (list 1 2 3) (list 'a 'b 'c)) (list 'a 'b 'c))
(check-equal? (lens-transform flat1-lens (list 1 2 3) reverse) (list 3 2 1))
(test-lens-laws flat1-lens
(list 1 2 3)
(list 'a 'b 'c)
(list "a" "b" "c")))
(test-case "(flatten/depth-lens 2) should be equivalent to append*-lens"
(define flat2-lens (flatten/depth-lens 2))
(check-equal? (lens-view flat2-lens
(list (list 1) (list 2 3) (list)))
(list 1 2 3))
(check-equal? (lens-set flat2-lens
(list (list 1) (list 2 3) (list))
(list 'a 'b 'c))
(list (list 'a) (list 'b 'c) (list)))
(check-equal? (lens-transform flat2-lens
(list (list 1) (list 2 3) (list))
reverse)
(list (list 3) (list 2 1) (list)))
(test-lens-laws flat2-lens
(list (list 1) (list 2 3) (list))
(list 'a 'b 'c)
(list "a" "b" "c")))
(test-case "(flatten/depth-lens 3) deals with lists of depth 3"
(define flat3-lens (flatten/depth-lens 3))
(check-equal? (lens-view flat3-lens
(list (list (list) (list 1))
(list (list 2 3))
(list)
(list (list 4) (list) (list 5 6))))
(list 1 2 3 4 5 6))
(check-equal? (lens-set flat3-lens
(list (list (list) (list 1))
(list (list 2 3))
(list)
(list (list 4) (list) (list 5 6)))
(list 'a 'b 'c 'd 'e 'f))
(list (list (list) (list 'a))
(list (list 'b 'c))
(list)
(list (list 'd) (list) (list 'e 'f))))
(check-equal? (lens-transform flat3-lens
(list (list (list) (list 1))
(list (list 2 3))
(list)
(list (list 4) (list) (list 5 6)))
reverse)
(list (list (list) (list 6))
(list (list 5 4))
(list)
(list (list 3) (list) (list 2 1))))
(check-exn #rx"expected: a nested list of depth 3\n *given: '\\(5\\)"
(λ () (lens-view flat3-lens (list 5))))
(check-exn #rx"expected: a nested list of depth 3\n given: '\\(5\\)"
(λ () (lens-set flat3-lens (list 5) (list 'a))))
(check-exn #rx"expected: a list of length 6\n given: '\\(a b\\)"
(λ () (lens-set flat3-lens
(list (list (list) (list 1))
(list (list 2 3))
(list)
(list (list 4) (list) (list 5 6)))
(list 'a 'b))))
(test-lens-laws flat3-lens
(list (list (list) (list 1))
(list (list 2 3))
(list)
(list (list 4) (list) (list 5 6)))
(list 'a 'b 'c 'd 'e 'f)
(list "a" "b" "c" "d" "e" "f")))
)
|
349c2b8a955e0103cf2807dfff08c93c3c609d703a0a7fe8406275dd5d8eccbd | mikeplus64/plissken | OBJ.hs | {-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
module OBJ
( OBJ, ObjCommand(..)
, readObj) where
import qualified Data.Attoparsec as A
import Data.Attoparsec.Char8
import qualified Data.ByteString.Char8 as B
import Data.ByteString.Char8 (ByteString)
import Control.Applicative
import Geometry (F,I,I2,I3)
-- | See
-- This type implements a single line of an obj file.
--
-- Not defined in the 'Types' module because this type only matters here.
data ObjCommand
= Comment !ByteString
| MTLlib !ByteString
| UseMTL !ByteString
| Object !ByteString
| Group !ByteString
| S !I
| V !F !F !F
| VT !F !F
| VN !F !F !F
| FV !I !I !I
| FVT !I2 !I2 !I2
| FVN !I2 !I2 !I2
| FVTN !I3 !I3 !I3
deriving (Show, Eq)
type OBJ = [ObjCommand]
readObj :: FilePath -> IO (Either String OBJ)
readObj file = parseOnly parseObj `fmap` B.readFile file
parseObj :: Parser OBJ
parseObj = do
objs <- (seperatedByLines . choice)
[ parseFace
, parseVert
, parseVertTex
, parseVertNorm
, parseSmooth
, parseGroup
, parseObject
, parseComment
, parseUseMTL
, parseMTLlib
, fail "Unrecognised .obj command."]
endOfInput <|> endOfLine >> endOfInput
return objs
where
seperatedByLines f = f `sepBy` endOfLine
-- | Farse a floating point number.
float :: (Fractional a, Real a) => Parser a
float = fmap realToFrac double
-- | Farse something seperated by spaces.
spaced :: Parser a -> Parser [a]
spaced f = f `sepBy` space
parseFace :: Parser ObjCommand
parseFace = do
string "f "
fvtn <|> fvn <|> fvt <|> fv
where
-- parse multiple vertex indices, vertex indices+texture indices, vertex
-- indices+vertex normal indices and vertex indices+texture indices+vertex
-- normal indices
fv = do [x,y,z] <- spaced fv' ; return (FV x y z)
fvt = do [x,y,z] <- spaced fvt' ; return (FVT x y z)
fvn = do [x,y,z] <- spaced fvn' ; return (FVN x y z)
fvtn = do [x,y,z] <- spaced fvtn' ; return (FVTN x y z)
-- individual face parsers
fv' = decimal
fvt' = do [x,y] <- decimal `sepBy` char '/' ; return (x,y)
fvn' = do [x,y] <- decimal `sepBy` string "//" ; return (x,y)
fvtn' = do [x,y,z] <- decimal `sepBy` char '/' ; return (x,y,z)
parseVert :: Parser ObjCommand
parseVert = do
string "v "
[x,y,z] <- spaced float
return (V x y z)
parseVertTex :: Parser ObjCommand
parseVertTex = do
string "vt "
[x,y] <- spaced float
return (VT x y)
parseVertNorm :: Parser ObjCommand
parseVertNorm = do
string "vn "
[x,y,z] <- spaced float
return (VN x y z)
parseSmooth :: Parser ObjCommand
parseSmooth = do
string "s "
smoothGroup <- fromInteger `fmap` decimal
return (S smoothGroup)
parseGroup :: Parser ObjCommand
parseGroup = do
string "g "
Group `fmap` A.takeTill isEndOfLine
parseObject :: Parser ObjCommand
parseObject = do
string "o "
Object `fmap` A.takeTill isEndOfLine
parseComment :: Parser ObjCommand
parseComment = do
char '#'
Comment `fmap` A.takeTill isEndOfLine
parseUseMTL :: Parser ObjCommand
parseUseMTL = do
string "usemtl "
UseMTL `fmap` A.takeTill isEndOfLine
parseMTLlib :: Parser ObjCommand
parseMTLlib = do
string "mtllib "
MTLlib `fmap` A.takeTill isEndOfLine
| null | https://raw.githubusercontent.com/mikeplus64/plissken/e872db14c2e6d0df9379f81aaeaa448ca1ade6fd/src/OBJ.hs | haskell | # LANGUAGE OverloadedStrings #
# OPTIONS_GHC -funbox-strict-fields #
| See
This type implements a single line of an obj file.
Not defined in the 'Types' module because this type only matters here.
| Farse a floating point number.
| Farse something seperated by spaces.
parse multiple vertex indices, vertex indices+texture indices, vertex
indices+vertex normal indices and vertex indices+texture indices+vertex
normal indices
individual face parsers | module OBJ
( OBJ, ObjCommand(..)
, readObj) where
import qualified Data.Attoparsec as A
import Data.Attoparsec.Char8
import qualified Data.ByteString.Char8 as B
import Data.ByteString.Char8 (ByteString)
import Control.Applicative
import Geometry (F,I,I2,I3)
data ObjCommand
= Comment !ByteString
| MTLlib !ByteString
| UseMTL !ByteString
| Object !ByteString
| Group !ByteString
| S !I
| V !F !F !F
| VT !F !F
| VN !F !F !F
| FV !I !I !I
| FVT !I2 !I2 !I2
| FVN !I2 !I2 !I2
| FVTN !I3 !I3 !I3
deriving (Show, Eq)
type OBJ = [ObjCommand]
readObj :: FilePath -> IO (Either String OBJ)
readObj file = parseOnly parseObj `fmap` B.readFile file
parseObj :: Parser OBJ
parseObj = do
objs <- (seperatedByLines . choice)
[ parseFace
, parseVert
, parseVertTex
, parseVertNorm
, parseSmooth
, parseGroup
, parseObject
, parseComment
, parseUseMTL
, parseMTLlib
, fail "Unrecognised .obj command."]
endOfInput <|> endOfLine >> endOfInput
return objs
where
seperatedByLines f = f `sepBy` endOfLine
float :: (Fractional a, Real a) => Parser a
float = fmap realToFrac double
spaced :: Parser a -> Parser [a]
spaced f = f `sepBy` space
parseFace :: Parser ObjCommand
parseFace = do
string "f "
fvtn <|> fvn <|> fvt <|> fv
where
fv = do [x,y,z] <- spaced fv' ; return (FV x y z)
fvt = do [x,y,z] <- spaced fvt' ; return (FVT x y z)
fvn = do [x,y,z] <- spaced fvn' ; return (FVN x y z)
fvtn = do [x,y,z] <- spaced fvtn' ; return (FVTN x y z)
fv' = decimal
fvt' = do [x,y] <- decimal `sepBy` char '/' ; return (x,y)
fvn' = do [x,y] <- decimal `sepBy` string "//" ; return (x,y)
fvtn' = do [x,y,z] <- decimal `sepBy` char '/' ; return (x,y,z)
parseVert :: Parser ObjCommand
parseVert = do
string "v "
[x,y,z] <- spaced float
return (V x y z)
parseVertTex :: Parser ObjCommand
parseVertTex = do
string "vt "
[x,y] <- spaced float
return (VT x y)
parseVertNorm :: Parser ObjCommand
parseVertNorm = do
string "vn "
[x,y,z] <- spaced float
return (VN x y z)
parseSmooth :: Parser ObjCommand
parseSmooth = do
string "s "
smoothGroup <- fromInteger `fmap` decimal
return (S smoothGroup)
parseGroup :: Parser ObjCommand
parseGroup = do
string "g "
Group `fmap` A.takeTill isEndOfLine
parseObject :: Parser ObjCommand
parseObject = do
string "o "
Object `fmap` A.takeTill isEndOfLine
parseComment :: Parser ObjCommand
parseComment = do
char '#'
Comment `fmap` A.takeTill isEndOfLine
parseUseMTL :: Parser ObjCommand
parseUseMTL = do
string "usemtl "
UseMTL `fmap` A.takeTill isEndOfLine
parseMTLlib :: Parser ObjCommand
parseMTLlib = do
string "mtllib "
MTLlib `fmap` A.takeTill isEndOfLine
|
fe742a1d58bf8584e59e4078e3803fff6d2771abdcf5c24074e1f7914e3e4e04 | phillord/identitas | core.clj | (ns identitas.core
(:require [identitas.proquint :as p]
[identitas.damm :as d]))
(def ^{:private true} max-val-by-10
(unchecked-divide-int
Integer/MAX_VALUE 10))
(def ^{:private true} min-val-by-10
(* -1
(unchecked-divide-int
Integer/MAX_VALUE 10)))
(defn random-damm-proint
"Returns a random int proquint after validate it with checksum."
([]
(random-damm-proint "-"))
([sep]
(p/int-to-proint
(d/add-check
(unchecked-int (rand-int (- max-val-by-10 min-val-by-10)))) sep)))
(defn proint-damm-valid?
"Returns a validation of a given int proquint."
[ident]
(d/valid?
(p/proint-to-int ident)))
| null | https://raw.githubusercontent.com/phillord/identitas/b1e9dc7883eaacc53feab46259bf24a5599cb7ad/src/identitas/core.clj | clojure | (ns identitas.core
(:require [identitas.proquint :as p]
[identitas.damm :as d]))
(def ^{:private true} max-val-by-10
(unchecked-divide-int
Integer/MAX_VALUE 10))
(def ^{:private true} min-val-by-10
(* -1
(unchecked-divide-int
Integer/MAX_VALUE 10)))
(defn random-damm-proint
"Returns a random int proquint after validate it with checksum."
([]
(random-damm-proint "-"))
([sep]
(p/int-to-proint
(d/add-check
(unchecked-int (rand-int (- max-val-by-10 min-val-by-10)))) sep)))
(defn proint-damm-valid?
"Returns a validation of a given int proquint."
[ident]
(d/valid?
(p/proint-to-int ident)))
| |
9f5f4249834907ad078bd70cadb4c9ca1ab83c29a97930eae9e3b5012b119232 | elektronaut/advent-of-code | day07.clj | (ns advent-of-code.2022.07
(:require [clojure.string :as str]))
(defn parse-command [string]
(let* [lines (str/split-lines string)
command (str/split (first lines) #" ")
name (first command)
arg (str/join " " (rest command))
output (drop 1 lines)]
{:name name :arg arg :output output}))
(defn cd [path arg]
(case arg
"/" ["/"]
".." (pop path)
(conj path arg)))
(defn ls-line [line]
(let [[value-str name] (str/split line #" ")]
{name (if (= "dir" value-str) {} (Integer/parseInt value-str))}))
(defn ls [output]
(reduce merge (map ls-line output)))
(defn step [[cwd tree] command]
(case (command :name)
"cd" [(cd cwd (command :arg)) tree]
"ls" [cwd (assoc-in tree cwd (ls (command :output)))]))
(def tree
(->> (str/split (slurp "2022/day07/input.txt") #"\n?\$ ")
(drop 1)
(map parse-command)
(reduce step [["/"] {}])
(last)))
(defn directories [node]
(let [subdirs (filter map? (vals node))]
(conj (mapcat directories subdirs) node)))
(defn directory-size [node]
(let [subdirs (filter map? (vals node))
size (reduce + (remove map? (vals node)))]
(+ size (reduce + (map directory-size subdirs)))))
(def sizes
(->> (directories (get-in tree ["/"]))
(map directory-size)
(sort)))
(println "Part 1:"
(->> (filter #(<= % 100000) sizes)
(reduce +)))
(println "Part 2:"
(let* [root-size (last sizes)
free-space (- 70000000 root-size)
required-size (- 30000000 free-space)]
(first (filter #(>= % required-size) sizes))))
| null | https://raw.githubusercontent.com/elektronaut/advent-of-code/a8bb7bbadc8167ebb1df0d532493317705bb7f0d/2022/day07/day07.clj | clojure | (ns advent-of-code.2022.07
(:require [clojure.string :as str]))
(defn parse-command [string]
(let* [lines (str/split-lines string)
command (str/split (first lines) #" ")
name (first command)
arg (str/join " " (rest command))
output (drop 1 lines)]
{:name name :arg arg :output output}))
(defn cd [path arg]
(case arg
"/" ["/"]
".." (pop path)
(conj path arg)))
(defn ls-line [line]
(let [[value-str name] (str/split line #" ")]
{name (if (= "dir" value-str) {} (Integer/parseInt value-str))}))
(defn ls [output]
(reduce merge (map ls-line output)))
(defn step [[cwd tree] command]
(case (command :name)
"cd" [(cd cwd (command :arg)) tree]
"ls" [cwd (assoc-in tree cwd (ls (command :output)))]))
(def tree
(->> (str/split (slurp "2022/day07/input.txt") #"\n?\$ ")
(drop 1)
(map parse-command)
(reduce step [["/"] {}])
(last)))
(defn directories [node]
(let [subdirs (filter map? (vals node))]
(conj (mapcat directories subdirs) node)))
(defn directory-size [node]
(let [subdirs (filter map? (vals node))
size (reduce + (remove map? (vals node)))]
(+ size (reduce + (map directory-size subdirs)))))
(def sizes
(->> (directories (get-in tree ["/"]))
(map directory-size)
(sort)))
(println "Part 1:"
(->> (filter #(<= % 100000) sizes)
(reduce +)))
(println "Part 2:"
(let* [root-size (last sizes)
free-space (- 70000000 root-size)
required-size (- 30000000 free-space)]
(first (filter #(>= % required-size) sizes))))
| |
ac3a2ba6ffcdc6d492c9ffcab89d7b663401e64fe13c919dd7a6d490dba240de | ghc/packages-directory | MakeAbsolute.hs | # LANGUAGE CPP #
module MakeAbsolute where
#include "util.inl"
import System.FilePath ((</>), addTrailingPathSeparator,
dropTrailingPathSeparator, normalise)
#if defined(mingw32_HOST_OS)
import System.FilePath (takeDrive)
#endif
main :: TestEnv -> IO ()
main _t = do
dot <- makeAbsolute ""
dot2 <- makeAbsolute "."
dot3 <- makeAbsolute "./."
T(expectEq) () dot (dropTrailingPathSeparator dot)
T(expectEq) () dot dot2
T(expectEq) () dot dot3
sdot <- makeAbsolute "./"
sdot2 <- makeAbsolute "././"
T(expectEq) () sdot (addTrailingPathSeparator sdot)
T(expectEq) () sdot sdot2
foo <- makeAbsolute "foo"
foo2 <- makeAbsolute "foo/."
foo3 <- makeAbsolute "./foo"
T(expectEq) () foo (normalise (dot </> "foo"))
T(expectEq) () foo foo2
T(expectEq) () foo foo3
sfoo <- makeAbsolute "foo/"
sfoo2 <- makeAbsolute "foo/./"
sfoo3 <- makeAbsolute "./foo/"
T(expectEq) () sfoo (normalise (dot </> "foo/"))
T(expectEq) () sfoo sfoo2
T(expectEq) () sfoo sfoo3
#if defined(mingw32_HOST_OS)
cwd <- getCurrentDirectory
let driveLetter = toUpper (head (takeDrive cwd))
let driveLetter' = if driveLetter == 'Z' then 'A' else succ driveLetter
drp1 <- makeAbsolute (driveLetter : ":foobar")
drp2 <- makeAbsolute (driveLetter' : ":foobar")
T(expectEq) () drp1 =<< makeAbsolute "foobar"
T(expectEq) () drp2 (driveLetter' : ":\\foobar")
#endif
| null | https://raw.githubusercontent.com/ghc/packages-directory/75165a9d69bebba96e0e3a1e519ab481d1362dd2/tests/MakeAbsolute.hs | haskell | # LANGUAGE CPP #
module MakeAbsolute where
#include "util.inl"
import System.FilePath ((</>), addTrailingPathSeparator,
dropTrailingPathSeparator, normalise)
#if defined(mingw32_HOST_OS)
import System.FilePath (takeDrive)
#endif
main :: TestEnv -> IO ()
main _t = do
dot <- makeAbsolute ""
dot2 <- makeAbsolute "."
dot3 <- makeAbsolute "./."
T(expectEq) () dot (dropTrailingPathSeparator dot)
T(expectEq) () dot dot2
T(expectEq) () dot dot3
sdot <- makeAbsolute "./"
sdot2 <- makeAbsolute "././"
T(expectEq) () sdot (addTrailingPathSeparator sdot)
T(expectEq) () sdot sdot2
foo <- makeAbsolute "foo"
foo2 <- makeAbsolute "foo/."
foo3 <- makeAbsolute "./foo"
T(expectEq) () foo (normalise (dot </> "foo"))
T(expectEq) () foo foo2
T(expectEq) () foo foo3
sfoo <- makeAbsolute "foo/"
sfoo2 <- makeAbsolute "foo/./"
sfoo3 <- makeAbsolute "./foo/"
T(expectEq) () sfoo (normalise (dot </> "foo/"))
T(expectEq) () sfoo sfoo2
T(expectEq) () sfoo sfoo3
#if defined(mingw32_HOST_OS)
cwd <- getCurrentDirectory
let driveLetter = toUpper (head (takeDrive cwd))
let driveLetter' = if driveLetter == 'Z' then 'A' else succ driveLetter
drp1 <- makeAbsolute (driveLetter : ":foobar")
drp2 <- makeAbsolute (driveLetter' : ":foobar")
T(expectEq) () drp1 =<< makeAbsolute "foobar"
T(expectEq) () drp2 (driveLetter' : ":\\foobar")
#endif
| |
0df079fe4cb5298e6b8297ba538e90f923cdc162219e850a494dbb43bc4f3e11 | fp-works/2019-winter-Haskell-school | Exercise01.hs | # OPTIONS_GHC -fno - warn - orphans #
module CIS194.Homework08.Exercise01 (glCons, moreFun) where
import CIS194.Homework08.Employee (Employee(..), GuestList(..))
instance Semigroup GuestList where
(GL gs1 f1) <> (GL gs2 f2) = GL (gs1 ++ gs2) (f1 + f2)
instance Monoid GuestList where
mempty = GL [] 0
Adds an Employee to the GuestList ( updating the cached Fun score appropriately )
Of course , in general this is impossible :
the updated fun score should depend on whether the Employee
being added is already in the list , or if any of their direct subordinates are in the list , and so on . For our purposes , though , you
may assume that none of these special cases will hold : that is ,
glCons should simply add the new Employee and add their fun
score without doing any kind of checks .
Adds an Employee to the GuestList (updating the cached Fun score appropriately)
Of course, in general this is impossible:
the updated fun score should depend on whether the Employee
being added is already in the list, or if any of their direct subordinates are in the list, and so on. For our purposes, though, you
may assume that none of these special cases will hold: that is,
glCons should simply add the new Employee and add their fun
score without doing any kind of checks.
-}
glCons :: Employee -> GuestList -> GuestList
glCons e (GL gs f) = GL (e : gs) (f + empFun e)
moreFun :: GuestList -> GuestList -> GuestList
moreFun = max
| null | https://raw.githubusercontent.com/fp-works/2019-winter-Haskell-school/823b67f019b9e7bc0d3be36711c0cc7da4eba7d2/cis194/week8/daniel-deng/src/Exercise01.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
module CIS194.Homework08.Exercise01 (glCons, moreFun) where
import CIS194.Homework08.Employee (Employee(..), GuestList(..))
instance Semigroup GuestList where
(GL gs1 f1) <> (GL gs2 f2) = GL (gs1 ++ gs2) (f1 + f2)
instance Monoid GuestList where
mempty = GL [] 0
Adds an Employee to the GuestList ( updating the cached Fun score appropriately )
Of course , in general this is impossible :
the updated fun score should depend on whether the Employee
being added is already in the list , or if any of their direct subordinates are in the list , and so on . For our purposes , though , you
may assume that none of these special cases will hold : that is ,
glCons should simply add the new Employee and add their fun
score without doing any kind of checks .
Adds an Employee to the GuestList (updating the cached Fun score appropriately)
Of course, in general this is impossible:
the updated fun score should depend on whether the Employee
being added is already in the list, or if any of their direct subordinates are in the list, and so on. For our purposes, though, you
may assume that none of these special cases will hold: that is,
glCons should simply add the new Employee and add their fun
score without doing any kind of checks.
-}
glCons :: Employee -> GuestList -> GuestList
glCons e (GL gs f) = GL (e : gs) (f + empFun e)
moreFun :: GuestList -> GuestList -> GuestList
moreFun = max
| |
996af167974993f060de02a13a73fc81091148b6867e248c668051daa921ef42 | unisonweb/unison | Completion.hs | # LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
# LANGUAGE QuasiQuotes #
# LANGUAGE RecordWildCards #
module Unison.LSP.Completion where
import Control.Comonad.Cofree
import Control.Lens hiding (List, (:<))
import Control.Monad.Reader
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson
import Data.Bifunctor (second)
import Data.List.Extra (nubOrdOn)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as Text
import Language.LSP.Types
import Language.LSP.Types.Lens
import Unison.Codebase.Path (Path)
import qualified Unison.Codebase.Path as Path
import qualified Unison.HashQualified as HQ
import qualified Unison.HashQualified' as HQ'
import Unison.LSP.FileAnalysis
import qualified Unison.LSP.Queries as LSPQ
import Unison.LSP.Types
import qualified Unison.LSP.VFS as VFS
import Unison.LabeledDependency (LabeledDependency)
import qualified Unison.LabeledDependency as LD
import Unison.Name (Name)
import qualified Unison.Name as Name
import Unison.NameSegment (NameSegment (..))
import qualified Unison.NameSegment as NameSegment
import Unison.Names (Names (..))
import Unison.Prelude
import qualified Unison.PrettyPrintEnv as PPE
import qualified Unison.PrettyPrintEnvDecl as PPED
import qualified Unison.Reference as Reference
import qualified Unison.Referent as Referent
import qualified Unison.Syntax.DeclPrinter as DeclPrinter
import qualified Unison.Syntax.HashQualified' as HQ' (toText)
import qualified Unison.Syntax.Name as Name (fromText, toText)
import qualified Unison.Syntax.TypePrinter as TypePrinter
import qualified Unison.Util.Monoid as Monoid
import qualified Unison.Util.Pretty as Pretty
import qualified Unison.Util.Relation as Relation
completionHandler :: RequestMessage 'TextDocumentCompletion -> (Either ResponseError (ResponseResult 'TextDocumentCompletion) -> Lsp ()) -> Lsp ()
completionHandler m respond =
respond . maybe (Right $ InL mempty) (Right . InR) =<< runMaybeT do
let fileUri = (m ^. params . textDocument . uri)
(range, prefix) <- VFS.completionPrefix (m ^. params . textDocument . uri) (m ^. params . position)
ppe <- PPED.suffixifiedPPE <$> lift globalPPED
codebaseCompletions <- lift getCodebaseCompletions
Config {maxCompletions} <- lift getConfig
let defMatches = matchCompletions codebaseCompletions prefix
let (isIncomplete, defCompletions) =
defMatches
& nubOrdOn (\(p, _name, ref) -> (p, ref))
& fmap (over _1 Path.toText)
& case maxCompletions of
Nothing -> (False,)
Just n -> takeCompletions n
let defCompletionItems =
defCompletions
& mapMaybe \(path, fqn, dep) ->
let biasedPPE = PPE.biasTo [fqn] ppe
hqName = LD.fold (PPE.types biasedPPE) (PPE.terms biasedPPE) dep
in hqName <&> \hqName -> mkDefCompletionItem fileUri range (HQ'.toName hqName) fqn path (HQ'.toText hqName) dep
pure . CompletionList isIncomplete . List $ defCompletionItems
where
-- Takes at most the specified number of completions, but also indicates with a boolean
-- whether there were more completions remaining so we can pass that along to the client.
takeCompletions :: Int -> [a] -> (Bool, [a])
takeCompletions 0 xs = (not $ null xs, [])
takeCompletions _ [] = (False, [])
takeCompletions n (x : xs) = second (x :) $ takeCompletions (pred n) xs
mkDefCompletionItem :: Uri -> Range -> Name -> Name -> Text -> Text -> LabeledDependency -> CompletionItem
mkDefCompletionItem fileUri range relativeName fullyQualifiedName path suffixified dep =
CompletionItem
{ _label = lbl,
_kind = case dep of
LD.TypeReference _ref -> Just CiClass
LD.TermReferent ref -> case ref of
Referent.Con {} -> Just CiConstructor
Referent.Ref {} -> Just CiValue,
_tags = Nothing,
_detail = Just (Name.toText fullyQualifiedName),
_documentation = Nothing,
_deprecated = Nothing,
_preselect = Nothing,
_sortText = Nothing,
_filterText = Just path,
_insertText = Nothing,
_insertTextFormat = Nothing,
_insertTextMode = Nothing,
_textEdit = Just (CompletionEditText $ TextEdit range suffixified),
_additionalTextEdits = Nothing,
_commitCharacters = Nothing,
_command = Nothing,
_xdata = Just $ Aeson.toJSON $ CompletionItemDetails {dep, relativeName, fullyQualifiedName, fileUri}
}
where
-- We should generally show the longer of the path or suffixified name in the label,
-- it helps the user understand the difference between options which may otherwise look
-- the same.
--
E.g. if I type " ma " then the suffixied options might be : List.map , Bag.map , but the
-- path matches are just "map" and "map" since the query starts at that segment, so we
-- show the suffixified version to disambiguate.
--
-- However, if the user types "base.List.ma" then the matching path is "base.List.map" and
the suffixification is just " List.map " , so we use the path in this case because it more
-- closely matches what the user actually typed.
--
-- This is what's felt best to me, anecdotally.
lbl =
if Text.length path > Text.length suffixified
then path
else suffixified
-- | Generate a completion tree from a set of names.
-- A completion tree is a suffix tree over the path segments of each name it contains.
-- The goal is to allow fast completion of names by any partial path suffix.
--
-- The tree is generated by building a trie where all possible suffixes of a name are
-- reachable from the root of the trie, with sharing over subtrees to improve memory
-- residency.
--
-- Currently we don't "summarize" all of the children of a node in the node itself, and
-- instead you have to crawl all the children to get the actual completions.
--
-- TODO: Would it be worthwhile to perform compression or include child summaries on the suffix tree?
-- I suspect most namespace trees won't actually compress very well since each node is likely
-- to have terms/types at it.
--
-- E.g. From the names:
* alpha.beta .
-- * alpha.Text
-- * foxtrot.Text
--
-- It will generate a tree like the following, where each bullet is a possible completion:
--
-- .
-- ├── foxtrot
│ ─ Text
│ ─ ─ * foxtrot . Text ( # # Text )
-- ├── beta
│ ─
│ ─ ─ * alpha.beta . ( # # Nat )
-- ├── alpha
-- │ ├── beta
│ │ ─
│ │ ─ ─ * alpha.beta . ( # # Nat )
│ ─ Text
│ ─ ─ * alpha . Text ( # # Text )
-- ├── Text
-- │ ├── * foxtrot.Text (##Text)
│ ─ ─ * alpha . Text ( # # Text )
└ ─ ─
─ ─ * alpha.beta . ( # # Nat )
namesToCompletionTree :: Names -> CompletionTree
namesToCompletionTree Names {terms, types} =
let typeCompls =
Relation.domain types
& ifoldMap
( \name refs ->
refs
& Monoid.whenM (not . isDefinitionDoc $ name)
& Set.map \ref -> (name, LD.typeRef ref)
)
termCompls =
Relation.domain terms
& ifoldMap
( \name refs ->
refs
& Monoid.whenM (not . isDefinitionDoc $ name)
& Set.map \ref -> (name, LD.referent ref)
)
in foldMap (uncurry nameToCompletionTree) (typeCompls <> termCompls)
where
-- It's annoying to see _all_ the definition docs in autocomplete so we filter them out.
-- Special docs like "README" will still appear since they're not named 'doc'
isDefinitionDoc name =
case Name.reverseSegments name of
("doc" :| _) -> True
_ -> False
nameToCompletionTree :: Name -> LabeledDependency -> CompletionTree
nameToCompletionTree name ref =
let (lastSegment :| prefix) = Name.reverseSegments name
complMap = helper (Map.singleton lastSegment (Set.singleton (name, ref) :< mempty)) prefix
in CompletionTree (mempty :< complMap)
where
We build the tree bottom - up rather than top - down so we can take ' share ' for
-- improved memory residency, each call is passed the submap that we built under the
-- current reversed path prefix.
helper ::
Map
NameSegment
(Cofree (Map NameSegment) (Set (Name, LabeledDependency))) ->
[NameSegment] ->
Map
NameSegment
(Cofree (Map NameSegment) (Set (Name, LabeledDependency)))
helper subMap revPrefix = case revPrefix of
[] -> subMap
(ns : rest) ->
mergeSubmaps (helper (Map.singleton ns (mempty :< subMap)) rest) subMap
where
mergeSubmaps = Map.unionWith (\a b -> unCompletionTree $ CompletionTree a <> CompletionTree b)
-- | Crawl the completion tree and return all valid prefix-based completions alongside their
-- Path from the provided prefix, and their full name.
--
-- E.g. if the term "alpha.beta.gamma.map (#abc)" exists in the completion map, and the query is "beta" the result would
-- be:
--
-- @@
[ ( [ " beta " , " gamma " , " map " ] , " alpha.beta.gamma.map " , TermReferent # abc ) ]
-- @@
matchCompletions :: CompletionTree -> Text -> [(Path, Name, LabeledDependency)]
matchCompletions (CompletionTree tree) txt =
matchSegments segments (Set.toList <$> tree)
where
segments :: [Text]
segments =
Text.splitOn "." txt
& filter (not . Text.null)
matchSegments :: [Text] -> Cofree (Map NameSegment) [(Name, LabeledDependency)] -> [(Path, Name, LabeledDependency)]
matchSegments xs (currentMatches :< subtreeMap) =
case xs of
[] ->
let current = currentMatches <&> (\(name, def) -> (Path.empty, name, def))
in (current <> mkDefMatches subtreeMap)
[prefix] ->
Map.dropWhileAntitone ((< prefix) . NameSegment.toText) subtreeMap
& Map.takeWhileAntitone (Text.isPrefixOf prefix . NameSegment.toText)
& \matchingSubtrees ->
let subMatches = ifoldMap (\ns subTree -> matchSegments [] subTree & consPathPrefix ns) matchingSubtrees
in subMatches
(ns : rest) ->
foldMap (matchSegments rest) (Map.lookup (NameSegment ns) subtreeMap)
& consPathPrefix (NameSegment ns)
consPathPrefix :: NameSegment -> ([(Path, Name, LabeledDependency)]) -> [(Path, Name, LabeledDependency)]
consPathPrefix ns = over (mapped . _1) (Path.cons ns)
mkDefMatches :: Map NameSegment (Cofree (Map NameSegment) [(Name, LabeledDependency)]) -> [(Path, Name, LabeledDependency)]
mkDefMatches xs = do
(ns, (matches :< rest)) <- Map.toList xs
let childMatches = mkDefMatches rest <&> over _1 (Path.cons ns)
let currentMatches = matches <&> \(name, dep) -> (Path.singleton ns, name, dep)
currentMatches <> childMatches
-- | Called to resolve additional details for a completion item that the user is considering.
completionItemResolveHandler :: RequestMessage 'CompletionItemResolve -> (Either ResponseError CompletionItem -> Lsp ()) -> Lsp ()
completionItemResolveHandler message respond = do
let completion :: CompletionItem
completion = message ^. params
respond . maybe (Right completion) Right =<< runMaybeT do
case Aeson.fromJSON <$> (completion ^. xdata) of
Just (Aeson.Success (CompletionItemDetails {dep, fullyQualifiedName, relativeName, fileUri})) -> do
pped <- lift $ ppedForFile fileUri
case dep of
LD.TermReferent ref -> do
typ <- LSPQ.getTypeOfReferent fileUri ref
let renderedType = ": " <> (Text.pack $ TypePrinter.prettyStr (Just typeWidth) (PPED.suffixifiedPPE pped) typ)
let doc = CompletionDocMarkup (toUnisonMarkup (Name.toText fullyQualifiedName))
pure $ (completion {_detail = Just renderedType, _documentation = Just doc} :: CompletionItem)
LD.TypeReference ref ->
case ref of
Reference.Builtin {} -> do
let renderedBuiltin = ": <builtin>"
let doc = CompletionDocMarkup (toUnisonMarkup (Name.toText fullyQualifiedName))
pure $ (completion {_detail = Just renderedBuiltin, _documentation = Just doc} :: CompletionItem)
Reference.DerivedId refId -> do
decl <- LSPQ.getTypeDeclaration fileUri refId
let renderedDecl = ": " <> (Text.pack . Pretty.toPlain typeWidth . Pretty.syntaxToColor $ DeclPrinter.prettyDecl pped ref (HQ.NameOnly relativeName) decl)
let doc = CompletionDocMarkup (toUnisonMarkup (Name.toText fullyQualifiedName))
pure $ (completion {_detail = Just renderedDecl, _documentation = Just doc} :: CompletionItem)
_ -> empty
where
toUnisonMarkup txt = MarkupContent {_kind = MkMarkdown, _value = Text.unlines ["```unison", txt, "```"]}
-- Completion windows can be very small, so this seems like a good default
typeWidth = Pretty.Width 20
-- | Data which will be provided back to us in the completion resolve handler when the user considers this completion.
data CompletionItemDetails = CompletionItemDetails
{ dep :: LD.LabeledDependency,
relativeName :: Name,
fullyQualifiedName :: Name,
fileUri :: Uri
}
instance Aeson.ToJSON CompletionItemDetails where
toJSON CompletionItemDetails {dep, relativeName, fullyQualifiedName, fileUri} =
Aeson.object
[ "relativeName" Aeson..= Name.toText relativeName,
"fullyQualifiedName" Aeson..= Name.toText fullyQualifiedName,
"fileUri" Aeson..= fileUri,
"dep" Aeson..= ldJSON dep
]
where
ldJSON :: LD.LabeledDependency -> Aeson.Value
ldJSON = \case
LD.TypeReference ref -> Aeson.object ["kind" Aeson..= ("type" :: Text), "ref" Aeson..= Reference.toText ref]
LD.TermReferent ref -> Aeson.object ["kind" Aeson..= ("term" :: Text), "ref" Aeson..= Referent.toText ref]
instance Aeson.FromJSON CompletionItemDetails where
parseJSON = Aeson.withObject "CompletionItemDetails" \obj -> do
dep <- ((obj Aeson..: "dep") >>= ldParser)
relativeName <- (obj Aeson..: "relativeName" >>= maybe (fail "Invalid name in CompletionItemDetails") pure . Name.fromText)
fullyQualifiedName <- (obj Aeson..: "fullyQualifiedName" >>= maybe (fail "Invalid name in CompletionItemDetails") pure . Name.fromText)
fileUri <- obj Aeson..: "fileUri"
pure $ CompletionItemDetails {..}
where
ldParser :: Aeson.Value -> Aeson.Parser LD.LabeledDependency
ldParser = Aeson.withObject "LabeledDependency" \obj -> do
kind <- obj Aeson..: "kind"
case kind of
("type" :: Text) -> LD.TypeReference <$> (obj Aeson..: "ref" >>= either (const $ fail "Invalid Reference in LabeledDependency") pure . Reference.fromText)
("term" :: Text) -> LD.TermReferent <$> (obj Aeson..: "ref" >>= maybe (fail "Invalid Referent in LabeledDependency") pure . Referent.fromText)
_ -> fail "Invalid LabeledDependency kind"
| null | https://raw.githubusercontent.com/unisonweb/unison/59acc0cbe429492a99bfebf2b783fc2fa3967f75/unison-cli/src/Unison/LSP/Completion.hs | haskell | Takes at most the specified number of completions, but also indicates with a boolean
whether there were more completions remaining so we can pass that along to the client.
We should generally show the longer of the path or suffixified name in the label,
it helps the user understand the difference between options which may otherwise look
the same.
path matches are just "map" and "map" since the query starts at that segment, so we
show the suffixified version to disambiguate.
However, if the user types "base.List.ma" then the matching path is "base.List.map" and
closely matches what the user actually typed.
This is what's felt best to me, anecdotally.
| Generate a completion tree from a set of names.
A completion tree is a suffix tree over the path segments of each name it contains.
The goal is to allow fast completion of names by any partial path suffix.
The tree is generated by building a trie where all possible suffixes of a name are
reachable from the root of the trie, with sharing over subtrees to improve memory
residency.
Currently we don't "summarize" all of the children of a node in the node itself, and
instead you have to crawl all the children to get the actual completions.
TODO: Would it be worthwhile to perform compression or include child summaries on the suffix tree?
I suspect most namespace trees won't actually compress very well since each node is likely
to have terms/types at it.
E.g. From the names:
* alpha.Text
* foxtrot.Text
It will generate a tree like the following, where each bullet is a possible completion:
.
├── foxtrot
├── beta
├── alpha
│ ├── beta
├── Text
│ ├── * foxtrot.Text (##Text)
It's annoying to see _all_ the definition docs in autocomplete so we filter them out.
Special docs like "README" will still appear since they're not named 'doc'
improved memory residency, each call is passed the submap that we built under the
current reversed path prefix.
| Crawl the completion tree and return all valid prefix-based completions alongside their
Path from the provided prefix, and their full name.
E.g. if the term "alpha.beta.gamma.map (#abc)" exists in the completion map, and the query is "beta" the result would
be:
@@
@@
| Called to resolve additional details for a completion item that the user is considering.
Completion windows can be very small, so this seems like a good default
| Data which will be provided back to us in the completion resolve handler when the user considers this completion. | # LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
# LANGUAGE QuasiQuotes #
# LANGUAGE RecordWildCards #
module Unison.LSP.Completion where
import Control.Comonad.Cofree
import Control.Lens hiding (List, (:<))
import Control.Monad.Reader
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson
import Data.Bifunctor (second)
import Data.List.Extra (nubOrdOn)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as Text
import Language.LSP.Types
import Language.LSP.Types.Lens
import Unison.Codebase.Path (Path)
import qualified Unison.Codebase.Path as Path
import qualified Unison.HashQualified as HQ
import qualified Unison.HashQualified' as HQ'
import Unison.LSP.FileAnalysis
import qualified Unison.LSP.Queries as LSPQ
import Unison.LSP.Types
import qualified Unison.LSP.VFS as VFS
import Unison.LabeledDependency (LabeledDependency)
import qualified Unison.LabeledDependency as LD
import Unison.Name (Name)
import qualified Unison.Name as Name
import Unison.NameSegment (NameSegment (..))
import qualified Unison.NameSegment as NameSegment
import Unison.Names (Names (..))
import Unison.Prelude
import qualified Unison.PrettyPrintEnv as PPE
import qualified Unison.PrettyPrintEnvDecl as PPED
import qualified Unison.Reference as Reference
import qualified Unison.Referent as Referent
import qualified Unison.Syntax.DeclPrinter as DeclPrinter
import qualified Unison.Syntax.HashQualified' as HQ' (toText)
import qualified Unison.Syntax.Name as Name (fromText, toText)
import qualified Unison.Syntax.TypePrinter as TypePrinter
import qualified Unison.Util.Monoid as Monoid
import qualified Unison.Util.Pretty as Pretty
import qualified Unison.Util.Relation as Relation
completionHandler :: RequestMessage 'TextDocumentCompletion -> (Either ResponseError (ResponseResult 'TextDocumentCompletion) -> Lsp ()) -> Lsp ()
completionHandler m respond =
respond . maybe (Right $ InL mempty) (Right . InR) =<< runMaybeT do
let fileUri = (m ^. params . textDocument . uri)
(range, prefix) <- VFS.completionPrefix (m ^. params . textDocument . uri) (m ^. params . position)
ppe <- PPED.suffixifiedPPE <$> lift globalPPED
codebaseCompletions <- lift getCodebaseCompletions
Config {maxCompletions} <- lift getConfig
let defMatches = matchCompletions codebaseCompletions prefix
let (isIncomplete, defCompletions) =
defMatches
& nubOrdOn (\(p, _name, ref) -> (p, ref))
& fmap (over _1 Path.toText)
& case maxCompletions of
Nothing -> (False,)
Just n -> takeCompletions n
let defCompletionItems =
defCompletions
& mapMaybe \(path, fqn, dep) ->
let biasedPPE = PPE.biasTo [fqn] ppe
hqName = LD.fold (PPE.types biasedPPE) (PPE.terms biasedPPE) dep
in hqName <&> \hqName -> mkDefCompletionItem fileUri range (HQ'.toName hqName) fqn path (HQ'.toText hqName) dep
pure . CompletionList isIncomplete . List $ defCompletionItems
where
takeCompletions :: Int -> [a] -> (Bool, [a])
takeCompletions 0 xs = (not $ null xs, [])
takeCompletions _ [] = (False, [])
takeCompletions n (x : xs) = second (x :) $ takeCompletions (pred n) xs
mkDefCompletionItem :: Uri -> Range -> Name -> Name -> Text -> Text -> LabeledDependency -> CompletionItem
mkDefCompletionItem fileUri range relativeName fullyQualifiedName path suffixified dep =
CompletionItem
{ _label = lbl,
_kind = case dep of
LD.TypeReference _ref -> Just CiClass
LD.TermReferent ref -> case ref of
Referent.Con {} -> Just CiConstructor
Referent.Ref {} -> Just CiValue,
_tags = Nothing,
_detail = Just (Name.toText fullyQualifiedName),
_documentation = Nothing,
_deprecated = Nothing,
_preselect = Nothing,
_sortText = Nothing,
_filterText = Just path,
_insertText = Nothing,
_insertTextFormat = Nothing,
_insertTextMode = Nothing,
_textEdit = Just (CompletionEditText $ TextEdit range suffixified),
_additionalTextEdits = Nothing,
_commitCharacters = Nothing,
_command = Nothing,
_xdata = Just $ Aeson.toJSON $ CompletionItemDetails {dep, relativeName, fullyQualifiedName, fileUri}
}
where
E.g. if I type " ma " then the suffixied options might be : List.map , Bag.map , but the
the suffixification is just " List.map " , so we use the path in this case because it more
lbl =
if Text.length path > Text.length suffixified
then path
else suffixified
* alpha.beta .
│ ─ Text
│ ─ ─ * foxtrot . Text ( # # Text )
│ ─
│ ─ ─ * alpha.beta . ( # # Nat )
│ │ ─
│ │ ─ ─ * alpha.beta . ( # # Nat )
│ ─ Text
│ ─ ─ * alpha . Text ( # # Text )
│ ─ ─ * alpha . Text ( # # Text )
└ ─ ─
─ ─ * alpha.beta . ( # # Nat )
namesToCompletionTree :: Names -> CompletionTree
namesToCompletionTree Names {terms, types} =
let typeCompls =
Relation.domain types
& ifoldMap
( \name refs ->
refs
& Monoid.whenM (not . isDefinitionDoc $ name)
& Set.map \ref -> (name, LD.typeRef ref)
)
termCompls =
Relation.domain terms
& ifoldMap
( \name refs ->
refs
& Monoid.whenM (not . isDefinitionDoc $ name)
& Set.map \ref -> (name, LD.referent ref)
)
in foldMap (uncurry nameToCompletionTree) (typeCompls <> termCompls)
where
isDefinitionDoc name =
case Name.reverseSegments name of
("doc" :| _) -> True
_ -> False
nameToCompletionTree :: Name -> LabeledDependency -> CompletionTree
nameToCompletionTree name ref =
let (lastSegment :| prefix) = Name.reverseSegments name
complMap = helper (Map.singleton lastSegment (Set.singleton (name, ref) :< mempty)) prefix
in CompletionTree (mempty :< complMap)
where
We build the tree bottom - up rather than top - down so we can take ' share ' for
helper ::
Map
NameSegment
(Cofree (Map NameSegment) (Set (Name, LabeledDependency))) ->
[NameSegment] ->
Map
NameSegment
(Cofree (Map NameSegment) (Set (Name, LabeledDependency)))
helper subMap revPrefix = case revPrefix of
[] -> subMap
(ns : rest) ->
mergeSubmaps (helper (Map.singleton ns (mempty :< subMap)) rest) subMap
where
mergeSubmaps = Map.unionWith (\a b -> unCompletionTree $ CompletionTree a <> CompletionTree b)
[ ( [ " beta " , " gamma " , " map " ] , " alpha.beta.gamma.map " , TermReferent # abc ) ]
matchCompletions :: CompletionTree -> Text -> [(Path, Name, LabeledDependency)]
matchCompletions (CompletionTree tree) txt =
matchSegments segments (Set.toList <$> tree)
where
segments :: [Text]
segments =
Text.splitOn "." txt
& filter (not . Text.null)
matchSegments :: [Text] -> Cofree (Map NameSegment) [(Name, LabeledDependency)] -> [(Path, Name, LabeledDependency)]
matchSegments xs (currentMatches :< subtreeMap) =
case xs of
[] ->
let current = currentMatches <&> (\(name, def) -> (Path.empty, name, def))
in (current <> mkDefMatches subtreeMap)
[prefix] ->
Map.dropWhileAntitone ((< prefix) . NameSegment.toText) subtreeMap
& Map.takeWhileAntitone (Text.isPrefixOf prefix . NameSegment.toText)
& \matchingSubtrees ->
let subMatches = ifoldMap (\ns subTree -> matchSegments [] subTree & consPathPrefix ns) matchingSubtrees
in subMatches
(ns : rest) ->
foldMap (matchSegments rest) (Map.lookup (NameSegment ns) subtreeMap)
& consPathPrefix (NameSegment ns)
consPathPrefix :: NameSegment -> ([(Path, Name, LabeledDependency)]) -> [(Path, Name, LabeledDependency)]
consPathPrefix ns = over (mapped . _1) (Path.cons ns)
mkDefMatches :: Map NameSegment (Cofree (Map NameSegment) [(Name, LabeledDependency)]) -> [(Path, Name, LabeledDependency)]
mkDefMatches xs = do
(ns, (matches :< rest)) <- Map.toList xs
let childMatches = mkDefMatches rest <&> over _1 (Path.cons ns)
let currentMatches = matches <&> \(name, dep) -> (Path.singleton ns, name, dep)
currentMatches <> childMatches
completionItemResolveHandler :: RequestMessage 'CompletionItemResolve -> (Either ResponseError CompletionItem -> Lsp ()) -> Lsp ()
completionItemResolveHandler message respond = do
let completion :: CompletionItem
completion = message ^. params
respond . maybe (Right completion) Right =<< runMaybeT do
case Aeson.fromJSON <$> (completion ^. xdata) of
Just (Aeson.Success (CompletionItemDetails {dep, fullyQualifiedName, relativeName, fileUri})) -> do
pped <- lift $ ppedForFile fileUri
case dep of
LD.TermReferent ref -> do
typ <- LSPQ.getTypeOfReferent fileUri ref
let renderedType = ": " <> (Text.pack $ TypePrinter.prettyStr (Just typeWidth) (PPED.suffixifiedPPE pped) typ)
let doc = CompletionDocMarkup (toUnisonMarkup (Name.toText fullyQualifiedName))
pure $ (completion {_detail = Just renderedType, _documentation = Just doc} :: CompletionItem)
LD.TypeReference ref ->
case ref of
Reference.Builtin {} -> do
let renderedBuiltin = ": <builtin>"
let doc = CompletionDocMarkup (toUnisonMarkup (Name.toText fullyQualifiedName))
pure $ (completion {_detail = Just renderedBuiltin, _documentation = Just doc} :: CompletionItem)
Reference.DerivedId refId -> do
decl <- LSPQ.getTypeDeclaration fileUri refId
let renderedDecl = ": " <> (Text.pack . Pretty.toPlain typeWidth . Pretty.syntaxToColor $ DeclPrinter.prettyDecl pped ref (HQ.NameOnly relativeName) decl)
let doc = CompletionDocMarkup (toUnisonMarkup (Name.toText fullyQualifiedName))
pure $ (completion {_detail = Just renderedDecl, _documentation = Just doc} :: CompletionItem)
_ -> empty
where
toUnisonMarkup txt = MarkupContent {_kind = MkMarkdown, _value = Text.unlines ["```unison", txt, "```"]}
typeWidth = Pretty.Width 20
data CompletionItemDetails = CompletionItemDetails
{ dep :: LD.LabeledDependency,
relativeName :: Name,
fullyQualifiedName :: Name,
fileUri :: Uri
}
instance Aeson.ToJSON CompletionItemDetails where
toJSON CompletionItemDetails {dep, relativeName, fullyQualifiedName, fileUri} =
Aeson.object
[ "relativeName" Aeson..= Name.toText relativeName,
"fullyQualifiedName" Aeson..= Name.toText fullyQualifiedName,
"fileUri" Aeson..= fileUri,
"dep" Aeson..= ldJSON dep
]
where
ldJSON :: LD.LabeledDependency -> Aeson.Value
ldJSON = \case
LD.TypeReference ref -> Aeson.object ["kind" Aeson..= ("type" :: Text), "ref" Aeson..= Reference.toText ref]
LD.TermReferent ref -> Aeson.object ["kind" Aeson..= ("term" :: Text), "ref" Aeson..= Referent.toText ref]
instance Aeson.FromJSON CompletionItemDetails where
parseJSON = Aeson.withObject "CompletionItemDetails" \obj -> do
dep <- ((obj Aeson..: "dep") >>= ldParser)
relativeName <- (obj Aeson..: "relativeName" >>= maybe (fail "Invalid name in CompletionItemDetails") pure . Name.fromText)
fullyQualifiedName <- (obj Aeson..: "fullyQualifiedName" >>= maybe (fail "Invalid name in CompletionItemDetails") pure . Name.fromText)
fileUri <- obj Aeson..: "fileUri"
pure $ CompletionItemDetails {..}
where
ldParser :: Aeson.Value -> Aeson.Parser LD.LabeledDependency
ldParser = Aeson.withObject "LabeledDependency" \obj -> do
kind <- obj Aeson..: "kind"
case kind of
("type" :: Text) -> LD.TypeReference <$> (obj Aeson..: "ref" >>= either (const $ fail "Invalid Reference in LabeledDependency") pure . Reference.fromText)
("term" :: Text) -> LD.TermReferent <$> (obj Aeson..: "ref" >>= maybe (fail "Invalid Referent in LabeledDependency") pure . Referent.fromText)
_ -> fail "Invalid LabeledDependency kind"
|
051d6536d740d22a328aea1c6cbb3c99d02e94b40561fa6311226dd0dc6a3a9e | facebook/flow | resizableArray.mli |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(* An array that automatically expands when needed *)
type 'a t
exception Out_of_bounds_set of string
` make x ` creates a ResizableArray.t where the underlying array has the initial size of ` x ` .
* However , this is purely for the purposes of optimization :
* ` ResizableArray.size ( ResizableArray.make 5 ) ` still * evaluates to ` 0 ` .
* However, this is purely for the purposes of optimization:
* `ResizableArray.size (ResizableArray.make 5)` still * evaluates to `0`. *)
val make : int -> 'a t
(* `set arr i x` raises `Out_of_bounds_set` if `i >= ResizableArray.size arr`, or if `i < 0` *)
val set : 'a t -> int -> 'a -> unit
(* Expands the underlying array if necessary *)
val push : 'a t -> 'a -> unit
(* Shrinks the representation to match the number of elements stored *)
val shrink : 'a t -> unit
(* Returns None if the index is out of bounds. *)
val get : 'a t -> int -> 'a option
val size : 'a t -> int
(* Exposed only for white box testing. Do not use this. Really. *)
val underlying_array_size_do_not_use : 'a t -> int
val to_hashtbl : 'a t -> ('a, int) Hashtbl.t
| null | https://raw.githubusercontent.com/facebook/flow/741104e69c43057ebd32804dd6bcc1b5e97548ea/src/common/utils/resizableArray.mli | ocaml | An array that automatically expands when needed
`set arr i x` raises `Out_of_bounds_set` if `i >= ResizableArray.size arr`, or if `i < 0`
Expands the underlying array if necessary
Shrinks the representation to match the number of elements stored
Returns None if the index is out of bounds.
Exposed only for white box testing. Do not use this. Really. |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
type 'a t
exception Out_of_bounds_set of string
` make x ` creates a ResizableArray.t where the underlying array has the initial size of ` x ` .
* However , this is purely for the purposes of optimization :
* ` ResizableArray.size ( ResizableArray.make 5 ) ` still * evaluates to ` 0 ` .
* However, this is purely for the purposes of optimization:
* `ResizableArray.size (ResizableArray.make 5)` still * evaluates to `0`. *)
val make : int -> 'a t
val set : 'a t -> int -> 'a -> unit
val push : 'a t -> 'a -> unit
val shrink : 'a t -> unit
val get : 'a t -> int -> 'a option
val size : 'a t -> int
val underlying_array_size_do_not_use : 'a t -> int
val to_hashtbl : 'a t -> ('a, int) Hashtbl.t
|
754da2f6e052d55294129c214cb8d01b7fa76e1d942d3d9f2caa9136ecb903cc | steshaw/PLAR | decidable.ml | (* ========================================================================= *)
Special procedures for decidable subsets of first order logic .
(* *)
Copyright ( c ) 2003 - 2007 , . ( See " LICENSE.txt " for details . )
(* ========================================================================= *)
* *
< < forall x. ) > > ; ;
tab < < forall x. ) > > ; ;
* *
meson <<forall x. p(x)>>;;
tab <<forall x. p(x)>>;;
***)
(* ------------------------------------------------------------------------- *)
(* Resolution does actually terminate with failure in simple cases! *)
(* ------------------------------------------------------------------------- *)
* *
resolution < < forall x. ) > > ; ;
* *
resolution <<forall x. p(x)>>;;
***)
(* ------------------------------------------------------------------------- *)
The Los example ; see how Skolemized form has no non - nullary functions .
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
let los =
<<(forall x y z. P(x,y) /\ P(y,z) ==> P(x,z)) /\
(forall x y z. Q(x,y) /\ Q(y,z) ==> Q(x,z)) /\
(forall x y. P(x,y) ==> P(y,x)) /\
(forall x y. P(x,y) \/ Q(x,y))
==> (forall x y. P(x,y)) \/ (forall x y. Q(x,y))>>;;
skolemize(Not los);;
(* ------------------------------------------------------------------------- *)
The old DP procedure works .
(* ------------------------------------------------------------------------- *)
davisputnam los;;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* However, we can just form all the ground instances. *)
(* ------------------------------------------------------------------------- *)
let aedecide fm =
let sfm = skolemize(Not fm) in
let fvs = fv sfm
and cnsts,funcs = partition (fun (_,ar) -> ar = 0) (functions sfm) in
if funcs <> [] then failwith "Not decidable" else
let consts = if cnsts = [] then ["c",0] else cnsts in
let cntms = map (fun (c,_) -> Fn(c,[])) consts in
let alltuples = groundtuples cntms [] 0 (length fvs) in
let cjs = simpcnf sfm in
let grounds = map
(fun tup -> image (image (subst (fpf fvs tup))) cjs) alltuples in
not(dpll(unions grounds));;
(* ------------------------------------------------------------------------- *)
(* In this case it's quicker. *)
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
aedecide los;;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* Show how we need to do PNF transformation with care. *)
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
let fm = <<(forall x. p(x)) \/ (exists y. p(y))>>;;
pnf fm;;
(* ------------------------------------------------------------------------- *)
(* Also the group theory problem. *)
(* ------------------------------------------------------------------------- *)
aedecide
<<(forall x. P(1,x,x)) /\ (forall x. P(x,x,1)) /\
(forall u v w x y z.
P(x,y,u) /\ P(y,z,w) ==> (P(x,w,v) <=> P(u,z,v)))
==> forall a b c. P(a,b,c) ==> P(b,a,c)>>;;
aedecide
<<(forall x. P(x,x,1)) /\
(forall u v w x y z.
P(x,y,u) /\ P(y,z,w) ==> (P(x,w,v) <=> P(u,z,v)))
==> forall a b c. P(a,b,c) ==> P(b,a,c)>>;;
(* ------------------------------------------------------------------------- *)
(* A bigger example. *)
(* ------------------------------------------------------------------------- *)
aedecide
<<(exists x. P(x)) /\ (exists x. G(x))
==> ((forall x. P(x) ==> H(x)) /\ (forall x. G(x) ==> J(x)) <=>
(forall x y. P(x) /\ G(y) ==> H(x) /\ J(y)))>>;;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* The following, however, doesn't work with aedecide. *)
(* ------------------------------------------------------------------------- *)
* * This is p18
aedecide < < exists y. forall x. ) = = > P(x ) > > ; ;
< < exists y. forall x. ) = = > P(x ) > > ; ;
* *
aedecide <<exists y. forall x. P(y) ==> P(x)>>;;
davisputnam <<exists y. forall x. P(y) ==> P(x)>>;;
***)
(* ------------------------------------------------------------------------- *)
(* Simple-minded miniscoping procedure. *)
(* ------------------------------------------------------------------------- *)
let separate x cjs =
let yes,no = partition (mem x ** fv) cjs in
if yes = [] then list_conj no
else if no = [] then Exists(x,list_conj yes)
else And(Exists(x,list_conj yes),list_conj no);;
let rec pushquant x p =
if not (mem x (fv p)) then p else
let djs = purednf(nnf p) in
list_disj (map (separate x) djs);;
let rec miniscope fm =
match fm with
Not p -> Not(miniscope p)
| And(p,q) -> And(miniscope p,miniscope q)
| Or(p,q) -> Or(miniscope p,miniscope q)
| Forall(x,p) -> Not(pushquant x (Not(miniscope p)))
| Exists(x,p) -> pushquant x (miniscope p)
| _ -> fm;;
(* ------------------------------------------------------------------------- *)
(* Examples. *)
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
miniscope(nnf <<exists y. forall x. P(y) ==> P(x)>>);;
let fm = miniscope(nnf
<<(forall x y. exists z. forall w. P(x) /\ Q(y) ==> R(z) /\ U(w))
==> (exists x y. P(x) /\ Q(y)) ==> (exists z. R(z))>>);;
pnf(nnf fm);;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
Stronger version of " aedecide " similar to Wang 's classic procedure .
(* ------------------------------------------------------------------------- *)
let wang fm = aedecide(miniscope(nnf(simplify fm)));;
(* ------------------------------------------------------------------------- *)
(* It works well on simple monadic formulas. *)
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
wang
<<(forall x y. exists z. forall w. P(x) /\ Q(y) ==> R(z) /\ U(w))
==> (exists x y. P(x) /\ Q(y)) ==> (exists z. R(z))>>;;
(* ------------------------------------------------------------------------- *)
(* But not on this one! *)
(* ------------------------------------------------------------------------- *)
pnf(nnf(miniscope(nnf
<<((exists x. forall y. P(x) <=> P(y)) <=>
((exists x. Q(x)) <=> (forall y. Q(y)))) <=>
((exists x. forall y. Q(x) <=> Q(y)) <=>
((exists x. P(x)) <=> (forall y. P(y))))>>)));;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* Checking classic Aristotelean syllogisms. *)
(* ------------------------------------------------------------------------- *)
let atom p x = Atom(R(p,[Var x]));;
let premiss_A (p,q) = Forall("x",Imp(atom p "x",atom q "x"))
and premiss_E (p,q) = Forall("x",Imp(atom p "x",Not(atom q "x")))
and premiss_I (p,q) = Exists("x",And(atom p "x",atom q "x"))
and premiss_O (p,q) = Exists("x",And(atom p "x",Not(atom q "x")));;
let anglicize_premiss fm =
match fm with
Forall(_,Imp(Atom(R(p,_)),Atom(R(q,_)))) -> "all "^p^" are "^q
| Forall(_,Imp(Atom(R(p,_)),Not(Atom(R(q,_))))) -> "no "^p^" are "^q
| Exists(_,And(Atom(R(p,_)),Atom(R(q,_)))) -> "some "^p^" are "^q
| Exists(_,And(Atom(R(p,_)),Not(Atom(R(q,_))))) ->
"some "^p^" are not "^q;;
let anglicize_syllogism (Imp(And(t1,t2),t3)) =
"If " ^ anglicize_premiss t1 ^ " and " ^ anglicize_premiss t2 ^
", then " ^ anglicize_premiss t3;;
let all_possible_syllogisms =
let sylltypes = [premiss_A; premiss_E; premiss_I; premiss_O] in
let prems1 = allpairs (fun x -> x) sylltypes ["M","P"; "P","M"]
and prems2 = allpairs (fun x -> x) sylltypes ["S","M"; "M","S"]
and prems3 = allpairs (fun x -> x) sylltypes ["S","P"] in
allpairs mk_imp (allpairs mk_and prems1 prems2) prems3;;
START_INTERACTIVE;;
let all_valid_syllogisms = filter aedecide all_possible_syllogisms;;
length all_valid_syllogisms;;
map anglicize_syllogism all_valid_syllogisms;;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* We can "fix" the traditional list by assuming nonemptiness. *)
(* ------------------------------------------------------------------------- *)
let all_possible_syllogisms' =
let p =
<<(exists x. P(x)) /\ (exists x. M(x)) /\ (exists x. S(x))>> in
map (fun t -> Imp(p,t)) all_possible_syllogisms;;
START_INTERACTIVE;;
let all_valid_syllogisms' = filter aedecide all_possible_syllogisms';;
length all_valid_syllogisms';;
map (anglicize_syllogism ** consequent) all_valid_syllogisms';;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* Decide a formula on all models of size n. *)
(* ------------------------------------------------------------------------- *)
let rec alltuples n l =
if n = 0 then [[]] else
let tups = alltuples (n - 1) l in
allpairs (fun h t -> h::t) l tups;;
let allmappings dom ran =
itlist (fun p -> allpairs (valmod p) ran) dom [undef];;
let alldepmappings dom ran =
itlist (fun (p,n) -> allpairs (valmod p) (ran n)) dom [undef];;
let allfunctions dom n = allmappings (alltuples n dom) dom;;
let allpredicates dom n = allmappings (alltuples n dom) [false;true];;
let decide_finite n fm =
let funcs = functions fm and preds = predicates fm and dom = 1--n in
let fints = alldepmappings funcs (allfunctions dom)
and pints = alldepmappings preds (allpredicates dom) in
let interps = allpairs (fun f p -> dom,f,p) fints pints in
let fm' = generalize fm in
forall (fun md -> holds md undefined fm') interps;;
(* ------------------------------------------------------------------------- *)
(* Decision procedure in principle for formulas with finite model property. *)
(* ------------------------------------------------------------------------- *)
let limmeson n fm =
let cls = simpcnf(specialize(pnf fm)) in
let rules = itlist ((@) ** contrapositives) cls [] in
mexpand rules [] False (fun x -> x) (undefined,n,0);;
let limited_meson n fm =
let fm1 = askolemize(Not(generalize fm)) in
map (limmeson n ** list_conj) (simpdnf fm1);;
let decide_fmp fm =
let rec test n =
try limited_meson n fm; true with Failure _ ->
if decide_finite n fm then test (n + 1) else false in
test 1;;
START_INTERACTIVE;;
decide_fmp
<<(forall x y. R(x,y) \/ R(y,x)) ==> forall x. R(x,x)>>;;
decide_fmp
<<(forall x y z. R(x,y) /\ R(y,z) ==> R(x,z)) ==> forall x. R(x,x)>>;;
* * This fails to terminate : has countermodels , but only infinite ones
decide_fmp
< < ~((forall , x ) ) /\
( forall x. exists , z ) ) /\
( forall x y z. R(x , y ) /\ R(y , z ) = = > R(x , z ) ) ) > > ; ;
* * *
decide_fmp
<<~((forall x. ~R(x,x)) /\
(forall x. exists z. R(x,z)) /\
(forall x y z. R(x,y) /\ R(y,z) ==> R(x,z)))>>;;
****)
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
Semantic decision procedure for the monadic fragment .
(* ------------------------------------------------------------------------- *)
let decide_monadic fm =
let funcs = functions fm and preds = predicates fm in
let monadic,other = partition (fun (_,ar) -> ar = 1) preds in
if funcs <> [] or exists (fun (_,ar) -> ar > 1) other
then failwith "Not in the monadic subset" else
let n = funpow (length monadic) (( * ) 2) 1 in
decide_finite n fm;;
(* ------------------------------------------------------------------------- *)
(* Example. *)
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
decide_monadic
<<((exists x. forall y. P(x) <=> P(y)) <=>
((exists x. Q(x)) <=> (forall y. Q(y)))) <=>
((exists x. forall y. Q(x) <=> Q(y)) <=>
((exists x. P(x)) <=> (forall y. P(y))))>>;;
* * * This is not feasible
decide_monadic
< < ( forall x y. exists ) /\ Q(y ) = = > R(z ) /\ U(w ) )
= = > ( exists x y. P(x ) /\ Q(y ) ) = = > ( exists ) ) > > ; ;
* * *
decide_monadic
<<(forall x y. exists z. forall w. P(x) /\ Q(y) ==> R(z) /\ U(w))
==> (exists x y. P(x) /\ Q(y)) ==> (exists z. R(z))>>;;
****)
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* Little auxiliary results for failure of finite model property. *)
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
(*** Our claimed equivalences are indeed correct ***)
meson
<<(exists x y z. forall u.
R(x,x) \/ ~R(x,u) \/ (R(x,y) /\ R(y,z) /\ ~R(x,z))) <=>
~((forall x. ~R(x,x)) /\
(forall x. exists z. R(x,z)) /\
(forall x y z. R(x,y) /\ R(y,z) ==> R(x,z)))>>;;
meson
<<(exists x. forall y. exists z. R(x,x) \/ ~R(x,y) \/ (R(y,z) /\ ~R(x,z))) <=>
~((forall x. ~R(x,x)) /\
(forall x. exists y. R(x,y) /\ forall z. R(y,z) ==> R(x,z)))>>;;
* * The second formula implies the first * *
meson
<<~((forall x. ~R(x,x)) /\
(forall x. exists y. R(x,y) /\ forall z. R(y,z) ==> R(x,z)))
==> ~((forall x. ~R(x,x)) /\
(forall x. exists z. R(x,z)) /\
(forall x y z. R(x,y) /\ R(y,z) ==> R(x,z)))>>;;
END_INTERACTIVE;;
| null | https://raw.githubusercontent.com/steshaw/PLAR/c143b097d1028963f4c1d24f45a1a56c8b65b838/decidable.ml | ocaml | =========================================================================
=========================================================================
-------------------------------------------------------------------------
Resolution does actually terminate with failure in simple cases!
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
However, we can just form all the ground instances.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
In this case it's quicker.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Show how we need to do PNF transformation with care.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Also the group theory problem.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
A bigger example.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
The following, however, doesn't work with aedecide.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Simple-minded miniscoping procedure.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Examples.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
It works well on simple monadic formulas.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
But not on this one!
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Checking classic Aristotelean syllogisms.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
We can "fix" the traditional list by assuming nonemptiness.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Decide a formula on all models of size n.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Decision procedure in principle for formulas with finite model property.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Example.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Little auxiliary results for failure of finite model property.
-------------------------------------------------------------------------
** Our claimed equivalences are indeed correct ** | Special procedures for decidable subsets of first order logic .
Copyright ( c ) 2003 - 2007 , . ( See " LICENSE.txt " for details . )
* *
< < forall x. ) > > ; ;
tab < < forall x. ) > > ; ;
* *
meson <<forall x. p(x)>>;;
tab <<forall x. p(x)>>;;
***)
* *
resolution < < forall x. ) > > ; ;
* *
resolution <<forall x. p(x)>>;;
***)
The Los example ; see how Skolemized form has no non - nullary functions .
START_INTERACTIVE;;
let los =
<<(forall x y z. P(x,y) /\ P(y,z) ==> P(x,z)) /\
(forall x y z. Q(x,y) /\ Q(y,z) ==> Q(x,z)) /\
(forall x y. P(x,y) ==> P(y,x)) /\
(forall x y. P(x,y) \/ Q(x,y))
==> (forall x y. P(x,y)) \/ (forall x y. Q(x,y))>>;;
skolemize(Not los);;
The old DP procedure works .
davisputnam los;;
END_INTERACTIVE;;
let aedecide fm =
let sfm = skolemize(Not fm) in
let fvs = fv sfm
and cnsts,funcs = partition (fun (_,ar) -> ar = 0) (functions sfm) in
if funcs <> [] then failwith "Not decidable" else
let consts = if cnsts = [] then ["c",0] else cnsts in
let cntms = map (fun (c,_) -> Fn(c,[])) consts in
let alltuples = groundtuples cntms [] 0 (length fvs) in
let cjs = simpcnf sfm in
let grounds = map
(fun tup -> image (image (subst (fpf fvs tup))) cjs) alltuples in
not(dpll(unions grounds));;
START_INTERACTIVE;;
aedecide los;;
END_INTERACTIVE;;
START_INTERACTIVE;;
let fm = <<(forall x. p(x)) \/ (exists y. p(y))>>;;
pnf fm;;
aedecide
<<(forall x. P(1,x,x)) /\ (forall x. P(x,x,1)) /\
(forall u v w x y z.
P(x,y,u) /\ P(y,z,w) ==> (P(x,w,v) <=> P(u,z,v)))
==> forall a b c. P(a,b,c) ==> P(b,a,c)>>;;
aedecide
<<(forall x. P(x,x,1)) /\
(forall u v w x y z.
P(x,y,u) /\ P(y,z,w) ==> (P(x,w,v) <=> P(u,z,v)))
==> forall a b c. P(a,b,c) ==> P(b,a,c)>>;;
aedecide
<<(exists x. P(x)) /\ (exists x. G(x))
==> ((forall x. P(x) ==> H(x)) /\ (forall x. G(x) ==> J(x)) <=>
(forall x y. P(x) /\ G(y) ==> H(x) /\ J(y)))>>;;
END_INTERACTIVE;;
* * This is p18
aedecide < < exists y. forall x. ) = = > P(x ) > > ; ;
< < exists y. forall x. ) = = > P(x ) > > ; ;
* *
aedecide <<exists y. forall x. P(y) ==> P(x)>>;;
davisputnam <<exists y. forall x. P(y) ==> P(x)>>;;
***)
let separate x cjs =
let yes,no = partition (mem x ** fv) cjs in
if yes = [] then list_conj no
else if no = [] then Exists(x,list_conj yes)
else And(Exists(x,list_conj yes),list_conj no);;
let rec pushquant x p =
if not (mem x (fv p)) then p else
let djs = purednf(nnf p) in
list_disj (map (separate x) djs);;
let rec miniscope fm =
match fm with
Not p -> Not(miniscope p)
| And(p,q) -> And(miniscope p,miniscope q)
| Or(p,q) -> Or(miniscope p,miniscope q)
| Forall(x,p) -> Not(pushquant x (Not(miniscope p)))
| Exists(x,p) -> pushquant x (miniscope p)
| _ -> fm;;
START_INTERACTIVE;;
miniscope(nnf <<exists y. forall x. P(y) ==> P(x)>>);;
let fm = miniscope(nnf
<<(forall x y. exists z. forall w. P(x) /\ Q(y) ==> R(z) /\ U(w))
==> (exists x y. P(x) /\ Q(y)) ==> (exists z. R(z))>>);;
pnf(nnf fm);;
END_INTERACTIVE;;
Stronger version of " aedecide " similar to Wang 's classic procedure .
let wang fm = aedecide(miniscope(nnf(simplify fm)));;
START_INTERACTIVE;;
wang
<<(forall x y. exists z. forall w. P(x) /\ Q(y) ==> R(z) /\ U(w))
==> (exists x y. P(x) /\ Q(y)) ==> (exists z. R(z))>>;;
pnf(nnf(miniscope(nnf
<<((exists x. forall y. P(x) <=> P(y)) <=>
((exists x. Q(x)) <=> (forall y. Q(y)))) <=>
((exists x. forall y. Q(x) <=> Q(y)) <=>
((exists x. P(x)) <=> (forall y. P(y))))>>)));;
END_INTERACTIVE;;
let atom p x = Atom(R(p,[Var x]));;
let premiss_A (p,q) = Forall("x",Imp(atom p "x",atom q "x"))
and premiss_E (p,q) = Forall("x",Imp(atom p "x",Not(atom q "x")))
and premiss_I (p,q) = Exists("x",And(atom p "x",atom q "x"))
and premiss_O (p,q) = Exists("x",And(atom p "x",Not(atom q "x")));;
let anglicize_premiss fm =
match fm with
Forall(_,Imp(Atom(R(p,_)),Atom(R(q,_)))) -> "all "^p^" are "^q
| Forall(_,Imp(Atom(R(p,_)),Not(Atom(R(q,_))))) -> "no "^p^" are "^q
| Exists(_,And(Atom(R(p,_)),Atom(R(q,_)))) -> "some "^p^" are "^q
| Exists(_,And(Atom(R(p,_)),Not(Atom(R(q,_))))) ->
"some "^p^" are not "^q;;
let anglicize_syllogism (Imp(And(t1,t2),t3)) =
"If " ^ anglicize_premiss t1 ^ " and " ^ anglicize_premiss t2 ^
", then " ^ anglicize_premiss t3;;
let all_possible_syllogisms =
let sylltypes = [premiss_A; premiss_E; premiss_I; premiss_O] in
let prems1 = allpairs (fun x -> x) sylltypes ["M","P"; "P","M"]
and prems2 = allpairs (fun x -> x) sylltypes ["S","M"; "M","S"]
and prems3 = allpairs (fun x -> x) sylltypes ["S","P"] in
allpairs mk_imp (allpairs mk_and prems1 prems2) prems3;;
START_INTERACTIVE;;
let all_valid_syllogisms = filter aedecide all_possible_syllogisms;;
length all_valid_syllogisms;;
map anglicize_syllogism all_valid_syllogisms;;
END_INTERACTIVE;;
let all_possible_syllogisms' =
let p =
<<(exists x. P(x)) /\ (exists x. M(x)) /\ (exists x. S(x))>> in
map (fun t -> Imp(p,t)) all_possible_syllogisms;;
START_INTERACTIVE;;
let all_valid_syllogisms' = filter aedecide all_possible_syllogisms';;
length all_valid_syllogisms';;
map (anglicize_syllogism ** consequent) all_valid_syllogisms';;
END_INTERACTIVE;;
let rec alltuples n l =
if n = 0 then [[]] else
let tups = alltuples (n - 1) l in
allpairs (fun h t -> h::t) l tups;;
let allmappings dom ran =
itlist (fun p -> allpairs (valmod p) ran) dom [undef];;
let alldepmappings dom ran =
itlist (fun (p,n) -> allpairs (valmod p) (ran n)) dom [undef];;
let allfunctions dom n = allmappings (alltuples n dom) dom;;
let allpredicates dom n = allmappings (alltuples n dom) [false;true];;
let decide_finite n fm =
let funcs = functions fm and preds = predicates fm and dom = 1--n in
let fints = alldepmappings funcs (allfunctions dom)
and pints = alldepmappings preds (allpredicates dom) in
let interps = allpairs (fun f p -> dom,f,p) fints pints in
let fm' = generalize fm in
forall (fun md -> holds md undefined fm') interps;;
let limmeson n fm =
let cls = simpcnf(specialize(pnf fm)) in
let rules = itlist ((@) ** contrapositives) cls [] in
mexpand rules [] False (fun x -> x) (undefined,n,0);;
let limited_meson n fm =
let fm1 = askolemize(Not(generalize fm)) in
map (limmeson n ** list_conj) (simpdnf fm1);;
let decide_fmp fm =
let rec test n =
try limited_meson n fm; true with Failure _ ->
if decide_finite n fm then test (n + 1) else false in
test 1;;
START_INTERACTIVE;;
decide_fmp
<<(forall x y. R(x,y) \/ R(y,x)) ==> forall x. R(x,x)>>;;
decide_fmp
<<(forall x y z. R(x,y) /\ R(y,z) ==> R(x,z)) ==> forall x. R(x,x)>>;;
* * This fails to terminate : has countermodels , but only infinite ones
decide_fmp
< < ~((forall , x ) ) /\
( forall x. exists , z ) ) /\
( forall x y z. R(x , y ) /\ R(y , z ) = = > R(x , z ) ) ) > > ; ;
* * *
decide_fmp
<<~((forall x. ~R(x,x)) /\
(forall x. exists z. R(x,z)) /\
(forall x y z. R(x,y) /\ R(y,z) ==> R(x,z)))>>;;
****)
END_INTERACTIVE;;
Semantic decision procedure for the monadic fragment .
let decide_monadic fm =
let funcs = functions fm and preds = predicates fm in
let monadic,other = partition (fun (_,ar) -> ar = 1) preds in
if funcs <> [] or exists (fun (_,ar) -> ar > 1) other
then failwith "Not in the monadic subset" else
let n = funpow (length monadic) (( * ) 2) 1 in
decide_finite n fm;;
START_INTERACTIVE;;
decide_monadic
<<((exists x. forall y. P(x) <=> P(y)) <=>
((exists x. Q(x)) <=> (forall y. Q(y)))) <=>
((exists x. forall y. Q(x) <=> Q(y)) <=>
((exists x. P(x)) <=> (forall y. P(y))))>>;;
* * * This is not feasible
decide_monadic
< < ( forall x y. exists ) /\ Q(y ) = = > R(z ) /\ U(w ) )
= = > ( exists x y. P(x ) /\ Q(y ) ) = = > ( exists ) ) > > ; ;
* * *
decide_monadic
<<(forall x y. exists z. forall w. P(x) /\ Q(y) ==> R(z) /\ U(w))
==> (exists x y. P(x) /\ Q(y)) ==> (exists z. R(z))>>;;
****)
END_INTERACTIVE;;
START_INTERACTIVE;;
meson
<<(exists x y z. forall u.
R(x,x) \/ ~R(x,u) \/ (R(x,y) /\ R(y,z) /\ ~R(x,z))) <=>
~((forall x. ~R(x,x)) /\
(forall x. exists z. R(x,z)) /\
(forall x y z. R(x,y) /\ R(y,z) ==> R(x,z)))>>;;
meson
<<(exists x. forall y. exists z. R(x,x) \/ ~R(x,y) \/ (R(y,z) /\ ~R(x,z))) <=>
~((forall x. ~R(x,x)) /\
(forall x. exists y. R(x,y) /\ forall z. R(y,z) ==> R(x,z)))>>;;
* * The second formula implies the first * *
meson
<<~((forall x. ~R(x,x)) /\
(forall x. exists y. R(x,y) /\ forall z. R(y,z) ==> R(x,z)))
==> ~((forall x. ~R(x,x)) /\
(forall x. exists z. R(x,z)) /\
(forall x y z. R(x,y) /\ R(y,z) ==> R(x,z)))>>;;
END_INTERACTIVE;;
|
7280b4f0fac76ecb545322fc553c742d62ffe3554b2c5480f99772e15978b430 | bhaskara/programmable-reinforcement-learning | alisp-log.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; alisp/log/alisp-log.lisp
;; Log all observations to a stream
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package alisp)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; class def
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass <alisp-log> (<alisp-observer>)
((output-stream
:type stream
:reader str
:initarg :str))
(:documentation "Class <alisp-log>. Has a single required initialization argument :str for the output stream. Implements all the methods from <learning-algorithm>, and in each case just prints the information about the message to the stream."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; definition macro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro deflogmessage (name lambda-list)
"deflogmessage NAME LAMBDA-LIST. Used to define messages to a alisp-log. For example, (deflogmessage inform-reset (s)) will expand to code that creates a method for inform-reset which prints 'inform-reset' and s to the stream. See examples in this file."
(with-gensyms (alg)
`(defmethod ,name ,(cons `(,alg <alisp-log>) lambda-list)
(format (str ,alg) "~&~%Alisp log informed of ~a" ,(string-downcase (symbol-name name)))
,@(loop for arg in lambda-list
for i from 0
collect `(format (str ,alg) "~&Arg ~a : ~a" ,i ,arg)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; methods overridden from <alisp-observer>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deflogmessage inform-start-episode (s))
(deflogmessage inform-env-step (act rew to term))
(deflogmessage inform-alisp-step (omega choice))
(deflogmessage inform-start-execution ())
(deflogmessage inform-finish-execution ())
(deflogmessage inform-end-choice-block (omega))
(deflogmessage inform-part-prog-terminated (omega))
| null | https://raw.githubusercontent.com/bhaskara/programmable-reinforcement-learning/8afc98116a8f78163b3f86076498d84b3f596217/lisp/alisp/obs/alisp-log.lisp | lisp |
alisp/log/alisp-log.lisp
Log all observations to a stream
class def
definition macro
methods overridden from <alisp-observer>
|
(in-package alisp)
(defclass <alisp-log> (<alisp-observer>)
((output-stream
:type stream
:reader str
:initarg :str))
(:documentation "Class <alisp-log>. Has a single required initialization argument :str for the output stream. Implements all the methods from <learning-algorithm>, and in each case just prints the information about the message to the stream."))
(defmacro deflogmessage (name lambda-list)
"deflogmessage NAME LAMBDA-LIST. Used to define messages to a alisp-log. For example, (deflogmessage inform-reset (s)) will expand to code that creates a method for inform-reset which prints 'inform-reset' and s to the stream. See examples in this file."
(with-gensyms (alg)
`(defmethod ,name ,(cons `(,alg <alisp-log>) lambda-list)
(format (str ,alg) "~&~%Alisp log informed of ~a" ,(string-downcase (symbol-name name)))
,@(loop for arg in lambda-list
for i from 0
collect `(format (str ,alg) "~&Arg ~a : ~a" ,i ,arg)))))
(deflogmessage inform-start-episode (s))
(deflogmessage inform-env-step (act rew to term))
(deflogmessage inform-alisp-step (omega choice))
(deflogmessage inform-start-execution ())
(deflogmessage inform-finish-execution ())
(deflogmessage inform-end-choice-block (omega))
(deflogmessage inform-part-prog-terminated (omega))
|
f5ea66e2538e1746fc607f1e3ddc4c23874160633c33caa563afc642ad010d1f | ocaml/num | nat.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. *)
(* *)
(**************************************************************************)
open Int_misc
type nat;;
external create_nat: int -> nat = "create_nat"
external set_to_zero_nat: nat -> int -> int -> unit = "set_to_zero_nat"
external blit_nat: nat -> int -> nat -> int -> int -> unit = "blit_nat"
external set_digit_nat: nat -> int -> int -> unit = "set_digit_nat"
external nth_digit_nat: nat -> int -> int = "nth_digit_nat"
external set_digit_nat_native: nat -> int -> nativeint -> unit
= "set_digit_nat_native"
external nth_digit_nat_native: nat -> int -> nativeint = "nth_digit_nat_native"
external num_digits_nat: nat -> int -> int -> int = "num_digits_nat"
external num_leading_zero_bits_in_digit: nat -> int -> int
= "num_leading_zero_bits_in_digit"
external is_digit_int: nat -> int -> bool = "is_digit_int"
external is_digit_zero: nat -> int -> bool = "is_digit_zero"
external is_digit_normalized: nat -> int -> bool = "is_digit_normalized"
external is_digit_odd: nat -> int -> bool = "is_digit_odd"
external incr_nat: nat -> int -> int -> int -> int = "incr_nat"
external add_nat: nat -> int -> int -> nat -> int -> int -> int -> int
= "add_nat" "add_nat_native"
external complement_nat: nat -> int -> int -> unit = "complement_nat"
external decr_nat: nat -> int -> int -> int -> int = "decr_nat"
external sub_nat: nat -> int -> int -> nat -> int -> int -> int -> int
= "sub_nat" "sub_nat_native"
external mult_digit_nat:
nat -> int -> int -> nat -> int -> int -> nat -> int -> int
= "mult_digit_nat" "mult_digit_nat_native"
external mult_nat:
nat -> int -> int -> nat -> int -> int -> nat -> int -> int -> int
= "mult_nat" "mult_nat_native"
external square_nat: nat -> int -> int -> nat -> int -> int -> int
= "square_nat" "square_nat_native"
external shift_left_nat: nat -> int -> int -> nat -> int -> int -> unit
= "shift_left_nat" "shift_left_nat_native"
external div_digit_nat:
nat -> int -> nat -> int -> nat -> int -> int -> nat -> int -> unit
= "div_digit_nat" "div_digit_nat_native"
external div_nat: nat -> int -> int -> nat -> int -> int -> unit
= "div_nat" "div_nat_native"
external shift_right_nat: nat -> int -> int -> nat -> int -> int -> unit
= "shift_right_nat" "shift_right_nat_native"
external compare_digits_nat: nat -> int -> nat -> int -> int
= "compare_digits_nat"
external compare_nat: nat -> int -> int -> nat -> int -> int -> int
= "compare_nat" "compare_nat_native"
external land_digit_nat: nat -> int -> nat -> int -> unit = "land_digit_nat"
external lor_digit_nat: nat -> int -> nat -> int -> unit = "lor_digit_nat"
external lxor_digit_nat: nat -> int -> nat -> int -> unit = "lxor_digit_nat"
external initialize_nat: unit -> unit = "initialize_nat"
let _ = initialize_nat()
let length_nat (n : nat) = Obj.size (Obj.repr n) - 1
let length_of_digit = Sys.word_size;;
let make_nat len =
if len < 0 then invalid_arg "make_nat" else
let res = create_nat len in set_to_zero_nat res 0 len; res
let copy_nat nat off_set length =
let res = create_nat (length) in
blit_nat res 0 nat off_set length;
res
let is_zero_nat n off len =
compare_nat (make_nat 1) 0 1 n off (num_digits_nat n off len) = 0
let is_nat_int nat off len =
num_digits_nat nat off len = 1 && is_digit_int nat off
let sys_int_of_nat nat off len =
if is_nat_int nat off len
then nth_digit_nat nat off
else failwith "int_of_nat"
let int_of_nat nat =
sys_int_of_nat nat 0 (length_nat nat)
let nat_of_int i =
if i < 0 then invalid_arg "nat_of_int" else
let res = make_nat 1 in
if i = 0 then res else begin set_digit_nat res 0 i; res end
let eq_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) = 0
and le_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) <= 0
and lt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) < 0
and ge_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) >= 0
and gt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) > 0
XL : now implemented in C for better performance .
The code below does n't handle carries correctly .
Fortunately , the carry is never used .
The code below doesn't handle carries correctly.
Fortunately, the carry is never used. *)
* *
let square_nat nat1 off1 len1 nat2 off2 len2 =
let c = ref 0
and trash = make_nat 1 in
( * Double product
let square_nat nat1 off1 len1 nat2 off2 len2 =
let c = ref 0
and trash = make_nat 1 in
(* Double product *)
for i = 0 to len2 - 2 do
c := !c + mult_digit_nat
nat1
(succ (off1 + 2 * i))
(2 * (pred (len2 - i)))
nat2
(succ (off2 + i))
(pred (len2 - i))
nat2
(off2 + i)
done;
shift_left_nat nat1 0 len1 trash 0 1;
(* Square of digit *)
for i = 0 to len2 - 1 do
c := !c + mult_digit_nat
nat1
(off1 + 2 * i)
(len1 - 2 * i)
nat2
(off2 + i)
1
nat2
(off2 + i)
done;
!c
***)
let =
if i = 0 then 1 else
if is_nat_int off len then begin
set_digit_nat nat off ( gcd_int ( nth_digit_nat off ) i ) ; 0
end else begin
let len_copy = succ len in
let copy = create_nat len_copy
and quotient = create_nat 1
and remainder = create_nat 1 in
blit_nat copy 0 nat off len ;
set_digit_nat copy len 0 ;
div_digit_nat quotient 0 remainder 0 copy 0 len_copy ( nat_of_int i ) 0 ;
set_digit_nat nat off ( gcd_int ( nth_digit_nat remainder 0 ) i ) ;
0
end
let gcd_int_nat i nat off len =
if i = 0 then 1 else
if is_nat_int nat off len then begin
set_digit_nat nat off (gcd_int (nth_digit_nat nat off) i); 0
end else begin
let len_copy = succ len in
let copy = create_nat len_copy
and quotient = create_nat 1
and remainder = create_nat 1 in
blit_nat copy 0 nat off len;
set_digit_nat copy len 0;
div_digit_nat quotient 0 remainder 0 copy 0 len_copy (nat_of_int i) 0;
set_digit_nat nat off (gcd_int (nth_digit_nat remainder 0) i);
0
end
*)
let exchange r1 r2 =
let old1 = !r1 in r1 := !r2; r2 := old1
let gcd_nat nat1 off1 len1 nat2 off2 len2 =
if is_zero_nat nat1 off1 len1 then begin
blit_nat nat1 off1 nat2 off2 len2; len2
end else begin
let copy1 = ref (create_nat (succ len1))
and copy2 = ref (create_nat (succ len2)) in
blit_nat !copy1 0 nat1 off1 len1;
blit_nat !copy2 0 nat2 off2 len2;
set_digit_nat !copy1 len1 0;
set_digit_nat !copy2 len2 0;
if lt_nat !copy1 0 len1 !copy2 0 len2
then exchange copy1 copy2;
let real_len1 =
ref (num_digits_nat !copy1 0 (length_nat !copy1))
and real_len2 =
ref (num_digits_nat !copy2 0 (length_nat !copy2)) in
while not (is_zero_nat !copy2 0 !real_len2) do
set_digit_nat !copy1 !real_len1 0;
div_nat !copy1 0 (succ !real_len1) !copy2 0 !real_len2;
exchange copy1 copy2;
real_len1 := !real_len2;
real_len2 := num_digits_nat !copy2 0 !real_len2
done;
blit_nat nat1 off1 !copy1 0 !real_len1;
!real_len1
end
Integer square root using method ( nearest integer by default )
Theorem : the sequence x_{n+1 } = ( x_n + a / x_n ) /2 converges toward
the integer square root ( by default ) of a for any starting value x_0
strictly greater than the square root of a except if a + 1 is a
perfect square . In this situation , the sequence alternates between
the excess and default integer square root . In any case , the last
strictly decreasing term is the expected result
the integer square root (by default) of a for any starting value x_0
strictly greater than the square root of a except if a + 1 is a
perfect square. In this situation, the sequence alternates between
the excess and default integer square root. In any case, the last
strictly decreasing term is the expected result *)
let sqrt_nat rad off len =
let len = num_digits_nat rad off len in
(* Working copy of radicand *)
let len_parity = len mod 2 in
let rad_len = len + 1 + len_parity in
let rad =
let res = create_nat rad_len in
blit_nat res 0 rad off len;
set_digit_nat res len 0;
set_digit_nat res (rad_len - 1) 0;
res in
let cand_len = (len + 1) / 2 in (* ceiling len / 2 *)
let cand_rest = rad_len - cand_len in
(* Candidate square root cand = "|FFFF .... |" *)
let cand = make_nat cand_len in
Improve starting square root :
We compute nbb , the number of significant bits of the first digit of the
candidate
( half of the number of significant bits in the first two digits
of the radicand extended to an even length ) .
shift_cand is word_size - nbb
We compute nbb, the number of significant bits of the first digit of the
candidate
(half of the number of significant bits in the first two digits
of the radicand extended to an even length).
shift_cand is word_size - nbb *)
let shift_cand =
((num_leading_zero_bits_in_digit rad (len-1)) +
length_of_digit * len_parity) / 2 in
(* All radicand bits are zeroed, we give back 0. *)
if shift_cand = length_of_digit then cand else
begin
complement_nat cand 0 cand_len;
let tmp = create_nat 1 in
shift_right_nat cand 0 1 tmp 0 shift_cand;
let next_cand = create_nat rad_len in
(* Repeat until *)
let rec loop () =
(* next_cand := rad *)
blit_nat next_cand 0 rad 0 rad_len;
(* next_cand <- next_cand / cand *)
div_nat next_cand 0 rad_len cand 0 cand_len;
(* next_cand (strong weight) <- next_cand (strong weight) + cand,
i.e. next_cand <- cand + rad / cand *)
ignore (add_nat next_cand cand_len cand_rest cand 0 cand_len 0);
(* next_cand <- next_cand / 2 *)
shift_right_nat next_cand cand_len cand_rest tmp 0 1;
if lt_nat next_cand cand_len cand_rest cand 0 cand_len then
begin (* cand <- next_cand *)
blit_nat cand 0 next_cand cand_len cand_len; loop ()
end
else cand in
loop ()
end;;
let power_base_max = make_nat 2;;
match length_of_digit with
| 64 ->
set_digit_nat power_base_max 0 (Int64.to_int 1000000000000000000L);
ignore
(mult_digit_nat power_base_max 0 2
power_base_max 0 1 (nat_of_int 9) 0)
| 32 -> set_digit_nat power_base_max 0 1000000000
| _ -> assert false
;;
let pmax =
match length_of_digit with
| 64 -> 19
| 32 -> 9
| _ -> assert false
;;
let raw_string_of_digit nat off =
Printf.sprintf "%nu" (nth_digit_nat_native nat off)
XL : suppression de string_of_digit et de sys_string_of_digit .
La copie est de toute facon faite dans string_of_nat , qui est le
seul point d entree public dans ce code .
| Deletion of string_of_digit and sys_string_of_digit .
The copy is already done in string_of_nat which is the only
public entry point in this code
La copie est de toute facon faite dans string_of_nat, qui est le
seul point d entree public dans ce code.
| Deletion of string_of_digit and sys_string_of_digit.
The copy is already done in string_of_nat which is the only
public entry point in this code
*)
* * * * *
let off =
let s = raw_string_of_digit off in
let result = String.create ( String.length s ) in
String.blit s 0 result 0 ( String.length s ) ;
s
let string_of_digit nat =
sys_string_of_digit
* * * * * *
let sys_string_of_digit nat off =
let s = raw_string_of_digit nat off in
let result = String.create (String.length s) in
String.blit s 0 result 0 (String.length s);
s
let string_of_digit nat =
sys_string_of_digit nat 0
*******)
make_power_base affecte power_base des puissances successives de base a
partir de la puissance 1 - ieme .
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int .
This function returns [ ( pmax , pint ) ] where :
[ pmax ] is the index of the digit of [ power_base ] that contains the
the maximum power of [ base ] that fits in a digit . This is also one
less than the exponent of that power .
[ pint ] is the exponent of the maximum power of [ base ] that fits in an [ int ] .
make_power_base affecte power_base des puissances successives de base a
partir de la puissance 1-ieme.
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int.
This function returns [(pmax, pint)] where:
[pmax] is the index of the digit of [power_base] that contains the
the maximum power of [base] that fits in a digit. This is also one
less than the exponent of that power.
[pint] is the exponent of the maximum power of [base] that fits in an [int].
*)
let make_power_base base power_base =
let i = ref 0
and j = ref 0 in
set_digit_nat power_base 0 base;
while incr i; is_digit_zero power_base !i do
ignore
(mult_digit_nat power_base !i 2
power_base (pred !i) 1
power_base 0)
done;
while !j < !i - 1 && is_digit_int power_base !j do incr j done;
(!i - 2, !j)
(*
(*
int_to_string places the representation of the integer int in base 'base'
in the string s by starting from the end position pos and going towards
the start, for 'times' places and updates the value of pos.
*)
let digits = "0123456789ABCDEF"
let int_to_string int s pos_ref base times =
let i = ref int
and j = ref times in
while ((!i != 0) || (!j != 0)) && (!pos_ref != -1) do
Bytes.set s !pos_ref (String.get digits (!i mod base));
decr pos_ref;
decr j;
i := !i / base
done
*)
let power_base_int base i =
if i = 0 || base = 1 then
nat_of_int 1
else if base = 0 then
nat_of_int 0
else if i < 0 then
invalid_arg "power_base_int"
else begin
let power_base = make_nat (succ length_of_digit) in
let (pmax, _pint) = make_power_base base power_base in
let n = i / (succ pmax)
and rem = i mod (succ pmax) in
if n > 0 then begin
let newn =
if i = biggest_int then n else (succ n) in
let res = make_nat newn
and res2 = make_nat newn
and l = num_bits_int n - 2 in
blit_nat res 0 power_base pmax 1;
for i = l downto 0 do
let len = num_digits_nat res 0 newn in
let len2 = min n (2 * len) in
let succ_len2 = succ len2 in
ignore (square_nat res2 0 len2 res 0 len);
if n land (1 lsl i) > 0 then begin
set_to_zero_nat res 0 len;
ignore
(mult_digit_nat res 0 succ_len2
res2 0 len2 power_base pmax)
end else
blit_nat res 0 res2 0 len2;
set_to_zero_nat res2 0 len2
done;
if rem > 0 then begin
ignore
(mult_digit_nat res2 0 newn
res 0 n power_base (pred rem));
res2
end else res
end else
copy_nat power_base (pred rem) 1
end
the ith element ( i > = 2 ) of num_digits_max_vector is :
| |
| biggest_string_length * log ( i ) |
| ------------------------------- | + 1
| length_of_digit * log ( 2 ) |
-- --
| |
| biggest_string_length * log (i) |
| ------------------------------- | + 1
| length_of_digit * log (2) |
-- --
*)
XL : ai specialise le code d origine a length_of_digit = 32 .
| the original code have been specialized to a length_of_digit = 32 .
| the original code have been specialized to a length_of_digit = 32. *)
(* Now deleted (useless?) *)
* * * * *
let num_digits_max_vector =
[ |0 ; 0 ; 1024 ; 1623 ; 2048 ; 2378 ; 2647 ; 2875 ; 3072 ; 3246 ; 3402 ;
3543 ; 3671 ; 3789 ; 3899 ; 4001 ; 4096| ]
let num_digits_max_vector =
match length_of_digit with
16 - > [ |0 ; 0 ; 2048 ; 3246 ; 4096 ; 4755 ; 5294 ; 5749 ; 6144 ; 6492 ; 6803 ;
7085 ; 7342 ; 7578 ; 7797 ; 8001 ; 8192| ]
( * If really exotic machines ! ! ! !
| 17 - > [ |0 ; 0 ; 1928 ; 3055 ; 3855 ; 4476 ; 4983 ; 5411 ; 5783 ; 6110 ; 6403 ;
6668 ; 6910 ; 7133 ; 7339 ; 7530 ; 7710| ]
| 18 - > [ |0 ; 0 ; 1821 ; 2886 ; 3641 ; 4227 ; 4706 ; 5111 ; 5461 ; 5771 ; 6047 ;
6298 ; 6526 ; 6736 ; 6931 ; 7112 ; 7282| ]
| 19 - > [ |0 ; 0 ; 1725 ; 2734 ; 3449 ; 4005 ; 4458 ; 4842 ; 5174 ; 5467 ; 5729 ;
5966 ; 6183 ; 6382 ; 6566 ; 6738 ; 6898| ]
| 20 - > [ |0 ; 0 ; 1639 ; 2597 ; 3277 ; 3804 ; 4235 ; 4600 ; 4915 ; 5194 ; 5443 ;
5668 ; 5874 ; 6063 ; 6238 ; 6401 ; 6553| ]
| 21 - > [ |0 ; 0 ; 1561 ; 2473 ; 3121 ; 3623 ; 4034 ; 4381 ; 4681 ; 4946 ; 5183 ;
5398 ; 5594 ; 5774 ; 5941 ; 6096 ; 6241| ]
| 22 - > [ |0 ; 0 ; 1490 ; 2361 ; 2979 ; 3459 ; 3850 ; 4182 ; 4468 ; 4722 ; 4948 ;
5153 ; 5340 ; 5512 ; 5671 ; 5819 ; 5958| ]
| 23 - > [ |0 ; 0 ; 1425 ; 2258 ; 2850 ; 3308 ; 3683 ; 4000 ; 4274 ; 4516 ; 4733 ;
4929 ; 5108 ; 5272 ; 5424 ; 5566 ; 5699| ]
| 24 - > [ |0 ; 0 ; 1366 ; 2164 ; 2731 ; 3170 ; 3530 ; 3833 ; 4096 ; ; 4536 ;
4723 ; 4895 ; 5052 ; 5198 ; 5334 ; 5461| ]
| 25 - > [ |0 ; 0 ; 1311 ; 2078 ; 2622 ; 3044 ; 3388 ; 3680 ; 3932 ; 4155 ; 4354 ;
4534 ; 4699 ; 4850 ; 4990 ; 5121 ; 5243| ]
| 26 - > [ |0 ; 0 ; 1261 ; 1998 ; 2521 ; 2927 ; 3258 ; 3538 ; 3781 ; 3995 ; 4187 ;
4360 ; 4518 ; 4664 ; 4798 ; 4924 ; 5041| ]
| 27 - > [ |0 ; 0 ; 1214 ; 1924 ; 2428 ; 2818 ; 3137 ; 3407 ; 3641 ; 3847 ; 4032 ;
4199 ; 4351 ; 4491 ; 4621 ; 4742 ; 4855| ]
| 28 - > [ |0 ; 0 ; 1171 ; 1855 ; 2341 ; 2718 ; 3025 ; 3286 ; 3511 ; 3710 ; 3888 ;
4049 ; 4196 ; 4331 ; 4456 ; 4572 ; 4681| ]
| 29 - > [ |0 ; 0 ; 1130 ; 1791 ; 2260 ; 2624 ; 2921 ; 3172 ; 3390 ; 3582 ; 3754 ;
3909 ; 4051 ; 4181 ; 4302 ; 4415 ; 4520| ]
| 30 - > [ |0 ; 0 ; 1093 ; 1732 ; 2185 ; 2536 ; 2824 ; 3067 ; 3277 ; 3463 ; 3629 ;
3779 ; 3916 ; 4042 ; 4159 ; 4267 ; 4369| ]
| 31 - > [ |0 ; 0 ; 1057 ; 1676 ; 2114 ; 2455 ; 2733 ; 2968 ; 3171 ; 3351 ; 3512 ;
3657 ; 3790 ; 3912 ; 4025 ; 4130 ; 4228| ]
let num_digits_max_vector =
[|0; 0; 1024; 1623; 2048; 2378; 2647; 2875; 3072; 3246; 3402;
3543; 3671; 3789; 3899; 4001; 4096|]
let num_digits_max_vector =
match length_of_digit with
16 -> [|0; 0; 2048; 3246; 4096; 4755; 5294; 5749; 6144; 6492; 6803;
7085; 7342; 7578; 7797; 8001; 8192|]
(* If really exotic machines !!!!
| 17 -> [|0; 0; 1928; 3055; 3855; 4476; 4983; 5411; 5783; 6110; 6403;
6668; 6910; 7133; 7339; 7530; 7710|]
| 18 -> [|0; 0; 1821; 2886; 3641; 4227; 4706; 5111; 5461; 5771; 6047;
6298; 6526; 6736; 6931; 7112; 7282|]
| 19 -> [|0; 0; 1725; 2734; 3449; 4005; 4458; 4842; 5174; 5467; 5729;
5966; 6183; 6382; 6566; 6738; 6898|]
| 20 -> [|0; 0; 1639; 2597; 3277; 3804; 4235; 4600; 4915; 5194; 5443;
5668; 5874; 6063; 6238; 6401; 6553|]
| 21 -> [|0; 0; 1561; 2473; 3121; 3623; 4034; 4381; 4681; 4946; 5183;
5398; 5594; 5774; 5941; 6096; 6241|]
| 22 -> [|0; 0; 1490; 2361; 2979; 3459; 3850; 4182; 4468; 4722; 4948;
5153; 5340; 5512; 5671; 5819; 5958|]
| 23 -> [|0; 0; 1425; 2258; 2850; 3308; 3683; 4000; 4274; 4516; 4733;
4929; 5108; 5272; 5424; 5566; 5699|]
| 24 -> [|0; 0; 1366; 2164; 2731; 3170; 3530; 3833; 4096; 4328; 4536;
4723; 4895; 5052; 5198; 5334; 5461|]
| 25 -> [|0; 0; 1311; 2078; 2622; 3044; 3388; 3680; 3932; 4155; 4354;
4534; 4699; 4850; 4990; 5121; 5243|]
| 26 -> [|0; 0; 1261; 1998; 2521; 2927; 3258; 3538; 3781; 3995; 4187;
4360; 4518; 4664; 4798; 4924; 5041|]
| 27 -> [|0; 0; 1214; 1924; 2428; 2818; 3137; 3407; 3641; 3847; 4032;
4199; 4351; 4491; 4621; 4742; 4855|]
| 28 -> [|0; 0; 1171; 1855; 2341; 2718; 3025; 3286; 3511; 3710; 3888;
4049; 4196; 4331; 4456; 4572; 4681|]
| 29 -> [|0; 0; 1130; 1791; 2260; 2624; 2921; 3172; 3390; 3582; 3754;
3909; 4051; 4181; 4302; 4415; 4520|]
| 30 -> [|0; 0; 1093; 1732; 2185; 2536; 2824; 3067; 3277; 3463; 3629;
3779; 3916; 4042; 4159; 4267; 4369|]
| 31 -> [|0; 0; 1057; 1676; 2114; 2455; 2733; 2968; 3171; 3351; 3512;
3657; 3790; 3912; 4025; 4130; 4228|]
*)
| 32 -> [|0; 0; 1024; 1623; 2048; 2378; 2647; 2875; 3072; 3246; 3402;
3543; 3671; 3789; 3899; 4001; 4096|]
| n -> failwith "num_digits_max_vector"
******)
let unadjusted_string_of_nat nat off len_nat =
let len = num_digits_nat nat off len_nat in
if len = 1 then
raw_string_of_digit nat off
else
let len_copy = ref (succ len) in
let copy1 = create_nat !len_copy
and copy2 = make_nat !len_copy
and rest_digit = make_nat 2 in
if len > biggest_int / (succ pmax)
then failwith "number too long"
else let len_s = (succ pmax) * len in
let s = Bytes.make len_s '0'
and pos_ref = ref len_s in
len_copy := pred !len_copy;
blit_nat copy1 0 nat off len;
set_digit_nat copy1 len 0;
while not (is_zero_nat copy1 0 !len_copy) do
div_digit_nat copy2 0
rest_digit 0
copy1 0 (succ !len_copy)
power_base_max 0;
let str = raw_string_of_digit rest_digit 0 in
String.blit str 0
s (!pos_ref - String.length str)
(String.length str);
pos_ref := !pos_ref - pmax;
len_copy := num_digits_nat copy2 0 !len_copy;
blit_nat copy1 0 copy2 0 !len_copy;
set_digit_nat copy1 !len_copy 0
done;
Bytes.unsafe_to_string s
let string_of_nat nat =
let s = unadjusted_string_of_nat nat 0 (length_nat nat)
and index = ref 0 in
begin try
for i = 0 to String.length s - 2 do
if String.get s i <> '0' then (index:= i; raise Exit)
done
with Exit -> ()
end;
String.sub s !index (String.length s - !index)
let base_digit_of_char c base =
let n = Char.code c in
if n >= 48 && n <= 47 + min base 10 then n - 48
else if n >= 65 && n <= 65 + base - 11 then n - 55
else if n >= 97 && n <= 97 + base - 11 then n - 87
else failwith "invalid digit"
The substring ( s , off , len ) represents a nat in base ' base ' which is
determined here
The substring (s, off, len) represents a nat in base 'base' which is
determined here
*)
let sys_nat_of_string base s off len =
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
let new_len = ref (1 + len / (pmax + 1))
and current_len = ref 1 in
let possible_len = ref (min 2 !new_len) in
let nat1 = make_nat !new_len
and nat2 = make_nat !new_len
and digits_read = ref 0
and bound = off + len - 1
and int = ref 0 in
for i = off to bound do
(*
we read (at most) pint digits, we transform them in a int
and integrate it to the number
*)
let c = String.get s i in
begin match c with
' ' | '\t' | '\n' | '\r' | '\\' -> ()
| '_' when i > off -> ()
| _ -> int := !int * base + base_digit_of_char c base;
incr digits_read
end;
if (!digits_read = pint || i = bound) && not (!digits_read = 0) then
begin
set_digit_nat nat1 0 !int;
let erase_len = if !new_len = !current_len then !current_len - 1
else !current_len in
for j = 1 to erase_len do
set_digit_nat nat1 j 0
done;
ignore
(mult_digit_nat nat1 0 !possible_len
nat2 0 !current_len power_base (pred !digits_read));
blit_nat nat2 0 nat1 0 !possible_len;
current_len := num_digits_nat nat1 0 !possible_len;
possible_len := min !new_len (succ !current_len);
int := 0;
digits_read := 0
end
done;
We reframe
We reframe nat
*)
let nat = create_nat !current_len in
blit_nat nat 0 nat1 0 !current_len;
nat
let nat_of_string s = sys_nat_of_string 10 s 0 (String.length s)
let float_of_nat nat = float_of_string(string_of_nat nat)
| null | https://raw.githubusercontent.com/ocaml/num/bdfee8067bfd78cf79cb8910c45cccfe2b061680/src/nat.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.
************************************************************************
Double product
Square of digit
Working copy of radicand
ceiling len / 2
Candidate square root cand = "|FFFF .... |"
All radicand bits are zeroed, we give back 0.
Repeat until
next_cand := rad
next_cand <- next_cand / cand
next_cand (strong weight) <- next_cand (strong weight) + cand,
i.e. next_cand <- cand + rad / cand
next_cand <- next_cand / 2
cand <- next_cand
(*
int_to_string places the representation of the integer int in base 'base'
in the string s by starting from the end position pos and going towards
the start, for 'times' places and updates the value of pos.
Now deleted (useless?)
If really exotic machines !!!!
| 17 -> [|0; 0; 1928; 3055; 3855; 4476; 4983; 5411; 5783; 6110; 6403;
6668; 6910; 7133; 7339; 7530; 7710|]
| 18 -> [|0; 0; 1821; 2886; 3641; 4227; 4706; 5111; 5461; 5771; 6047;
6298; 6526; 6736; 6931; 7112; 7282|]
| 19 -> [|0; 0; 1725; 2734; 3449; 4005; 4458; 4842; 5174; 5467; 5729;
5966; 6183; 6382; 6566; 6738; 6898|]
| 20 -> [|0; 0; 1639; 2597; 3277; 3804; 4235; 4600; 4915; 5194; 5443;
5668; 5874; 6063; 6238; 6401; 6553|]
| 21 -> [|0; 0; 1561; 2473; 3121; 3623; 4034; 4381; 4681; 4946; 5183;
5398; 5594; 5774; 5941; 6096; 6241|]
| 22 -> [|0; 0; 1490; 2361; 2979; 3459; 3850; 4182; 4468; 4722; 4948;
5153; 5340; 5512; 5671; 5819; 5958|]
| 23 -> [|0; 0; 1425; 2258; 2850; 3308; 3683; 4000; 4274; 4516; 4733;
4929; 5108; 5272; 5424; 5566; 5699|]
| 24 -> [|0; 0; 1366; 2164; 2731; 3170; 3530; 3833; 4096; 4328; 4536;
4723; 4895; 5052; 5198; 5334; 5461|]
| 25 -> [|0; 0; 1311; 2078; 2622; 3044; 3388; 3680; 3932; 4155; 4354;
4534; 4699; 4850; 4990; 5121; 5243|]
| 26 -> [|0; 0; 1261; 1998; 2521; 2927; 3258; 3538; 3781; 3995; 4187;
4360; 4518; 4664; 4798; 4924; 5041|]
| 27 -> [|0; 0; 1214; 1924; 2428; 2818; 3137; 3407; 3641; 3847; 4032;
4199; 4351; 4491; 4621; 4742; 4855|]
| 28 -> [|0; 0; 1171; 1855; 2341; 2718; 3025; 3286; 3511; 3710; 3888;
4049; 4196; 4331; 4456; 4572; 4681|]
| 29 -> [|0; 0; 1130; 1791; 2260; 2624; 2921; 3172; 3390; 3582; 3754;
3909; 4051; 4181; 4302; 4415; 4520|]
| 30 -> [|0; 0; 1093; 1732; 2185; 2536; 2824; 3067; 3277; 3463; 3629;
3779; 3916; 4042; 4159; 4267; 4369|]
| 31 -> [|0; 0; 1057; 1676; 2114; 2455; 2733; 2968; 3171; 3351; 3512;
3657; 3790; 3912; 4025; 4130; 4228|]
we read (at most) pint digits, we transform them in a int
and integrate it to the number
| , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Int_misc
type nat;;
external create_nat: int -> nat = "create_nat"
external set_to_zero_nat: nat -> int -> int -> unit = "set_to_zero_nat"
external blit_nat: nat -> int -> nat -> int -> int -> unit = "blit_nat"
external set_digit_nat: nat -> int -> int -> unit = "set_digit_nat"
external nth_digit_nat: nat -> int -> int = "nth_digit_nat"
external set_digit_nat_native: nat -> int -> nativeint -> unit
= "set_digit_nat_native"
external nth_digit_nat_native: nat -> int -> nativeint = "nth_digit_nat_native"
external num_digits_nat: nat -> int -> int -> int = "num_digits_nat"
external num_leading_zero_bits_in_digit: nat -> int -> int
= "num_leading_zero_bits_in_digit"
external is_digit_int: nat -> int -> bool = "is_digit_int"
external is_digit_zero: nat -> int -> bool = "is_digit_zero"
external is_digit_normalized: nat -> int -> bool = "is_digit_normalized"
external is_digit_odd: nat -> int -> bool = "is_digit_odd"
external incr_nat: nat -> int -> int -> int -> int = "incr_nat"
external add_nat: nat -> int -> int -> nat -> int -> int -> int -> int
= "add_nat" "add_nat_native"
external complement_nat: nat -> int -> int -> unit = "complement_nat"
external decr_nat: nat -> int -> int -> int -> int = "decr_nat"
external sub_nat: nat -> int -> int -> nat -> int -> int -> int -> int
= "sub_nat" "sub_nat_native"
external mult_digit_nat:
nat -> int -> int -> nat -> int -> int -> nat -> int -> int
= "mult_digit_nat" "mult_digit_nat_native"
external mult_nat:
nat -> int -> int -> nat -> int -> int -> nat -> int -> int -> int
= "mult_nat" "mult_nat_native"
external square_nat: nat -> int -> int -> nat -> int -> int -> int
= "square_nat" "square_nat_native"
external shift_left_nat: nat -> int -> int -> nat -> int -> int -> unit
= "shift_left_nat" "shift_left_nat_native"
external div_digit_nat:
nat -> int -> nat -> int -> nat -> int -> int -> nat -> int -> unit
= "div_digit_nat" "div_digit_nat_native"
external div_nat: nat -> int -> int -> nat -> int -> int -> unit
= "div_nat" "div_nat_native"
external shift_right_nat: nat -> int -> int -> nat -> int -> int -> unit
= "shift_right_nat" "shift_right_nat_native"
external compare_digits_nat: nat -> int -> nat -> int -> int
= "compare_digits_nat"
external compare_nat: nat -> int -> int -> nat -> int -> int -> int
= "compare_nat" "compare_nat_native"
external land_digit_nat: nat -> int -> nat -> int -> unit = "land_digit_nat"
external lor_digit_nat: nat -> int -> nat -> int -> unit = "lor_digit_nat"
external lxor_digit_nat: nat -> int -> nat -> int -> unit = "lxor_digit_nat"
external initialize_nat: unit -> unit = "initialize_nat"
let _ = initialize_nat()
let length_nat (n : nat) = Obj.size (Obj.repr n) - 1
let length_of_digit = Sys.word_size;;
let make_nat len =
if len < 0 then invalid_arg "make_nat" else
let res = create_nat len in set_to_zero_nat res 0 len; res
let copy_nat nat off_set length =
let res = create_nat (length) in
blit_nat res 0 nat off_set length;
res
let is_zero_nat n off len =
compare_nat (make_nat 1) 0 1 n off (num_digits_nat n off len) = 0
let is_nat_int nat off len =
num_digits_nat nat off len = 1 && is_digit_int nat off
let sys_int_of_nat nat off len =
if is_nat_int nat off len
then nth_digit_nat nat off
else failwith "int_of_nat"
let int_of_nat nat =
sys_int_of_nat nat 0 (length_nat nat)
let nat_of_int i =
if i < 0 then invalid_arg "nat_of_int" else
let res = make_nat 1 in
if i = 0 then res else begin set_digit_nat res 0 i; res end
let eq_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) = 0
and le_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) <= 0
and lt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) < 0
and ge_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) >= 0
and gt_nat nat1 off1 len1 nat2 off2 len2 =
compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
nat2 off2 (num_digits_nat nat2 off2 len2) > 0
XL : now implemented in C for better performance .
The code below does n't handle carries correctly .
Fortunately , the carry is never used .
The code below doesn't handle carries correctly.
Fortunately, the carry is never used. *)
* *
let square_nat nat1 off1 len1 nat2 off2 len2 =
let c = ref 0
and trash = make_nat 1 in
( * Double product
let square_nat nat1 off1 len1 nat2 off2 len2 =
let c = ref 0
and trash = make_nat 1 in
for i = 0 to len2 - 2 do
c := !c + mult_digit_nat
nat1
(succ (off1 + 2 * i))
(2 * (pred (len2 - i)))
nat2
(succ (off2 + i))
(pred (len2 - i))
nat2
(off2 + i)
done;
shift_left_nat nat1 0 len1 trash 0 1;
for i = 0 to len2 - 1 do
c := !c + mult_digit_nat
nat1
(off1 + 2 * i)
(len1 - 2 * i)
nat2
(off2 + i)
1
nat2
(off2 + i)
done;
!c
***)
let =
if i = 0 then 1 else
if is_nat_int off len then begin
set_digit_nat nat off ( gcd_int ( nth_digit_nat off ) i ) ; 0
end else begin
let len_copy = succ len in
let copy = create_nat len_copy
and quotient = create_nat 1
and remainder = create_nat 1 in
blit_nat copy 0 nat off len ;
set_digit_nat copy len 0 ;
div_digit_nat quotient 0 remainder 0 copy 0 len_copy ( nat_of_int i ) 0 ;
set_digit_nat nat off ( gcd_int ( nth_digit_nat remainder 0 ) i ) ;
0
end
let gcd_int_nat i nat off len =
if i = 0 then 1 else
if is_nat_int nat off len then begin
set_digit_nat nat off (gcd_int (nth_digit_nat nat off) i); 0
end else begin
let len_copy = succ len in
let copy = create_nat len_copy
and quotient = create_nat 1
and remainder = create_nat 1 in
blit_nat copy 0 nat off len;
set_digit_nat copy len 0;
div_digit_nat quotient 0 remainder 0 copy 0 len_copy (nat_of_int i) 0;
set_digit_nat nat off (gcd_int (nth_digit_nat remainder 0) i);
0
end
*)
let exchange r1 r2 =
let old1 = !r1 in r1 := !r2; r2 := old1
let gcd_nat nat1 off1 len1 nat2 off2 len2 =
if is_zero_nat nat1 off1 len1 then begin
blit_nat nat1 off1 nat2 off2 len2; len2
end else begin
let copy1 = ref (create_nat (succ len1))
and copy2 = ref (create_nat (succ len2)) in
blit_nat !copy1 0 nat1 off1 len1;
blit_nat !copy2 0 nat2 off2 len2;
set_digit_nat !copy1 len1 0;
set_digit_nat !copy2 len2 0;
if lt_nat !copy1 0 len1 !copy2 0 len2
then exchange copy1 copy2;
let real_len1 =
ref (num_digits_nat !copy1 0 (length_nat !copy1))
and real_len2 =
ref (num_digits_nat !copy2 0 (length_nat !copy2)) in
while not (is_zero_nat !copy2 0 !real_len2) do
set_digit_nat !copy1 !real_len1 0;
div_nat !copy1 0 (succ !real_len1) !copy2 0 !real_len2;
exchange copy1 copy2;
real_len1 := !real_len2;
real_len2 := num_digits_nat !copy2 0 !real_len2
done;
blit_nat nat1 off1 !copy1 0 !real_len1;
!real_len1
end
Integer square root using method ( nearest integer by default )
Theorem : the sequence x_{n+1 } = ( x_n + a / x_n ) /2 converges toward
the integer square root ( by default ) of a for any starting value x_0
strictly greater than the square root of a except if a + 1 is a
perfect square . In this situation , the sequence alternates between
the excess and default integer square root . In any case , the last
strictly decreasing term is the expected result
the integer square root (by default) of a for any starting value x_0
strictly greater than the square root of a except if a + 1 is a
perfect square. In this situation, the sequence alternates between
the excess and default integer square root. In any case, the last
strictly decreasing term is the expected result *)
let sqrt_nat rad off len =
let len = num_digits_nat rad off len in
let len_parity = len mod 2 in
let rad_len = len + 1 + len_parity in
let rad =
let res = create_nat rad_len in
blit_nat res 0 rad off len;
set_digit_nat res len 0;
set_digit_nat res (rad_len - 1) 0;
res in
let cand_rest = rad_len - cand_len in
let cand = make_nat cand_len in
Improve starting square root :
We compute nbb , the number of significant bits of the first digit of the
candidate
( half of the number of significant bits in the first two digits
of the radicand extended to an even length ) .
shift_cand is word_size - nbb
We compute nbb, the number of significant bits of the first digit of the
candidate
(half of the number of significant bits in the first two digits
of the radicand extended to an even length).
shift_cand is word_size - nbb *)
let shift_cand =
((num_leading_zero_bits_in_digit rad (len-1)) +
length_of_digit * len_parity) / 2 in
if shift_cand = length_of_digit then cand else
begin
complement_nat cand 0 cand_len;
let tmp = create_nat 1 in
shift_right_nat cand 0 1 tmp 0 shift_cand;
let next_cand = create_nat rad_len in
let rec loop () =
blit_nat next_cand 0 rad 0 rad_len;
div_nat next_cand 0 rad_len cand 0 cand_len;
ignore (add_nat next_cand cand_len cand_rest cand 0 cand_len 0);
shift_right_nat next_cand cand_len cand_rest tmp 0 1;
if lt_nat next_cand cand_len cand_rest cand 0 cand_len then
blit_nat cand 0 next_cand cand_len cand_len; loop ()
end
else cand in
loop ()
end;;
let power_base_max = make_nat 2;;
match length_of_digit with
| 64 ->
set_digit_nat power_base_max 0 (Int64.to_int 1000000000000000000L);
ignore
(mult_digit_nat power_base_max 0 2
power_base_max 0 1 (nat_of_int 9) 0)
| 32 -> set_digit_nat power_base_max 0 1000000000
| _ -> assert false
;;
let pmax =
match length_of_digit with
| 64 -> 19
| 32 -> 9
| _ -> assert false
;;
let raw_string_of_digit nat off =
Printf.sprintf "%nu" (nth_digit_nat_native nat off)
XL : suppression de string_of_digit et de sys_string_of_digit .
La copie est de toute facon faite dans string_of_nat , qui est le
seul point d entree public dans ce code .
| Deletion of string_of_digit and sys_string_of_digit .
The copy is already done in string_of_nat which is the only
public entry point in this code
La copie est de toute facon faite dans string_of_nat, qui est le
seul point d entree public dans ce code.
| Deletion of string_of_digit and sys_string_of_digit.
The copy is already done in string_of_nat which is the only
public entry point in this code
*)
* * * * *
let off =
let s = raw_string_of_digit off in
let result = String.create ( String.length s ) in
String.blit s 0 result 0 ( String.length s ) ;
s
let string_of_digit nat =
sys_string_of_digit
* * * * * *
let sys_string_of_digit nat off =
let s = raw_string_of_digit nat off in
let result = String.create (String.length s) in
String.blit s 0 result 0 (String.length s);
s
let string_of_digit nat =
sys_string_of_digit nat 0
*******)
make_power_base affecte power_base des puissances successives de base a
partir de la puissance 1 - ieme .
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int .
This function returns [ ( pmax , pint ) ] where :
[ pmax ] is the index of the digit of [ power_base ] that contains the
the maximum power of [ base ] that fits in a digit . This is also one
less than the exponent of that power .
[ pint ] is the exponent of the maximum power of [ base ] that fits in an [ int ] .
make_power_base affecte power_base des puissances successives de base a
partir de la puissance 1-ieme.
A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
sur un seul digit et j est la plus grande puissance de la base qui tient
sur un int.
This function returns [(pmax, pint)] where:
[pmax] is the index of the digit of [power_base] that contains the
the maximum power of [base] that fits in a digit. This is also one
less than the exponent of that power.
[pint] is the exponent of the maximum power of [base] that fits in an [int].
*)
let make_power_base base power_base =
let i = ref 0
and j = ref 0 in
set_digit_nat power_base 0 base;
while incr i; is_digit_zero power_base !i do
ignore
(mult_digit_nat power_base !i 2
power_base (pred !i) 1
power_base 0)
done;
while !j < !i - 1 && is_digit_int power_base !j do incr j done;
(!i - 2, !j)
let digits = "0123456789ABCDEF"
let int_to_string int s pos_ref base times =
let i = ref int
and j = ref times in
while ((!i != 0) || (!j != 0)) && (!pos_ref != -1) do
Bytes.set s !pos_ref (String.get digits (!i mod base));
decr pos_ref;
decr j;
i := !i / base
done
*)
let power_base_int base i =
if i = 0 || base = 1 then
nat_of_int 1
else if base = 0 then
nat_of_int 0
else if i < 0 then
invalid_arg "power_base_int"
else begin
let power_base = make_nat (succ length_of_digit) in
let (pmax, _pint) = make_power_base base power_base in
let n = i / (succ pmax)
and rem = i mod (succ pmax) in
if n > 0 then begin
let newn =
if i = biggest_int then n else (succ n) in
let res = make_nat newn
and res2 = make_nat newn
and l = num_bits_int n - 2 in
blit_nat res 0 power_base pmax 1;
for i = l downto 0 do
let len = num_digits_nat res 0 newn in
let len2 = min n (2 * len) in
let succ_len2 = succ len2 in
ignore (square_nat res2 0 len2 res 0 len);
if n land (1 lsl i) > 0 then begin
set_to_zero_nat res 0 len;
ignore
(mult_digit_nat res 0 succ_len2
res2 0 len2 power_base pmax)
end else
blit_nat res 0 res2 0 len2;
set_to_zero_nat res2 0 len2
done;
if rem > 0 then begin
ignore
(mult_digit_nat res2 0 newn
res 0 n power_base (pred rem));
res2
end else res
end else
copy_nat power_base (pred rem) 1
end
the ith element ( i > = 2 ) of num_digits_max_vector is :
| |
| biggest_string_length * log ( i ) |
| ------------------------------- | + 1
| length_of_digit * log ( 2 ) |
-- --
| |
| biggest_string_length * log (i) |
| ------------------------------- | + 1
| length_of_digit * log (2) |
-- --
*)
XL : ai specialise le code d origine a length_of_digit = 32 .
| the original code have been specialized to a length_of_digit = 32 .
| the original code have been specialized to a length_of_digit = 32. *)
* * * * *
let num_digits_max_vector =
[ |0 ; 0 ; 1024 ; 1623 ; 2048 ; 2378 ; 2647 ; 2875 ; 3072 ; 3246 ; 3402 ;
3543 ; 3671 ; 3789 ; 3899 ; 4001 ; 4096| ]
let num_digits_max_vector =
match length_of_digit with
16 - > [ |0 ; 0 ; 2048 ; 3246 ; 4096 ; 4755 ; 5294 ; 5749 ; 6144 ; 6492 ; 6803 ;
7085 ; 7342 ; 7578 ; 7797 ; 8001 ; 8192| ]
( * If really exotic machines ! ! ! !
| 17 - > [ |0 ; 0 ; 1928 ; 3055 ; 3855 ; 4476 ; 4983 ; 5411 ; 5783 ; 6110 ; 6403 ;
6668 ; 6910 ; 7133 ; 7339 ; 7530 ; 7710| ]
| 18 - > [ |0 ; 0 ; 1821 ; 2886 ; 3641 ; 4227 ; 4706 ; 5111 ; 5461 ; 5771 ; 6047 ;
6298 ; 6526 ; 6736 ; 6931 ; 7112 ; 7282| ]
| 19 - > [ |0 ; 0 ; 1725 ; 2734 ; 3449 ; 4005 ; 4458 ; 4842 ; 5174 ; 5467 ; 5729 ;
5966 ; 6183 ; 6382 ; 6566 ; 6738 ; 6898| ]
| 20 - > [ |0 ; 0 ; 1639 ; 2597 ; 3277 ; 3804 ; 4235 ; 4600 ; 4915 ; 5194 ; 5443 ;
5668 ; 5874 ; 6063 ; 6238 ; 6401 ; 6553| ]
| 21 - > [ |0 ; 0 ; 1561 ; 2473 ; 3121 ; 3623 ; 4034 ; 4381 ; 4681 ; 4946 ; 5183 ;
5398 ; 5594 ; 5774 ; 5941 ; 6096 ; 6241| ]
| 22 - > [ |0 ; 0 ; 1490 ; 2361 ; 2979 ; 3459 ; 3850 ; 4182 ; 4468 ; 4722 ; 4948 ;
5153 ; 5340 ; 5512 ; 5671 ; 5819 ; 5958| ]
| 23 - > [ |0 ; 0 ; 1425 ; 2258 ; 2850 ; 3308 ; 3683 ; 4000 ; 4274 ; 4516 ; 4733 ;
4929 ; 5108 ; 5272 ; 5424 ; 5566 ; 5699| ]
| 24 - > [ |0 ; 0 ; 1366 ; 2164 ; 2731 ; 3170 ; 3530 ; 3833 ; 4096 ; ; 4536 ;
4723 ; 4895 ; 5052 ; 5198 ; 5334 ; 5461| ]
| 25 - > [ |0 ; 0 ; 1311 ; 2078 ; 2622 ; 3044 ; 3388 ; 3680 ; 3932 ; 4155 ; 4354 ;
4534 ; 4699 ; 4850 ; 4990 ; 5121 ; 5243| ]
| 26 - > [ |0 ; 0 ; 1261 ; 1998 ; 2521 ; 2927 ; 3258 ; 3538 ; 3781 ; 3995 ; 4187 ;
4360 ; 4518 ; 4664 ; 4798 ; 4924 ; 5041| ]
| 27 - > [ |0 ; 0 ; 1214 ; 1924 ; 2428 ; 2818 ; 3137 ; 3407 ; 3641 ; 3847 ; 4032 ;
4199 ; 4351 ; 4491 ; 4621 ; 4742 ; 4855| ]
| 28 - > [ |0 ; 0 ; 1171 ; 1855 ; 2341 ; 2718 ; 3025 ; 3286 ; 3511 ; 3710 ; 3888 ;
4049 ; 4196 ; 4331 ; 4456 ; 4572 ; 4681| ]
| 29 - > [ |0 ; 0 ; 1130 ; 1791 ; 2260 ; 2624 ; 2921 ; 3172 ; 3390 ; 3582 ; 3754 ;
3909 ; 4051 ; 4181 ; 4302 ; 4415 ; 4520| ]
| 30 - > [ |0 ; 0 ; 1093 ; 1732 ; 2185 ; 2536 ; 2824 ; 3067 ; 3277 ; 3463 ; 3629 ;
3779 ; 3916 ; 4042 ; 4159 ; 4267 ; 4369| ]
| 31 - > [ |0 ; 0 ; 1057 ; 1676 ; 2114 ; 2455 ; 2733 ; 2968 ; 3171 ; 3351 ; 3512 ;
3657 ; 3790 ; 3912 ; 4025 ; 4130 ; 4228| ]
let num_digits_max_vector =
[|0; 0; 1024; 1623; 2048; 2378; 2647; 2875; 3072; 3246; 3402;
3543; 3671; 3789; 3899; 4001; 4096|]
let num_digits_max_vector =
match length_of_digit with
16 -> [|0; 0; 2048; 3246; 4096; 4755; 5294; 5749; 6144; 6492; 6803;
7085; 7342; 7578; 7797; 8001; 8192|]
| 32 -> [|0; 0; 1024; 1623; 2048; 2378; 2647; 2875; 3072; 3246; 3402;
3543; 3671; 3789; 3899; 4001; 4096|]
| n -> failwith "num_digits_max_vector"
******)
let unadjusted_string_of_nat nat off len_nat =
let len = num_digits_nat nat off len_nat in
if len = 1 then
raw_string_of_digit nat off
else
let len_copy = ref (succ len) in
let copy1 = create_nat !len_copy
and copy2 = make_nat !len_copy
and rest_digit = make_nat 2 in
if len > biggest_int / (succ pmax)
then failwith "number too long"
else let len_s = (succ pmax) * len in
let s = Bytes.make len_s '0'
and pos_ref = ref len_s in
len_copy := pred !len_copy;
blit_nat copy1 0 nat off len;
set_digit_nat copy1 len 0;
while not (is_zero_nat copy1 0 !len_copy) do
div_digit_nat copy2 0
rest_digit 0
copy1 0 (succ !len_copy)
power_base_max 0;
let str = raw_string_of_digit rest_digit 0 in
String.blit str 0
s (!pos_ref - String.length str)
(String.length str);
pos_ref := !pos_ref - pmax;
len_copy := num_digits_nat copy2 0 !len_copy;
blit_nat copy1 0 copy2 0 !len_copy;
set_digit_nat copy1 !len_copy 0
done;
Bytes.unsafe_to_string s
let string_of_nat nat =
let s = unadjusted_string_of_nat nat 0 (length_nat nat)
and index = ref 0 in
begin try
for i = 0 to String.length s - 2 do
if String.get s i <> '0' then (index:= i; raise Exit)
done
with Exit -> ()
end;
String.sub s !index (String.length s - !index)
let base_digit_of_char c base =
let n = Char.code c in
if n >= 48 && n <= 47 + min base 10 then n - 48
else if n >= 65 && n <= 65 + base - 11 then n - 55
else if n >= 97 && n <= 97 + base - 11 then n - 87
else failwith "invalid digit"
The substring ( s , off , len ) represents a nat in base ' base ' which is
determined here
The substring (s, off, len) represents a nat in base 'base' which is
determined here
*)
let sys_nat_of_string base s off len =
let power_base = make_nat (succ length_of_digit) in
let (pmax, pint) = make_power_base base power_base in
let new_len = ref (1 + len / (pmax + 1))
and current_len = ref 1 in
let possible_len = ref (min 2 !new_len) in
let nat1 = make_nat !new_len
and nat2 = make_nat !new_len
and digits_read = ref 0
and bound = off + len - 1
and int = ref 0 in
for i = off to bound do
let c = String.get s i in
begin match c with
' ' | '\t' | '\n' | '\r' | '\\' -> ()
| '_' when i > off -> ()
| _ -> int := !int * base + base_digit_of_char c base;
incr digits_read
end;
if (!digits_read = pint || i = bound) && not (!digits_read = 0) then
begin
set_digit_nat nat1 0 !int;
let erase_len = if !new_len = !current_len then !current_len - 1
else !current_len in
for j = 1 to erase_len do
set_digit_nat nat1 j 0
done;
ignore
(mult_digit_nat nat1 0 !possible_len
nat2 0 !current_len power_base (pred !digits_read));
blit_nat nat2 0 nat1 0 !possible_len;
current_len := num_digits_nat nat1 0 !possible_len;
possible_len := min !new_len (succ !current_len);
int := 0;
digits_read := 0
end
done;
We reframe
We reframe nat
*)
let nat = create_nat !current_len in
blit_nat nat 0 nat1 0 !current_len;
nat
let nat_of_string s = sys_nat_of_string 10 s 0 (String.length s)
let float_of_nat nat = float_of_string(string_of_nat nat)
|
0698618e111647a25c2a8f0b6aefe608d8646c3242f24c347b6079c846e7e0b3 | funcool/dost | stream.cljs | Copyright 2016 < >
;;
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.
(ns dost.core.stream
(:require [cljs.nodejs :as node]))
(def stream (node/require "stream"))
(def Stream (.-Stream stream))
(def Readable (.-Readable stream))
(def Writable (.-Writable stream))
(defn stream?
[v]
(instance? Stream v))
(defn readable?
[v]
(and (stream? v)
(instance? Readable v)))
(defn writable?
[v]
(and (stream? v)
(instance? Writable v)))
| null | https://raw.githubusercontent.com/funcool/dost/e68a23ff7d99892d3f2d7bc6fe733bd74d1743a3/src/dost/core/stream.cljs | clojure |
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. | Copyright 2016 < >
Licensed under the Apache License , Version 2.0 ( the " License " )
distributed under the License is distributed on an " AS IS " BASIS ,
(ns dost.core.stream
(:require [cljs.nodejs :as node]))
(def stream (node/require "stream"))
(def Stream (.-Stream stream))
(def Readable (.-Readable stream))
(def Writable (.-Writable stream))
(defn stream?
[v]
(instance? Stream v))
(defn readable?
[v]
(and (stream? v)
(instance? Readable v)))
(defn writable?
[v]
(and (stream? v)
(instance? Writable v)))
|
61ed6d5936ec0d343bb45be47ddc4c63704846c1f25f133f1cf898bb57d82883 | haskell/haskell-language-server | MetaLetSimple.expected.hs | test :: Int
test
= let
a = _w0
b = _w1
c = _w2
in _w3
| null | https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/golden/MetaLetSimple.expected.hs | haskell | test :: Int
test
= let
a = _w0
b = _w1
c = _w2
in _w3
| |
8f4219eaafb9345cac55b9479e4364ab105bfdeed0d138e16245e4eb6790e798 | Heasummn/Crab-ML | CrabCommon.ml | (* Maybe add a wrapper over other functions here. But for now, just to stop warnings *) | null | https://raw.githubusercontent.com/Heasummn/Crab-ML/45a79373a620878b9c24464a7e009ecf3ea7f908/src/CrabCommon/CrabCommon.ml | ocaml | Maybe add a wrapper over other functions here. But for now, just to stop warnings | |
6b26d57972aad6f6f47838e2038fc6412b4c01f346ab11fdd69ee57be7e377af | zoomhub/zoomhub | Logger.hs | {-# LANGUAGE OverloadedStrings #-}
module ZoomHub.Log.Logger
( logDebug,
logDebugT,
logDebug_,
logError,
logError_,
logException,
logException_,
logInfo,
logInfoT,
logInfo_,
logWarning,
logWarning_,
log,
log_,
LogLevel
LogLevel (..),
-- Encoding
encodeLogLine,
)
where
import Control.Exception (SomeException)
import Data.Aeson (Value, object, (.=))
import Data.Aeson.Encode.Pretty
( Config,
Indent (Spaces),
confCompare,
confIndent,
defConfig,
encodePretty',
keyOrder,
)
import Data.Aeson.Types (Pair)
import qualified Data.ByteString.Lazy as BL
import Data.Monoid ((<>))
import Data.Ord (comparing)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Data.Time.Clock (getCurrentTime)
import Data.Time.Units (Millisecond)
import Data.Time.Units.Instances ()
import System.IO (hSetEncoding, stderr, stdout, utf8)
import System.TimeIt (timeItT)
import ZoomHub.Log.LogLevel (LogLevel (..))
import ZoomHub.Utils (lenientDecodeUtf8)
import Prelude hiding (log)
logDebug :: String -> [Pair] -> IO ()
logDebug = log Debug
logDebug_ :: String -> IO ()
logDebug_ = log_ Debug
logDebugT :: String -> [Pair] -> IO a -> IO a
logDebugT = logT Debug
logInfo :: String -> [Pair] -> IO ()
logInfo = log Info
logInfoT :: String -> [Pair] -> IO a -> IO a
logInfoT = logT Info
logInfo_ :: String -> IO ()
logInfo_ = log_ Info
logWarning :: String -> [Pair] -> IO ()
logWarning = log Warning
logWarning_ :: String -> IO ()
logWarning_ = log_ Warning
logError :: String -> [Pair] -> IO ()
logError = log Error
logError_ :: String -> IO ()
logError_ = log_ Error
logException :: String -> SomeException -> [Pair] -> IO ()
logException msg e meta = logError msg (meta ++ ["error" .= show e])
logException_ :: String -> SomeException -> IO ()
logException_ msg e = logException msg e []
log_ :: LogLevel -> String -> IO ()
log_ level message = log level message []
logT :: LogLevel -> String -> [Pair] -> IO a -> IO a
logT level msg meta action = do
(duration, result) <- timeItT action
log
level
msg
(meta ++ ["duration" .= (round (duration * 1000) :: Millisecond)])
return result
log :: LogLevel -> String -> [Pair] -> IO ()
log level message meta = do
now <- getCurrentTime
-- Force to UTF8 to avoid the dreaded `<stdout>: commitAndReleaseBuffer:
-- invalid argument` error when the locale is improperly configured and
-- a non-ASCII character is output:
Source : -dashboard/blob/800710d81324835d90b6dde25a28de4493ef2b92/Trace.hs#L61-L69
hSetEncoding (handle level) utf8
TIO.hPutStrLn (handle level) $ line now <> "\n"
where
line time =
encodeLogLine . object $
[ "time" .= time,
"type" .= ("app" :: Text),
"level" .= show level,
"message" .= message
]
++ meta
handle Error = stderr
handle _ = stdout
encodeLogLine :: Value -> Text
encodeLogLine = removeNewlines . lenientDecodeUtf8 . BL.toStrict . prettyEncode
where
removeNewlines = T.intercalate "" . T.lines
prettyEncode = encodePretty' prettyEncodeConfig
-- JSON
prettyEncodeConfig :: Config
prettyEncodeConfig =
defConfig
{ confIndent = Spaces 0,
confCompare = keyCompare
}
keyCompare :: Text -> Text -> Ordering
keyCompare = keyOrder keyOrdering `mappend` comparing id
keyOrdering :: [Text]
keyOrdering =
[ "time",
"type",
"level",
"message",
"req",
"res",
"worker"
]
| null | https://raw.githubusercontent.com/zoomhub/zoomhub/2c97e96af0dc2f033793f3d41fc38fea8dff867b/src/ZoomHub/Log/Logger.hs | haskell | # LANGUAGE OverloadedStrings #
Encoding
Force to UTF8 to avoid the dreaded `<stdout>: commitAndReleaseBuffer:
invalid argument` error when the locale is improperly configured and
a non-ASCII character is output:
JSON |
module ZoomHub.Log.Logger
( logDebug,
logDebugT,
logDebug_,
logError,
logError_,
logException,
logException_,
logInfo,
logInfoT,
logInfo_,
logWarning,
logWarning_,
log,
log_,
LogLevel
LogLevel (..),
encodeLogLine,
)
where
import Control.Exception (SomeException)
import Data.Aeson (Value, object, (.=))
import Data.Aeson.Encode.Pretty
( Config,
Indent (Spaces),
confCompare,
confIndent,
defConfig,
encodePretty',
keyOrder,
)
import Data.Aeson.Types (Pair)
import qualified Data.ByteString.Lazy as BL
import Data.Monoid ((<>))
import Data.Ord (comparing)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Data.Time.Clock (getCurrentTime)
import Data.Time.Units (Millisecond)
import Data.Time.Units.Instances ()
import System.IO (hSetEncoding, stderr, stdout, utf8)
import System.TimeIt (timeItT)
import ZoomHub.Log.LogLevel (LogLevel (..))
import ZoomHub.Utils (lenientDecodeUtf8)
import Prelude hiding (log)
logDebug :: String -> [Pair] -> IO ()
logDebug = log Debug
logDebug_ :: String -> IO ()
logDebug_ = log_ Debug
logDebugT :: String -> [Pair] -> IO a -> IO a
logDebugT = logT Debug
logInfo :: String -> [Pair] -> IO ()
logInfo = log Info
logInfoT :: String -> [Pair] -> IO a -> IO a
logInfoT = logT Info
logInfo_ :: String -> IO ()
logInfo_ = log_ Info
logWarning :: String -> [Pair] -> IO ()
logWarning = log Warning
logWarning_ :: String -> IO ()
logWarning_ = log_ Warning
logError :: String -> [Pair] -> IO ()
logError = log Error
logError_ :: String -> IO ()
logError_ = log_ Error
logException :: String -> SomeException -> [Pair] -> IO ()
logException msg e meta = logError msg (meta ++ ["error" .= show e])
logException_ :: String -> SomeException -> IO ()
logException_ msg e = logException msg e []
log_ :: LogLevel -> String -> IO ()
log_ level message = log level message []
logT :: LogLevel -> String -> [Pair] -> IO a -> IO a
logT level msg meta action = do
(duration, result) <- timeItT action
log
level
msg
(meta ++ ["duration" .= (round (duration * 1000) :: Millisecond)])
return result
log :: LogLevel -> String -> [Pair] -> IO ()
log level message meta = do
now <- getCurrentTime
Source : -dashboard/blob/800710d81324835d90b6dde25a28de4493ef2b92/Trace.hs#L61-L69
hSetEncoding (handle level) utf8
TIO.hPutStrLn (handle level) $ line now <> "\n"
where
line time =
encodeLogLine . object $
[ "time" .= time,
"type" .= ("app" :: Text),
"level" .= show level,
"message" .= message
]
++ meta
handle Error = stderr
handle _ = stdout
encodeLogLine :: Value -> Text
encodeLogLine = removeNewlines . lenientDecodeUtf8 . BL.toStrict . prettyEncode
where
removeNewlines = T.intercalate "" . T.lines
prettyEncode = encodePretty' prettyEncodeConfig
prettyEncodeConfig :: Config
prettyEncodeConfig =
defConfig
{ confIndent = Spaces 0,
confCompare = keyCompare
}
keyCompare :: Text -> Text -> Ordering
keyCompare = keyOrder keyOrdering `mappend` comparing id
keyOrdering :: [Text]
keyOrdering =
[ "time",
"type",
"level",
"message",
"req",
"res",
"worker"
]
|
b248fc820cfc65dbf407e97949c4509a9402585b09ea1339cc30e5032a89f7f6 | input-output-hk/cardano-addresses | ShelleySpec.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -fno - warn - orphans #
module Cardano.Address.Style.ShelleySpec
( spec
) where
import Prelude
import Cardano.Address
( Address
, ChainPointer (..)
, HasNetworkDiscriminant (..)
, bech32
, bech32With
, fromBech32
, unsafeMkAddress
)
import Cardano.Address.Derivation
( Depth (..)
, DerivationType (..)
, GenMasterKey (..)
, HardDerivation (..)
, Index (..)
, Pub
, SoftDerivation (..)
, XPrv
, XPub
, hashCredential
, indexFromWord32
, pubFromBytes
, toXPub
, unsafeMkIndex
, xprvToBytes
, xpubFromBytes
, xpubToBytes
)
import Cardano.Address.Script
( KeyHash (..), KeyRole (..) )
import Cardano.Address.Style.Shelley
( Credential (..)
, Role (..)
, Shelley (..)
, delegationAddress
, deriveDelegationPrivateKey
, liftPub
, liftXPub
, mkNetworkDiscriminant
, paymentAddress
, pointerAddress
, roleFromIndex
, roleToIndex
)
import Cardano.Mnemonic
( SomeMnemonic, mkSomeMnemonic )
import Codec.Binary.Encoding
( AbstractEncoding (..), encode, fromBase16 )
import Control.Monad
( (<=<) )
import Data.Aeson
( ToJSON, Value (..) )
import Data.ByteArray
( ByteArrayAccess, ScrubbedBytes )
import Data.ByteString
( ByteString )
import Data.Either
( rights )
import Data.Function
( (&) )
import Data.Maybe
( fromMaybe, isNothing )
import Data.Text
( Text )
import GHC.Generics
( Generic )
import Test.Arbitrary
()
import Test.Hspec
( Spec, SpecWith, describe, it, shouldBe )
import Test.Hspec.Golden
( Golden (..) )
import Test.Hspec.QuickCheck
( prop )
import Test.QuickCheck
( Arbitrary (..)
, Property
, choose
, counterexample
, label
, property
, vector
, (===)
)
import Text.Pretty.Simple
( defaultOutputOptionsNoColor, pShowOpt )
import qualified Cardano.Address.Style.Shelley as Shelley
import qualified Cardano.Codec.Bech32.Prefixes as CIP5
import qualified Data.Aeson.Encode.Pretty as Aeson
import qualified Data.ByteArray as BA
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TLE
import qualified Data.Text.Lazy.IO as TL
spec :: Spec
spec = do
describe "BIP-0044 Derivation Properties" $ do
it "deriveAccountPrivateKey works for various indexes" $
property prop_accountKeyDerivation
it "N(CKDpriv((kpar, cpar), i)) === CKDpub(N(kpar, cpar), i) for any key" $
property prop_publicChildKeyDerivation
describe "Role indices" $ do
it "Calling indexFromWord32 for invalid value fails)" $
property prop_fromWord32Role
it "Roundtrip index" $ property prop_roundtripIndexRole
describe "Proper pointer addresses construction" $ do
it "Using different numbers in DelegationPointerAddress does not fail"
(property prop_pointerAddressConstruction)
describe "Text Encoding Roundtrips" $ do
prop "bech32 . fromBech32 - Shelley - payment address" $
prop_roundtripTextEncoding bech32 fromBech32
prop "bech32 . fromBech32 - Shelley - delegation address" $
prop_roundtripTextEncodingDelegation bech32 fromBech32
prop "bech32 . fromBech32 - Shelley - pointer address" $
prop_roundtripTextEncodingPointer bech32 fromBech32
describe "Golden tests" $ do
goldenTestPointerAddress GoldenTestPointerAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, stakePtr = ChainPointer 128 2 3
, netTag = 0
, expectedAddr =
"408a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d481000203"
}
goldenTestPointerAddress GoldenTestPointerAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, stakePtr = ChainPointer 128 2 3
, netTag = 1
, expectedAddr =
"418a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d481000203"
}
goldenTestEnterpriseAddress GoldenTestEnterpriseAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, netTag = 0
, expectedAddr =
"608a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d4"
}
goldenTestEnterpriseAddress GoldenTestEnterpriseAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, netTag = 1
, expectedAddr =
"618a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d4"
}
goldenTestEnterpriseAddressKeyHash GoldenTestEnterpriseAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, netTag = 0
, expectedAddr =
"608a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d4"
}
goldenTestEnterpriseAddressKeyHash GoldenTestEnterpriseAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, netTag = 1
, expectedAddr =
"618a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d4"
}
goldenTestBaseAddressPayFromXPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressPayFromXPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressPayFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressPayFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressPayFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressPayFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressStakeFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressStakeFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressStakeFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressStakeFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressBothFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressBothFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressBothFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressBothFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
describe "Test vectors" $ do
testVectors
[ "test", "child", "burst", "immense", "armed", "parrot"
, "company", "walk", "dog" ]
testVectors
[ "test", "walk", "nut", "penalty", "hip", "pave", "soap",
"entry", "language", "right", "filter", "choice" ]
testVectors
[ "art", "forum", "devote", "street", "sure", "rather",
"head", "chuckle", "guard", "poverty", "release",
"quote", "oak", "craft", "enemy"]
testVectors
[ "churn", "shaft", "spoon", "second", "erode", "useless",
"thrive", "burst", "group", "seed", "element", "sign",
"scrub", "buffalo", "jelly", "grace", "neck", "useless" ]
testVectors
[ "draft", "ability", "female", "child", "jump", "maid",
"roof", "hurt", "below", "live", "topple", "paper",
"exclude", "ordinary", "coach", "churn", "sunset",
"emerge", "blame", "ketchup", "much" ]
testVectors
[ "excess", "behave", "track", "soul", "table", "wear",
"ocean", "cash", "stay", "nature", "item", "turtle",
"palm", "soccer", "lunch", "horror", "start", "stumble",
"month", "panic", "right", "must", "lock", "dress" ]
{-------------------------------------------------------------------------------
Properties
-------------------------------------------------------------------------------}
prop_publicChildKeyDerivation
:: (SomeMnemonic, SndFactor)
-> Role
-> Index 'Soft 'PaymentK
-> Property
prop_publicChildKeyDerivation (mw, (SndFactor sndFactor)) cc ix =
addrXPub1 === addrXPub2
where
rootXPrv = genMasterKeyFromMnemonic mw sndFactor :: Shelley 'RootK XPrv
accXPrv = deriveAccountPrivateKey rootXPrv minBound
addrXPub1 = toXPub <$> deriveAddressPrivateKey accXPrv cc ix
addrXPub2 = deriveAddressPublicKey (toXPub <$> accXPrv) cc ix
prop_accountKeyDerivation
:: (SomeMnemonic, SndFactor)
-> Index 'Hardened 'AccountK
-> Property
prop_accountKeyDerivation (mw, (SndFactor sndFactor)) ix =
accXPrv `seq` property ()
where
rootXPrv = genMasterKeyFromMnemonic mw sndFactor :: Shelley 'RootK XPrv
accXPrv = deriveAccountPrivateKey rootXPrv ix
prop_fromWord32Role :: Int -> Property
prop_fromWord32Role n =
isNothing (toRole n)
===
(n > fromRole maxBound || n < fromRole minBound)
where
fromRole = fromIntegral . indexToWord32 . roleToIndex
toRole = roleFromIndex . unsafeMkIndex . fromIntegral
prop_roundtripIndexRole :: Role -> Property
prop_roundtripIndexRole ix = (roleFromIndex . roleToIndex) ix === Just ix
prop_pointerAddressConstruction
:: (SomeMnemonic, SndFactor)
-> Role
-> Index 'Soft 'PaymentK
-> NetworkDiscriminant Shelley
-> ChainPointer
-> Property
prop_pointerAddressConstruction (mw, (SndFactor sndFactor)) cc ix net ptr =
pointerAddr `seq` property ()
where
rootXPrv = genMasterKeyFromMnemonic mw sndFactor :: Shelley 'RootK XPrv
accXPrv = deriveAccountPrivateKey rootXPrv minBound
addrXPub = toXPub <$> deriveAddressPrivateKey accXPrv cc ix
pointerAddr = pointerAddress net (PaymentFromExtendedKey addrXPub) ptr
{-------------------------------------------------------------------------------
Golden tests
-------------------------------------------------------------------------------}
-- | Definitions: Let's assume we have private key < xprv | pub | cc >
Then , extended private key should be understood as < xprv | | cc >
-- extended public key should be understood as < | pub | cc >
-- verification public key should be understood as < | pub | >
data GoldenTestPointerAddress = GoldenTestPointerAddress
{
-- | The verification public key as string to be encoded into base16 form
After that it should have 32 - byte length
verKey :: Text
-- | Location of stake cerificate in the blockchain
, stakePtr :: ChainPointer
-- | Network tag
, netTag :: Integer
-- | Expected address as encoded into base16 form
, expectedAddr :: Text
}
goldenTestPointerAddress :: GoldenTestPointerAddress -> SpecWith ()
goldenTestPointerAddress GoldenTestPointerAddress{..} =
it ("pointer address for networkId " <> show netTag) $ do
let (Just xPub) = xpubFromBytes $ b16encode $ T.append verKey verKey
let addrXPub = liftXPub xPub :: Shelley 'PaymentK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let ptrAddr = pointerAddress tag (PaymentFromExtendedKey addrXPub) stakePtr
let (Right bytes) = b16decode expectedAddr
ptrAddr `shouldBe` unsafeMkAddress bytes
data GoldenTestEnterpriseAddress = GoldenTestEnterpriseAddress
{
-- | The verification public key as string to be encoded into base16 form
After that it should have 32 - byte length
verKey :: Text
-- | Network tag
, netTag :: Integer
-- | Expected address as encoded into base16 form
, expectedAddr :: Text
}
goldenTestEnterpriseAddress :: GoldenTestEnterpriseAddress -> SpecWith ()
goldenTestEnterpriseAddress GoldenTestEnterpriseAddress{..} =
it ("enterprise address for networkId " <> show netTag) $ do
let (Just xPub) = xpubFromBytes $ b16encode $ T.append verKey verKey
let addrXPub = liftXPub xPub :: Shelley 'PaymentK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let enterpriseAddr = Shelley.paymentAddress tag (PaymentFromExtendedKey addrXPub)
let (Right bytes) = b16decode expectedAddr
enterpriseAddr `shouldBe` unsafeMkAddress bytes
goldenTestEnterpriseAddressKeyHash :: GoldenTestEnterpriseAddress -> SpecWith ()
goldenTestEnterpriseAddressKeyHash GoldenTestEnterpriseAddress{..} =
it ("enterprise address for networkId " <> show netTag) $ do
let bs = b16encode $ T.append verKey verKey
let (Just xPub) = xpubFromBytes bs
let addrXPub = liftXPub xPub :: Shelley 'PaymentK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let enterpriseAddrFromKey =
Shelley.paymentAddress tag (PaymentFromExtendedKey addrXPub)
let keyHashDigest = hashCredential $ BS.take 32 bs
let keyHash = KeyHash Payment keyHashDigest
let enterpriseAddrFromKeyHash =
Shelley.paymentAddress tag (PaymentFromKeyHash keyHash)
enterpriseAddrFromKey `shouldBe` enterpriseAddrFromKeyHash
data GoldenTestBaseAddress = GoldenTestBaseAddress
{
-- | The verification public key as string to be encoded into base16 form
After that it should have 32 - byte length
verKeyPayment :: Text
-- | The verification public key as string to be encoded into base16 form
After that it should have 32 - byte length
, verKeyStake :: Text
-- | Network tag
, netTag :: Integer
-- | Expected address as encoded into base16 form
, expectedAddr :: Text
}
goldenTestBaseAddressPayFromXPub :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressPayFromXPub GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let (Just xPub1) =
xpubFromBytes $ b16encode $ T.append verKeyPayment verKeyPayment
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let (Just xPub2) =
xpubFromBytes $ b16encode $ T.append verKeyStake verKeyStake
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddr =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let (Right bytes) = b16decode expectedAddr
baseAddr `shouldBe` unsafeMkAddress bytes
goldenTestBaseAddressPayFromPub :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressPayFromPub GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let (Just pub1) =
pubFromBytes $ b16encode verKeyPayment
let addrPub = liftPub pub1 :: Shelley 'PaymentK Pub
let (Just xPub2) =
xpubFromBytes $ b16encode $ T.append verKeyStake verKeyStake
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddr =
delegationAddress tag (PaymentFromKey addrPub)
(DelegationFromExtendedKey stakeXPub)
let (Right bytes) = b16decode expectedAddr
baseAddr `shouldBe` unsafeMkAddress bytes
goldenTestBaseAddressPayFromKeyHash :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressPayFromKeyHash GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let paymentBs = b16encode $ T.append verKeyPayment verKeyPayment
let (Just xPub1) = xpubFromBytes paymentBs
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let (Just xPub2) =
xpubFromBytes $ b16encode $ T.append verKeyStake verKeyStake
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddrPayFromKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let keyHashDigest = hashCredential $ BS.take 32 paymentBs
let keyHash = KeyHash Payment keyHashDigest
let baseAddrPayFromKeyHash =
delegationAddress tag (PaymentFromKeyHash keyHash)
(DelegationFromExtendedKey stakeXPub)
baseAddrPayFromKey `shouldBe` baseAddrPayFromKeyHash
goldenTestBaseAddressStakeFromKeyHash :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressStakeFromKeyHash GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let paymentBs = b16encode $ T.append verKeyPayment verKeyPayment
let (Just xPub1) = xpubFromBytes paymentBs
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let stakeBs = b16encode $ T.append verKeyStake verKeyStake
let (Just xPub2) = xpubFromBytes stakeBs
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddrStakeFromKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let keyHashDigest = hashCredential $ BS.take 32 stakeBs
let keyHash = KeyHash Delegation keyHashDigest
let baseAddrStakeFromKeyHash =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromKeyHash keyHash)
baseAddrStakeFromKey `shouldBe` baseAddrStakeFromKeyHash
goldenTestBaseAddressStakeFromPub :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressStakeFromPub GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let paymentBs = b16encode $ T.append verKeyPayment verKeyPayment
let (Just xPub1) = xpubFromBytes paymentBs
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let stakeBs = b16encode $ T.append verKeyStake verKeyStake
let (Just xPub2) = xpubFromBytes stakeBs
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddrStakeFromExtendedKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let stakeBs1 = b16encode verKeyStake
let (Just pub2) = pubFromBytes stakeBs1
let stakePub = liftPub pub2 :: Shelley 'DelegationK Pub
let baseAddrStakeFromKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromKey stakePub)
baseAddrStakeFromExtendedKey `shouldBe` baseAddrStakeFromKey
goldenTestBaseAddressBothFromKeyHash :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressBothFromKeyHash GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let paymentBs = b16encode $ T.append verKeyPayment verKeyPayment
let (Just xPub1) = xpubFromBytes paymentBs
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let stakeBs = b16encode $ T.append verKeyStake verKeyStake
let (Just xPub2) = xpubFromBytes stakeBs
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddrBothFromKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let paymentKeyHashDigest = hashCredential $ BS.take 32 paymentBs
let paymentKeyHash = KeyHash Payment paymentKeyHashDigest
let stakeKeyHashDigest = hashCredential $ BS.take 32 stakeBs
let stakeKeyHash = KeyHash Delegation stakeKeyHashDigest
let baseAddrBothFromKeyHash =
delegationAddress tag (PaymentFromKeyHash paymentKeyHash)
(DelegationFromKeyHash stakeKeyHash)
baseAddrBothFromKey `shouldBe` baseAddrBothFromKeyHash
goldenTestBaseAddressBothFromPub :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressBothFromPub GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let paymentBs = b16encode $ T.append verKeyPayment verKeyPayment
let (Just xPub1) = xpubFromBytes paymentBs
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let stakeBs = b16encode $ T.append verKeyStake verKeyStake
let (Just xPub2) = xpubFromBytes stakeBs
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddrBothFromKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let paymentBs1 = b16encode verKeyPayment
let (Just pub1) = pubFromBytes paymentBs1
let addrPub = liftPub pub1 :: Shelley 'PaymentK Pub
let stakeBs1 = b16encode verKeyStake
let (Just pub2) = pubFromBytes stakeBs1
let stakePub = liftPub pub2 :: Shelley 'DelegationK Pub
let baseAddrBothFromPub =
delegationAddress tag (PaymentFromKey addrPub)
(DelegationFromKey stakePub)
baseAddrBothFromKey `shouldBe` baseAddrBothFromPub
data TestVector = TestVector
{
-- | The extended root private key, bech32 encoded prefixed with 'root_xsk'
rootXPrv :: Text
| The extended 0th account private key , bech32 encoded prefixed with ' acct_xsk '
, accXPrv0 :: Text
| The extended 1st account private key , bech32 encoded prefixed with ' acct_xsk '
, accXPrv1 :: Text
| The extended 0th address private key , bech32 encoded prefixed with ' addr_xsk '
, addrXPrv0 :: Text
| The extended 0th address public key , bech32 encoded prefixed with ' addr_xvk '
, addrXPub0 :: Text
| The extended 1st address private key , bech32 encoded prefixed with ' addr_xsk '
, addrXPrv1 :: Text
| The extended 1st address public key , bech32 encoded prefixed with ' addr_xvk '
, addrXPub1 :: Text
-- | The extended 1442nd address private key, bech32 encoded prefixed with 'addr_xsk'
, addrXPrv1442 :: Text
-- | The extended 1442nd address public key, bech32 encoded prefixed with 'addr_xvk'
, addrXPub1442 :: Text
| The payment address for 0th address key , with a networking tag 0 , 3 and 6 , respectively .
-- Each bech32 encoded prefixed with 'addr'
, paymentAddr0 :: [Text]
| The payment address for 1st address key , with a networking tag 0 , 3 and 6 , respectively .
-- Each bech32 encoded prefixed with 'addr'
, paymentAddr1 :: [Text]
| The payment address for 1442nd address key , with a networking tag 0 , 3 and 6 , respectively .
-- Each bech32 encoded prefixed with 'addr'
, paymentAddr1442 :: [Text]
| Delegation addresses for the 0th address key and the 0th account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr0Stake0 :: [Text]
| Delegation addresses for the 1st address key and the 0th account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr1Stake0 :: [Text]
| Delegation addresses for the 1442nd address key and the 0th account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr1442Stake0 :: [Text]
| Delegation addresses for the 0th address key and the 1st account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr0Stake1 :: [Text]
| Delegation addresses for the 1st address key and the 1st account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr1Stake1 :: [Text]
| Delegation addresses for the 1442nd address key and the 1st account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr1442Stake1 :: [Text]
| Pointer addresses for the 0th address key and the delegation certificate located in slot 1 ,
transaction index 2 , certificte list index 3 , with a networking tag 0 , 3 and 6 , respectively .
-- Each bech32 encoded prefixed with 'addr'
, pointerAddr0Slot1 :: [Text]
| Pointer addresses for the 0th address key and the delegation certificate located in slot 24157 ,
transaction index 177 , certificte list index 42 , with a networking tag 0 , 3 and 6 , respectively .
-- Each bech32 encoded prefixed with 'addr'
, pointerAddr0Slot2 :: [Text]
-- | Corresponding Mnemonic
, mnemonic :: [Text]
} deriving Show
data InspectVector a = InspectVector
{ addrXPub0 :: a
, addrXPub1 :: a
, addrXPub1442 :: a
, paymentAddr0 :: [a]
, paymentAddr1 :: [a]
, paymentAddr1442 :: [a]
, delegationAddr0Stake0 :: [a]
, delegationAddr1Stake0 :: [a]
, delegationAddr1442Stake0 :: [a]
, delegationAddr0Stake1 :: [a]
, delegationAddr1Stake1 :: [a]
, delegationAddr1442Stake1 :: [a]
, pointerAddr0Slot1 :: [a]
, pointerAddr0Slot2 :: [a]
} deriving (Generic, Show, Functor)
deriving anyclass ToJSON
testVectors :: [Text] -> SpecWith ()
testVectors mnemonic = describe (show $ T.unpack <$> mnemonic) $ do
let (Right mw) = mkSomeMnemonic @'[9,12,15,18,21,24] mnemonic
let sndFactor = mempty
let rootK = genMasterKeyFromMnemonic mw sndFactor :: Shelley 'RootK XPrv
let rootXPrv = bech32With CIP5.root_xsk $ getExtendedKeyAddr rootK
let Just accIx0 = indexFromWord32 @(Index 'Hardened _) 0x80000000
let acctK0 = deriveAccountPrivateKey rootK accIx0
let accXPrv0 = bech32With CIP5.acct_xsk $ getExtendedKeyAddr acctK0
let Just accIx1 = indexFromWord32 @(Index 'Hardened _) 0x80000001
let acctK1 = deriveAccountPrivateKey rootK accIx1
let accXPrv1 = bech32With CIP5.acct_xsk $ getExtendedKeyAddr acctK1
let Just addIx0 = indexFromWord32 @(Index 'Soft _) 0x00000000
let addrK0prv = deriveAddressPrivateKey acctK0 UTxOExternal addIx0
let addrXPrv0 = bech32With CIP5.addr_xsk $ getExtendedKeyAddr addrK0prv
let addrXPub0 = bech32With CIP5.addr_xvk $ getPublicKeyAddr $ toXPub <$> addrK0prv
let Just addIx1 = indexFromWord32 @(Index 'Soft _) 0x00000001
let addrK1prv = deriveAddressPrivateKey acctK0 UTxOExternal addIx1
let addrXPrv1 = bech32With CIP5.addr_xsk $ getExtendedKeyAddr addrK1prv
let addrXPub1 = bech32With CIP5.addr_xvk $ getPublicKeyAddr $ toXPub <$> addrK1prv
let Just addIx1442 = indexFromWord32 @(Index 'Soft _) 0x000005a2
let addrK1442prv = deriveAddressPrivateKey acctK0 UTxOExternal addIx1442
let addrXPrv1442 = bech32With CIP5.addr_xsk $ getExtendedKeyAddr addrK1442prv
let addrXPub1442 = bech32With CIP5.addr_xvk $ getPublicKeyAddr $ toXPub <$> addrK1442prv
let networkTags = rights $ mkNetworkDiscriminant <$> [0,3,6]
let paymentAddr0 = getPaymentAddr addrK0prv <$> networkTags
let paymentAddr1 = getPaymentAddr addrK1prv <$> networkTags
let paymentAddr1442 = getPaymentAddr addrK1442prv <$> networkTags
let slot1 = ChainPointer 1 2 3
let pointerAddr0Slot1 = getPointerAddr addrK0prv slot1 <$> networkTags
let slot2 = ChainPointer 24157 177 42
let pointerAddr0Slot2 = getPointerAddr addrK0prv slot2 <$> networkTags
let stakeKPub0 = toXPub <$> deriveDelegationPrivateKey acctK0
let delegationAddr0Stake0 = getDelegationAddr addrK0prv (DelegationFromExtendedKey stakeKPub0) <$> networkTags
let delegationAddr1Stake0 = getDelegationAddr addrK1prv (DelegationFromExtendedKey stakeKPub0) <$> networkTags
let delegationAddr1442Stake0 = getDelegationAddr addrK1442prv (DelegationFromExtendedKey stakeKPub0) <$> networkTags
let stakeKPub1 = toXPub <$> deriveDelegationPrivateKey acctK1
let delegationAddr0Stake1 = getDelegationAddr addrK0prv (DelegationFromExtendedKey stakeKPub1) <$> networkTags
let delegationAddr1Stake1 = getDelegationAddr addrK1prv (DelegationFromExtendedKey stakeKPub1) <$> networkTags
let delegationAddr1442Stake1 = getDelegationAddr addrK1442prv (DelegationFromExtendedKey stakeKPub1) <$> networkTags
let vec = TestVector {..}
let inspectVec = InspectVector {..}
it "should generate correct addresses" $ do
goldenTextLazy ("addresses_" <> T.intercalate "_" mnemonic)
(pShowOpt defaultOutputOptionsNoColor vec)
it "should inspect correctly" $ do
goldenByteStringLazy ("inspects" <> T.intercalate "_" mnemonic) $
goldenEncodeJSON $ toInspect <$> inspectVec
where
getExtendedKeyAddr = unsafeMkAddress . xprvToBytes . getKey
getPublicKeyAddr = unsafeMkAddress . xpubToBytes . getKey
getPaymentAddr addrKPrv net = bech32 $ paymentAddress net (PaymentFromExtendedKey (toXPub <$> addrKPrv))
getPointerAddr addrKPrv ptr net = bech32 $ pointerAddress net (PaymentFromExtendedKey (toXPub <$> addrKPrv)) ptr
getDelegationAddr addrKPrv stakeKPub net =
bech32 $ delegationAddress net (PaymentFromExtendedKey (toXPub <$> addrKPrv)) stakeKPub
toInspect :: Text -> Value
toInspect = fromMaybe (String "couldn't inspect") .
(Shelley.inspectAddress Nothing <=< fromBech32)
goldenEncodeJSON :: ToJSON a => a -> BL.ByteString
goldenEncodeJSON = Aeson.encodePretty' cfg
where
cfg = Aeson.defConfig { Aeson.confCompare = compare }
prop_roundtripTextEncoding
:: (Address -> Text)
-- ^ encode to 'Text'
-> (Text -> Maybe Address)
-- ^ decode from 'Text'
-> Shelley 'PaymentK XPub
-- ^ An arbitrary public key
-> NetworkDiscriminant Shelley
-- ^ An arbitrary network discriminant
-> Property
prop_roundtripTextEncoding encode' decode addXPub discrimination =
(result == pure address)
& counterexample (unlines
[ "Address " <> T.unpack (encode' address)
, "↳ " <> maybe "ø" (T.unpack . encode') result
])
& label (show $ addressDiscrimination @Shelley discrimination)
where
address = paymentAddress discrimination (PaymentFromExtendedKey addXPub)
result = decode (encode' address)
prop_roundtripTextEncodingDelegation
:: (Address -> Text)
-- ^ encode to 'Text'
-> (Text -> Maybe Address)
-- ^ decode from 'Text'
-> Shelley 'PaymentK XPub
-- ^ An arbitrary address public key
-> Shelley 'DelegationK XPub
-- ^ An arbitrary delegation public key
-> NetworkDiscriminant Shelley
-- ^ An arbitrary network discriminant
-> Property
prop_roundtripTextEncodingDelegation encode' decode addXPub delegXPub discrimination =
(result == pure address)
& counterexample (unlines
[ "Address " <> T.unpack (encode' address)
, "↳ " <> maybe "ø" (T.unpack . encode') result
])
& label (show $ addressDiscrimination @Shelley discrimination)
where
address = delegationAddress discrimination (PaymentFromExtendedKey addXPub) (DelegationFromExtendedKey delegXPub)
result = decode (encode' address)
prop_roundtripTextEncodingPointer
:: (Address -> Text)
-- ^ encode to 'Text'
-> (Text -> Maybe Address)
-- ^ decode from 'Text'
-> Shelley 'PaymentK XPub
-- ^ An arbitrary address public key
-> ChainPointer
-- ^ An arbitrary delegation key locator
-> NetworkDiscriminant Shelley
-- ^ An arbitrary network discriminant
-> Property
prop_roundtripTextEncodingPointer encode' decode addXPub ptr discrimination =
(result == pure address)
& counterexample (unlines
[ "Address " <> T.unpack (encode' address)
, "↳ " <> maybe "ø" (T.unpack . encode') result
])
& label (show $ addressDiscrimination @Shelley discrimination)
where
address = pointerAddress discrimination (PaymentFromExtendedKey addXPub) ptr
result = decode (encode' address)
goldenTextLazy :: Text -> TL.Text -> Golden TL.Text
goldenTextLazy name output =
Golden
{ output = output
, encodePretty = TL.unpack
, writeToFile = TL.writeFile
, readFromFile = TL.readFile
, testName = T.unpack name
, directory = "test/golden"
, failFirstTime = False
}
goldenByteStringLazy :: Text -> BL.ByteString -> Golden BL.ByteString
goldenByteStringLazy name output =
Golden
{ output = output
, encodePretty = TL.unpack . TLE.decodeUtf8
, writeToFile = BL.writeFile
, readFromFile = BL.readFile
, testName = T.unpack name
, directory = "test/golden"
, failFirstTime = False
}
{-------------------------------------------------------------------------------
Arbitrary Instances
-------------------------------------------------------------------------------}
newtype SndFactor = SndFactor ScrubbedBytes
deriving stock (Eq, Show)
deriving newtype (ByteArrayAccess)
instance Arbitrary SndFactor where
arbitrary = do
n <- choose (0, 64)
bytes <- BS.pack <$> vector n
return $ SndFactor $ BA.convert bytes
b16encode :: Text -> ByteString
b16encode = encode EBase16 . T.encodeUtf8
b16decode :: Text -> Either String ByteString
b16decode = fromBase16 . T.encodeUtf8
| null | https://raw.githubusercontent.com/input-output-hk/cardano-addresses/d6dcd277d92c76e45d1024f7d82837fc0907aa12/core/test/Cardano/Address/Style/ShelleySpec.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
------------------------------------------------------------------------------
Properties
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Golden tests
------------------------------------------------------------------------------
| Definitions: Let's assume we have private key < xprv | pub | cc >
extended public key should be understood as < | pub | cc >
verification public key should be understood as < | pub | >
| The verification public key as string to be encoded into base16 form
| Location of stake cerificate in the blockchain
| Network tag
| Expected address as encoded into base16 form
| The verification public key as string to be encoded into base16 form
| Network tag
| Expected address as encoded into base16 form
| The verification public key as string to be encoded into base16 form
| The verification public key as string to be encoded into base16 form
| Network tag
| Expected address as encoded into base16 form
| The extended root private key, bech32 encoded prefixed with 'root_xsk'
| The extended 1442nd address private key, bech32 encoded prefixed with 'addr_xsk'
| The extended 1442nd address public key, bech32 encoded prefixed with 'addr_xvk'
Each bech32 encoded prefixed with 'addr'
Each bech32 encoded prefixed with 'addr'
Each bech32 encoded prefixed with 'addr'
Each bech32 encoded prefixed with 'addr'
Each bech32 encoded prefixed with 'addr'
| Corresponding Mnemonic
^ encode to 'Text'
^ decode from 'Text'
^ An arbitrary public key
^ An arbitrary network discriminant
^ encode to 'Text'
^ decode from 'Text'
^ An arbitrary address public key
^ An arbitrary delegation public key
^ An arbitrary network discriminant
^ encode to 'Text'
^ decode from 'Text'
^ An arbitrary address public key
^ An arbitrary delegation key locator
^ An arbitrary network discriminant
------------------------------------------------------------------------------
Arbitrary Instances
------------------------------------------------------------------------------ | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -fno - warn - orphans #
module Cardano.Address.Style.ShelleySpec
( spec
) where
import Prelude
import Cardano.Address
( Address
, ChainPointer (..)
, HasNetworkDiscriminant (..)
, bech32
, bech32With
, fromBech32
, unsafeMkAddress
)
import Cardano.Address.Derivation
( Depth (..)
, DerivationType (..)
, GenMasterKey (..)
, HardDerivation (..)
, Index (..)
, Pub
, SoftDerivation (..)
, XPrv
, XPub
, hashCredential
, indexFromWord32
, pubFromBytes
, toXPub
, unsafeMkIndex
, xprvToBytes
, xpubFromBytes
, xpubToBytes
)
import Cardano.Address.Script
( KeyHash (..), KeyRole (..) )
import Cardano.Address.Style.Shelley
( Credential (..)
, Role (..)
, Shelley (..)
, delegationAddress
, deriveDelegationPrivateKey
, liftPub
, liftXPub
, mkNetworkDiscriminant
, paymentAddress
, pointerAddress
, roleFromIndex
, roleToIndex
)
import Cardano.Mnemonic
( SomeMnemonic, mkSomeMnemonic )
import Codec.Binary.Encoding
( AbstractEncoding (..), encode, fromBase16 )
import Control.Monad
( (<=<) )
import Data.Aeson
( ToJSON, Value (..) )
import Data.ByteArray
( ByteArrayAccess, ScrubbedBytes )
import Data.ByteString
( ByteString )
import Data.Either
( rights )
import Data.Function
( (&) )
import Data.Maybe
( fromMaybe, isNothing )
import Data.Text
( Text )
import GHC.Generics
( Generic )
import Test.Arbitrary
()
import Test.Hspec
( Spec, SpecWith, describe, it, shouldBe )
import Test.Hspec.Golden
( Golden (..) )
import Test.Hspec.QuickCheck
( prop )
import Test.QuickCheck
( Arbitrary (..)
, Property
, choose
, counterexample
, label
, property
, vector
, (===)
)
import Text.Pretty.Simple
( defaultOutputOptionsNoColor, pShowOpt )
import qualified Cardano.Address.Style.Shelley as Shelley
import qualified Cardano.Codec.Bech32.Prefixes as CIP5
import qualified Data.Aeson.Encode.Pretty as Aeson
import qualified Data.ByteArray as BA
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TLE
import qualified Data.Text.Lazy.IO as TL
spec :: Spec
spec = do
describe "BIP-0044 Derivation Properties" $ do
it "deriveAccountPrivateKey works for various indexes" $
property prop_accountKeyDerivation
it "N(CKDpriv((kpar, cpar), i)) === CKDpub(N(kpar, cpar), i) for any key" $
property prop_publicChildKeyDerivation
describe "Role indices" $ do
it "Calling indexFromWord32 for invalid value fails)" $
property prop_fromWord32Role
it "Roundtrip index" $ property prop_roundtripIndexRole
describe "Proper pointer addresses construction" $ do
it "Using different numbers in DelegationPointerAddress does not fail"
(property prop_pointerAddressConstruction)
describe "Text Encoding Roundtrips" $ do
prop "bech32 . fromBech32 - Shelley - payment address" $
prop_roundtripTextEncoding bech32 fromBech32
prop "bech32 . fromBech32 - Shelley - delegation address" $
prop_roundtripTextEncodingDelegation bech32 fromBech32
prop "bech32 . fromBech32 - Shelley - pointer address" $
prop_roundtripTextEncodingPointer bech32 fromBech32
describe "Golden tests" $ do
goldenTestPointerAddress GoldenTestPointerAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, stakePtr = ChainPointer 128 2 3
, netTag = 0
, expectedAddr =
"408a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d481000203"
}
goldenTestPointerAddress GoldenTestPointerAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, stakePtr = ChainPointer 128 2 3
, netTag = 1
, expectedAddr =
"418a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d481000203"
}
goldenTestEnterpriseAddress GoldenTestEnterpriseAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, netTag = 0
, expectedAddr =
"608a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d4"
}
goldenTestEnterpriseAddress GoldenTestEnterpriseAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, netTag = 1
, expectedAddr =
"618a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d4"
}
goldenTestEnterpriseAddressKeyHash GoldenTestEnterpriseAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, netTag = 0
, expectedAddr =
"608a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d4"
}
goldenTestEnterpriseAddressKeyHash GoldenTestEnterpriseAddress
{ verKey = "1a2a3a4a5a6a7a8a"
, netTag = 1
, expectedAddr =
"618a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d4"
}
goldenTestBaseAddressPayFromXPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressPayFromXPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressPayFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressPayFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressPayFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressPayFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressStakeFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressStakeFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressStakeFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressStakeFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressBothFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressBothFromKeyHash GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressBothFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 0
, expectedAddr =
"008a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
goldenTestBaseAddressBothFromPub GoldenTestBaseAddress
{ verKeyPayment = "1a2a3a4a5a6a7a8a"
, verKeyStake = "1c2c3c4c5c6c7c8c"
, netTag = 1
, expectedAddr =
"018a4d111f71a79169c50bcbc27e1e20b6e13e87ff8f33edc3cab419d408b2d658668c2e341ee5bda4477b63c5aca7ec7ae4e3d196163556a4"
}
describe "Test vectors" $ do
testVectors
[ "test", "child", "burst", "immense", "armed", "parrot"
, "company", "walk", "dog" ]
testVectors
[ "test", "walk", "nut", "penalty", "hip", "pave", "soap",
"entry", "language", "right", "filter", "choice" ]
testVectors
[ "art", "forum", "devote", "street", "sure", "rather",
"head", "chuckle", "guard", "poverty", "release",
"quote", "oak", "craft", "enemy"]
testVectors
[ "churn", "shaft", "spoon", "second", "erode", "useless",
"thrive", "burst", "group", "seed", "element", "sign",
"scrub", "buffalo", "jelly", "grace", "neck", "useless" ]
testVectors
[ "draft", "ability", "female", "child", "jump", "maid",
"roof", "hurt", "below", "live", "topple", "paper",
"exclude", "ordinary", "coach", "churn", "sunset",
"emerge", "blame", "ketchup", "much" ]
testVectors
[ "excess", "behave", "track", "soul", "table", "wear",
"ocean", "cash", "stay", "nature", "item", "turtle",
"palm", "soccer", "lunch", "horror", "start", "stumble",
"month", "panic", "right", "must", "lock", "dress" ]
prop_publicChildKeyDerivation
:: (SomeMnemonic, SndFactor)
-> Role
-> Index 'Soft 'PaymentK
-> Property
prop_publicChildKeyDerivation (mw, (SndFactor sndFactor)) cc ix =
addrXPub1 === addrXPub2
where
rootXPrv = genMasterKeyFromMnemonic mw sndFactor :: Shelley 'RootK XPrv
accXPrv = deriveAccountPrivateKey rootXPrv minBound
addrXPub1 = toXPub <$> deriveAddressPrivateKey accXPrv cc ix
addrXPub2 = deriveAddressPublicKey (toXPub <$> accXPrv) cc ix
prop_accountKeyDerivation
:: (SomeMnemonic, SndFactor)
-> Index 'Hardened 'AccountK
-> Property
prop_accountKeyDerivation (mw, (SndFactor sndFactor)) ix =
accXPrv `seq` property ()
where
rootXPrv = genMasterKeyFromMnemonic mw sndFactor :: Shelley 'RootK XPrv
accXPrv = deriveAccountPrivateKey rootXPrv ix
prop_fromWord32Role :: Int -> Property
prop_fromWord32Role n =
isNothing (toRole n)
===
(n > fromRole maxBound || n < fromRole minBound)
where
fromRole = fromIntegral . indexToWord32 . roleToIndex
toRole = roleFromIndex . unsafeMkIndex . fromIntegral
prop_roundtripIndexRole :: Role -> Property
prop_roundtripIndexRole ix = (roleFromIndex . roleToIndex) ix === Just ix
prop_pointerAddressConstruction
:: (SomeMnemonic, SndFactor)
-> Role
-> Index 'Soft 'PaymentK
-> NetworkDiscriminant Shelley
-> ChainPointer
-> Property
prop_pointerAddressConstruction (mw, (SndFactor sndFactor)) cc ix net ptr =
pointerAddr `seq` property ()
where
rootXPrv = genMasterKeyFromMnemonic mw sndFactor :: Shelley 'RootK XPrv
accXPrv = deriveAccountPrivateKey rootXPrv minBound
addrXPub = toXPub <$> deriveAddressPrivateKey accXPrv cc ix
pointerAddr = pointerAddress net (PaymentFromExtendedKey addrXPub) ptr
Then , extended private key should be understood as < xprv | | cc >
data GoldenTestPointerAddress = GoldenTestPointerAddress
{
After that it should have 32 - byte length
verKey :: Text
, stakePtr :: ChainPointer
, netTag :: Integer
, expectedAddr :: Text
}
goldenTestPointerAddress :: GoldenTestPointerAddress -> SpecWith ()
goldenTestPointerAddress GoldenTestPointerAddress{..} =
it ("pointer address for networkId " <> show netTag) $ do
let (Just xPub) = xpubFromBytes $ b16encode $ T.append verKey verKey
let addrXPub = liftXPub xPub :: Shelley 'PaymentK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let ptrAddr = pointerAddress tag (PaymentFromExtendedKey addrXPub) stakePtr
let (Right bytes) = b16decode expectedAddr
ptrAddr `shouldBe` unsafeMkAddress bytes
data GoldenTestEnterpriseAddress = GoldenTestEnterpriseAddress
{
After that it should have 32 - byte length
verKey :: Text
, netTag :: Integer
, expectedAddr :: Text
}
goldenTestEnterpriseAddress :: GoldenTestEnterpriseAddress -> SpecWith ()
goldenTestEnterpriseAddress GoldenTestEnterpriseAddress{..} =
it ("enterprise address for networkId " <> show netTag) $ do
let (Just xPub) = xpubFromBytes $ b16encode $ T.append verKey verKey
let addrXPub = liftXPub xPub :: Shelley 'PaymentK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let enterpriseAddr = Shelley.paymentAddress tag (PaymentFromExtendedKey addrXPub)
let (Right bytes) = b16decode expectedAddr
enterpriseAddr `shouldBe` unsafeMkAddress bytes
goldenTestEnterpriseAddressKeyHash :: GoldenTestEnterpriseAddress -> SpecWith ()
goldenTestEnterpriseAddressKeyHash GoldenTestEnterpriseAddress{..} =
it ("enterprise address for networkId " <> show netTag) $ do
let bs = b16encode $ T.append verKey verKey
let (Just xPub) = xpubFromBytes bs
let addrXPub = liftXPub xPub :: Shelley 'PaymentK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let enterpriseAddrFromKey =
Shelley.paymentAddress tag (PaymentFromExtendedKey addrXPub)
let keyHashDigest = hashCredential $ BS.take 32 bs
let keyHash = KeyHash Payment keyHashDigest
let enterpriseAddrFromKeyHash =
Shelley.paymentAddress tag (PaymentFromKeyHash keyHash)
enterpriseAddrFromKey `shouldBe` enterpriseAddrFromKeyHash
data GoldenTestBaseAddress = GoldenTestBaseAddress
{
After that it should have 32 - byte length
verKeyPayment :: Text
After that it should have 32 - byte length
, verKeyStake :: Text
, netTag :: Integer
, expectedAddr :: Text
}
goldenTestBaseAddressPayFromXPub :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressPayFromXPub GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let (Just xPub1) =
xpubFromBytes $ b16encode $ T.append verKeyPayment verKeyPayment
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let (Just xPub2) =
xpubFromBytes $ b16encode $ T.append verKeyStake verKeyStake
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddr =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let (Right bytes) = b16decode expectedAddr
baseAddr `shouldBe` unsafeMkAddress bytes
goldenTestBaseAddressPayFromPub :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressPayFromPub GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let (Just pub1) =
pubFromBytes $ b16encode verKeyPayment
let addrPub = liftPub pub1 :: Shelley 'PaymentK Pub
let (Just xPub2) =
xpubFromBytes $ b16encode $ T.append verKeyStake verKeyStake
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddr =
delegationAddress tag (PaymentFromKey addrPub)
(DelegationFromExtendedKey stakeXPub)
let (Right bytes) = b16decode expectedAddr
baseAddr `shouldBe` unsafeMkAddress bytes
goldenTestBaseAddressPayFromKeyHash :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressPayFromKeyHash GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let paymentBs = b16encode $ T.append verKeyPayment verKeyPayment
let (Just xPub1) = xpubFromBytes paymentBs
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let (Just xPub2) =
xpubFromBytes $ b16encode $ T.append verKeyStake verKeyStake
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddrPayFromKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let keyHashDigest = hashCredential $ BS.take 32 paymentBs
let keyHash = KeyHash Payment keyHashDigest
let baseAddrPayFromKeyHash =
delegationAddress tag (PaymentFromKeyHash keyHash)
(DelegationFromExtendedKey stakeXPub)
baseAddrPayFromKey `shouldBe` baseAddrPayFromKeyHash
goldenTestBaseAddressStakeFromKeyHash :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressStakeFromKeyHash GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let paymentBs = b16encode $ T.append verKeyPayment verKeyPayment
let (Just xPub1) = xpubFromBytes paymentBs
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let stakeBs = b16encode $ T.append verKeyStake verKeyStake
let (Just xPub2) = xpubFromBytes stakeBs
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddrStakeFromKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let keyHashDigest = hashCredential $ BS.take 32 stakeBs
let keyHash = KeyHash Delegation keyHashDigest
let baseAddrStakeFromKeyHash =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromKeyHash keyHash)
baseAddrStakeFromKey `shouldBe` baseAddrStakeFromKeyHash
goldenTestBaseAddressStakeFromPub :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressStakeFromPub GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let paymentBs = b16encode $ T.append verKeyPayment verKeyPayment
let (Just xPub1) = xpubFromBytes paymentBs
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let stakeBs = b16encode $ T.append verKeyStake verKeyStake
let (Just xPub2) = xpubFromBytes stakeBs
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddrStakeFromExtendedKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let stakeBs1 = b16encode verKeyStake
let (Just pub2) = pubFromBytes stakeBs1
let stakePub = liftPub pub2 :: Shelley 'DelegationK Pub
let baseAddrStakeFromKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromKey stakePub)
baseAddrStakeFromExtendedKey `shouldBe` baseAddrStakeFromKey
goldenTestBaseAddressBothFromKeyHash :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressBothFromKeyHash GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let paymentBs = b16encode $ T.append verKeyPayment verKeyPayment
let (Just xPub1) = xpubFromBytes paymentBs
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let stakeBs = b16encode $ T.append verKeyStake verKeyStake
let (Just xPub2) = xpubFromBytes stakeBs
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddrBothFromKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let paymentKeyHashDigest = hashCredential $ BS.take 32 paymentBs
let paymentKeyHash = KeyHash Payment paymentKeyHashDigest
let stakeKeyHashDigest = hashCredential $ BS.take 32 stakeBs
let stakeKeyHash = KeyHash Delegation stakeKeyHashDigest
let baseAddrBothFromKeyHash =
delegationAddress tag (PaymentFromKeyHash paymentKeyHash)
(DelegationFromKeyHash stakeKeyHash)
baseAddrBothFromKey `shouldBe` baseAddrBothFromKeyHash
goldenTestBaseAddressBothFromPub :: GoldenTestBaseAddress -> SpecWith ()
goldenTestBaseAddressBothFromPub GoldenTestBaseAddress{..} =
it ("base address for networkId " <> show netTag) $ do
let paymentBs = b16encode $ T.append verKeyPayment verKeyPayment
let (Just xPub1) = xpubFromBytes paymentBs
let addrXPub = liftXPub xPub1 :: Shelley 'PaymentK XPub
let stakeBs = b16encode $ T.append verKeyStake verKeyStake
let (Just xPub2) = xpubFromBytes stakeBs
let stakeXPub = liftXPub xPub2 :: Shelley 'DelegationK XPub
let (Right tag) = mkNetworkDiscriminant netTag
let baseAddrBothFromKey =
delegationAddress tag (PaymentFromExtendedKey addrXPub)
(DelegationFromExtendedKey stakeXPub)
let paymentBs1 = b16encode verKeyPayment
let (Just pub1) = pubFromBytes paymentBs1
let addrPub = liftPub pub1 :: Shelley 'PaymentK Pub
let stakeBs1 = b16encode verKeyStake
let (Just pub2) = pubFromBytes stakeBs1
let stakePub = liftPub pub2 :: Shelley 'DelegationK Pub
let baseAddrBothFromPub =
delegationAddress tag (PaymentFromKey addrPub)
(DelegationFromKey stakePub)
baseAddrBothFromKey `shouldBe` baseAddrBothFromPub
data TestVector = TestVector
{
rootXPrv :: Text
| The extended 0th account private key , bech32 encoded prefixed with ' acct_xsk '
, accXPrv0 :: Text
| The extended 1st account private key , bech32 encoded prefixed with ' acct_xsk '
, accXPrv1 :: Text
| The extended 0th address private key , bech32 encoded prefixed with ' addr_xsk '
, addrXPrv0 :: Text
| The extended 0th address public key , bech32 encoded prefixed with ' addr_xvk '
, addrXPub0 :: Text
| The extended 1st address private key , bech32 encoded prefixed with ' addr_xsk '
, addrXPrv1 :: Text
| The extended 1st address public key , bech32 encoded prefixed with ' addr_xvk '
, addrXPub1 :: Text
, addrXPrv1442 :: Text
, addrXPub1442 :: Text
| The payment address for 0th address key , with a networking tag 0 , 3 and 6 , respectively .
, paymentAddr0 :: [Text]
| The payment address for 1st address key , with a networking tag 0 , 3 and 6 , respectively .
, paymentAddr1 :: [Text]
| The payment address for 1442nd address key , with a networking tag 0 , 3 and 6 , respectively .
, paymentAddr1442 :: [Text]
| Delegation addresses for the 0th address key and the 0th account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr0Stake0 :: [Text]
| Delegation addresses for the 1st address key and the 0th account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr1Stake0 :: [Text]
| Delegation addresses for the 1442nd address key and the 0th account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr1442Stake0 :: [Text]
| Delegation addresses for the 0th address key and the 1st account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr0Stake1 :: [Text]
| Delegation addresses for the 1st address key and the 1st account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr1Stake1 :: [Text]
| Delegation addresses for the 1442nd address key and the 1st account delegation key ,
with a networking tag 0 , 3 and 6 , respectively . Each bech32 encoded prefixed with ' addr '
, delegationAddr1442Stake1 :: [Text]
| Pointer addresses for the 0th address key and the delegation certificate located in slot 1 ,
transaction index 2 , certificte list index 3 , with a networking tag 0 , 3 and 6 , respectively .
, pointerAddr0Slot1 :: [Text]
| Pointer addresses for the 0th address key and the delegation certificate located in slot 24157 ,
transaction index 177 , certificte list index 42 , with a networking tag 0 , 3 and 6 , respectively .
, pointerAddr0Slot2 :: [Text]
, mnemonic :: [Text]
} deriving Show
data InspectVector a = InspectVector
{ addrXPub0 :: a
, addrXPub1 :: a
, addrXPub1442 :: a
, paymentAddr0 :: [a]
, paymentAddr1 :: [a]
, paymentAddr1442 :: [a]
, delegationAddr0Stake0 :: [a]
, delegationAddr1Stake0 :: [a]
, delegationAddr1442Stake0 :: [a]
, delegationAddr0Stake1 :: [a]
, delegationAddr1Stake1 :: [a]
, delegationAddr1442Stake1 :: [a]
, pointerAddr0Slot1 :: [a]
, pointerAddr0Slot2 :: [a]
} deriving (Generic, Show, Functor)
deriving anyclass ToJSON
testVectors :: [Text] -> SpecWith ()
testVectors mnemonic = describe (show $ T.unpack <$> mnemonic) $ do
let (Right mw) = mkSomeMnemonic @'[9,12,15,18,21,24] mnemonic
let sndFactor = mempty
let rootK = genMasterKeyFromMnemonic mw sndFactor :: Shelley 'RootK XPrv
let rootXPrv = bech32With CIP5.root_xsk $ getExtendedKeyAddr rootK
let Just accIx0 = indexFromWord32 @(Index 'Hardened _) 0x80000000
let acctK0 = deriveAccountPrivateKey rootK accIx0
let accXPrv0 = bech32With CIP5.acct_xsk $ getExtendedKeyAddr acctK0
let Just accIx1 = indexFromWord32 @(Index 'Hardened _) 0x80000001
let acctK1 = deriveAccountPrivateKey rootK accIx1
let accXPrv1 = bech32With CIP5.acct_xsk $ getExtendedKeyAddr acctK1
let Just addIx0 = indexFromWord32 @(Index 'Soft _) 0x00000000
let addrK0prv = deriveAddressPrivateKey acctK0 UTxOExternal addIx0
let addrXPrv0 = bech32With CIP5.addr_xsk $ getExtendedKeyAddr addrK0prv
let addrXPub0 = bech32With CIP5.addr_xvk $ getPublicKeyAddr $ toXPub <$> addrK0prv
let Just addIx1 = indexFromWord32 @(Index 'Soft _) 0x00000001
let addrK1prv = deriveAddressPrivateKey acctK0 UTxOExternal addIx1
let addrXPrv1 = bech32With CIP5.addr_xsk $ getExtendedKeyAddr addrK1prv
let addrXPub1 = bech32With CIP5.addr_xvk $ getPublicKeyAddr $ toXPub <$> addrK1prv
let Just addIx1442 = indexFromWord32 @(Index 'Soft _) 0x000005a2
let addrK1442prv = deriveAddressPrivateKey acctK0 UTxOExternal addIx1442
let addrXPrv1442 = bech32With CIP5.addr_xsk $ getExtendedKeyAddr addrK1442prv
let addrXPub1442 = bech32With CIP5.addr_xvk $ getPublicKeyAddr $ toXPub <$> addrK1442prv
let networkTags = rights $ mkNetworkDiscriminant <$> [0,3,6]
let paymentAddr0 = getPaymentAddr addrK0prv <$> networkTags
let paymentAddr1 = getPaymentAddr addrK1prv <$> networkTags
let paymentAddr1442 = getPaymentAddr addrK1442prv <$> networkTags
let slot1 = ChainPointer 1 2 3
let pointerAddr0Slot1 = getPointerAddr addrK0prv slot1 <$> networkTags
let slot2 = ChainPointer 24157 177 42
let pointerAddr0Slot2 = getPointerAddr addrK0prv slot2 <$> networkTags
let stakeKPub0 = toXPub <$> deriveDelegationPrivateKey acctK0
let delegationAddr0Stake0 = getDelegationAddr addrK0prv (DelegationFromExtendedKey stakeKPub0) <$> networkTags
let delegationAddr1Stake0 = getDelegationAddr addrK1prv (DelegationFromExtendedKey stakeKPub0) <$> networkTags
let delegationAddr1442Stake0 = getDelegationAddr addrK1442prv (DelegationFromExtendedKey stakeKPub0) <$> networkTags
let stakeKPub1 = toXPub <$> deriveDelegationPrivateKey acctK1
let delegationAddr0Stake1 = getDelegationAddr addrK0prv (DelegationFromExtendedKey stakeKPub1) <$> networkTags
let delegationAddr1Stake1 = getDelegationAddr addrK1prv (DelegationFromExtendedKey stakeKPub1) <$> networkTags
let delegationAddr1442Stake1 = getDelegationAddr addrK1442prv (DelegationFromExtendedKey stakeKPub1) <$> networkTags
let vec = TestVector {..}
let inspectVec = InspectVector {..}
it "should generate correct addresses" $ do
goldenTextLazy ("addresses_" <> T.intercalate "_" mnemonic)
(pShowOpt defaultOutputOptionsNoColor vec)
it "should inspect correctly" $ do
goldenByteStringLazy ("inspects" <> T.intercalate "_" mnemonic) $
goldenEncodeJSON $ toInspect <$> inspectVec
where
getExtendedKeyAddr = unsafeMkAddress . xprvToBytes . getKey
getPublicKeyAddr = unsafeMkAddress . xpubToBytes . getKey
getPaymentAddr addrKPrv net = bech32 $ paymentAddress net (PaymentFromExtendedKey (toXPub <$> addrKPrv))
getPointerAddr addrKPrv ptr net = bech32 $ pointerAddress net (PaymentFromExtendedKey (toXPub <$> addrKPrv)) ptr
getDelegationAddr addrKPrv stakeKPub net =
bech32 $ delegationAddress net (PaymentFromExtendedKey (toXPub <$> addrKPrv)) stakeKPub
toInspect :: Text -> Value
toInspect = fromMaybe (String "couldn't inspect") .
(Shelley.inspectAddress Nothing <=< fromBech32)
goldenEncodeJSON :: ToJSON a => a -> BL.ByteString
goldenEncodeJSON = Aeson.encodePretty' cfg
where
cfg = Aeson.defConfig { Aeson.confCompare = compare }
prop_roundtripTextEncoding
:: (Address -> Text)
-> (Text -> Maybe Address)
-> Shelley 'PaymentK XPub
-> NetworkDiscriminant Shelley
-> Property
prop_roundtripTextEncoding encode' decode addXPub discrimination =
(result == pure address)
& counterexample (unlines
[ "Address " <> T.unpack (encode' address)
, "↳ " <> maybe "ø" (T.unpack . encode') result
])
& label (show $ addressDiscrimination @Shelley discrimination)
where
address = paymentAddress discrimination (PaymentFromExtendedKey addXPub)
result = decode (encode' address)
prop_roundtripTextEncodingDelegation
:: (Address -> Text)
-> (Text -> Maybe Address)
-> Shelley 'PaymentK XPub
-> Shelley 'DelegationK XPub
-> NetworkDiscriminant Shelley
-> Property
prop_roundtripTextEncodingDelegation encode' decode addXPub delegXPub discrimination =
(result == pure address)
& counterexample (unlines
[ "Address " <> T.unpack (encode' address)
, "↳ " <> maybe "ø" (T.unpack . encode') result
])
& label (show $ addressDiscrimination @Shelley discrimination)
where
address = delegationAddress discrimination (PaymentFromExtendedKey addXPub) (DelegationFromExtendedKey delegXPub)
result = decode (encode' address)
prop_roundtripTextEncodingPointer
:: (Address -> Text)
-> (Text -> Maybe Address)
-> Shelley 'PaymentK XPub
-> ChainPointer
-> NetworkDiscriminant Shelley
-> Property
prop_roundtripTextEncodingPointer encode' decode addXPub ptr discrimination =
(result == pure address)
& counterexample (unlines
[ "Address " <> T.unpack (encode' address)
, "↳ " <> maybe "ø" (T.unpack . encode') result
])
& label (show $ addressDiscrimination @Shelley discrimination)
where
address = pointerAddress discrimination (PaymentFromExtendedKey addXPub) ptr
result = decode (encode' address)
goldenTextLazy :: Text -> TL.Text -> Golden TL.Text
goldenTextLazy name output =
Golden
{ output = output
, encodePretty = TL.unpack
, writeToFile = TL.writeFile
, readFromFile = TL.readFile
, testName = T.unpack name
, directory = "test/golden"
, failFirstTime = False
}
goldenByteStringLazy :: Text -> BL.ByteString -> Golden BL.ByteString
goldenByteStringLazy name output =
Golden
{ output = output
, encodePretty = TL.unpack . TLE.decodeUtf8
, writeToFile = BL.writeFile
, readFromFile = BL.readFile
, testName = T.unpack name
, directory = "test/golden"
, failFirstTime = False
}
newtype SndFactor = SndFactor ScrubbedBytes
deriving stock (Eq, Show)
deriving newtype (ByteArrayAccess)
instance Arbitrary SndFactor where
arbitrary = do
n <- choose (0, 64)
bytes <- BS.pack <$> vector n
return $ SndFactor $ BA.convert bytes
b16encode :: Text -> ByteString
b16encode = encode EBase16 . T.encodeUtf8
b16decode :: Text -> Either String ByteString
b16decode = fromBase16 . T.encodeUtf8
|
3c4c4e7a42fac847a37f09d374fbc1971a35230cf4684c1912ab461fb6229202 | ericnormand/lispcast-clojure-core-async | chapter4.clj | Exercise 1
(def chan5 (chan 5))
(go
(doseq [x 10]
(>! chan5 x)
(println x)))
Exercise 2
(defn assembly-line []
(let [body-chan (chan 10)
wheel1-chan (chan 10)
wheel2-chan (chan 10)
body+wheel-chan (chan 10)
body+2-wheels-chan (chan 10)
box-chan (chan 10)]
(go-body body-chan)
(go-wheel1 wheel1-chan)
(go-wheel2 wheel2-chan)
(dotimes [x 2]
(go-attach-wheel1 body-chan wheel1-chan body+wheel-chan))
(dotimes [x 2]
(go-attach-wheel2 body+wheel-chan wheel2-chan body+2-wheels-chan))
(dotimes [x 2]
(go-box-up body+2-wheels-chan box-chan))
(go-put-in-truck box-chan)))
Exercise 3
(assembly-line)
| null | https://raw.githubusercontent.com/ericnormand/lispcast-clojure-core-async/ac1140be188a261155eb353928aa03f9f8048eb1/exercises/chapter4.clj | clojure | Exercise 1
(def chan5 (chan 5))
(go
(doseq [x 10]
(>! chan5 x)
(println x)))
Exercise 2
(defn assembly-line []
(let [body-chan (chan 10)
wheel1-chan (chan 10)
wheel2-chan (chan 10)
body+wheel-chan (chan 10)
body+2-wheels-chan (chan 10)
box-chan (chan 10)]
(go-body body-chan)
(go-wheel1 wheel1-chan)
(go-wheel2 wheel2-chan)
(dotimes [x 2]
(go-attach-wheel1 body-chan wheel1-chan body+wheel-chan))
(dotimes [x 2]
(go-attach-wheel2 body+wheel-chan wheel2-chan body+2-wheels-chan))
(dotimes [x 2]
(go-box-up body+2-wheels-chan box-chan))
(go-put-in-truck box-chan)))
Exercise 3
(assembly-line)
| |
397f3cac84a35bd6e2a4b9660e7ae058d8b0f24a39c1091627e9832e54cdb188 | Tipoca/hlvm | expr.ml | type ty =
[ `Unit
| `Bool
| `Int
| `Float
| `Tuple of ty list
| `Array of ty ]
type cmp = [`Lt|`Le|`Eq|`Ne|`Ge|`Gt]
type patt =
| PVar of string
| PTup of patt list
type t =
| Unit
| Int of int
| Float of float
| String of string
| Var of string
| Apply of t * t
| Tuple of t list
| UnArith of [`Neg] * t
| BinArith of [`Add|`Sub|`Mul|`Div] * t * t
| Cmp of cmp * t * t
| If of t * t * t
| LetIn of patt * t * t
| ArrayGet of t * t
| ArraySet of t * t * t
type toplevel =
| Expr of t
| Defun of string * patt * ty * ty * t
| null | https://raw.githubusercontent.com/Tipoca/hlvm/5b6fe8d1ce95d5cfc130dd0e56f0f36bae9b2e0d/examples/compiler2/expr.ml | ocaml | type ty =
[ `Unit
| `Bool
| `Int
| `Float
| `Tuple of ty list
| `Array of ty ]
type cmp = [`Lt|`Le|`Eq|`Ne|`Ge|`Gt]
type patt =
| PVar of string
| PTup of patt list
type t =
| Unit
| Int of int
| Float of float
| String of string
| Var of string
| Apply of t * t
| Tuple of t list
| UnArith of [`Neg] * t
| BinArith of [`Add|`Sub|`Mul|`Div] * t * t
| Cmp of cmp * t * t
| If of t * t * t
| LetIn of patt * t * t
| ArrayGet of t * t
| ArraySet of t * t * t
type toplevel =
| Expr of t
| Defun of string * patt * ty * ty * t
| |
6e93acbfe2b4f53bff9c20e51e39db627e662c1f171037776001dcf3a14c8a27 | coq-community/coqffi | pp.ml | open Format
open Repr
open Conflict
let print_prefix_suffix = function _ :: _ -> true | [] -> false
let pp_list ?(enclose = print_prefix_suffix) ?(pp_prefix = fun _ _ -> ())
?(pp_suffix = fun _ _ -> ()) ~pp_sep pp fmt l =
if enclose l then (
pp_prefix fmt ();
pp_print_list ~pp_sep pp fmt l;
pp_suffix fmt ())
let not_empty = function _ :: _ -> true | _ -> false
let pp_if_not_empty pp fmt l = if not_empty l then pp fmt ()
let pp_arg_name fmt { position; _ } = fprintf fmt "x%d" position
let pp_arg_call fmt { position; kind } =
match kind with
| PositionedArg -> fprintf fmt "x%d" position
| LabeledArg name -> fprintf fmt "~%s:x%d" name position
| OptionalArg name -> fprintf fmt "?%s:x%d" name position
let pp_args_list fmt args_list =
pp_print_list ~pp_sep:pp_print_space
(fun fmt (argtyp, arg) ->
fprintf fmt "(%a : %a)" pp_arg_name argtyp pp_type_repr arg)
fmt args_list
let pp_type_args_list fmt type_args_list =
pp_print_list ~pp_sep:pp_print_space
(fun fmt arg -> fprintf fmt "(%s : Type)" arg)
fmt type_args_list
let pp_try_with pp fmt _ =
fprintf fmt "try Stdlib.Result.ok %a with e -> Stdlib.Result.error e" pp ()
let pp_fun_call ?(paren = true) fn_name args fmt _ =
fprintf fmt "%a%a%a%a"
(fun fmt l -> if not_empty l && paren then pp_print_string fmt "(")
args pp_ocaml_name fn_name
(pp_list
~pp_prefix:(fun fmt _ -> pp_print_string fmt " ")
~pp_sep:(fun fmt _ -> pp_print_string fmt " ")
pp_print_string)
args
(fun fmt l -> if not_empty l && paren then pp_print_string fmt ")")
args
| null | https://raw.githubusercontent.com/coq-community/coqffi/b76d6623a47dfc90ac4e7f8b7ee71fb101de1cee/src/pp.ml | ocaml | open Format
open Repr
open Conflict
let print_prefix_suffix = function _ :: _ -> true | [] -> false
let pp_list ?(enclose = print_prefix_suffix) ?(pp_prefix = fun _ _ -> ())
?(pp_suffix = fun _ _ -> ()) ~pp_sep pp fmt l =
if enclose l then (
pp_prefix fmt ();
pp_print_list ~pp_sep pp fmt l;
pp_suffix fmt ())
let not_empty = function _ :: _ -> true | _ -> false
let pp_if_not_empty pp fmt l = if not_empty l then pp fmt ()
let pp_arg_name fmt { position; _ } = fprintf fmt "x%d" position
let pp_arg_call fmt { position; kind } =
match kind with
| PositionedArg -> fprintf fmt "x%d" position
| LabeledArg name -> fprintf fmt "~%s:x%d" name position
| OptionalArg name -> fprintf fmt "?%s:x%d" name position
let pp_args_list fmt args_list =
pp_print_list ~pp_sep:pp_print_space
(fun fmt (argtyp, arg) ->
fprintf fmt "(%a : %a)" pp_arg_name argtyp pp_type_repr arg)
fmt args_list
let pp_type_args_list fmt type_args_list =
pp_print_list ~pp_sep:pp_print_space
(fun fmt arg -> fprintf fmt "(%s : Type)" arg)
fmt type_args_list
let pp_try_with pp fmt _ =
fprintf fmt "try Stdlib.Result.ok %a with e -> Stdlib.Result.error e" pp ()
let pp_fun_call ?(paren = true) fn_name args fmt _ =
fprintf fmt "%a%a%a%a"
(fun fmt l -> if not_empty l && paren then pp_print_string fmt "(")
args pp_ocaml_name fn_name
(pp_list
~pp_prefix:(fun fmt _ -> pp_print_string fmt " ")
~pp_sep:(fun fmt _ -> pp_print_string fmt " ")
pp_print_string)
args
(fun fmt l -> if not_empty l && paren then pp_print_string fmt ")")
args
| |
b3503d73f57c632fefedf4234cc301a1c3f2cf726c1dab3141326b1566ca34fe | lazy-cat-io/metaverse | solid.cljs | (ns heroicons.solid
(:require
["@heroicons/react/solid/esm" :as icons]
[reagent.core :as r]))
(def academic-cap-icon (r/adapt-react-class icons/AcademicCapIcon))
(def adjustments-icon (r/adapt-react-class icons/AdjustmentsIcon))
(def annotation-icon (r/adapt-react-class icons/AnnotationIcon))
(def archive-icon (r/adapt-react-class icons/ArchiveIcon))
(def arrow-circle-down-icon (r/adapt-react-class icons/ArrowCircleDownIcon))
(def arrow-circle-left-icon (r/adapt-react-class icons/ArrowCircleLeftIcon))
(def arrow-circle-right-icon (r/adapt-react-class icons/ArrowCircleRightIcon))
(def arrow-circle-up-icon (r/adapt-react-class icons/ArrowCircleUpIcon))
(def arrow-down-icon (r/adapt-react-class icons/ArrowDownIcon))
(def arrow-left-icon (r/adapt-react-class icons/ArrowLeftIcon))
(def arrow-narrow-down-icon (r/adapt-react-class icons/ArrowNarrowDownIcon))
(def arrow-narrow-left-icon (r/adapt-react-class icons/ArrowNarrowLeftIcon))
(def arrow-narrow-right-icon (r/adapt-react-class icons/ArrowNarrowRightIcon))
(def arrow-narrow-up-icon (r/adapt-react-class icons/ArrowNarrowUpIcon))
(def arrow-right-icon (r/adapt-react-class icons/ArrowRightIcon))
(def arrow-sm-down-icon (r/adapt-react-class icons/ArrowSmDownIcon))
(def arrow-sm-left-icon (r/adapt-react-class icons/ArrowSmLeftIcon))
(def arrow-sm-right-icon (r/adapt-react-class icons/ArrowSmRightIcon))
(def arrow-sm-up-icon (r/adapt-react-class icons/ArrowSmUpIcon))
(def arrow-up-icon (r/adapt-react-class icons/ArrowUpIcon))
(def arrows-expand-icon (r/adapt-react-class icons/ArrowsExpandIcon))
(def at-symbol-icon (r/adapt-react-class icons/AtSymbolIcon))
(def backspace-icon (r/adapt-react-class icons/BackspaceIcon))
(def badge-check-icon (r/adapt-react-class icons/BadgeCheckIcon))
(def ban-icon (r/adapt-react-class icons/BanIcon))
(def beaker-icon (r/adapt-react-class icons/BeakerIcon))
(def bell-icon (r/adapt-react-class icons/BellIcon))
(def book-open-icon (r/adapt-react-class icons/BookOpenIcon))
(def bookmark-alt-icon (r/adapt-react-class icons/BookmarkAltIcon))
(def bookmark-icon (r/adapt-react-class icons/BookmarkIcon))
(def briefcase-icon (r/adapt-react-class icons/BriefcaseIcon))
(def cake-icon (r/adapt-react-class icons/CakeIcon))
(def calculator-icon (r/adapt-react-class icons/CalculatorIcon))
(def calendar-icon (r/adapt-react-class icons/CalendarIcon))
(def camera-icon (r/adapt-react-class icons/CameraIcon))
(def cash-icon (r/adapt-react-class icons/CashIcon))
(def chart-bar-icon (r/adapt-react-class icons/ChartBarIcon))
(def chart-pie-icon (r/adapt-react-class icons/ChartPieIcon))
(def chart-square-bar-icon (r/adapt-react-class icons/ChartSquareBarIcon))
(def chat-alt-2-icon (r/adapt-react-class icons/ChatAlt2Icon))
(def chat-alt-icon (r/adapt-react-class icons/ChatAltIcon))
(def chat-icon (r/adapt-react-class icons/ChatIcon))
(def check-circle-icon (r/adapt-react-class icons/CheckCircleIcon))
(def check-icon (r/adapt-react-class icons/CheckIcon))
(def chevron-double-down-icon (r/adapt-react-class icons/ChevronDoubleDownIcon))
(def chevron-double-left-icon (r/adapt-react-class icons/ChevronDoubleLeftIcon))
(def chevron-double-right-icon (r/adapt-react-class icons/ChevronDoubleRightIcon))
(def chevron-double-up-icon (r/adapt-react-class icons/ChevronDoubleUpIcon))
(def chevron-down-icon (r/adapt-react-class icons/ChevronDownIcon))
(def chevron-left-icon (r/adapt-react-class icons/ChevronLeftIcon))
(def chevron-right-icon (r/adapt-react-class icons/ChevronRightIcon))
(def chevron-up-icon (r/adapt-react-class icons/ChevronUpIcon))
(def chip-icon (r/adapt-react-class icons/ChipIcon))
(def clipboard-check-icon (r/adapt-react-class icons/ClipboardCheckIcon))
(def clipboard-copy-icon (r/adapt-react-class icons/ClipboardCopyIcon))
(def clipboard-icon (r/adapt-react-class icons/ClipboardIcon))
(def clipboard-list-icon (r/adapt-react-class icons/ClipboardListIcon))
(def clock-icon (r/adapt-react-class icons/ClockIcon))
(def cloud-download-icon (r/adapt-react-class icons/CloudDownloadIcon))
(def cloud-icon (r/adapt-react-class icons/CloudIcon))
(def cloud-upload-icon (r/adapt-react-class icons/CloudUploadIcon))
(def code-icon (r/adapt-react-class icons/CodeIcon))
(def cog-icon (r/adapt-react-class icons/CogIcon))
(def collection-icon (r/adapt-react-class icons/CollectionIcon))
(def color-swatch-icon (r/adapt-react-class icons/ColorSwatchIcon))
(def credit-card-icon (r/adapt-react-class icons/CreditCardIcon))
(def cube-icon (r/adapt-react-class icons/CubeIcon))
(def cube-transparent-icon (r/adapt-react-class icons/CubeTransparentIcon))
(def currency-bangladeshi-icon (r/adapt-react-class icons/CurrencyBangladeshiIcon))
(def currency-dollar-icon (r/adapt-react-class icons/CurrencyDollarIcon))
(def currency-euro-icon (r/adapt-react-class icons/CurrencyEuroIcon))
(def currency-pound-icon (r/adapt-react-class icons/CurrencyPoundIcon))
(def currency-rupee-icon (r/adapt-react-class icons/CurrencyRupeeIcon))
(def currency-yen-icon (r/adapt-react-class icons/CurrencyYenIcon))
(def cursor-click-icon (r/adapt-react-class icons/CursorClickIcon))
(def database-icon (r/adapt-react-class icons/DatabaseIcon))
(def desktop-computer-icon (r/adapt-react-class icons/DesktopComputerIcon))
(def device-mobile-icon (r/adapt-react-class icons/DeviceMobileIcon))
(def device-tablet-icon (r/adapt-react-class icons/DeviceTabletIcon))
(def document-add-icon (r/adapt-react-class icons/DocumentAddIcon))
(def document-download-icon (r/adapt-react-class icons/DocumentDownloadIcon))
(def document-duplicate-icon (r/adapt-react-class icons/DocumentDuplicateIcon))
(def document-icon (r/adapt-react-class icons/DocumentIcon))
(def document-remove-icon (r/adapt-react-class icons/DocumentRemoveIcon))
(def document-report-icon (r/adapt-react-class icons/DocumentReportIcon))
(def document-search-icon (r/adapt-react-class icons/DocumentSearchIcon))
(def document-text-icon (r/adapt-react-class icons/DocumentTextIcon))
(def dots-circle-horizontal-icon (r/adapt-react-class icons/DotsCircleHorizontalIcon))
(def dots-horizontal-icon (r/adapt-react-class icons/DotsHorizontalIcon))
(def dots-vertical-icon (r/adapt-react-class icons/DotsVerticalIcon))
(def download-icon (r/adapt-react-class icons/DownloadIcon))
(def duplicate-icon (r/adapt-react-class icons/DuplicateIcon))
(def emoji-happy-icon (r/adapt-react-class icons/EmojiHappyIcon))
(def emoji-sad-icon (r/adapt-react-class icons/EmojiSadIcon))
(def exclamation-circle-icon (r/adapt-react-class icons/ExclamationCircleIcon))
(def exclamation-icon (r/adapt-react-class icons/ExclamationIcon))
(def external-link-icon (r/adapt-react-class icons/ExternalLinkIcon))
(def eye-icon (r/adapt-react-class icons/EyeIcon))
(def eye-off-icon (r/adapt-react-class icons/EyeOffIcon))
(def fast-forward-icon (r/adapt-react-class icons/FastForwardIcon))
(def film-icon (r/adapt-react-class icons/FilmIcon))
(def filter-icon (r/adapt-react-class icons/FilterIcon))
(def finger-print-icon (r/adapt-react-class icons/FingerPrintIcon))
(def fire-icon (r/adapt-react-class icons/FireIcon))
(def flag-icon (r/adapt-react-class icons/FlagIcon))
(def folder-add-icon (r/adapt-react-class icons/FolderAddIcon))
(def folder-download-icon (r/adapt-react-class icons/FolderDownloadIcon))
(def folder-icon (r/adapt-react-class icons/FolderIcon))
(def folder-open-icon (r/adapt-react-class icons/FolderOpenIcon))
(def folder-remove-icon (r/adapt-react-class icons/FolderRemoveIcon))
(def gift-icon (r/adapt-react-class icons/GiftIcon))
(def globe-alt-icon (r/adapt-react-class icons/GlobeAltIcon))
(def globe-icon (r/adapt-react-class icons/GlobeIcon))
(def hand-icon (r/adapt-react-class icons/HandIcon))
(def hashtag-icon (r/adapt-react-class icons/HashtagIcon))
(def heart-icon (r/adapt-react-class icons/HeartIcon))
(def home-icon (r/adapt-react-class icons/HomeIcon))
(def identification-icon (r/adapt-react-class icons/IdentificationIcon))
(def inbox-icon (r/adapt-react-class icons/InboxIcon))
(def inbox-in-icon (r/adapt-react-class icons/InboxInIcon))
(def information-circle-icon (r/adapt-react-class icons/InformationCircleIcon))
(def key-icon (r/adapt-react-class icons/KeyIcon))
(def library-icon (r/adapt-react-class icons/LibraryIcon))
(def light-bulb-icon (r/adapt-react-class icons/LightBulbIcon))
(def lightning-bolt-icon (r/adapt-react-class icons/LightningBoltIcon))
(def link-icon (r/adapt-react-class icons/LinkIcon))
(def location-marker-icon (r/adapt-react-class icons/LocationMarkerIcon))
(def lock-closed-icon (r/adapt-react-class icons/LockClosedIcon))
(def lock-open-icon (r/adapt-react-class icons/LockOpenIcon))
(def login-icon (r/adapt-react-class icons/LoginIcon))
(def logout-icon (r/adapt-react-class icons/LogoutIcon))
(def mail-icon (r/adapt-react-class icons/MailIcon))
(def mail-open-icon (r/adapt-react-class icons/MailOpenIcon))
(def map-icon (r/adapt-react-class icons/MapIcon))
(def menu-alt-1-icon (r/adapt-react-class icons/MenuAlt1Icon))
(def menu-alt-2-icon (r/adapt-react-class icons/MenuAlt2Icon))
(def menu-alt-3-icon (r/adapt-react-class icons/MenuAlt3Icon))
(def menu-alt-4-icon (r/adapt-react-class icons/MenuAlt4Icon))
(def menu-icon (r/adapt-react-class icons/MenuIcon))
(def microphone-icon (r/adapt-react-class icons/MicrophoneIcon))
(def minus-circle-icon (r/adapt-react-class icons/MinusCircleIcon))
(def minus-icon (r/adapt-react-class icons/MinusIcon))
(def minus-sm-icon (r/adapt-react-class icons/MinusSmIcon))
(def moon-icon (r/adapt-react-class icons/MoonIcon))
(def music-note-icon (r/adapt-react-class icons/MusicNoteIcon))
(def newspaper-icon (r/adapt-react-class icons/NewspaperIcon))
(def office-building-icon (r/adapt-react-class icons/OfficeBuildingIcon))
(def paper-airplane-icon (r/adapt-react-class icons/PaperAirplaneIcon))
(def paper-clip-icon (r/adapt-react-class icons/PaperClipIcon))
(def pause-icon (r/adapt-react-class icons/PauseIcon))
(def pencil-alt-icon (r/adapt-react-class icons/PencilAltIcon))
(def pencil-icon (r/adapt-react-class icons/PencilIcon))
(def phone-icon (r/adapt-react-class icons/PhoneIcon))
(def phone-incoming-icon (r/adapt-react-class icons/PhoneIncomingIcon))
(def phone-missed-call-icon (r/adapt-react-class icons/PhoneMissedCallIcon))
(def phone-outgoing-icon (r/adapt-react-class icons/PhoneOutgoingIcon))
(def photograph-icon (r/adapt-react-class icons/PhotographIcon))
(def play-icon (r/adapt-react-class icons/PlayIcon))
(def plus-circle-icon (r/adapt-react-class icons/PlusCircleIcon))
(def plus-icon (r/adapt-react-class icons/PlusIcon))
(def plus-sm-icon (r/adapt-react-class icons/PlusSmIcon))
(def presentation-chart-bar-icon (r/adapt-react-class icons/PresentationChartBarIcon))
(def presentation-chart-line-icon (r/adapt-react-class icons/PresentationChartLineIcon))
(def printer-icon (r/adapt-react-class icons/PrinterIcon))
(def puzzle-icon (r/adapt-react-class icons/PuzzleIcon))
(def qrcode-icon (r/adapt-react-class icons/QrcodeIcon))
(def question-mark-circle-icon (r/adapt-react-class icons/QuestionMarkCircleIcon))
(def receipt-refund-icon (r/adapt-react-class icons/ReceiptRefundIcon))
(def receipt-tax-icon (r/adapt-react-class icons/ReceiptTaxIcon))
(def refresh-icon (r/adapt-react-class icons/RefreshIcon))
(def reply-icon (r/adapt-react-class icons/ReplyIcon))
(def rewind-icon (r/adapt-react-class icons/RewindIcon))
(def rss-icon (r/adapt-react-class icons/RssIcon))
(def save-as-icon (r/adapt-react-class icons/SaveAsIcon))
(def save-icon (r/adapt-react-class icons/SaveIcon))
(def scale-icon (r/adapt-react-class icons/ScaleIcon))
(def scissors-icon (r/adapt-react-class icons/ScissorsIcon))
(def search-circle-icon (r/adapt-react-class icons/SearchCircleIcon))
(def search-icon (r/adapt-react-class icons/SearchIcon))
(def selector-icon (r/adapt-react-class icons/SelectorIcon))
(def server-icon (r/adapt-react-class icons/ServerIcon))
(def share-icon (r/adapt-react-class icons/ShareIcon))
(def shield-check-icon (r/adapt-react-class icons/ShieldCheckIcon))
(def shield-exclamation-icon (r/adapt-react-class icons/ShieldExclamationIcon))
(def shopping-bag-icon (r/adapt-react-class icons/ShoppingBagIcon))
(def shopping-cart-icon (r/adapt-react-class icons/ShoppingCartIcon))
(def sort-ascending-icon (r/adapt-react-class icons/SortAscendingIcon))
(def sort-descending-icon (r/adapt-react-class icons/SortDescendingIcon))
(def sparkles-icon (r/adapt-react-class icons/SparklesIcon))
(def speakerphone-icon (r/adapt-react-class icons/SpeakerphoneIcon))
(def star-icon (r/adapt-react-class icons/StarIcon))
(def status-offline-icon (r/adapt-react-class icons/StatusOfflineIcon))
(def status-online-icon (r/adapt-react-class icons/StatusOnlineIcon))
(def stop-icon (r/adapt-react-class icons/StopIcon))
(def sun-icon (r/adapt-react-class icons/SunIcon))
(def support-icon (r/adapt-react-class icons/SupportIcon))
(def switch-horizontal-icon (r/adapt-react-class icons/SwitchHorizontalIcon))
(def switch-vertical-icon (r/adapt-react-class icons/SwitchVerticalIcon))
(def table-icon (r/adapt-react-class icons/TableIcon))
(def tag-icon (r/adapt-react-class icons/TagIcon))
(def template-icon (r/adapt-react-class icons/TemplateIcon))
(def terminal-icon (r/adapt-react-class icons/TerminalIcon))
(def thumb-down-icon (r/adapt-react-class icons/ThumbDownIcon))
(def thumb-up-icon (r/adapt-react-class icons/ThumbUpIcon))
(def ticket-icon (r/adapt-react-class icons/TicketIcon))
(def translate-icon (r/adapt-react-class icons/TranslateIcon))
(def trash-icon (r/adapt-react-class icons/TrashIcon))
(def trending-down-icon (r/adapt-react-class icons/TrendingDownIcon))
(def trending-up-icon (r/adapt-react-class icons/TrendingUpIcon))
(def truck-icon (r/adapt-react-class icons/TruckIcon))
(def upload-icon (r/adapt-react-class icons/UploadIcon))
(def user-add-icon (r/adapt-react-class icons/UserAddIcon))
(def user-circle-icon (r/adapt-react-class icons/UserCircleIcon))
(def user-group-icon (r/adapt-react-class icons/UserGroupIcon))
(def user-icon (r/adapt-react-class icons/UserIcon))
(def user-remove-icon (r/adapt-react-class icons/UserRemoveIcon))
(def users-icon (r/adapt-react-class icons/UsersIcon))
(def variable-icon (r/adapt-react-class icons/VariableIcon))
(def video-camera-icon (r/adapt-react-class icons/VideoCameraIcon))
(def view-boards-icon (r/adapt-react-class icons/ViewBoardsIcon))
(def view-grid-add-icon (r/adapt-react-class icons/ViewGridAddIcon))
(def view-grid-icon (r/adapt-react-class icons/ViewGridIcon))
(def view-list-icon (r/adapt-react-class icons/ViewListIcon))
(def volume-off-icon (r/adapt-react-class icons/VolumeOffIcon))
(def volume-up-icon (r/adapt-react-class icons/VolumeUpIcon))
(def wifi-icon (r/adapt-react-class icons/WifiIcon))
(def xcircle-icon (r/adapt-react-class icons/XCircleIcon))
(def xicon (r/adapt-react-class icons/XIcon))
(def zoom-in-icon (r/adapt-react-class icons/ZoomInIcon))
(def zoom-out-icon (r/adapt-react-class icons/ZoomOutIcon))
| null | https://raw.githubusercontent.com/lazy-cat-io/metaverse/da076f1c802984930acc6a2a9b4ef77e95a8d6ab/src/main/clojure/heroicons/solid.cljs | clojure | (ns heroicons.solid
(:require
["@heroicons/react/solid/esm" :as icons]
[reagent.core :as r]))
(def academic-cap-icon (r/adapt-react-class icons/AcademicCapIcon))
(def adjustments-icon (r/adapt-react-class icons/AdjustmentsIcon))
(def annotation-icon (r/adapt-react-class icons/AnnotationIcon))
(def archive-icon (r/adapt-react-class icons/ArchiveIcon))
(def arrow-circle-down-icon (r/adapt-react-class icons/ArrowCircleDownIcon))
(def arrow-circle-left-icon (r/adapt-react-class icons/ArrowCircleLeftIcon))
(def arrow-circle-right-icon (r/adapt-react-class icons/ArrowCircleRightIcon))
(def arrow-circle-up-icon (r/adapt-react-class icons/ArrowCircleUpIcon))
(def arrow-down-icon (r/adapt-react-class icons/ArrowDownIcon))
(def arrow-left-icon (r/adapt-react-class icons/ArrowLeftIcon))
(def arrow-narrow-down-icon (r/adapt-react-class icons/ArrowNarrowDownIcon))
(def arrow-narrow-left-icon (r/adapt-react-class icons/ArrowNarrowLeftIcon))
(def arrow-narrow-right-icon (r/adapt-react-class icons/ArrowNarrowRightIcon))
(def arrow-narrow-up-icon (r/adapt-react-class icons/ArrowNarrowUpIcon))
(def arrow-right-icon (r/adapt-react-class icons/ArrowRightIcon))
(def arrow-sm-down-icon (r/adapt-react-class icons/ArrowSmDownIcon))
(def arrow-sm-left-icon (r/adapt-react-class icons/ArrowSmLeftIcon))
(def arrow-sm-right-icon (r/adapt-react-class icons/ArrowSmRightIcon))
(def arrow-sm-up-icon (r/adapt-react-class icons/ArrowSmUpIcon))
(def arrow-up-icon (r/adapt-react-class icons/ArrowUpIcon))
(def arrows-expand-icon (r/adapt-react-class icons/ArrowsExpandIcon))
(def at-symbol-icon (r/adapt-react-class icons/AtSymbolIcon))
(def backspace-icon (r/adapt-react-class icons/BackspaceIcon))
(def badge-check-icon (r/adapt-react-class icons/BadgeCheckIcon))
(def ban-icon (r/adapt-react-class icons/BanIcon))
(def beaker-icon (r/adapt-react-class icons/BeakerIcon))
(def bell-icon (r/adapt-react-class icons/BellIcon))
(def book-open-icon (r/adapt-react-class icons/BookOpenIcon))
(def bookmark-alt-icon (r/adapt-react-class icons/BookmarkAltIcon))
(def bookmark-icon (r/adapt-react-class icons/BookmarkIcon))
(def briefcase-icon (r/adapt-react-class icons/BriefcaseIcon))
(def cake-icon (r/adapt-react-class icons/CakeIcon))
(def calculator-icon (r/adapt-react-class icons/CalculatorIcon))
(def calendar-icon (r/adapt-react-class icons/CalendarIcon))
(def camera-icon (r/adapt-react-class icons/CameraIcon))
(def cash-icon (r/adapt-react-class icons/CashIcon))
(def chart-bar-icon (r/adapt-react-class icons/ChartBarIcon))
(def chart-pie-icon (r/adapt-react-class icons/ChartPieIcon))
(def chart-square-bar-icon (r/adapt-react-class icons/ChartSquareBarIcon))
(def chat-alt-2-icon (r/adapt-react-class icons/ChatAlt2Icon))
(def chat-alt-icon (r/adapt-react-class icons/ChatAltIcon))
(def chat-icon (r/adapt-react-class icons/ChatIcon))
(def check-circle-icon (r/adapt-react-class icons/CheckCircleIcon))
(def check-icon (r/adapt-react-class icons/CheckIcon))
(def chevron-double-down-icon (r/adapt-react-class icons/ChevronDoubleDownIcon))
(def chevron-double-left-icon (r/adapt-react-class icons/ChevronDoubleLeftIcon))
(def chevron-double-right-icon (r/adapt-react-class icons/ChevronDoubleRightIcon))
(def chevron-double-up-icon (r/adapt-react-class icons/ChevronDoubleUpIcon))
(def chevron-down-icon (r/adapt-react-class icons/ChevronDownIcon))
(def chevron-left-icon (r/adapt-react-class icons/ChevronLeftIcon))
(def chevron-right-icon (r/adapt-react-class icons/ChevronRightIcon))
(def chevron-up-icon (r/adapt-react-class icons/ChevronUpIcon))
(def chip-icon (r/adapt-react-class icons/ChipIcon))
(def clipboard-check-icon (r/adapt-react-class icons/ClipboardCheckIcon))
(def clipboard-copy-icon (r/adapt-react-class icons/ClipboardCopyIcon))
(def clipboard-icon (r/adapt-react-class icons/ClipboardIcon))
(def clipboard-list-icon (r/adapt-react-class icons/ClipboardListIcon))
(def clock-icon (r/adapt-react-class icons/ClockIcon))
(def cloud-download-icon (r/adapt-react-class icons/CloudDownloadIcon))
(def cloud-icon (r/adapt-react-class icons/CloudIcon))
(def cloud-upload-icon (r/adapt-react-class icons/CloudUploadIcon))
(def code-icon (r/adapt-react-class icons/CodeIcon))
(def cog-icon (r/adapt-react-class icons/CogIcon))
(def collection-icon (r/adapt-react-class icons/CollectionIcon))
(def color-swatch-icon (r/adapt-react-class icons/ColorSwatchIcon))
(def credit-card-icon (r/adapt-react-class icons/CreditCardIcon))
(def cube-icon (r/adapt-react-class icons/CubeIcon))
(def cube-transparent-icon (r/adapt-react-class icons/CubeTransparentIcon))
(def currency-bangladeshi-icon (r/adapt-react-class icons/CurrencyBangladeshiIcon))
(def currency-dollar-icon (r/adapt-react-class icons/CurrencyDollarIcon))
(def currency-euro-icon (r/adapt-react-class icons/CurrencyEuroIcon))
(def currency-pound-icon (r/adapt-react-class icons/CurrencyPoundIcon))
(def currency-rupee-icon (r/adapt-react-class icons/CurrencyRupeeIcon))
(def currency-yen-icon (r/adapt-react-class icons/CurrencyYenIcon))
(def cursor-click-icon (r/adapt-react-class icons/CursorClickIcon))
(def database-icon (r/adapt-react-class icons/DatabaseIcon))
(def desktop-computer-icon (r/adapt-react-class icons/DesktopComputerIcon))
(def device-mobile-icon (r/adapt-react-class icons/DeviceMobileIcon))
(def device-tablet-icon (r/adapt-react-class icons/DeviceTabletIcon))
(def document-add-icon (r/adapt-react-class icons/DocumentAddIcon))
(def document-download-icon (r/adapt-react-class icons/DocumentDownloadIcon))
(def document-duplicate-icon (r/adapt-react-class icons/DocumentDuplicateIcon))
(def document-icon (r/adapt-react-class icons/DocumentIcon))
(def document-remove-icon (r/adapt-react-class icons/DocumentRemoveIcon))
(def document-report-icon (r/adapt-react-class icons/DocumentReportIcon))
(def document-search-icon (r/adapt-react-class icons/DocumentSearchIcon))
(def document-text-icon (r/adapt-react-class icons/DocumentTextIcon))
(def dots-circle-horizontal-icon (r/adapt-react-class icons/DotsCircleHorizontalIcon))
(def dots-horizontal-icon (r/adapt-react-class icons/DotsHorizontalIcon))
(def dots-vertical-icon (r/adapt-react-class icons/DotsVerticalIcon))
(def download-icon (r/adapt-react-class icons/DownloadIcon))
(def duplicate-icon (r/adapt-react-class icons/DuplicateIcon))
(def emoji-happy-icon (r/adapt-react-class icons/EmojiHappyIcon))
(def emoji-sad-icon (r/adapt-react-class icons/EmojiSadIcon))
(def exclamation-circle-icon (r/adapt-react-class icons/ExclamationCircleIcon))
(def exclamation-icon (r/adapt-react-class icons/ExclamationIcon))
(def external-link-icon (r/adapt-react-class icons/ExternalLinkIcon))
(def eye-icon (r/adapt-react-class icons/EyeIcon))
(def eye-off-icon (r/adapt-react-class icons/EyeOffIcon))
(def fast-forward-icon (r/adapt-react-class icons/FastForwardIcon))
(def film-icon (r/adapt-react-class icons/FilmIcon))
(def filter-icon (r/adapt-react-class icons/FilterIcon))
(def finger-print-icon (r/adapt-react-class icons/FingerPrintIcon))
(def fire-icon (r/adapt-react-class icons/FireIcon))
(def flag-icon (r/adapt-react-class icons/FlagIcon))
(def folder-add-icon (r/adapt-react-class icons/FolderAddIcon))
(def folder-download-icon (r/adapt-react-class icons/FolderDownloadIcon))
(def folder-icon (r/adapt-react-class icons/FolderIcon))
(def folder-open-icon (r/adapt-react-class icons/FolderOpenIcon))
(def folder-remove-icon (r/adapt-react-class icons/FolderRemoveIcon))
(def gift-icon (r/adapt-react-class icons/GiftIcon))
(def globe-alt-icon (r/adapt-react-class icons/GlobeAltIcon))
(def globe-icon (r/adapt-react-class icons/GlobeIcon))
(def hand-icon (r/adapt-react-class icons/HandIcon))
(def hashtag-icon (r/adapt-react-class icons/HashtagIcon))
(def heart-icon (r/adapt-react-class icons/HeartIcon))
(def home-icon (r/adapt-react-class icons/HomeIcon))
(def identification-icon (r/adapt-react-class icons/IdentificationIcon))
(def inbox-icon (r/adapt-react-class icons/InboxIcon))
(def inbox-in-icon (r/adapt-react-class icons/InboxInIcon))
(def information-circle-icon (r/adapt-react-class icons/InformationCircleIcon))
(def key-icon (r/adapt-react-class icons/KeyIcon))
(def library-icon (r/adapt-react-class icons/LibraryIcon))
(def light-bulb-icon (r/adapt-react-class icons/LightBulbIcon))
(def lightning-bolt-icon (r/adapt-react-class icons/LightningBoltIcon))
(def link-icon (r/adapt-react-class icons/LinkIcon))
(def location-marker-icon (r/adapt-react-class icons/LocationMarkerIcon))
(def lock-closed-icon (r/adapt-react-class icons/LockClosedIcon))
(def lock-open-icon (r/adapt-react-class icons/LockOpenIcon))
(def login-icon (r/adapt-react-class icons/LoginIcon))
(def logout-icon (r/adapt-react-class icons/LogoutIcon))
(def mail-icon (r/adapt-react-class icons/MailIcon))
(def mail-open-icon (r/adapt-react-class icons/MailOpenIcon))
(def map-icon (r/adapt-react-class icons/MapIcon))
(def menu-alt-1-icon (r/adapt-react-class icons/MenuAlt1Icon))
(def menu-alt-2-icon (r/adapt-react-class icons/MenuAlt2Icon))
(def menu-alt-3-icon (r/adapt-react-class icons/MenuAlt3Icon))
(def menu-alt-4-icon (r/adapt-react-class icons/MenuAlt4Icon))
(def menu-icon (r/adapt-react-class icons/MenuIcon))
(def microphone-icon (r/adapt-react-class icons/MicrophoneIcon))
(def minus-circle-icon (r/adapt-react-class icons/MinusCircleIcon))
(def minus-icon (r/adapt-react-class icons/MinusIcon))
(def minus-sm-icon (r/adapt-react-class icons/MinusSmIcon))
(def moon-icon (r/adapt-react-class icons/MoonIcon))
(def music-note-icon (r/adapt-react-class icons/MusicNoteIcon))
(def newspaper-icon (r/adapt-react-class icons/NewspaperIcon))
(def office-building-icon (r/adapt-react-class icons/OfficeBuildingIcon))
(def paper-airplane-icon (r/adapt-react-class icons/PaperAirplaneIcon))
(def paper-clip-icon (r/adapt-react-class icons/PaperClipIcon))
(def pause-icon (r/adapt-react-class icons/PauseIcon))
(def pencil-alt-icon (r/adapt-react-class icons/PencilAltIcon))
(def pencil-icon (r/adapt-react-class icons/PencilIcon))
(def phone-icon (r/adapt-react-class icons/PhoneIcon))
(def phone-incoming-icon (r/adapt-react-class icons/PhoneIncomingIcon))
(def phone-missed-call-icon (r/adapt-react-class icons/PhoneMissedCallIcon))
(def phone-outgoing-icon (r/adapt-react-class icons/PhoneOutgoingIcon))
(def photograph-icon (r/adapt-react-class icons/PhotographIcon))
(def play-icon (r/adapt-react-class icons/PlayIcon))
(def plus-circle-icon (r/adapt-react-class icons/PlusCircleIcon))
(def plus-icon (r/adapt-react-class icons/PlusIcon))
(def plus-sm-icon (r/adapt-react-class icons/PlusSmIcon))
(def presentation-chart-bar-icon (r/adapt-react-class icons/PresentationChartBarIcon))
(def presentation-chart-line-icon (r/adapt-react-class icons/PresentationChartLineIcon))
(def printer-icon (r/adapt-react-class icons/PrinterIcon))
(def puzzle-icon (r/adapt-react-class icons/PuzzleIcon))
(def qrcode-icon (r/adapt-react-class icons/QrcodeIcon))
(def question-mark-circle-icon (r/adapt-react-class icons/QuestionMarkCircleIcon))
(def receipt-refund-icon (r/adapt-react-class icons/ReceiptRefundIcon))
(def receipt-tax-icon (r/adapt-react-class icons/ReceiptTaxIcon))
(def refresh-icon (r/adapt-react-class icons/RefreshIcon))
(def reply-icon (r/adapt-react-class icons/ReplyIcon))
(def rewind-icon (r/adapt-react-class icons/RewindIcon))
(def rss-icon (r/adapt-react-class icons/RssIcon))
(def save-as-icon (r/adapt-react-class icons/SaveAsIcon))
(def save-icon (r/adapt-react-class icons/SaveIcon))
(def scale-icon (r/adapt-react-class icons/ScaleIcon))
(def scissors-icon (r/adapt-react-class icons/ScissorsIcon))
(def search-circle-icon (r/adapt-react-class icons/SearchCircleIcon))
(def search-icon (r/adapt-react-class icons/SearchIcon))
(def selector-icon (r/adapt-react-class icons/SelectorIcon))
(def server-icon (r/adapt-react-class icons/ServerIcon))
(def share-icon (r/adapt-react-class icons/ShareIcon))
(def shield-check-icon (r/adapt-react-class icons/ShieldCheckIcon))
(def shield-exclamation-icon (r/adapt-react-class icons/ShieldExclamationIcon))
(def shopping-bag-icon (r/adapt-react-class icons/ShoppingBagIcon))
(def shopping-cart-icon (r/adapt-react-class icons/ShoppingCartIcon))
(def sort-ascending-icon (r/adapt-react-class icons/SortAscendingIcon))
(def sort-descending-icon (r/adapt-react-class icons/SortDescendingIcon))
(def sparkles-icon (r/adapt-react-class icons/SparklesIcon))
(def speakerphone-icon (r/adapt-react-class icons/SpeakerphoneIcon))
(def star-icon (r/adapt-react-class icons/StarIcon))
(def status-offline-icon (r/adapt-react-class icons/StatusOfflineIcon))
(def status-online-icon (r/adapt-react-class icons/StatusOnlineIcon))
(def stop-icon (r/adapt-react-class icons/StopIcon))
(def sun-icon (r/adapt-react-class icons/SunIcon))
(def support-icon (r/adapt-react-class icons/SupportIcon))
(def switch-horizontal-icon (r/adapt-react-class icons/SwitchHorizontalIcon))
(def switch-vertical-icon (r/adapt-react-class icons/SwitchVerticalIcon))
(def table-icon (r/adapt-react-class icons/TableIcon))
(def tag-icon (r/adapt-react-class icons/TagIcon))
(def template-icon (r/adapt-react-class icons/TemplateIcon))
(def terminal-icon (r/adapt-react-class icons/TerminalIcon))
(def thumb-down-icon (r/adapt-react-class icons/ThumbDownIcon))
(def thumb-up-icon (r/adapt-react-class icons/ThumbUpIcon))
(def ticket-icon (r/adapt-react-class icons/TicketIcon))
(def translate-icon (r/adapt-react-class icons/TranslateIcon))
(def trash-icon (r/adapt-react-class icons/TrashIcon))
(def trending-down-icon (r/adapt-react-class icons/TrendingDownIcon))
(def trending-up-icon (r/adapt-react-class icons/TrendingUpIcon))
(def truck-icon (r/adapt-react-class icons/TruckIcon))
(def upload-icon (r/adapt-react-class icons/UploadIcon))
(def user-add-icon (r/adapt-react-class icons/UserAddIcon))
(def user-circle-icon (r/adapt-react-class icons/UserCircleIcon))
(def user-group-icon (r/adapt-react-class icons/UserGroupIcon))
(def user-icon (r/adapt-react-class icons/UserIcon))
(def user-remove-icon (r/adapt-react-class icons/UserRemoveIcon))
(def users-icon (r/adapt-react-class icons/UsersIcon))
(def variable-icon (r/adapt-react-class icons/VariableIcon))
(def video-camera-icon (r/adapt-react-class icons/VideoCameraIcon))
(def view-boards-icon (r/adapt-react-class icons/ViewBoardsIcon))
(def view-grid-add-icon (r/adapt-react-class icons/ViewGridAddIcon))
(def view-grid-icon (r/adapt-react-class icons/ViewGridIcon))
(def view-list-icon (r/adapt-react-class icons/ViewListIcon))
(def volume-off-icon (r/adapt-react-class icons/VolumeOffIcon))
(def volume-up-icon (r/adapt-react-class icons/VolumeUpIcon))
(def wifi-icon (r/adapt-react-class icons/WifiIcon))
(def xcircle-icon (r/adapt-react-class icons/XCircleIcon))
(def xicon (r/adapt-react-class icons/XIcon))
(def zoom-in-icon (r/adapt-react-class icons/ZoomInIcon))
(def zoom-out-icon (r/adapt-react-class icons/ZoomOutIcon))
| |
6ca7cf5836d6f4a5f7ff1244643f2e980bf13663b113c7223a9b4b4b02c2528f | sadiqj/ocaml-esp32 | t090-acc4.ml | open Lib;;
let x = true in
let y = false in
let z = false in
let a = false in
let b = false in
();
if not x then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 CONST1
10 PUSHCONST0
11 PUSHCONST0
12 PUSHCONST0
13 PUSHCONST0
14 PUSHCONST0
15 ACC4
16 BOOLNOT
17 BRANCHIFNOT 24
19 GETGLOBAL Not_found
21 MAKEBLOCK1 0
23 RAISE
24 POP 5
26 ATOM0
27
29 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 CONST1
10 PUSHCONST0
11 PUSHCONST0
12 PUSHCONST0
13 PUSHCONST0
14 PUSHCONST0
15 ACC4
16 BOOLNOT
17 BRANCHIFNOT 24
19 GETGLOBAL Not_found
21 MAKEBLOCK1 0
23 RAISE
24 POP 5
26 ATOM0
27 SETGLOBAL T090-acc4
29 STOP
**)
| null | https://raw.githubusercontent.com/sadiqj/ocaml-esp32/33aad4ca2becb9701eb90d779c1b1183aefeb578/testsuite/tests/tool-ocaml/t090-acc4.ml | ocaml | open Lib;;
let x = true in
let y = false in
let z = false in
let a = false in
let b = false in
();
if not x then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 CONST1
10 PUSHCONST0
11 PUSHCONST0
12 PUSHCONST0
13 PUSHCONST0
14 PUSHCONST0
15 ACC4
16 BOOLNOT
17 BRANCHIFNOT 24
19 GETGLOBAL Not_found
21 MAKEBLOCK1 0
23 RAISE
24 POP 5
26 ATOM0
27
29 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 CONST1
10 PUSHCONST0
11 PUSHCONST0
12 PUSHCONST0
13 PUSHCONST0
14 PUSHCONST0
15 ACC4
16 BOOLNOT
17 BRANCHIFNOT 24
19 GETGLOBAL Not_found
21 MAKEBLOCK1 0
23 RAISE
24 POP 5
26 ATOM0
27 SETGLOBAL T090-acc4
29 STOP
**)
| |
937254b44d00b50c4b922f5f45e4d45f9cbdd50f3460d24cd03af9ef7986cc6a | gsakkas/rite | 20060302-17:56:00-27ff2306cdb017964c28aea1d4f4f156.seminal.ml | let rec reverseHelp len place str =
let firstChar = str.[place] in
str
let rec reverseHelper str =
let temp = str in
temp.[0] = 'z'
let reverse str =
let currChar = str.[0] in
str
let _ = print_string(reverseHelper "fast") | null | https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/features/data/seminal/20060302-17%3A56%3A00-27ff2306cdb017964c28aea1d4f4f156.seminal.ml | ocaml | let rec reverseHelp len place str =
let firstChar = str.[place] in
str
let rec reverseHelper str =
let temp = str in
temp.[0] = 'z'
let reverse str =
let currChar = str.[0] in
str
let _ = print_string(reverseHelper "fast") | |
d98e7a0d89062791a788324dd61c24fc000a505634bb2a1e4c4c5c7dda1e7500 | chrovis/cljam | sorter_test.clj | (ns cljam.algo.sorter-test
(:require [clojure.test :refer [deftest is use-fixtures]]
[cljam.test-common
:refer [deftest-slow
deftest-remote
disable-log-fixture
get-shuffled-test-sam
spit-sam-for-test
spit-bam-for-test
slurp-sam-for-test
slurp-bam-for-test
with-before-after
prepare-cache!
prepare-cavia!
clean-cache!
not-throw?
check-sort-order
qname-sorted?
coord-sorted?
temp-dir
test-sam-file
test-bam-file
medium-bam-file
large-bam-file]]
[cljam.io.sam :as sam]
[cljam.algo.sorter :as sorter]
[cljam.io.sam.util.header :as header])
(:import [java.io Closeable]))
(use-fixtures :once disable-log-fixture)
(def tmp-coordinate-sorted-sam-file (str temp-dir "/" "tmp.coordinate.sorted.sam"))
(def tmp-coordinate-sorted-bam-file (str temp-dir "/" "tmp.coordinate.sorted.bam"))
(def tmp-queryname-sorted-sam-file (str temp-dir "/" "tmp.queryname.sorted.sam"))
(def tmp-queryname-sorted-bam-file (str temp-dir "/" "tmp.queryname.sorted.bam"))
(def tmp-shuffled-sam-file (str temp-dir "/" "tmp.shuffled.sam"))
(def tmp-shuffled-bam-file (str temp-dir "/" "tmp.shuffled.bam"))
(def tmp-coordinate-sorted-sam-sam-file (str temp-dir "/" "tmp.coordinate.sorted.2.sam.sam"))
(def tmp-coordinate-sorted-sam-bam-file (str temp-dir "/" "tmp.coordinate.sorted.2.sam.bam"))
(def tmp-coordinate-sorted-bam-bam-file (str temp-dir "/" "tmp.coordinate.sorted.2.bam.bam"))
(def tmp-coordinate-sorted-bam-sam-file (str temp-dir "/" "tmp.coordinate.sorted.2.bam.sam"))
(def tmp-queryname-sorted-sam-file-2 (str temp-dir "/" "tmp.queryname.sorted.2.sam"))
(def tmp-queryname-sorted-bam-file-2 (str temp-dir "/" "tmp.queryname.sorted.2.bam"))
(defn- prepare-shuffled-files!
[]
(let [x (get-shuffled-test-sam)]
(spit-sam-for-test tmp-shuffled-sam-file x)
(spit-bam-for-test tmp-shuffled-bam-file x)))
(defn- with-reader
[target-fn src-file & [dst-file]]
(let [src-rdr (sam/reader src-file)
dst-wtr (when dst-file (sam/writer dst-file))]
(if-not (nil? dst-wtr)
(with-open [src ^Closeable src-rdr
dst ^Closeable dst-wtr] (target-fn src dst))
(with-open [src ^Closeable src-rdr] (target-fn src)))))
(deftest sort-test-files
(with-before-after {:before (prepare-cache!)
:after (clean-cache!)}
;; tests by test-sam-file and test-bam-file
(is (not-throw? (with-reader sorter/sort-by-pos test-sam-file tmp-coordinate-sorted-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-pos test-bam-file tmp-coordinate-sorted-bam-file)))
(is (not-throw? (with-reader sorter/sort-by-qname test-sam-file tmp-queryname-sorted-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-qname test-bam-file tmp-queryname-sorted-bam-file)))
(is (not (with-reader sorter/sorted? test-sam-file)))
(is (not (with-reader sorter/sorted? test-bam-file)))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-sam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-sam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-bam-file))
(is (= (with-reader sorter/sort-order test-sam-file)
header/order-unknown))
(is (= (with-reader sorter/sort-order test-bam-file)
header/order-unknown))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-sam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-bam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-sam-file)
header/order-queryname))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-bam-file)
header/order-queryname))
(is (qname-sorted? tmp-queryname-sorted-sam-file))
(is (qname-sorted? tmp-queryname-sorted-bam-file))))
(deftest about-sorting-shuffled-files
(with-before-after {:before (do (prepare-cache!)
(prepare-shuffled-files!))
:after (clean-cache!)}
;; tests by shuffled files (its may sorted by chance)
(is (not-throw? (with-reader sorter/sort-by-pos tmp-shuffled-sam-file tmp-coordinate-sorted-sam-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-pos tmp-shuffled-sam-file tmp-coordinate-sorted-sam-bam-file)))
(is (not-throw? (with-reader sorter/sort-by-pos tmp-shuffled-bam-file tmp-coordinate-sorted-bam-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-pos tmp-shuffled-bam-file tmp-coordinate-sorted-bam-bam-file)))
(is (not-throw? (with-reader sorter/sort-by-qname tmp-shuffled-sam-file tmp-queryname-sorted-sam-file-2)))
(is (not-throw? (with-reader sorter/sort-by-qname tmp-shuffled-bam-file tmp-queryname-sorted-bam-file-2)))
(is (not (with-reader sorter/sorted? tmp-shuffled-sam-file)))
(is (not (with-reader sorter/sorted? tmp-shuffled-bam-file)))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-sam-sam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-sam-bam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-sam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-bam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-sam-file-2))
(is (with-reader sorter/sorted? tmp-queryname-sorted-bam-file-2))
(is (get #{:queryname :coordinate :unsorted :unknown}
(with-reader sorter/sort-order tmp-shuffled-sam-file)))
(is (get #{:queryname :coordinate :unsorted :unknown}
(with-reader sorter/sort-order tmp-shuffled-bam-file)))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-sam-sam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-sam-bam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-bam-sam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-bam-bam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-sam-file-2)
header/order-queryname))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-bam-file-2)
header/order-queryname))
;; check sorting order
(is (not-throw? (check-sort-order (slurp-sam-for-test tmp-coordinate-sorted-sam-sam-file))))
(is (not-throw? (check-sort-order (slurp-sam-for-test tmp-coordinate-sorted-bam-sam-file))))
(is (not-throw? (check-sort-order (slurp-bam-for-test tmp-coordinate-sorted-sam-bam-file))))
(is (not-throw? (check-sort-order (slurp-bam-for-test tmp-coordinate-sorted-bam-bam-file))))
(is (coord-sorted? tmp-coordinate-sorted-sam-sam-file))
(is (coord-sorted? tmp-coordinate-sorted-sam-bam-file))
(is (coord-sorted? tmp-coordinate-sorted-bam-sam-file))
(is (coord-sorted? tmp-coordinate-sorted-bam-bam-file))
(is (qname-sorted? tmp-queryname-sorted-sam-file-2))
(is (qname-sorted? tmp-queryname-sorted-bam-file-2))
;; compare generated files
(is (= (slurp-sam-for-test tmp-coordinate-sorted-sam-sam-file)
(slurp-bam-for-test tmp-coordinate-sorted-sam-bam-file)
(slurp-sam-for-test tmp-coordinate-sorted-bam-sam-file)
(slurp-bam-for-test tmp-coordinate-sorted-bam-bam-file)))
(is (= (slurp-sam-for-test tmp-queryname-sorted-sam-file-2)
(slurp-bam-for-test tmp-queryname-sorted-bam-file-2)))))
(deftest about-sorting-small-chunks
(with-before-after {:before (do (prepare-cache!)
(prepare-shuffled-files!))
:after (clean-cache!)}
;; coordinate
(is (not-throw?
(with-open [r (sam/reader tmp-shuffled-bam-file)
w (sam/writer tmp-coordinate-sorted-bam-bam-file)]
(sorter/sort-by-pos r w {:chunk-size 3}))))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-bam-file))
(is (not-throw? (check-sort-order (slurp-bam-for-test tmp-coordinate-sorted-bam-bam-file))))
(is (coord-sorted? tmp-coordinate-sorted-bam-bam-file))
(is (not-throw?
(with-open [r (sam/reader tmp-shuffled-sam-file)
w (sam/writer tmp-coordinate-sorted-sam-sam-file)]
(sorter/sort-by-pos r w {:chunk-size 3 :cache-fmt :sam}))))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-sam-sam-file))
(is (not-throw? (check-sort-order (slurp-sam-for-test tmp-coordinate-sorted-sam-sam-file))))
(is (coord-sorted? tmp-coordinate-sorted-sam-sam-file))
;; queryname
(is (not-throw?
(with-open [r (sam/reader tmp-shuffled-bam-file)
w (sam/writer tmp-queryname-sorted-bam-file-2)]
(sorter/sort-by-qname r w {:chunk-size 3}))))
(with-reader sorter/sorted? tmp-queryname-sorted-bam-file-2)
(is (qname-sorted? tmp-queryname-sorted-bam-file-2))
(is (not-throw?
(with-open [r (sam/reader tmp-shuffled-bam-file)
w (sam/writer tmp-queryname-sorted-sam-file-2)]
(sorter/sort-by-qname r w {:chunk-size 3 :cache-fmt :sam}))))
(with-reader sorter/sorted? tmp-queryname-sorted-sam-file-2)
(is (qname-sorted? tmp-queryname-sorted-sam-file-2))))
(deftest-slow about-sorting-medium-file
(with-before-after {:before (prepare-cache!)
:after (clean-cache!)}
(is (not-throw? (with-reader sorter/sort-by-pos medium-bam-file tmp-coordinate-sorted-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-pos medium-bam-file tmp-coordinate-sorted-bam-file)))
(is (not-throw? (with-reader sorter/sort-by-qname medium-bam-file tmp-queryname-sorted-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-qname medium-bam-file tmp-queryname-sorted-bam-file)))
(is (not (with-reader sorter/sorted? medium-bam-file)))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-sam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-sam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-bam-file))
(is (= (with-reader sorter/sort-order medium-bam-file) header/order-unknown))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-sam-file) header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-bam-file) header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-sam-file) header/order-queryname))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-bam-file) header/order-queryname))
;; check sorting order
(is (not-throw? (check-sort-order (slurp-sam-for-test tmp-coordinate-sorted-sam-file))))
(is (not-throw? (check-sort-order (slurp-bam-for-test tmp-coordinate-sorted-bam-file))))
(is (coord-sorted? tmp-coordinate-sorted-sam-file))
(is (coord-sorted? tmp-coordinate-sorted-bam-file))
(is (qname-sorted? tmp-queryname-sorted-sam-file))
(is (qname-sorted? tmp-queryname-sorted-bam-file))))
(deftest-remote about-sorting-large-file
(with-before-after {:before (do (prepare-cavia!)
(prepare-cache!))
:after (clean-cache!)}
(is (not-throw?
(with-open [r (sam/reader large-bam-file)
w (sam/writer tmp-coordinate-sorted-bam-file)]
Use small chunk size to avoid OOM
(sorter/sort-by-pos r w {:chunk-size 100000}))))
(is (not-throw?
(with-open [r (sam/reader large-bam-file)
w (sam/writer tmp-queryname-sorted-bam-file)]
Use small chunk size to avoid OOM
(sorter/sort-by-qname r w {:chunk-size 100000}))))
(is (with-reader sorter/sorted? large-bam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-bam-file))
(is (= (with-reader sorter/sort-order large-bam-file) header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-bam-file) header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-bam-file) header/order-queryname))
;; check sorting order
(is (coord-sorted? tmp-coordinate-sorted-bam-file))
(is (qname-sorted? tmp-queryname-sorted-bam-file))))
| null | https://raw.githubusercontent.com/chrovis/cljam/2b8e7386765be8efdbbbb4f18dbc52447f4a08af/test/cljam/algo/sorter_test.clj | clojure | tests by test-sam-file and test-bam-file
tests by shuffled files (its may sorted by chance)
check sorting order
compare generated files
coordinate
queryname
check sorting order
check sorting order | (ns cljam.algo.sorter-test
(:require [clojure.test :refer [deftest is use-fixtures]]
[cljam.test-common
:refer [deftest-slow
deftest-remote
disable-log-fixture
get-shuffled-test-sam
spit-sam-for-test
spit-bam-for-test
slurp-sam-for-test
slurp-bam-for-test
with-before-after
prepare-cache!
prepare-cavia!
clean-cache!
not-throw?
check-sort-order
qname-sorted?
coord-sorted?
temp-dir
test-sam-file
test-bam-file
medium-bam-file
large-bam-file]]
[cljam.io.sam :as sam]
[cljam.algo.sorter :as sorter]
[cljam.io.sam.util.header :as header])
(:import [java.io Closeable]))
(use-fixtures :once disable-log-fixture)
(def tmp-coordinate-sorted-sam-file (str temp-dir "/" "tmp.coordinate.sorted.sam"))
(def tmp-coordinate-sorted-bam-file (str temp-dir "/" "tmp.coordinate.sorted.bam"))
(def tmp-queryname-sorted-sam-file (str temp-dir "/" "tmp.queryname.sorted.sam"))
(def tmp-queryname-sorted-bam-file (str temp-dir "/" "tmp.queryname.sorted.bam"))
(def tmp-shuffled-sam-file (str temp-dir "/" "tmp.shuffled.sam"))
(def tmp-shuffled-bam-file (str temp-dir "/" "tmp.shuffled.bam"))
(def tmp-coordinate-sorted-sam-sam-file (str temp-dir "/" "tmp.coordinate.sorted.2.sam.sam"))
(def tmp-coordinate-sorted-sam-bam-file (str temp-dir "/" "tmp.coordinate.sorted.2.sam.bam"))
(def tmp-coordinate-sorted-bam-bam-file (str temp-dir "/" "tmp.coordinate.sorted.2.bam.bam"))
(def tmp-coordinate-sorted-bam-sam-file (str temp-dir "/" "tmp.coordinate.sorted.2.bam.sam"))
(def tmp-queryname-sorted-sam-file-2 (str temp-dir "/" "tmp.queryname.sorted.2.sam"))
(def tmp-queryname-sorted-bam-file-2 (str temp-dir "/" "tmp.queryname.sorted.2.bam"))
(defn- prepare-shuffled-files!
[]
(let [x (get-shuffled-test-sam)]
(spit-sam-for-test tmp-shuffled-sam-file x)
(spit-bam-for-test tmp-shuffled-bam-file x)))
(defn- with-reader
[target-fn src-file & [dst-file]]
(let [src-rdr (sam/reader src-file)
dst-wtr (when dst-file (sam/writer dst-file))]
(if-not (nil? dst-wtr)
(with-open [src ^Closeable src-rdr
dst ^Closeable dst-wtr] (target-fn src dst))
(with-open [src ^Closeable src-rdr] (target-fn src)))))
(deftest sort-test-files
(with-before-after {:before (prepare-cache!)
:after (clean-cache!)}
(is (not-throw? (with-reader sorter/sort-by-pos test-sam-file tmp-coordinate-sorted-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-pos test-bam-file tmp-coordinate-sorted-bam-file)))
(is (not-throw? (with-reader sorter/sort-by-qname test-sam-file tmp-queryname-sorted-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-qname test-bam-file tmp-queryname-sorted-bam-file)))
(is (not (with-reader sorter/sorted? test-sam-file)))
(is (not (with-reader sorter/sorted? test-bam-file)))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-sam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-sam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-bam-file))
(is (= (with-reader sorter/sort-order test-sam-file)
header/order-unknown))
(is (= (with-reader sorter/sort-order test-bam-file)
header/order-unknown))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-sam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-bam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-sam-file)
header/order-queryname))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-bam-file)
header/order-queryname))
(is (qname-sorted? tmp-queryname-sorted-sam-file))
(is (qname-sorted? tmp-queryname-sorted-bam-file))))
(deftest about-sorting-shuffled-files
(with-before-after {:before (do (prepare-cache!)
(prepare-shuffled-files!))
:after (clean-cache!)}
(is (not-throw? (with-reader sorter/sort-by-pos tmp-shuffled-sam-file tmp-coordinate-sorted-sam-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-pos tmp-shuffled-sam-file tmp-coordinate-sorted-sam-bam-file)))
(is (not-throw? (with-reader sorter/sort-by-pos tmp-shuffled-bam-file tmp-coordinate-sorted-bam-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-pos tmp-shuffled-bam-file tmp-coordinate-sorted-bam-bam-file)))
(is (not-throw? (with-reader sorter/sort-by-qname tmp-shuffled-sam-file tmp-queryname-sorted-sam-file-2)))
(is (not-throw? (with-reader sorter/sort-by-qname tmp-shuffled-bam-file tmp-queryname-sorted-bam-file-2)))
(is (not (with-reader sorter/sorted? tmp-shuffled-sam-file)))
(is (not (with-reader sorter/sorted? tmp-shuffled-bam-file)))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-sam-sam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-sam-bam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-sam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-bam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-sam-file-2))
(is (with-reader sorter/sorted? tmp-queryname-sorted-bam-file-2))
(is (get #{:queryname :coordinate :unsorted :unknown}
(with-reader sorter/sort-order tmp-shuffled-sam-file)))
(is (get #{:queryname :coordinate :unsorted :unknown}
(with-reader sorter/sort-order tmp-shuffled-bam-file)))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-sam-sam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-sam-bam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-bam-sam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-bam-bam-file)
header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-sam-file-2)
header/order-queryname))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-bam-file-2)
header/order-queryname))
(is (not-throw? (check-sort-order (slurp-sam-for-test tmp-coordinate-sorted-sam-sam-file))))
(is (not-throw? (check-sort-order (slurp-sam-for-test tmp-coordinate-sorted-bam-sam-file))))
(is (not-throw? (check-sort-order (slurp-bam-for-test tmp-coordinate-sorted-sam-bam-file))))
(is (not-throw? (check-sort-order (slurp-bam-for-test tmp-coordinate-sorted-bam-bam-file))))
(is (coord-sorted? tmp-coordinate-sorted-sam-sam-file))
(is (coord-sorted? tmp-coordinate-sorted-sam-bam-file))
(is (coord-sorted? tmp-coordinate-sorted-bam-sam-file))
(is (coord-sorted? tmp-coordinate-sorted-bam-bam-file))
(is (qname-sorted? tmp-queryname-sorted-sam-file-2))
(is (qname-sorted? tmp-queryname-sorted-bam-file-2))
(is (= (slurp-sam-for-test tmp-coordinate-sorted-sam-sam-file)
(slurp-bam-for-test tmp-coordinate-sorted-sam-bam-file)
(slurp-sam-for-test tmp-coordinate-sorted-bam-sam-file)
(slurp-bam-for-test tmp-coordinate-sorted-bam-bam-file)))
(is (= (slurp-sam-for-test tmp-queryname-sorted-sam-file-2)
(slurp-bam-for-test tmp-queryname-sorted-bam-file-2)))))
(deftest about-sorting-small-chunks
(with-before-after {:before (do (prepare-cache!)
(prepare-shuffled-files!))
:after (clean-cache!)}
(is (not-throw?
(with-open [r (sam/reader tmp-shuffled-bam-file)
w (sam/writer tmp-coordinate-sorted-bam-bam-file)]
(sorter/sort-by-pos r w {:chunk-size 3}))))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-bam-file))
(is (not-throw? (check-sort-order (slurp-bam-for-test tmp-coordinate-sorted-bam-bam-file))))
(is (coord-sorted? tmp-coordinate-sorted-bam-bam-file))
(is (not-throw?
(with-open [r (sam/reader tmp-shuffled-sam-file)
w (sam/writer tmp-coordinate-sorted-sam-sam-file)]
(sorter/sort-by-pos r w {:chunk-size 3 :cache-fmt :sam}))))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-sam-sam-file))
(is (not-throw? (check-sort-order (slurp-sam-for-test tmp-coordinate-sorted-sam-sam-file))))
(is (coord-sorted? tmp-coordinate-sorted-sam-sam-file))
(is (not-throw?
(with-open [r (sam/reader tmp-shuffled-bam-file)
w (sam/writer tmp-queryname-sorted-bam-file-2)]
(sorter/sort-by-qname r w {:chunk-size 3}))))
(with-reader sorter/sorted? tmp-queryname-sorted-bam-file-2)
(is (qname-sorted? tmp-queryname-sorted-bam-file-2))
(is (not-throw?
(with-open [r (sam/reader tmp-shuffled-bam-file)
w (sam/writer tmp-queryname-sorted-sam-file-2)]
(sorter/sort-by-qname r w {:chunk-size 3 :cache-fmt :sam}))))
(with-reader sorter/sorted? tmp-queryname-sorted-sam-file-2)
(is (qname-sorted? tmp-queryname-sorted-sam-file-2))))
(deftest-slow about-sorting-medium-file
(with-before-after {:before (prepare-cache!)
:after (clean-cache!)}
(is (not-throw? (with-reader sorter/sort-by-pos medium-bam-file tmp-coordinate-sorted-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-pos medium-bam-file tmp-coordinate-sorted-bam-file)))
(is (not-throw? (with-reader sorter/sort-by-qname medium-bam-file tmp-queryname-sorted-sam-file)))
(is (not-throw? (with-reader sorter/sort-by-qname medium-bam-file tmp-queryname-sorted-bam-file)))
(is (not (with-reader sorter/sorted? medium-bam-file)))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-sam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-sam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-bam-file))
(is (= (with-reader sorter/sort-order medium-bam-file) header/order-unknown))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-sam-file) header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-bam-file) header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-sam-file) header/order-queryname))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-bam-file) header/order-queryname))
(is (not-throw? (check-sort-order (slurp-sam-for-test tmp-coordinate-sorted-sam-file))))
(is (not-throw? (check-sort-order (slurp-bam-for-test tmp-coordinate-sorted-bam-file))))
(is (coord-sorted? tmp-coordinate-sorted-sam-file))
(is (coord-sorted? tmp-coordinate-sorted-bam-file))
(is (qname-sorted? tmp-queryname-sorted-sam-file))
(is (qname-sorted? tmp-queryname-sorted-bam-file))))
(deftest-remote about-sorting-large-file
(with-before-after {:before (do (prepare-cavia!)
(prepare-cache!))
:after (clean-cache!)}
(is (not-throw?
(with-open [r (sam/reader large-bam-file)
w (sam/writer tmp-coordinate-sorted-bam-file)]
Use small chunk size to avoid OOM
(sorter/sort-by-pos r w {:chunk-size 100000}))))
(is (not-throw?
(with-open [r (sam/reader large-bam-file)
w (sam/writer tmp-queryname-sorted-bam-file)]
Use small chunk size to avoid OOM
(sorter/sort-by-qname r w {:chunk-size 100000}))))
(is (with-reader sorter/sorted? large-bam-file))
(is (with-reader sorter/sorted? tmp-coordinate-sorted-bam-file))
(is (with-reader sorter/sorted? tmp-queryname-sorted-bam-file))
(is (= (with-reader sorter/sort-order large-bam-file) header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-coordinate-sorted-bam-file) header/order-coordinate))
(is (= (with-reader sorter/sort-order tmp-queryname-sorted-bam-file) header/order-queryname))
(is (coord-sorted? tmp-coordinate-sorted-bam-file))
(is (qname-sorted? tmp-queryname-sorted-bam-file))))
|
28a801b85b432969599786386c56d65ad23d1d11b6bb8509e2ed2d48f7eba7e5 | bluddy/rails | segment.ml | open Containers
type id = int
[@@deriving yojson]
module Map = struct
type t = {
mutable last: int;
map: (id, int) Utils.Hashtbl.t; (* segment id to count *)
}[@@deriving yojson]
let make () = { last=0; map=Hashtbl.create 10; }
let get_id v =
Hashtbl.replace v.map v.last 0;
let ret = v.last in
v.last <- succ v.last;
ret
let incr_train v idx = Hashtbl.incr v.map idx
let decr_train v idx = Hashtbl.decr v.map idx
end
| null | https://raw.githubusercontent.com/bluddy/rails/20e753887bc6db4b4bd087a1b78584f5b53b45ad/bin/backend/segment.ml | ocaml | segment id to count | open Containers
type id = int
[@@deriving yojson]
module Map = struct
type t = {
mutable last: int;
}[@@deriving yojson]
let make () = { last=0; map=Hashtbl.create 10; }
let get_id v =
Hashtbl.replace v.map v.last 0;
let ret = v.last in
v.last <- succ v.last;
ret
let incr_train v idx = Hashtbl.incr v.map idx
let decr_train v idx = Hashtbl.decr v.map idx
end
|
d243a5eb5ece24a18c13da55c7cd69965d997b909d472866fbcb762254a0d9be | txkaduo/weixin-mp-sdk | PublicPlatform.hs | # LANGUAGE CPP #
module WeiXin.PublicPlatform
( module WeiXin.PublicPlatform.Error
, module WeiXin.PublicPlatform.Types
, module WeiXin.PublicPlatform.Class
, module WeiXin.PublicPlatform.WS
#if defined(VERSION_acid_state)
, module WeiXin.PublicPlatform.Acid
#endif
, module WeiXin.PublicPlatform.Security
, module WeiXin.PublicPlatform.Media
, module WeiXin.PublicPlatform.Material
, module WeiXin.PublicPlatform.AutoReplyRules
, module WeiXin.PublicPlatform.Message
, module WeiXin.PublicPlatform.Message.Template
, module WeiXin.PublicPlatform.InMsgHandler
, module WeiXin.PublicPlatform.Menu
, module WeiXin.PublicPlatform.CS
, module WeiXin.PublicPlatform.QRCode
, module WeiXin.PublicPlatform.EndUser
, module WeiXin.PublicPlatform.EndUser.Tag
, module WeiXin.PublicPlatform.Propagate
, module WeiXin.PublicPlatform.Yesod.Utils
, module WeiXin.PublicPlatform.Yesod.Site
, module WeiXin.PublicPlatform.Yesod.Types
, module WeiXin.PublicPlatform.Yesod.Model
, module WeiXin.PublicPlatform.Yesod.Site.Function
, module WeiXin.PublicPlatform.Yesod.Site.Data
, module WeiXin.PublicPlatform.BgWork
, module WeiXin . PublicPlatform . Utils
, module WeiXin.PublicPlatform.Misc
, module WeiXin.PublicPlatform.Conversation
, module WeiXin.PublicPlatform.Conversation.Yesod
, module WeiXin.PublicPlatform.Conversation.Message
, module WeiXin . PublicPlatform . Conversation . TextParser
, module WeiXin.PublicPlatform.Center
, module WeiXin.PublicPlatform.OAuth
, module WeiXin.PublicPlatform.JS
, module WeiXin.PublicPlatform.Pay
, module WeiXin.PublicPlatform.ThirdParty
#if defined(CLOUD_HASKELL)
, module WeiXin.PublicPlatform.CloudHaskell
#endif
) where
import WeiXin.PublicPlatform.Error
import WeiXin.PublicPlatform.Types
import WeiXin.PublicPlatform.Class
import WeiXin.PublicPlatform.WS
#if defined(VERSION_acid_state)
import WeiXin.PublicPlatform.Acid
#endif
import WeiXin.PublicPlatform.Security
import WeiXin.PublicPlatform.Media
import WeiXin.PublicPlatform.Material
import WeiXin.PublicPlatform.AutoReplyRules
import WeiXin.PublicPlatform.Message
import WeiXin.PublicPlatform.Message.Template
import WeiXin.PublicPlatform.InMsgHandler
import WeiXin.PublicPlatform.Menu
import WeiXin.PublicPlatform.CS
import WeiXin.PublicPlatform.QRCode
import WeiXin.PublicPlatform.EndUser
import WeiXin.PublicPlatform.EndUser.Tag
import WeiXin.PublicPlatform.Propagate
import WeiXin.PublicPlatform.Yesod.Utils
import WeiXin.PublicPlatform.Yesod.Site
import WeiXin.PublicPlatform.Yesod.Types
import WeiXin.PublicPlatform.Yesod.Model
import WeiXin.PublicPlatform.Yesod.Site.Function
import WeiXin.PublicPlatform.Yesod.Site.Data
import WeiXin.PublicPlatform.BgWork
import WeiXin . PublicPlatform . Utils
import WeiXin.PublicPlatform.Misc
import WeiXin.PublicPlatform.Conversation
import WeiXin.PublicPlatform.Conversation.Yesod
import WeiXin.PublicPlatform.Conversation.Message
import WeiXin . PublicPlatform . Conversation . TextParser
import WeiXin.PublicPlatform.Center
import WeiXin.PublicPlatform.OAuth
import WeiXin.PublicPlatform.JS
import WeiXin.PublicPlatform.Pay
import WeiXin.PublicPlatform.ThirdParty
#if defined(CLOUD_HASKELL)
import WeiXin.PublicPlatform.CloudHaskell
#endif
| null | https://raw.githubusercontent.com/txkaduo/weixin-mp-sdk/77abe31d06ccf266aad358373b9cde34b222b305/WeiXin/PublicPlatform.hs | haskell | # LANGUAGE CPP #
module WeiXin.PublicPlatform
( module WeiXin.PublicPlatform.Error
, module WeiXin.PublicPlatform.Types
, module WeiXin.PublicPlatform.Class
, module WeiXin.PublicPlatform.WS
#if defined(VERSION_acid_state)
, module WeiXin.PublicPlatform.Acid
#endif
, module WeiXin.PublicPlatform.Security
, module WeiXin.PublicPlatform.Media
, module WeiXin.PublicPlatform.Material
, module WeiXin.PublicPlatform.AutoReplyRules
, module WeiXin.PublicPlatform.Message
, module WeiXin.PublicPlatform.Message.Template
, module WeiXin.PublicPlatform.InMsgHandler
, module WeiXin.PublicPlatform.Menu
, module WeiXin.PublicPlatform.CS
, module WeiXin.PublicPlatform.QRCode
, module WeiXin.PublicPlatform.EndUser
, module WeiXin.PublicPlatform.EndUser.Tag
, module WeiXin.PublicPlatform.Propagate
, module WeiXin.PublicPlatform.Yesod.Utils
, module WeiXin.PublicPlatform.Yesod.Site
, module WeiXin.PublicPlatform.Yesod.Types
, module WeiXin.PublicPlatform.Yesod.Model
, module WeiXin.PublicPlatform.Yesod.Site.Function
, module WeiXin.PublicPlatform.Yesod.Site.Data
, module WeiXin.PublicPlatform.BgWork
, module WeiXin . PublicPlatform . Utils
, module WeiXin.PublicPlatform.Misc
, module WeiXin.PublicPlatform.Conversation
, module WeiXin.PublicPlatform.Conversation.Yesod
, module WeiXin.PublicPlatform.Conversation.Message
, module WeiXin . PublicPlatform . Conversation . TextParser
, module WeiXin.PublicPlatform.Center
, module WeiXin.PublicPlatform.OAuth
, module WeiXin.PublicPlatform.JS
, module WeiXin.PublicPlatform.Pay
, module WeiXin.PublicPlatform.ThirdParty
#if defined(CLOUD_HASKELL)
, module WeiXin.PublicPlatform.CloudHaskell
#endif
) where
import WeiXin.PublicPlatform.Error
import WeiXin.PublicPlatform.Types
import WeiXin.PublicPlatform.Class
import WeiXin.PublicPlatform.WS
#if defined(VERSION_acid_state)
import WeiXin.PublicPlatform.Acid
#endif
import WeiXin.PublicPlatform.Security
import WeiXin.PublicPlatform.Media
import WeiXin.PublicPlatform.Material
import WeiXin.PublicPlatform.AutoReplyRules
import WeiXin.PublicPlatform.Message
import WeiXin.PublicPlatform.Message.Template
import WeiXin.PublicPlatform.InMsgHandler
import WeiXin.PublicPlatform.Menu
import WeiXin.PublicPlatform.CS
import WeiXin.PublicPlatform.QRCode
import WeiXin.PublicPlatform.EndUser
import WeiXin.PublicPlatform.EndUser.Tag
import WeiXin.PublicPlatform.Propagate
import WeiXin.PublicPlatform.Yesod.Utils
import WeiXin.PublicPlatform.Yesod.Site
import WeiXin.PublicPlatform.Yesod.Types
import WeiXin.PublicPlatform.Yesod.Model
import WeiXin.PublicPlatform.Yesod.Site.Function
import WeiXin.PublicPlatform.Yesod.Site.Data
import WeiXin.PublicPlatform.BgWork
import WeiXin . PublicPlatform . Utils
import WeiXin.PublicPlatform.Misc
import WeiXin.PublicPlatform.Conversation
import WeiXin.PublicPlatform.Conversation.Yesod
import WeiXin.PublicPlatform.Conversation.Message
import WeiXin . PublicPlatform . Conversation . TextParser
import WeiXin.PublicPlatform.Center
import WeiXin.PublicPlatform.OAuth
import WeiXin.PublicPlatform.JS
import WeiXin.PublicPlatform.Pay
import WeiXin.PublicPlatform.ThirdParty
#if defined(CLOUD_HASKELL)
import WeiXin.PublicPlatform.CloudHaskell
#endif
| |
f036e3e2faa278fbf5946b345d24aab6784390f0c4726d3e3f1be5acc3854805 | JoelSanchez/ventas | category_list.cljs | (ns ventas.devcards.category-list
(:require
[devcards.core :refer-macros [defcard-rg]]
[ventas.components.category-list :as components.category-list]))
(defn- category-list-wrapper []
[components.category-list/category-list
(for [n (range 4)]
{:id (gensym)
:name (random-uuid)
:description "A sample description"})])
(defcard-rg regular-category-list
"Regular category list"
[category-list-wrapper]
{:inspect-data true})
| null | https://raw.githubusercontent.com/JoelSanchez/ventas/dc8fc8ff9f63dfc8558ecdaacfc4983903b8e9a1/dev/cljs/ventas/devcards/category_list.cljs | clojure | (ns ventas.devcards.category-list
(:require
[devcards.core :refer-macros [defcard-rg]]
[ventas.components.category-list :as components.category-list]))
(defn- category-list-wrapper []
[components.category-list/category-list
(for [n (range 4)]
{:id (gensym)
:name (random-uuid)
:description "A sample description"})])
(defcard-rg regular-category-list
"Regular category list"
[category-list-wrapper]
{:inspect-data true})
| |
ead148948e870fb74e7d1587a31c6427f5f5fcbfb73488aad137ae28ad8f1fa0 | tweag/ormolu | stack-header-2-out.hs | #!/usr/bin/env stack
{- stack
script
--resolver lts-6.25
--package turtle
--package "stm async"
--package http-client,http-conduit
-}
{-# LANGUAGE OverloadedStrings #-}
main = return ()
| null | https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/module-header/stack-header-2-out.hs | haskell | stack
script
--resolver lts-6.25
--package turtle
--package "stm async"
--package http-client,http-conduit
# LANGUAGE OverloadedStrings # | #!/usr/bin/env stack
main = return ()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.