_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
b9dc94c028d1d79a93ae701a2cb86300d3776fff66db8352801a2e94a6176272
sacerdot/CovidMonitoring
utils.erl
-module(utils). -export([sleep/1, set_subtract/2, get_random/2, make_probability/1, check_service/1]). sleep(T) -> receive after T -> ok end. L1 -- L2 set_subtract(L1, L2) -> lists:filter(fun(X) -> not lists:member(X, L2) end, L1). get_random(L, N) -> F = fun(_, _, 0, Result) -> Result; (_, [], _, Result) -> Result; (_, _, Number, _) when Number < 0 -> []; (Fun, List, Number, []) -> E = lists:nth(rand:uniform(length(List)), List), Fun(Fun, set_subtract(List, [E]), Number - 1, [E]); (Fun, List, Number, Result) -> E = lists:nth(rand:uniform(length(List)), List), Fun(Fun, set_subtract(List, [E]), Number - 1, [E | Result]) end, F(F, L, N, []). make_probability(X) -> fun() -> rand:uniform(100) =< X end. Check server and ospedale check_service(X) -> PidService = global:whereis_name(X), case PidService of undefined -> io:format("~p non trovato ~n", [X]), case X of ospedale -> exit(ospedale_not_registered); server -> exit(server_not_registered) end; P -> P end.
null
https://raw.githubusercontent.com/sacerdot/CovidMonitoring/fe969cd51869bbe6479da509c9a6ab21d43e6d11/BartoliniFapohundaGuerra/src/utils.erl
erlang
-module(utils). -export([sleep/1, set_subtract/2, get_random/2, make_probability/1, check_service/1]). sleep(T) -> receive after T -> ok end. L1 -- L2 set_subtract(L1, L2) -> lists:filter(fun(X) -> not lists:member(X, L2) end, L1). get_random(L, N) -> F = fun(_, _, 0, Result) -> Result; (_, [], _, Result) -> Result; (_, _, Number, _) when Number < 0 -> []; (Fun, List, Number, []) -> E = lists:nth(rand:uniform(length(List)), List), Fun(Fun, set_subtract(List, [E]), Number - 1, [E]); (Fun, List, Number, Result) -> E = lists:nth(rand:uniform(length(List)), List), Fun(Fun, set_subtract(List, [E]), Number - 1, [E | Result]) end, F(F, L, N, []). make_probability(X) -> fun() -> rand:uniform(100) =< X end. Check server and ospedale check_service(X) -> PidService = global:whereis_name(X), case PidService of undefined -> io:format("~p non trovato ~n", [X]), case X of ospedale -> exit(ospedale_not_registered); server -> exit(server_not_registered) end; P -> P end.
55f777cb80836ad179c456c63eb06d587d15beaeb7eadc4ffa822e58740bba51
nfrisby/coxswain
T9999.hs
Possible GHC bug ? -- Yes , indeed : # LANGUAGE TypeFamilyDependencies # import Data.Proxy (Proxy(Proxy)) type family T (a :: *) = (r :: *) | r -> a where f :: ( T a ~ T b ) => a -> b f x = x
null
https://raw.githubusercontent.com/nfrisby/coxswain/bfd5777964a5b4ba64e1bcc4cf18df1c9d8fc558/coxswain/test/ill-typed/T9999.hs
haskell
Possible GHC bug ? Yes , indeed : # LANGUAGE TypeFamilyDependencies # import Data.Proxy (Proxy(Proxy)) type family T (a :: *) = (r :: *) | r -> a where f :: ( T a ~ T b ) => a -> b f x = x
5cb5e6562032462e1b5415f6336c7a4d983bbdca241c642e2aa60b8090ab1c7e
mfp/ocsiblog
run_tests.ml
Copyright ( C ) 2009 < > open OUnit let tests = "All tests" >::: [ Test_simple_markup.tests; ] let () = ignore (run_test_tt_main tests)
null
https://raw.githubusercontent.com/mfp/ocsiblog/e5048a971f3e4289855214418338ac032f11ea4c/run_tests.ml
ocaml
Copyright ( C ) 2009 < > open OUnit let tests = "All tests" >::: [ Test_simple_markup.tests; ] let () = ignore (run_test_tt_main tests)
01009cc6f0a903467d0c51980d73e5106869772fcfd8820f1b17ac2205c5b09c
ufo5260987423/scheme-langserver
test-shrinker.sps
#!/usr/bin/env scheme-script -*- mode : scheme ; coding : utf-8 -*- ! # Copyright ( c ) 2022 WANG SPDX - License - Identifier : MIT #!r6rs (import ( rnrs ( 6 ) ) (chezscheme) (srfi :64 testing) (scheme-langserver virtual-file-system file-node) (scheme-langserver analysis workspace) (scheme-langserver analysis package-manager akku) (scheme-langserver analysis dependency shrinker) (scheme-langserver analysis dependency file-linkage)) (test-begin "test shrink-paths") (let* ([root-file-node (init-virtual-file-system (current-directory) '() akku-acceptable-file?)] [root-library-node (init-library-node root-file-node)] [file-linkage (init-file-linkage root-library-node)] [paths (get-init-reference-path file-linkage)]) (test-equal #f (zero? (length (shrink-paths file-linkage paths))))) (test-end) (exit (if (zero? (test-runner-fail-count (test-runner-get))) 0 1))
null
https://raw.githubusercontent.com/ufo5260987423/scheme-langserver/1d76523142a7b963a18bcb54fc71a9b52edcaa52/tests/analysis/dependency/test-shrinker.sps
scheme
coding : utf-8 -*- ! #
#!/usr/bin/env scheme-script Copyright ( c ) 2022 WANG SPDX - License - Identifier : MIT #!r6rs (import ( rnrs ( 6 ) ) (chezscheme) (srfi :64 testing) (scheme-langserver virtual-file-system file-node) (scheme-langserver analysis workspace) (scheme-langserver analysis package-manager akku) (scheme-langserver analysis dependency shrinker) (scheme-langserver analysis dependency file-linkage)) (test-begin "test shrink-paths") (let* ([root-file-node (init-virtual-file-system (current-directory) '() akku-acceptable-file?)] [root-library-node (init-library-node root-file-node)] [file-linkage (init-file-linkage root-library-node)] [paths (get-init-reference-path file-linkage)]) (test-equal #f (zero? (length (shrink-paths file-linkage paths))))) (test-end) (exit (if (zero? (test-runner-fail-count (test-runner-get))) 0 1))
92402f97c40d92d99d87863c2b9dc89e7c768cea347664b55db9787e08164827
fadbadml-dev/FADBADml
interval.ml
(**************************************************************************) (* *) (* FADBADml *) (* *) OCaml port by and Based on FADBAD++ , written by and (* *) Copyright 2019 - 2020 (* *) This file is distributed under the terms of the CeCILL - C license . (* *) (**************************************************************************) type scalar = float type elt = { min: scalar; max: scalar; } type t = { mutable min: scalar; mutable max: scalar; } let is_point i = i.min = i.max let is_positive i = 0. < i.min let is_negative i = i.max < 0. let is_null i = i.min = 0. && i.max = 0. let is_not_positive i = i.max <= 0. let is_not_negative i = 0. <= i.min let create () = { min = Float.nan; max = Float.nan; } let make_point f = { min = f; max = f; } let make_float f = make_point f let make_bounds min max = {min; max} let make (i : elt) : t = make_bounds i.min i.max let integer i = make_point (float i) let get (i : t) : elt = { min = i.min; max = i.max; } let ( !! ) = get let get_min i = i.min let get_max i = i.max let get_min_max i = (i.min, i.max) let radius i = let min, max = get_min_max i in (max -. min) /. 2. let print2d x y _ = let () = Printf.printf "%f\t%f\n" x.min y.min in let () = Printf.printf "%f\t%f\n" x.max y.min in let () = Printf.printf "%f\t%f\n" x.max y.max in let () = Printf.printf "%f\t%f\n" x.min y.max in let () = Printf.printf "%f\t%f\n" x.min y.min in () let to_string i = Printf.sprintf "[%f,%f]" i.min i.max let string_of_scalar = string_of_float let string_of_elt (i : elt) = Printf.sprintf "[%f,%f]" i.min i.max let copy i = { min = i.min; max = i.max; } let deepcopy = copy let zero () = integer 0 let one () = integer 1 let two () = integer 2 let scale i f = make { min = i.min *. f; max = i.max *. f; } let translate i f = make { min = i.min +. f; max = i.max +. f; } let ( ~+ ) = copy let ( ~- ) i = make { min = -. i.max; max = -. i.min; } let ( + ) i1 i2 = { min = i1.min +. i2.min; max = i1.max +. i2.max; } let ( += ) i1 i2 = let () = i1.min <- i1.min +. i2.min in let () = i1.max <- i1.max +. i2.max in i1 let ( - ) i1 i2 = { min = i1.min -. i2.max; max = i1.max -. i2.min; } let ( -= ) i1 i2 = let () = i1.min <- i1.min -. i2.max in let () = i1.max <- i1.max -. i2.min in i1 let ( * ) i1 i2 = let a = i1.min *. i2.min in let b = i1.min *. i2.max in let c = i1.max *. i2.min in let d = i1.max *. i2.max in { min = min (min a b) (min c d); max = max (max a b) (max c d); } let ( *= ) i1 i2 = let i = i1 * i2 in let () = i1.min <- i.min in let () = i1.max <- i.max in i1 let inv i = match i.min = 0., i.max = 0. with | true, true -> begin Printf.eprintf "Interval: zero division"; exit 1 end | true, false -> { min = 1. /. i.max; max = Float.infinity; } | false, true -> { min = Float.neg_infinity; max = 1. /. i.min; } | false, false -> begin if i.min <= 0. && 0. <= i.max then { min = Float.neg_infinity; max = Float.infinity; } else { min = 1. /. i.max; max = 1. /. i.min; } end let ( / ) i1 i2 = i1 * (inv i2) let ( /= ) i1 i2 = let i = i1 / i2 in let () = i1.min <- i.min in let () = i1.max <- i.max in i1 let sqr i = if i.max <= 0. then { min = i.max *. i.max; max = i.min *. i.min; } else if 0. <= i.min then { min = i.min *. i.min; max = i.max *. i.max; } i.min < 0 . & & 0 . < i.max { min = 0.; max = max (i.min *. i.min) (i.max *. i.max); } let sqrt i = { min = sqrt i.min; max = sqrt i.max; } let log i = if not (is_not_negative i) then begin Printf.eprintf "User assertion failed: %s\n" "(Interval) log not defined for negative numbers"; exit 1 end; { min = log i.min; max = log i.max; } let exp i = { min = exp i.min; max = exp i.max; } let pow_int i n = let pmin = Stdlib.(i.min ** (float n)) in let pmax = Stdlib.(i.max ** (float n)) in if n mod 2 = 0 then if 0. <= i.min then { min = pmin; max = pmax; } else if i.max <= 0. then { min = pmax; max = pmin; } else { min = 0.; max = max pmin pmax; } else { min = pmin; max = pmax; } let ( ** ) i1 i2 = exp (i2 * (log i1)) let sin i = TODO let cos i = TODO let tan i = TODO let asin i = TODO let acos i = TODO let atan i = TODO let ( = ) i1 i2 = i1.min = i2.min && i1.max = i2.max let ( <> ) i1 i2 = i1.min <> i2.min || i1.max <> i2.max let ( < ) i1 i2 = i1.max < i2.min let ( <= ) i1 i2 = i1.max <= i2.min let ( > ) i1 i2 = i1.min > i2.max let ( >= ) i1 i2 = i1.min >= i2.max (** [subset s1 s2] tests whether the set s1 is a subset of the set s2. *) let subset i1 i2 = Stdlib.(i2.min <= i1.min && i1.max <= i2.max) let add = ( + ) let sub = ( - ) let mul = ( * ) let div = ( / ) let neg = ( ~- )
null
https://raw.githubusercontent.com/fadbadml-dev/FADBADml/bd5668433b8ad297aa70e91a032953d55923b533/example/reachability/interval.ml
ocaml
************************************************************************ FADBADml ************************************************************************ * [subset s1 s2] tests whether the set s1 is a subset of the set s2.
OCaml port by and Based on FADBAD++ , written by and Copyright 2019 - 2020 This file is distributed under the terms of the CeCILL - C license . type scalar = float type elt = { min: scalar; max: scalar; } type t = { mutable min: scalar; mutable max: scalar; } let is_point i = i.min = i.max let is_positive i = 0. < i.min let is_negative i = i.max < 0. let is_null i = i.min = 0. && i.max = 0. let is_not_positive i = i.max <= 0. let is_not_negative i = 0. <= i.min let create () = { min = Float.nan; max = Float.nan; } let make_point f = { min = f; max = f; } let make_float f = make_point f let make_bounds min max = {min; max} let make (i : elt) : t = make_bounds i.min i.max let integer i = make_point (float i) let get (i : t) : elt = { min = i.min; max = i.max; } let ( !! ) = get let get_min i = i.min let get_max i = i.max let get_min_max i = (i.min, i.max) let radius i = let min, max = get_min_max i in (max -. min) /. 2. let print2d x y _ = let () = Printf.printf "%f\t%f\n" x.min y.min in let () = Printf.printf "%f\t%f\n" x.max y.min in let () = Printf.printf "%f\t%f\n" x.max y.max in let () = Printf.printf "%f\t%f\n" x.min y.max in let () = Printf.printf "%f\t%f\n" x.min y.min in () let to_string i = Printf.sprintf "[%f,%f]" i.min i.max let string_of_scalar = string_of_float let string_of_elt (i : elt) = Printf.sprintf "[%f,%f]" i.min i.max let copy i = { min = i.min; max = i.max; } let deepcopy = copy let zero () = integer 0 let one () = integer 1 let two () = integer 2 let scale i f = make { min = i.min *. f; max = i.max *. f; } let translate i f = make { min = i.min +. f; max = i.max +. f; } let ( ~+ ) = copy let ( ~- ) i = make { min = -. i.max; max = -. i.min; } let ( + ) i1 i2 = { min = i1.min +. i2.min; max = i1.max +. i2.max; } let ( += ) i1 i2 = let () = i1.min <- i1.min +. i2.min in let () = i1.max <- i1.max +. i2.max in i1 let ( - ) i1 i2 = { min = i1.min -. i2.max; max = i1.max -. i2.min; } let ( -= ) i1 i2 = let () = i1.min <- i1.min -. i2.max in let () = i1.max <- i1.max -. i2.min in i1 let ( * ) i1 i2 = let a = i1.min *. i2.min in let b = i1.min *. i2.max in let c = i1.max *. i2.min in let d = i1.max *. i2.max in { min = min (min a b) (min c d); max = max (max a b) (max c d); } let ( *= ) i1 i2 = let i = i1 * i2 in let () = i1.min <- i.min in let () = i1.max <- i.max in i1 let inv i = match i.min = 0., i.max = 0. with | true, true -> begin Printf.eprintf "Interval: zero division"; exit 1 end | true, false -> { min = 1. /. i.max; max = Float.infinity; } | false, true -> { min = Float.neg_infinity; max = 1. /. i.min; } | false, false -> begin if i.min <= 0. && 0. <= i.max then { min = Float.neg_infinity; max = Float.infinity; } else { min = 1. /. i.max; max = 1. /. i.min; } end let ( / ) i1 i2 = i1 * (inv i2) let ( /= ) i1 i2 = let i = i1 / i2 in let () = i1.min <- i.min in let () = i1.max <- i.max in i1 let sqr i = if i.max <= 0. then { min = i.max *. i.max; max = i.min *. i.min; } else if 0. <= i.min then { min = i.min *. i.min; max = i.max *. i.max; } i.min < 0 . & & 0 . < i.max { min = 0.; max = max (i.min *. i.min) (i.max *. i.max); } let sqrt i = { min = sqrt i.min; max = sqrt i.max; } let log i = if not (is_not_negative i) then begin Printf.eprintf "User assertion failed: %s\n" "(Interval) log not defined for negative numbers"; exit 1 end; { min = log i.min; max = log i.max; } let exp i = { min = exp i.min; max = exp i.max; } let pow_int i n = let pmin = Stdlib.(i.min ** (float n)) in let pmax = Stdlib.(i.max ** (float n)) in if n mod 2 = 0 then if 0. <= i.min then { min = pmin; max = pmax; } else if i.max <= 0. then { min = pmax; max = pmin; } else { min = 0.; max = max pmin pmax; } else { min = pmin; max = pmax; } let ( ** ) i1 i2 = exp (i2 * (log i1)) let sin i = TODO let cos i = TODO let tan i = TODO let asin i = TODO let acos i = TODO let atan i = TODO let ( = ) i1 i2 = i1.min = i2.min && i1.max = i2.max let ( <> ) i1 i2 = i1.min <> i2.min || i1.max <> i2.max let ( < ) i1 i2 = i1.max < i2.min let ( <= ) i1 i2 = i1.max <= i2.min let ( > ) i1 i2 = i1.min > i2.max let ( >= ) i1 i2 = i1.min >= i2.max let subset i1 i2 = Stdlib.(i2.min <= i1.min && i1.max <= i2.max) let add = ( + ) let sub = ( - ) let mul = ( * ) let div = ( / ) let neg = ( ~- )
ab610a335ee61ece123795865b1830e72d814372c3efe03e27bd835c0eb900db
ComputerAidedLL/click-and-collect
parse_sequent.ml
let ll_parse sequent_as_string = Ll_parser.main Ll_lexer.token (Lexing.from_string sequent_as_string);; let except_syntax_error parse_method s = try parse_method s with t when Printexc.to_string t = "Parsing.Parse_error" || Printexc.to_string t = "(Failure \"lexing: empty token\")" -> `Assoc [("is_valid", `Bool false);("error_message", `String "Syntax error: please read the syntax rules.")] let safe_parse sequent_as_string = except_syntax_error (fun s -> let raw_sequent = ll_parse s in let sequent = Raw_sequent.to_sequent raw_sequent in let proof = Proof.Hypothesis_proof sequent in `Assoc [("is_valid", `Bool true);("proof", Proof.to_json proof)] ) sequent_as_string;; let safe_parse_formula formula_as_string = except_syntax_error (fun s -> let raw_sequent = ll_parse s in match raw_sequent with | {hyp=[]; cons=[e]} -> `Assoc [("is_valid", `Bool true); ("formula", Raw_sequent.raw_formula_to_json e)] | _ -> `Assoc [("is_valid", `Bool false); ("error_message", `String "Input must contain exactly one formula.")] ) formula_as_string;; let safe_is_valid_litt litt = except_syntax_error (fun l -> let raw_sequent = ll_parse l in match raw_sequent with | {hyp=[]; cons=[Litt s]} -> `Assoc [("is_valid", `Bool true); ("value", `String s)] | _ -> `Assoc [("is_valid", `Bool false); ("error_message", `String "Input must contain exactly one litteral.")] ) litt;;
null
https://raw.githubusercontent.com/ComputerAidedLL/click-and-collect/c1e882a496aaec054a05164ada6fc1056dd8ec18/parse_sequent.ml
ocaml
let ll_parse sequent_as_string = Ll_parser.main Ll_lexer.token (Lexing.from_string sequent_as_string);; let except_syntax_error parse_method s = try parse_method s with t when Printexc.to_string t = "Parsing.Parse_error" || Printexc.to_string t = "(Failure \"lexing: empty token\")" -> `Assoc [("is_valid", `Bool false);("error_message", `String "Syntax error: please read the syntax rules.")] let safe_parse sequent_as_string = except_syntax_error (fun s -> let raw_sequent = ll_parse s in let sequent = Raw_sequent.to_sequent raw_sequent in let proof = Proof.Hypothesis_proof sequent in `Assoc [("is_valid", `Bool true);("proof", Proof.to_json proof)] ) sequent_as_string;; let safe_parse_formula formula_as_string = except_syntax_error (fun s -> let raw_sequent = ll_parse s in match raw_sequent with | {hyp=[]; cons=[e]} -> `Assoc [("is_valid", `Bool true); ("formula", Raw_sequent.raw_formula_to_json e)] | _ -> `Assoc [("is_valid", `Bool false); ("error_message", `String "Input must contain exactly one formula.")] ) formula_as_string;; let safe_is_valid_litt litt = except_syntax_error (fun l -> let raw_sequent = ll_parse l in match raw_sequent with | {hyp=[]; cons=[Litt s]} -> `Assoc [("is_valid", `Bool true); ("value", `String s)] | _ -> `Assoc [("is_valid", `Bool false); ("error_message", `String "Input must contain exactly one litteral.")] ) litt;;
811be2679529caa23564bee7145949ef713430b5189e4f02e10c5130d8cb42a0
bobot/FetedelascienceINRIAsaclay
expose.ml
(* Generate the graphics for the talk *) open Rubik module D = Display_base (* Left associative *) let ( >> ) c m = Cubie.mul c (Cubie.move(Move.make m)) let geom = { D.geom with D.width = 1.; height = 1. } let save fname ?(geom=geom) cube = let fh = open_out ("expose-" ^ fname ^ ".tex") in D.cube_tikz fh ~geom cube; close_out fh let () = save "id" Cubie.id; save "F1" (Cubie.id >> (F,1)); save "F2" (Cubie.id >> (F,2)); save "F3" (Cubie.id >> (F,3)); save "R1" (Cubie.id >> (R,1)); save "R1R3" (Cubie.id >> (R,1) >> (R,3)); save "F1R2" (Cubie.id >> (F,1) >> (R,2)); save "F1B2" (Cubie.id >> (F,1) >> (B,2)); save "F1R2U3" (Cubie.id >> (F,1) >> (R,2) >> (U,3)); let scrambled = Cubie.id >> (D,1) >> (L,2) >> (U,3) >> (F,1) in save "scrambled" scrambled; save "scrambledR1" (scrambled >> (R,1)); save "scrambledR3" (scrambled >> (R,3)); save "F1R2U3" (Cubie.id >> (F,1) >> (R,2) >> (U,3)); save "F1R2U3F1" (Cubie.id >> (F,1) >> (R,2) >> (U,3) >> (F,1)); save "F1R2U3D3" (Cubie.id >> (F,1) >> (R,2) >> (U,3) >> (D,3)); (* Local Variables: *) compile - command : " make expose.exe " (* End: *)
null
https://raw.githubusercontent.com/bobot/FetedelascienceINRIAsaclay/87765db9f9c7211a26a09eb93e9c92f99a49b0bc/2010/robot/examples_mindstorm_lab/rubik/expose.ml
ocaml
Generate the graphics for the talk Left associative Local Variables: End:
open Rubik module D = Display_base let ( >> ) c m = Cubie.mul c (Cubie.move(Move.make m)) let geom = { D.geom with D.width = 1.; height = 1. } let save fname ?(geom=geom) cube = let fh = open_out ("expose-" ^ fname ^ ".tex") in D.cube_tikz fh ~geom cube; close_out fh let () = save "id" Cubie.id; save "F1" (Cubie.id >> (F,1)); save "F2" (Cubie.id >> (F,2)); save "F3" (Cubie.id >> (F,3)); save "R1" (Cubie.id >> (R,1)); save "R1R3" (Cubie.id >> (R,1) >> (R,3)); save "F1R2" (Cubie.id >> (F,1) >> (R,2)); save "F1B2" (Cubie.id >> (F,1) >> (B,2)); save "F1R2U3" (Cubie.id >> (F,1) >> (R,2) >> (U,3)); let scrambled = Cubie.id >> (D,1) >> (L,2) >> (U,3) >> (F,1) in save "scrambled" scrambled; save "scrambledR1" (scrambled >> (R,1)); save "scrambledR3" (scrambled >> (R,3)); save "F1R2U3" (Cubie.id >> (F,1) >> (R,2) >> (U,3)); save "F1R2U3F1" (Cubie.id >> (F,1) >> (R,2) >> (U,3) >> (F,1)); save "F1R2U3D3" (Cubie.id >> (F,1) >> (R,2) >> (U,3) >> (D,3)); compile - command : " make expose.exe "
ece1a8781c1d17a8f015dd05161ccaace78006b16307bd658fb214c14531b2cd
huiyaozheng/Mirage-zmq
config.ml
open Mirage let main = foreign ~packages:[package "mirage-zmq"] "Local_lat.Main" (stackv4 @-> job) let stack = generic_stackv4 default_network let () = register "local_lat" [ main $ stack ]
null
https://raw.githubusercontent.com/huiyaozheng/Mirage-zmq/af288a3378a7c357bd5646a3abf4fd5ae777369b/perf/libzmq/local/unikernel_lat/config.ml
ocaml
open Mirage let main = foreign ~packages:[package "mirage-zmq"] "Local_lat.Main" (stackv4 @-> job) let stack = generic_stackv4 default_network let () = register "local_lat" [ main $ stack ]
46452fb0938bdedd8957c9888d1db0b4d4279a424561c63f3fd73529d845dde0
IBM-Watson/kale
cloud_foundry_test.clj
;; ( C ) Copyright IBM Corp. 2016 All Rights Reserved . ;; (ns kale.cloud-foundry-test (:require [kale.cloud-foundry :as cf] [kale.cloud-foundry-constants :refer :all] [kale.common :refer [set-language prompt-user new-line]] [org.httpkit.fake :refer [with-fake-http]] [cheshire.core :as json] [clojure.test :as t :refer [deftest is]] [slingshot.slingshot :refer [try+ throw+]] [slingshot.test :refer :all])) (set-language :en) (deftest cf-request-invalid-token (is (thrown+-with-msg? [:type :kale.common/fail] (re-pattern (str "The authentication token for this session " "is either invalid or expired.*" "Please run 'kale login' to acquire a new one.")) (cf/cf-request (fn [] (throw+ {:status 401 :body (json/encode {"code" 1000 "error_code" "CF-InvalidAuthToken"})})) nil)))) (deftest cf-request-other-cf-error (let [body (json/encode {"code" 1000 "error_code" "CF-Error"})] (is (= body (try+ (cf/cf-request (fn [] (throw+ {:status 401 :body body})) nil) (catch (number? (:status %)) e (e :body))))))) (deftest cf-request-other-exception (is (= "Divide by zero" (try+ (cf/cf-request (fn [] (/ 1 0)) nil) (catch Exception e (.getMessage e)))))) (deftest cf-request-multiple-pages (with-fake-http [(cf-url "/v2/info") (respond {:body (json/encode (assoc (results-response ["data1" "data2"]) :next_url "/v2/info?page=2"))}) (cf-url "/v2/info?page=2") (respond {:body (json/encode (results-response ["data3"]))})] (is (= ["data1" "data2" "data3"] (cf/cf-paged-json :get cf-auth "/v2/info"))))) (deftest get-oauth-tokens (with-fake-http [(cf-url "/v2/info") (respond {:body (json/encode {:authorization_endpoint ""})}) "" (respond {:body (json/encode {:access_token "ACCESS_TOKEN" :refresh_token "REFRESH_TOKEN"})})] (is (= {:access_token "ACCESS_TOKEN" :refresh_token "REFRESH_TOKEN"} (cf/get-oauth-tokens "redshirt" "scotty" (cf-auth :url)))))) (def sso-prompt-output (str new-line "To log in, you will need to provide a passcode from:" new-line "" new-line new-line "If you already have a passcode, type it in now; otherwise " new-line "press ENTER to automatically open a browser to the URL: ")) (deftest get-oauth-tokens-sso (with-fake-http [(cf-url "/v2/info") (respond {:body (json/encode {:authorization_endpoint ""})}) "" (respond {:body (json/encode {:prompts {:passcode ["password" (str "One Time Code (Get one at " "/" "UAALoginServerWAR/passcode)")]}})}) "" (respond {:body (json/encode {:access_token "ACCESS_TOKEN" :refresh_token "REFRESH_TOKEN"})})] (with-redefs [prompt-user (fn [prompt _] (is (= sso-prompt-output prompt)) "CODE")] (is (= {:access_token "ACCESS_TOKEN" :refresh_token "REFRESH_TOKEN"} (cf/get-oauth-tokens-sso (cf-auth :url))))))) (deftest get-user-data-bad-token (is (thrown+-with-msg? [:type :kale.common/fail] #"Unable to determine user ID." (cf/get-user-data nil)))) (def get-user-data-indeed (is (= "3-3-2222" ((cf/get-user-data "WlXnkhdzWge0.eyJ1c2VyX2lkIjoiMy0zLTIyMjIifQo=.WlXnkhdzWge0") "user_id")))) (deftest create-space (with-fake-http [(cf-url "/v2/spaces?async=true") (respond {:body (json/encode (space-entity "SPACE_GUID" "space"))})] (is (= (space-entity "SPACE_GUID" "space") (cf/create-space cf-auth "ORG_GUID" "USER_GUID" "space"))))) (deftest create-service-entry (let [entity (service-entity "RNR_GUID" "rnr-service" "retrieve_and_rank")] (is (= entry1 (cf/service-entry entity (service-keys-response :resources)))))) (deftest create-service-entry-with-no-credentials (let [entity (service-entity "SERVICE_GUID3" "service-name3" "service-type3")] (is (= {:service-name3 {:key-guid nil :credentials nil :plan "standard" :guid "SERVICE_GUID3" :type "service-type3"}} (cf/service-entry entity (service-keys-response :resources)))))) (deftest get-service-information (with-fake-http [(cf-url "/v2/spaces/SPACE_GUID/summary") (respond {:body (json/encode space-summary-response)}) (cf-url "/v2/service_keys") (respond {:body (json/encode service-keys-response)})] (with-redefs [cf/service-entry (fn [{:keys [guid]} _] (cond (= guid "RNR_GUID") entry1 (= guid "DC_GUID") entry2 :else nil))] (is (= (merge entry1 entry2) (cf/get-services cf-auth "SPACE_GUID")))))) (deftest get-service-plan-guid (with-fake-http [(cf-url "/v2/spaces/SPACE_GUID/services?q=label%3Aservice-type") (respond {:body (json/encode service-type-response)}) (cf-url "/v2/service_plans?q=service_guid%3ATYPE_GUID") (respond {:body (json/encode service-plan-response)})] (is (= "PLAN_GUID" (cf/get-service-plan-guid cf-auth "SPACE_GUID" "service-type" "standard"))))) (deftest get-service-status (with-fake-http [(cf-url "/v2/service_instances/SERVICE_GUID") (respond {:body (json/encode (service-instance-entity "GUID" "service-name"))})] (is (= "create succeeded" (cf/get-service-status cf-auth "SERVICE_GUID"))))) (deftest delete-service-key (with-fake-http [(cf-url "/v2/service_keys/KEY_GUID?async=true") (respond nil)] (is (empty? (cf/delete-service-key cf-auth "KEY_GUID"))))) (deftest delete-service-service (with-fake-http [(cf-url "/v2/service_instances/GUID?accepts_incomplete=true&async=true") (respond nil)] (is (empty? (cf/delete-service cf-auth "GUID")))))
null
https://raw.githubusercontent.com/IBM-Watson/kale/f1c5e312e5db0e3fc01c47dfb965f175b5b0a5b6/test/kale/cloud_foundry_test.clj
clojure
( C ) Copyright IBM Corp. 2016 All Rights Reserved . (ns kale.cloud-foundry-test (:require [kale.cloud-foundry :as cf] [kale.cloud-foundry-constants :refer :all] [kale.common :refer [set-language prompt-user new-line]] [org.httpkit.fake :refer [with-fake-http]] [cheshire.core :as json] [clojure.test :as t :refer [deftest is]] [slingshot.slingshot :refer [try+ throw+]] [slingshot.test :refer :all])) (set-language :en) (deftest cf-request-invalid-token (is (thrown+-with-msg? [:type :kale.common/fail] (re-pattern (str "The authentication token for this session " "is either invalid or expired.*" "Please run 'kale login' to acquire a new one.")) (cf/cf-request (fn [] (throw+ {:status 401 :body (json/encode {"code" 1000 "error_code" "CF-InvalidAuthToken"})})) nil)))) (deftest cf-request-other-cf-error (let [body (json/encode {"code" 1000 "error_code" "CF-Error"})] (is (= body (try+ (cf/cf-request (fn [] (throw+ {:status 401 :body body})) nil) (catch (number? (:status %)) e (e :body))))))) (deftest cf-request-other-exception (is (= "Divide by zero" (try+ (cf/cf-request (fn [] (/ 1 0)) nil) (catch Exception e (.getMessage e)))))) (deftest cf-request-multiple-pages (with-fake-http [(cf-url "/v2/info") (respond {:body (json/encode (assoc (results-response ["data1" "data2"]) :next_url "/v2/info?page=2"))}) (cf-url "/v2/info?page=2") (respond {:body (json/encode (results-response ["data3"]))})] (is (= ["data1" "data2" "data3"] (cf/cf-paged-json :get cf-auth "/v2/info"))))) (deftest get-oauth-tokens (with-fake-http [(cf-url "/v2/info") (respond {:body (json/encode {:authorization_endpoint ""})}) "" (respond {:body (json/encode {:access_token "ACCESS_TOKEN" :refresh_token "REFRESH_TOKEN"})})] (is (= {:access_token "ACCESS_TOKEN" :refresh_token "REFRESH_TOKEN"} (cf/get-oauth-tokens "redshirt" "scotty" (cf-auth :url)))))) (def sso-prompt-output (str new-line "To log in, you will need to provide a passcode from:" new-line "" new-line new-line "If you already have a passcode, type it in now; otherwise " new-line "press ENTER to automatically open a browser to the URL: ")) (deftest get-oauth-tokens-sso (with-fake-http [(cf-url "/v2/info") (respond {:body (json/encode {:authorization_endpoint ""})}) "" (respond {:body (json/encode {:prompts {:passcode ["password" (str "One Time Code (Get one at " "/" "UAALoginServerWAR/passcode)")]}})}) "" (respond {:body (json/encode {:access_token "ACCESS_TOKEN" :refresh_token "REFRESH_TOKEN"})})] (with-redefs [prompt-user (fn [prompt _] (is (= sso-prompt-output prompt)) "CODE")] (is (= {:access_token "ACCESS_TOKEN" :refresh_token "REFRESH_TOKEN"} (cf/get-oauth-tokens-sso (cf-auth :url))))))) (deftest get-user-data-bad-token (is (thrown+-with-msg? [:type :kale.common/fail] #"Unable to determine user ID." (cf/get-user-data nil)))) (def get-user-data-indeed (is (= "3-3-2222" ((cf/get-user-data "WlXnkhdzWge0.eyJ1c2VyX2lkIjoiMy0zLTIyMjIifQo=.WlXnkhdzWge0") "user_id")))) (deftest create-space (with-fake-http [(cf-url "/v2/spaces?async=true") (respond {:body (json/encode (space-entity "SPACE_GUID" "space"))})] (is (= (space-entity "SPACE_GUID" "space") (cf/create-space cf-auth "ORG_GUID" "USER_GUID" "space"))))) (deftest create-service-entry (let [entity (service-entity "RNR_GUID" "rnr-service" "retrieve_and_rank")] (is (= entry1 (cf/service-entry entity (service-keys-response :resources)))))) (deftest create-service-entry-with-no-credentials (let [entity (service-entity "SERVICE_GUID3" "service-name3" "service-type3")] (is (= {:service-name3 {:key-guid nil :credentials nil :plan "standard" :guid "SERVICE_GUID3" :type "service-type3"}} (cf/service-entry entity (service-keys-response :resources)))))) (deftest get-service-information (with-fake-http [(cf-url "/v2/spaces/SPACE_GUID/summary") (respond {:body (json/encode space-summary-response)}) (cf-url "/v2/service_keys") (respond {:body (json/encode service-keys-response)})] (with-redefs [cf/service-entry (fn [{:keys [guid]} _] (cond (= guid "RNR_GUID") entry1 (= guid "DC_GUID") entry2 :else nil))] (is (= (merge entry1 entry2) (cf/get-services cf-auth "SPACE_GUID")))))) (deftest get-service-plan-guid (with-fake-http [(cf-url "/v2/spaces/SPACE_GUID/services?q=label%3Aservice-type") (respond {:body (json/encode service-type-response)}) (cf-url "/v2/service_plans?q=service_guid%3ATYPE_GUID") (respond {:body (json/encode service-plan-response)})] (is (= "PLAN_GUID" (cf/get-service-plan-guid cf-auth "SPACE_GUID" "service-type" "standard"))))) (deftest get-service-status (with-fake-http [(cf-url "/v2/service_instances/SERVICE_GUID") (respond {:body (json/encode (service-instance-entity "GUID" "service-name"))})] (is (= "create succeeded" (cf/get-service-status cf-auth "SERVICE_GUID"))))) (deftest delete-service-key (with-fake-http [(cf-url "/v2/service_keys/KEY_GUID?async=true") (respond nil)] (is (empty? (cf/delete-service-key cf-auth "KEY_GUID"))))) (deftest delete-service-service (with-fake-http [(cf-url "/v2/service_instances/GUID?accepts_incomplete=true&async=true") (respond nil)] (is (empty? (cf/delete-service cf-auth "GUID")))))
fa65d8165c3b8cc2de72661708162a17478d69717099e410cc6b0c3475e40020
threatgrid/ctim
sorting_test.cljc
(ns ctim.domain.sorting-test (:require [clj-momo.lib.clj-time.core :as time] [clj-momo.lib.clj-time.coerce :as time-coerce] [ctim.domain.sorting :as sut] #?(:clj [clojure.test :refer [deftest is testing]] :cljs [cljs.test :refer-macros [deftest is testing]]))) (deftest sort-judgements-test (with-redefs [time/internal-now (constantly (time/internal-date 2017 5 12))] (is (= (sut/sort-judgements [{:disposition 5, :disposition_name "Unknown", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", ;; This one is expired based on mocked 'now' :end_time "2017-05-10T21:46:41.690Z"}} {:disposition 1, :disposition_name "Clean", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 3, :disposition_name "Suspicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T21:46:41.690Z", :end_time "2017-05-15T22:46:41.690Z"}} {:disposition 4, :disposition_name "Common", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}}]) [{:disposition 1, :disposition_name "Clean", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T21:46:41.690Z", :end_time "2017-05-15T22:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 3, :disposition_name "Suspicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 4, :disposition_name "Common", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 5, :disposition_name "Unknown", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", ;; Expired one comes last :end_time "2017-05-10T21:46:41.690Z"}}])))) (deftest sort-judgements-with-internal-date-test (with-redefs [time/internal-now (constantly (time/internal-date 2017 5 12))] (is (= (->> [{:disposition 5, :disposition_name "Unknown", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T21:46:41.690Z")}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T21:46:41.690Z")}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), ;; This one is expired based on mocked 'now' :end_time (time-coerce/to-internal-date "2017-05-10T21:46:41.690Z")}} {:disposition 1, :disposition_name "Clean", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T21:46:41.690Z")}} {:disposition 3, :disposition_name "Suspicious", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T21:46:41.690Z")}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T21:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T22:46:41.690Z")}} {:disposition 4, :disposition_name "Common", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T21:46:41.690Z")}}] sut/sort-judgements ;; JS dates of the same instant are still not equal, so ;; convert them back to strings for equality check (map (fn [m] (-> m (update-in [:valid_time :start_time] time-coerce/to-internal-string) (update-in [:valid_time :end_time] time-coerce/to-internal-string))))) [{:disposition 1, :disposition_name "Clean", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T21:46:41.690Z", :end_time "2017-05-15T22:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 3, :disposition_name "Suspicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 4, :disposition_name "Common", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 5, :disposition_name "Unknown", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", ;; Expired one comes last :end_time "2017-05-10T21:46:41.690Z"}}])))) (deftest sort-sightings-test (testing "sort sightings" (is (= (sut/sort-sightings [{:id 1 :observed_time {:start_time "2017-01-12T00:00:00.002Z"}} {:id 2 :observed_time {:start_time "2017-01-12T00:00:00.001Z"}} {:id 3 :observed_time {:start_time "2017-01-12T00:00:00.000Z"}}]) [{:id 3 :observed_time {:start_time "2017-01-12T00:00:00.000Z"}} {:id 2 :observed_time {:start_time "2017-01-12T00:00:00.001Z"}} {:id 1 :observed_time {:start_time "2017-01-12T00:00:00.002Z"}}]))))
null
https://raw.githubusercontent.com/threatgrid/ctim/2ecae70682e69495cc3a12fd58a474d4ea57ae9c/test/ctim/domain/sorting_test.cljc
clojure
This one is expired based on mocked 'now' Expired one comes last This one is expired based on mocked 'now' JS dates of the same instant are still not equal, so convert them back to strings for equality check Expired one comes last
(ns ctim.domain.sorting-test (:require [clj-momo.lib.clj-time.core :as time] [clj-momo.lib.clj-time.coerce :as time-coerce] [ctim.domain.sorting :as sut] #?(:clj [clojure.test :refer [deftest is testing]] :cljs [cljs.test :refer-macros [deftest is testing]]))) (deftest sort-judgements-test (with-redefs [time/internal-now (constantly (time/internal-date 2017 5 12))] (is (= (sut/sort-judgements [{:disposition 5, :disposition_name "Unknown", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-10T21:46:41.690Z"}} {:disposition 1, :disposition_name "Clean", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 3, :disposition_name "Suspicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T21:46:41.690Z", :end_time "2017-05-15T22:46:41.690Z"}} {:disposition 4, :disposition_name "Common", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}}]) [{:disposition 1, :disposition_name "Clean", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T21:46:41.690Z", :end_time "2017-05-15T22:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 3, :disposition_name "Suspicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 4, :disposition_name "Common", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 5, :disposition_name "Unknown", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-10T21:46:41.690Z"}}])))) (deftest sort-judgements-with-internal-date-test (with-redefs [time/internal-now (constantly (time/internal-date 2017 5 12))] (is (= (->> [{:disposition 5, :disposition_name "Unknown", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T21:46:41.690Z")}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T21:46:41.690Z")}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-10T21:46:41.690Z")}} {:disposition 1, :disposition_name "Clean", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T21:46:41.690Z")}} {:disposition 3, :disposition_name "Suspicious", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T21:46:41.690Z")}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T21:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T22:46:41.690Z")}} {:disposition 4, :disposition_name "Common", :valid_time {:start_time (time-coerce/to-internal-date "2017-05-01T20:46:41.690Z"), :end_time (time-coerce/to-internal-date "2017-05-15T21:46:41.690Z")}}] sut/sort-judgements (map (fn [m] (-> m (update-in [:valid_time :start_time] time-coerce/to-internal-string) (update-in [:valid_time :end_time] time-coerce/to-internal-string))))) [{:disposition 1, :disposition_name "Clean", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T21:46:41.690Z", :end_time "2017-05-15T22:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 3, :disposition_name "Suspicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 4, :disposition_name "Common", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 5, :disposition_name "Unknown", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-15T21:46:41.690Z"}} {:disposition 2, :disposition_name "Malicious", :valid_time {:start_time "2017-05-01T20:46:41.690Z", :end_time "2017-05-10T21:46:41.690Z"}}])))) (deftest sort-sightings-test (testing "sort sightings" (is (= (sut/sort-sightings [{:id 1 :observed_time {:start_time "2017-01-12T00:00:00.002Z"}} {:id 2 :observed_time {:start_time "2017-01-12T00:00:00.001Z"}} {:id 3 :observed_time {:start_time "2017-01-12T00:00:00.000Z"}}]) [{:id 3 :observed_time {:start_time "2017-01-12T00:00:00.000Z"}} {:id 2 :observed_time {:start_time "2017-01-12T00:00:00.001Z"}} {:id 1 :observed_time {:start_time "2017-01-12T00:00:00.002Z"}}]))))
51834470bbc2f88078ac407b0cb1a977ae036f4433522eecaedb568ffd9b27cc
ocamllabs/ocaml-modular-implicits
class_2.ml
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Gallium , INRIA Rocquencourt (* *) Copyright 2012 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) (* class expressions may also contain local recursive bindings *) class test = let rec f = print_endline "f"; fun x -> g x and g = print_endline "g"; fun x -> f x in object method f : 'a 'b. 'a -> 'b = f method g : 'a 'b. 'a -> 'b = g end
null
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/letrec/class_2.ml
ocaml
********************************************************************* OCaml ********************************************************************* class expressions may also contain local recursive bindings
, projet Gallium , INRIA Rocquencourt Copyright 2012 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . class test = let rec f = print_endline "f"; fun x -> g x and g = print_endline "g"; fun x -> f x in object method f : 'a 'b. 'a -> 'b = f method g : 'a 'b. 'a -> 'b = g end
f58c740ad4c5d5b766c0c6013a90771d08837bd9f742616c05fd755156e8d857
kupl/LearnML
patch.ml
let rec isUniq (lst : 'a list) m : bool = match lst with | [] -> true | hd :: tl -> if hd = m then false else isUniq tl m let rec __s3 (__s4 : 'b list) __s5 : bool = match __s4 with | [] -> false | __s11 :: __s12 -> if __s11 = __s5 then true else __s3 __s12 __s5 let rec __s6 (__s7 : 'b list) (__s8 : 'b list) : 'b list = match __s7 with | [] -> __s8 | __s9 :: __s10 -> if __s3 __s8 __s9 then __s6 __s10 __s8 else __s6 __s10 (__s8 @ [ __s9 ]) let rec uniq (lst : 'c list) : 'd list = let rec unique (uniList : 'c list) (givenList : 'c list) : 'c list = match givenList with | [] -> uniList | hd :: tl -> if isUniq uniList hd then unique (hd :: uniList) tl else unique uniList tl in __s6 lst [] let (_ : int list) = uniq [ 3; 2; 1; 3; 4 ]
null
https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/uniq/sub12/patch.ml
ocaml
let rec isUniq (lst : 'a list) m : bool = match lst with | [] -> true | hd :: tl -> if hd = m then false else isUniq tl m let rec __s3 (__s4 : 'b list) __s5 : bool = match __s4 with | [] -> false | __s11 :: __s12 -> if __s11 = __s5 then true else __s3 __s12 __s5 let rec __s6 (__s7 : 'b list) (__s8 : 'b list) : 'b list = match __s7 with | [] -> __s8 | __s9 :: __s10 -> if __s3 __s8 __s9 then __s6 __s10 __s8 else __s6 __s10 (__s8 @ [ __s9 ]) let rec uniq (lst : 'c list) : 'd list = let rec unique (uniList : 'c list) (givenList : 'c list) : 'c list = match givenList with | [] -> uniList | hd :: tl -> if isUniq uniList hd then unique (hd :: uniList) tl else unique uniList tl in __s6 lst [] let (_ : int list) = uniq [ 3; 2; 1; 3; 4 ]
a1a2b787c95b98761ab579834d554e9a5593045cb43624e4596cac348868a1a1
EFanZh/EOPL-Exercises
exercise-1.29.rkt
#lang eopl Exercise 1.29 [ ★ ★ ] ( sort ) returns a list of the elements of loi in ascending order . ;; > ( sort ' ( 8 2 5 2 3 ) ) ;; (2 2 3 5 8) (define get-run (lambda (loi) (let ([head1 (car loi)] [tail1 (cdr loi)]) (if (null? tail1) (cons loi '()) (let ([head2 (car tail1)]) (if (<= head1 head2) (let ([tail-run (get-run tail1)]) (cons (cons head1 (car tail-run)) (cdr tail-run))) (cons (list head1) tail1))))))) (define merge (lambda (run1 run2) (let ([head1 (car run1)] [head2 (car run2)]) (if (<= head1 head2) (let ([tail1 (cdr run1)]) (if (null? tail1) (cons head1 run2) (cons head1 (merge tail1 run2)))) (let ([tail2 (cdr run2)]) (if (null? tail2) (cons head2 run1) (cons head2 (merge run1 tail2)))))))) (define collapse-all (lambda (stack run) (if (null? stack) run (collapse-all (cdr stack) (merge (cdar stack) run))))) (define collapse (lambda (stack level run) (if (null? stack) (list (cons level run)) (let ([top (car stack)]) (if (= (car top) level) (collapse (cdr stack) (+ level 1) (merge (cdr top) run)) (cons (cons level run) stack)))))) (define sort-helper (lambda (stack loi) (let* ([run-and-tail (get-run loi)] [run (car run-and-tail)] [tail (cdr run-and-tail)]) (if (null? tail) (collapse-all stack run) (sort-helper (collapse stack 0 run) tail))))) (define sort (lambda (loi) (if (null? loi) '() (sort-helper '() loi)))) (provide sort)
null
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-1.29.rkt
racket
(2 2 3 5 8)
#lang eopl Exercise 1.29 [ ★ ★ ] ( sort ) returns a list of the elements of loi in ascending order . > ( sort ' ( 8 2 5 2 3 ) ) (define get-run (lambda (loi) (let ([head1 (car loi)] [tail1 (cdr loi)]) (if (null? tail1) (cons loi '()) (let ([head2 (car tail1)]) (if (<= head1 head2) (let ([tail-run (get-run tail1)]) (cons (cons head1 (car tail-run)) (cdr tail-run))) (cons (list head1) tail1))))))) (define merge (lambda (run1 run2) (let ([head1 (car run1)] [head2 (car run2)]) (if (<= head1 head2) (let ([tail1 (cdr run1)]) (if (null? tail1) (cons head1 run2) (cons head1 (merge tail1 run2)))) (let ([tail2 (cdr run2)]) (if (null? tail2) (cons head2 run1) (cons head2 (merge run1 tail2)))))))) (define collapse-all (lambda (stack run) (if (null? stack) run (collapse-all (cdr stack) (merge (cdar stack) run))))) (define collapse (lambda (stack level run) (if (null? stack) (list (cons level run)) (let ([top (car stack)]) (if (= (car top) level) (collapse (cdr stack) (+ level 1) (merge (cdr top) run)) (cons (cons level run) stack)))))) (define sort-helper (lambda (stack loi) (let* ([run-and-tail (get-run loi)] [run (car run-and-tail)] [tail (cdr run-and-tail)]) (if (null? tail) (collapse-all stack run) (sort-helper (collapse stack 0 run) tail))))) (define sort (lambda (loi) (if (null? loi) '() (sort-helper '() loi)))) (provide sort)
6a1d193a162d2246f8d2cd325b29696f00cab12e9cb29c37566880b7565faa67
spurious/chibi-scheme-mirror
hash-tests.scm
(cond-expand (modules (import (srfi 1) (srfi 69) (chibi test))) (else #f)) (test-begin "hash") (define-syntax test-lset-eq? (syntax-rules () ((test-lset= . args) (test-equal (lambda (a b) (lset= eq? a b)) . args)))) (define-syntax test-lset-equal? (syntax-rules () ((test-lset-equal? . args) (test-equal (lambda (a b) (lset= equal? a b)) . args)))) (let ((ht (make-hash-table eq?))) 3 initial elements (test 0 (hash-table-size ht)) (hash-table-set! ht 'cat 'black) (hash-table-set! ht 'dog 'white) (hash-table-set! ht 'elephant 'pink) (test 3 (hash-table-size ht)) (test-assert (hash-table-exists? ht 'dog)) (test-assert (hash-table-exists? ht 'cat)) (test-assert (hash-table-exists? ht 'elephant)) (test-not (hash-table-exists? ht 'goose)) (test 'white (hash-table-ref ht 'dog)) (test 'black (hash-table-ref ht 'cat)) (test 'pink (hash-table-ref ht 'elephant)) (test-error (hash-table-ref ht 'goose)) (test 'grey (hash-table-ref ht 'goose (lambda () 'grey))) (test 'grey (hash-table-ref/default ht 'goose 'grey)) (test-lset-eq? '(cat dog elephant) (hash-table-keys ht)) (test-lset-eq? '(black white pink) (hash-table-values ht)) (test-lset-equal? '((cat . black) (dog . white) (elephant . pink)) (hash-table->alist ht)) ;; remove an element (hash-table-delete! ht 'dog) (test 2 (hash-table-size ht)) (test-not (hash-table-exists? ht 'dog)) (test-assert (hash-table-exists? ht 'cat)) (test-assert (hash-table-exists? ht 'elephant)) (test-error (hash-table-ref ht 'dog)) (test 'black (hash-table-ref ht 'cat)) (test 'pink (hash-table-ref ht 'elephant)) (test-lset-eq? '(cat elephant) (hash-table-keys ht)) (test-lset-eq? '(black pink) (hash-table-values ht)) (test-lset-equal? '((cat . black) (elephant . pink)) (hash-table->alist ht)) ;; remove a non-existing element (hash-table-delete! ht 'dog) (test 2 (hash-table-size ht)) (test-not (hash-table-exists? ht 'dog)) ;; overwrite an existing element (hash-table-set! ht 'cat 'calico) (test 2 (hash-table-size ht)) (test-not (hash-table-exists? ht 'dog)) (test-assert (hash-table-exists? ht 'cat)) (test-assert (hash-table-exists? ht 'elephant)) (test-error (hash-table-ref ht 'dog)) (test 'calico (hash-table-ref ht 'cat)) (test 'pink (hash-table-ref ht 'elephant)) (test-lset-eq? '(cat elephant) (hash-table-keys ht)) (test-lset-eq? '(calico pink) (hash-table-values ht)) (test-lset-equal? '((cat . calico) (elephant . pink)) (hash-table->alist ht)) ;; walk and fold (test-lset-equal? '((cat . calico) (elephant . pink)) (let ((a '())) (hash-table-walk ht (lambda (k v) (set! a (cons (cons k v) a)))) a)) (test-lset-equal? '((cat . calico) (elephant . pink)) (hash-table-fold ht (lambda (k v a) (cons (cons k v) a)) '())) ;; copy (let ((ht2 (hash-table-copy ht))) (test 2 (hash-table-size ht2)) (test-not (hash-table-exists? ht2 'dog)) (test-assert (hash-table-exists? ht2 'cat)) (test-assert (hash-table-exists? ht2 'elephant)) (test-error (hash-table-ref ht2 'dog)) (test 'calico (hash-table-ref ht2 'cat)) (test 'pink (hash-table-ref ht2 'elephant)) (test-lset-eq? '(cat elephant) (hash-table-keys ht2)) (test-lset-eq? '(calico pink) (hash-table-values ht2)) (test-lset-equal? '((cat . calico) (elephant . pink)) (hash-table->alist ht2))) ;; merge (let ((ht2 (make-hash-table eq?))) (hash-table-set! ht2 'bear 'brown) (test 1 (hash-table-size ht2)) (test-not (hash-table-exists? ht2 'dog)) (test-assert (hash-table-exists? ht2 'bear)) (hash-table-merge! ht2 ht) (test 3 (hash-table-size ht2)) (test-assert (hash-table-exists? ht2 'bear)) (test-assert (hash-table-exists? ht2 'cat)) (test-assert (hash-table-exists? ht2 'elephant)) (test-not (hash-table-exists? ht2 'goose)) (test 'brown (hash-table-ref ht2 'bear)) (test 'calico (hash-table-ref ht2 'cat)) (test 'pink (hash-table-ref ht2 'elephant)) (test-error (hash-table-ref ht2 'goose)) (test 'grey (hash-table-ref/default ht2 'goose 'grey)) (test-lset-eq? '(bear cat elephant) (hash-table-keys ht2)) (test-lset-eq? '(brown calico pink) (hash-table-values ht2)) (test-lset-equal? '((cat . calico) (bear . brown) (elephant . pink)) (hash-table->alist ht2))) ;; alist->hash-table (test-lset-equal? (hash-table->alist ht) (hash-table->alist (alist->hash-table '((cat . calico) (elephant . pink)))))) ;; update (let ((ht (make-hash-table eq?)) (add1 (lambda (x) (+ x 1)))) (hash-table-set! ht 'sheep 0) (hash-table-update! ht 'sheep add1) (hash-table-update! ht 'sheep add1) (test 2 (hash-table-ref ht 'sheep)) (hash-table-update!/default ht 'crows add1 0) (hash-table-update!/default ht 'crows add1 0) (hash-table-update!/default ht 'crows add1 0) (test 3 (hash-table-ref ht 'crows))) ;; string keys (let ((ht (make-hash-table equal?))) (hash-table-set! ht "cat" 'black) (hash-table-set! ht "dog" 'white) (hash-table-set! ht "elephant" 'pink) (hash-table-ref/default ht "dog" #f) (test 'white (hash-table-ref ht "dog")) (test 'black (hash-table-ref ht "cat")) (test 'pink (hash-table-ref ht "elephant")) (test-error (hash-table-ref ht "goose")) (test 'grey (hash-table-ref/default ht "goose" 'grey)) (test-lset-equal? '("cat" "dog" "elephant") (hash-table-keys ht)) (test-lset-equal? '(black white pink) (hash-table-values ht)) (test-lset-equal? '(("cat" . black) ("dog" . white) ("elephant" . pink)) (hash-table->alist ht))) ;; string-ci keys (let ((ht (make-hash-table string-ci=? string-ci-hash))) (hash-table-set! ht "cat" 'black) (hash-table-set! ht "dog" 'white) (hash-table-set! ht "elephant" 'pink) (hash-table-ref/default ht "DOG" #f) (test 'white (hash-table-ref ht "DOG")) (test 'black (hash-table-ref ht "Cat")) (test 'pink (hash-table-ref ht "eLePhAnT")) (test-error (hash-table-ref ht "goose")) (test-lset-equal? '("cat" "dog" "elephant") (hash-table-keys ht)) (test-lset-equal? '(black white pink) (hash-table-values ht)) (test-lset-equal? '(("cat" . black) ("dog" . white) ("elephant" . pink)) (hash-table->alist ht))) ;; Exception values - this works because the return value from the ;; primitives is a cell, and we use the cdr opcode to retrieve the cell value . Thus there is no FFI issue with storing exceptions . (let ((ht (make-hash-table))) (hash-table-set! ht 'boom (make-exception 'my-exn-type "boom!" '() #f #f)) (test 'my-exn-type (exception-kind (hash-table-ref ht 'boom)))) ;; stress test (test 625 (let ((ht (make-hash-table))) (do ((i 0 (+ i 1))) ((= i 1000)) (hash-table-set! ht i (* i i))) (hash-table-ref/default ht 25 #f))) (test-end)
null
https://raw.githubusercontent.com/spurious/chibi-scheme-mirror/49168ab073f64a95c834b5f584a9aaea3469594d/tests/hash-tests.scm
scheme
remove an element remove a non-existing element overwrite an existing element walk and fold copy merge alist->hash-table update string keys string-ci keys Exception values - this works because the return value from the primitives is a cell, and we use the cdr opcode to retrieve the stress test
(cond-expand (modules (import (srfi 1) (srfi 69) (chibi test))) (else #f)) (test-begin "hash") (define-syntax test-lset-eq? (syntax-rules () ((test-lset= . args) (test-equal (lambda (a b) (lset= eq? a b)) . args)))) (define-syntax test-lset-equal? (syntax-rules () ((test-lset-equal? . args) (test-equal (lambda (a b) (lset= equal? a b)) . args)))) (let ((ht (make-hash-table eq?))) 3 initial elements (test 0 (hash-table-size ht)) (hash-table-set! ht 'cat 'black) (hash-table-set! ht 'dog 'white) (hash-table-set! ht 'elephant 'pink) (test 3 (hash-table-size ht)) (test-assert (hash-table-exists? ht 'dog)) (test-assert (hash-table-exists? ht 'cat)) (test-assert (hash-table-exists? ht 'elephant)) (test-not (hash-table-exists? ht 'goose)) (test 'white (hash-table-ref ht 'dog)) (test 'black (hash-table-ref ht 'cat)) (test 'pink (hash-table-ref ht 'elephant)) (test-error (hash-table-ref ht 'goose)) (test 'grey (hash-table-ref ht 'goose (lambda () 'grey))) (test 'grey (hash-table-ref/default ht 'goose 'grey)) (test-lset-eq? '(cat dog elephant) (hash-table-keys ht)) (test-lset-eq? '(black white pink) (hash-table-values ht)) (test-lset-equal? '((cat . black) (dog . white) (elephant . pink)) (hash-table->alist ht)) (hash-table-delete! ht 'dog) (test 2 (hash-table-size ht)) (test-not (hash-table-exists? ht 'dog)) (test-assert (hash-table-exists? ht 'cat)) (test-assert (hash-table-exists? ht 'elephant)) (test-error (hash-table-ref ht 'dog)) (test 'black (hash-table-ref ht 'cat)) (test 'pink (hash-table-ref ht 'elephant)) (test-lset-eq? '(cat elephant) (hash-table-keys ht)) (test-lset-eq? '(black pink) (hash-table-values ht)) (test-lset-equal? '((cat . black) (elephant . pink)) (hash-table->alist ht)) (hash-table-delete! ht 'dog) (test 2 (hash-table-size ht)) (test-not (hash-table-exists? ht 'dog)) (hash-table-set! ht 'cat 'calico) (test 2 (hash-table-size ht)) (test-not (hash-table-exists? ht 'dog)) (test-assert (hash-table-exists? ht 'cat)) (test-assert (hash-table-exists? ht 'elephant)) (test-error (hash-table-ref ht 'dog)) (test 'calico (hash-table-ref ht 'cat)) (test 'pink (hash-table-ref ht 'elephant)) (test-lset-eq? '(cat elephant) (hash-table-keys ht)) (test-lset-eq? '(calico pink) (hash-table-values ht)) (test-lset-equal? '((cat . calico) (elephant . pink)) (hash-table->alist ht)) (test-lset-equal? '((cat . calico) (elephant . pink)) (let ((a '())) (hash-table-walk ht (lambda (k v) (set! a (cons (cons k v) a)))) a)) (test-lset-equal? '((cat . calico) (elephant . pink)) (hash-table-fold ht (lambda (k v a) (cons (cons k v) a)) '())) (let ((ht2 (hash-table-copy ht))) (test 2 (hash-table-size ht2)) (test-not (hash-table-exists? ht2 'dog)) (test-assert (hash-table-exists? ht2 'cat)) (test-assert (hash-table-exists? ht2 'elephant)) (test-error (hash-table-ref ht2 'dog)) (test 'calico (hash-table-ref ht2 'cat)) (test 'pink (hash-table-ref ht2 'elephant)) (test-lset-eq? '(cat elephant) (hash-table-keys ht2)) (test-lset-eq? '(calico pink) (hash-table-values ht2)) (test-lset-equal? '((cat . calico) (elephant . pink)) (hash-table->alist ht2))) (let ((ht2 (make-hash-table eq?))) (hash-table-set! ht2 'bear 'brown) (test 1 (hash-table-size ht2)) (test-not (hash-table-exists? ht2 'dog)) (test-assert (hash-table-exists? ht2 'bear)) (hash-table-merge! ht2 ht) (test 3 (hash-table-size ht2)) (test-assert (hash-table-exists? ht2 'bear)) (test-assert (hash-table-exists? ht2 'cat)) (test-assert (hash-table-exists? ht2 'elephant)) (test-not (hash-table-exists? ht2 'goose)) (test 'brown (hash-table-ref ht2 'bear)) (test 'calico (hash-table-ref ht2 'cat)) (test 'pink (hash-table-ref ht2 'elephant)) (test-error (hash-table-ref ht2 'goose)) (test 'grey (hash-table-ref/default ht2 'goose 'grey)) (test-lset-eq? '(bear cat elephant) (hash-table-keys ht2)) (test-lset-eq? '(brown calico pink) (hash-table-values ht2)) (test-lset-equal? '((cat . calico) (bear . brown) (elephant . pink)) (hash-table->alist ht2))) (test-lset-equal? (hash-table->alist ht) (hash-table->alist (alist->hash-table '((cat . calico) (elephant . pink)))))) (let ((ht (make-hash-table eq?)) (add1 (lambda (x) (+ x 1)))) (hash-table-set! ht 'sheep 0) (hash-table-update! ht 'sheep add1) (hash-table-update! ht 'sheep add1) (test 2 (hash-table-ref ht 'sheep)) (hash-table-update!/default ht 'crows add1 0) (hash-table-update!/default ht 'crows add1 0) (hash-table-update!/default ht 'crows add1 0) (test 3 (hash-table-ref ht 'crows))) (let ((ht (make-hash-table equal?))) (hash-table-set! ht "cat" 'black) (hash-table-set! ht "dog" 'white) (hash-table-set! ht "elephant" 'pink) (hash-table-ref/default ht "dog" #f) (test 'white (hash-table-ref ht "dog")) (test 'black (hash-table-ref ht "cat")) (test 'pink (hash-table-ref ht "elephant")) (test-error (hash-table-ref ht "goose")) (test 'grey (hash-table-ref/default ht "goose" 'grey)) (test-lset-equal? '("cat" "dog" "elephant") (hash-table-keys ht)) (test-lset-equal? '(black white pink) (hash-table-values ht)) (test-lset-equal? '(("cat" . black) ("dog" . white) ("elephant" . pink)) (hash-table->alist ht))) (let ((ht (make-hash-table string-ci=? string-ci-hash))) (hash-table-set! ht "cat" 'black) (hash-table-set! ht "dog" 'white) (hash-table-set! ht "elephant" 'pink) (hash-table-ref/default ht "DOG" #f) (test 'white (hash-table-ref ht "DOG")) (test 'black (hash-table-ref ht "Cat")) (test 'pink (hash-table-ref ht "eLePhAnT")) (test-error (hash-table-ref ht "goose")) (test-lset-equal? '("cat" "dog" "elephant") (hash-table-keys ht)) (test-lset-equal? '(black white pink) (hash-table-values ht)) (test-lset-equal? '(("cat" . black) ("dog" . white) ("elephant" . pink)) (hash-table->alist ht))) cell value . Thus there is no FFI issue with storing exceptions . (let ((ht (make-hash-table))) (hash-table-set! ht 'boom (make-exception 'my-exn-type "boom!" '() #f #f)) (test 'my-exn-type (exception-kind (hash-table-ref ht 'boom)))) (test 625 (let ((ht (make-hash-table))) (do ((i 0 (+ i 1))) ((= i 1000)) (hash-table-set! ht i (* i i))) (hash-table-ref/default ht 25 #f))) (test-end)
3ce910a416142eda84c122b302364fb8bfdf1943aba8aae2e708813640446e1f
rwmjones/guestfs-tools
append_line.mli
virt - customize * Copyright ( C ) 2016 Red Hat Inc. * * 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 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 program ; if not , write to the Free Software Foundation , Inc. , * 51 Franklin Street , Fifth Floor , Boston , USA . * Copyright (C) 2016 Red Hat Inc. * * 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 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *) val append_line : Guestfs.guestfs -> string -> string -> string -> unit (** append_line [g root file line] appends a single line to a text file. *)
null
https://raw.githubusercontent.com/rwmjones/guestfs-tools/3a498512f58bc431db490e96cdb712b19389bda4/customize/append_line.mli
ocaml
* append_line [g root file line] appends a single line to a text file.
virt - customize * Copyright ( C ) 2016 Red Hat Inc. * * 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 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 program ; if not , write to the Free Software Foundation , Inc. , * 51 Franklin Street , Fifth Floor , Boston , USA . * Copyright (C) 2016 Red Hat Inc. * * 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 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *) val append_line : Guestfs.guestfs -> string -> string -> string -> unit
0e54684f6ace44815145250fe9b5d62afa5317303bf5f075f1e785434f497edf
helmutkian/cl-wasm-runtime
memory-example.lisp
(defvar *memory-wat* "(module (type $mem_size_t (func (result i32))) (type $get_at_t (func (param i32) (result i32))) (type $set_at_t (func (param i32) (param i32))) (memory $mem 1) (func $get_at (type $get_at_t) (param $idx i32) (result i32) (i32.load (local.get $idx))) (func $set_at (type $set_at_t) (param $idx i32) (param $val i32) (i32.store (local.get $idx) (local.get $val))) (func $mem_size (type $mem_size_t) (result i32) (memory.size)) (export \"get_at\" (func $get_at)) (export \"set_at\" (func $set_at)) (export \"mem_size\" (func $mem_size)) (export \"memory\" (memory $mem)))") (defun run-memory-example () (let* ((engine (wasm-rt:make-wasm-engine)) (store (wasm-rt:make-wasm-store engine)) (module (wasm-rt:wat-to-wasm-module store *memory-wat*)) (imports (wasm-rt:make-wasm-imports module)) (instance (wasm-rt:make-wasm-instance store module imports)) (exports (wasm-rt:exports instance)) (mem-size (wasm-rt:get-export exports "mem_size" 'wasm-rt:wasm-func)) (get-at (wasm-rt:get-export exports "get_at" 'wasm-rt:wasm-func)) (set-at (wasm-rt:get-export exports "set_at" 'wasm-rt:wasm-func)) (memory (wasm-rt:get-export exports "memory" 'wasm-rt:wasm-memory))) (format t "Memory size (pages): ~a~%" (wasm-rt:size memory)) (format t "Memory size (pages as bytes): ~a~%" (wasm-rt:bytes (wasm-rt:size memory))) (format t "Memory size (byes): ~a~%" (wasm-rt:buffer-size memory)) (format t "Memory size (pages): ~a~%" (wasm-rt:wasm-funcall mem-size)) (wasm-rt:grow memory 2) (format t "New memory size (pages): ~a~%" (wasm-rt:size memory)) (let ((mem-addr #x2220) (val #xFEFEFFE)) (wasm-rt:wasm-funcall set-at mem-addr val) (format t "Value at 0x~X: 0x~X~%" mem-addr (wasm-rt:wasm-funcall get-at mem-addr)) (let* ((page-size #x10000) (mem-addr (- (* page-size 2) (cffi:foreign-type-size :uint32))) (val #xFEA09)) (wasm-rt:wasm-funcall set-at mem-addr val) (format t "Value at 0x~X: 0x~X" mem-addr (wasm-rt:wasm-funcall get-at mem-addr))))))
null
https://raw.githubusercontent.com/helmutkian/cl-wasm-runtime/283dc86fee11191d3a32a6116cc0cb4207e5dc3e/examples/memory-example.lisp
lisp
(defvar *memory-wat* "(module (type $mem_size_t (func (result i32))) (type $get_at_t (func (param i32) (result i32))) (type $set_at_t (func (param i32) (param i32))) (memory $mem 1) (func $get_at (type $get_at_t) (param $idx i32) (result i32) (i32.load (local.get $idx))) (func $set_at (type $set_at_t) (param $idx i32) (param $val i32) (i32.store (local.get $idx) (local.get $val))) (func $mem_size (type $mem_size_t) (result i32) (memory.size)) (export \"get_at\" (func $get_at)) (export \"set_at\" (func $set_at)) (export \"mem_size\" (func $mem_size)) (export \"memory\" (memory $mem)))") (defun run-memory-example () (let* ((engine (wasm-rt:make-wasm-engine)) (store (wasm-rt:make-wasm-store engine)) (module (wasm-rt:wat-to-wasm-module store *memory-wat*)) (imports (wasm-rt:make-wasm-imports module)) (instance (wasm-rt:make-wasm-instance store module imports)) (exports (wasm-rt:exports instance)) (mem-size (wasm-rt:get-export exports "mem_size" 'wasm-rt:wasm-func)) (get-at (wasm-rt:get-export exports "get_at" 'wasm-rt:wasm-func)) (set-at (wasm-rt:get-export exports "set_at" 'wasm-rt:wasm-func)) (memory (wasm-rt:get-export exports "memory" 'wasm-rt:wasm-memory))) (format t "Memory size (pages): ~a~%" (wasm-rt:size memory)) (format t "Memory size (pages as bytes): ~a~%" (wasm-rt:bytes (wasm-rt:size memory))) (format t "Memory size (byes): ~a~%" (wasm-rt:buffer-size memory)) (format t "Memory size (pages): ~a~%" (wasm-rt:wasm-funcall mem-size)) (wasm-rt:grow memory 2) (format t "New memory size (pages): ~a~%" (wasm-rt:size memory)) (let ((mem-addr #x2220) (val #xFEFEFFE)) (wasm-rt:wasm-funcall set-at mem-addr val) (format t "Value at 0x~X: 0x~X~%" mem-addr (wasm-rt:wasm-funcall get-at mem-addr)) (let* ((page-size #x10000) (mem-addr (- (* page-size 2) (cffi:foreign-type-size :uint32))) (val #xFEA09)) (wasm-rt:wasm-funcall set-at mem-addr val) (format t "Value at 0x~X: 0x~X" mem-addr (wasm-rt:wasm-funcall get-at mem-addr))))))
515236e092f1cf31046bb7e13c3721ab4f2f7fd7e36b80d84c84d8208f805b0b
inanna-malick/merkle-schemes
Orphans.hs
-- FIXME: can I remove this? # LANGUAGE IncoherentInstances # # OPTIONS_GHC -fno - warn - orphans # module Data.Aeson.Orphans where -------------------------------------------- import Data.Aeson -------------------------------------------- import Util.RecursionSchemes -------------------------------------------- -- FIXME: orphans, but these should exist instance (ToJSON1 f, ToJSON a) => ToJSON (f a) where toJSON = liftToJSON toJSON toJSONList instance (FromJSON1 f, FromJSON a) => FromJSON (f a) where parseJSON = liftParseJSON parseJSON parseJSONList instance (Traversable f, FromJSON1 f) => FromJSON (Fix f) where parseJSON = anaM parseJSON instance (Functor f, ToJSON1 f) => ToJSON (Fix f) where toJSON = cata toJSON
null
https://raw.githubusercontent.com/inanna-malick/merkle-schemes/4eac64f4df12ea7d1d1f3bb34010424db19e0a9e/merkle-schemes/src/Data/Aeson/Orphans.hs
haskell
FIXME: can I remove this? ------------------------------------------ ------------------------------------------ ------------------------------------------ FIXME: orphans, but these should exist
# LANGUAGE IncoherentInstances # # OPTIONS_GHC -fno - warn - orphans # module Data.Aeson.Orphans where import Data.Aeson import Util.RecursionSchemes instance (ToJSON1 f, ToJSON a) => ToJSON (f a) where toJSON = liftToJSON toJSON toJSONList instance (FromJSON1 f, FromJSON a) => FromJSON (f a) where parseJSON = liftParseJSON parseJSON parseJSONList instance (Traversable f, FromJSON1 f) => FromJSON (Fix f) where parseJSON = anaM parseJSON instance (Functor f, ToJSON1 f) => ToJSON (Fix f) where toJSON = cata toJSON
5d134fe9e48f802c006aaac7334d485db6be7fc5f0f324a26febdd7033ed5837
msakai/toysolver
TextUtil.hs
{-# OPTIONS_HADDOCK show-extensions #-} {-# LANGUAGE BangPatterns #-} ----------------------------------------------------------------------------- -- | -- Module : ToySolver.Internal.TextUtil Copyright : ( c ) 2012 - 2014 -- License : BSD-style -- -- Maintainer : -- Stability : provisional -- Portability : non-portable -- ----------------------------------------------------------------------------- module ToySolver.Internal.TextUtil ( readInt , readUnsignedInteger ) where import Control.Exception import Data.Word # INLINABLE readInt # readInt :: String -> Int readInt ('-':str) = - readUnsignedInt str readInt str = readUnsignedInt str {-# INLINABLE readUnsignedInt #-} readUnsignedInt :: String -> Int readUnsignedInt str = go 0 str where go !r [] = r go !r (c:cs) = go (r*10 + charToInt c) cs charToInt :: Char -> Int charToInt '0' = 0 charToInt '1' = 1 charToInt '2' = 2 charToInt '3' = 3 charToInt '4' = 4 charToInt '5' = 5 charToInt '6' = 6 charToInt '7' = 7 charToInt '8' = 8 charToInt '9' = 9 -- | 'read' allocate too many intermediate 'Integer'. -- Therefore we use this optimized implementation instead. -- Many intermediate values in this implementation will be optimized -- away by worker-wrapper transformation and unboxing. # INLINABLE readUnsignedInteger # readUnsignedInteger :: String -> Integer readUnsignedInteger str = assert (result == read str) $ result where result :: Integer result = go 0 str lim :: Word lim = maxBound `div` 10 go :: Integer -> [Char] -> Integer go !r [] = r go !r ds = case go2 0 1 ds of (r2,b,ds2) -> go (r * fromIntegral b + fromIntegral r2) ds2 go2 :: Word -> Word -> [Char] -> (Word, Word, [Char]) go2 !r !b dds | assert (b > r) (b > lim) = (r,b,dds) go2 !r !b [] = (r, b, []) go2 !r !b (d:ds) = go2 (r*10 + charToWord d) (b*10) ds charToWord :: Char -> Word charToWord '0' = 0 charToWord '1' = 1 charToWord '2' = 2 charToWord '3' = 3 charToWord '4' = 4 charToWord '5' = 5 charToWord '6' = 6 charToWord '7' = 7 charToWord '8' = 8 charToWord '9' = 9
null
https://raw.githubusercontent.com/msakai/toysolver/5dc84559c2ec782b2247febe529e4abd0971d1d3/src/ToySolver/Internal/TextUtil.hs
haskell
# OPTIONS_HADDOCK show-extensions # # LANGUAGE BangPatterns # --------------------------------------------------------------------------- | Module : ToySolver.Internal.TextUtil License : BSD-style Maintainer : Stability : provisional Portability : non-portable --------------------------------------------------------------------------- # INLINABLE readUnsignedInt # | 'read' allocate too many intermediate 'Integer'. Therefore we use this optimized implementation instead. Many intermediate values in this implementation will be optimized away by worker-wrapper transformation and unboxing.
Copyright : ( c ) 2012 - 2014 module ToySolver.Internal.TextUtil ( readInt , readUnsignedInteger ) where import Control.Exception import Data.Word # INLINABLE readInt # readInt :: String -> Int readInt ('-':str) = - readUnsignedInt str readInt str = readUnsignedInt str readUnsignedInt :: String -> Int readUnsignedInt str = go 0 str where go !r [] = r go !r (c:cs) = go (r*10 + charToInt c) cs charToInt :: Char -> Int charToInt '0' = 0 charToInt '1' = 1 charToInt '2' = 2 charToInt '3' = 3 charToInt '4' = 4 charToInt '5' = 5 charToInt '6' = 6 charToInt '7' = 7 charToInt '8' = 8 charToInt '9' = 9 # INLINABLE readUnsignedInteger # readUnsignedInteger :: String -> Integer readUnsignedInteger str = assert (result == read str) $ result where result :: Integer result = go 0 str lim :: Word lim = maxBound `div` 10 go :: Integer -> [Char] -> Integer go !r [] = r go !r ds = case go2 0 1 ds of (r2,b,ds2) -> go (r * fromIntegral b + fromIntegral r2) ds2 go2 :: Word -> Word -> [Char] -> (Word, Word, [Char]) go2 !r !b dds | assert (b > r) (b > lim) = (r,b,dds) go2 !r !b [] = (r, b, []) go2 !r !b (d:ds) = go2 (r*10 + charToWord d) (b*10) ds charToWord :: Char -> Word charToWord '0' = 0 charToWord '1' = 1 charToWord '2' = 2 charToWord '3' = 3 charToWord '4' = 4 charToWord '5' = 5 charToWord '6' = 6 charToWord '7' = 7 charToWord '8' = 8 charToWord '9' = 9
985203257fb0995177f548aae339999bb5bfa391de0aa8acaa7ab0aef5429cd3
tek/polysemy-hasql
LookupPartialTest.hs
module Polysemy.Hasql.Test.Tree.LookupPartialTest where import Polysemy.Db.Kind.Data.Tree (PrimTree, ProdRoot, ProdTree) import Polysemy.Db.Tree.Lookup (lookupNames) import Polysemy.Db.Tree.Partial (PartialTree, field, partially, (++>)) import Polysemy.Test (UnitTest, runTestAuto, (===)) data Sub1 = Sub1 { int :: Int } deriving stock (Eq, Show, Generic) data Sub = Sub { double :: Double, sub1 :: Sub1 } deriving stock (Eq, Show, Generic) data Dat = Dat { sub :: Sub } deriving stock (Eq, Show, Generic) type Sub1Tree = ProdTree "Sub1" Sub1 '[ PrimTree "int" Int ] type DatTree = ProdRoot Dat '[ ProdTree "sub" Sub '[ PrimTree "double" Double, ProdTree "sub1" Sub1 '[ PrimTree "int" Int ] ] ] tree :: PartialTree DatTree tree = partially @Dat ++> field @"int" (5 :: Int) ++> field @"double" (2.4 :: Double) target :: PartialTree Sub1Tree target = partially @Sub1 ++> field @"int" (5 :: Int) test_lookupPartial :: UnitTest test_lookupPartial = runTestAuto do target === lookupNames @["sub", "sub1"] tree
null
https://raw.githubusercontent.com/tek/polysemy-hasql/443ccf348bb8af0ec0543981d58af8aa26fc4c10/packages/hasql/test/Polysemy/Hasql/Test/Tree/LookupPartialTest.hs
haskell
module Polysemy.Hasql.Test.Tree.LookupPartialTest where import Polysemy.Db.Kind.Data.Tree (PrimTree, ProdRoot, ProdTree) import Polysemy.Db.Tree.Lookup (lookupNames) import Polysemy.Db.Tree.Partial (PartialTree, field, partially, (++>)) import Polysemy.Test (UnitTest, runTestAuto, (===)) data Sub1 = Sub1 { int :: Int } deriving stock (Eq, Show, Generic) data Sub = Sub { double :: Double, sub1 :: Sub1 } deriving stock (Eq, Show, Generic) data Dat = Dat { sub :: Sub } deriving stock (Eq, Show, Generic) type Sub1Tree = ProdTree "Sub1" Sub1 '[ PrimTree "int" Int ] type DatTree = ProdRoot Dat '[ ProdTree "sub" Sub '[ PrimTree "double" Double, ProdTree "sub1" Sub1 '[ PrimTree "int" Int ] ] ] tree :: PartialTree DatTree tree = partially @Dat ++> field @"int" (5 :: Int) ++> field @"double" (2.4 :: Double) target :: PartialTree Sub1Tree target = partially @Sub1 ++> field @"int" (5 :: Int) test_lookupPartial :: UnitTest test_lookupPartial = runTestAuto do target === lookupNames @["sub", "sub1"] tree
c3be9d7fae71785c4a77353a67e618bdea64a8dd1a2d7a1a34279749feb38ed5
shuieryin/wechat_mud
csv_to_object.erl
%%%------------------------------------------------------------------- @author shuieryin ( C ) 2015 , Shuieryin %%% @doc %%% %%% Converts csv files to object configs according to function %%% provided from caller. %%% %%% @end Created : 04 . Nov 2015 9:13 PM %%%------------------------------------------------------------------- -module(csv_to_object). -author("shuieryin"). %% API -export([ traverse_merge_files/4, traverse_files/3, traverse_files/4, parse_file/2, parse_file/3, convert_priv_paths/1 ]). -define(FILE_EXTENSION, ".csv"). -define(NAME_TYPE_SEPARATOR, ":"). -type key() :: atom(). % generic atom -type value() :: term(). % generic term -type field_type() :: atom(). % generic atom -type csv_line() :: string(). -type csv_row_data() :: tuple(). % generic tuple -type csv_data() :: #{key() => csv_row_data()}. -type field_info() :: {key(), field_type()}. -type field_infos() :: [field_info()]. -type csv_object() :: #{key() => csv_data()}. -type csv_data_struct() :: {module(), [atom()]} | module() | {module(), [atom()], function()}. % generic atom -include("../data_type/player_profile.hrl"). -export_type([ csv_data/0, csv_object/0, csv_data_struct/0 ]). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc Generates object configs from files of given folder and merge as one map . %% %% @end %%-------------------------------------------------------------------- -spec traverse_merge_files(FilePathList, AccValuesMap, ExistingValuesMap, RowFun) -> {ValuesMap, ChangedValuesMap} when FilePathList :: [file:filename_all()], RowFun :: function(), ValuesMap :: csv_data(), AccValuesMap :: ValuesMap, ExistingValuesMap :: ValuesMap, ChangedValuesMap :: ValuesMap. traverse_merge_files(FilePathList, AccValuesMap, ExistingValuesMap, RowFun) -> {ValuesMap, ChangedValuesMap, _ExistingValuesMap} = lists:foldl( fun(FilePath, {AccValues, AccChangedValues, ExistingValues}) -> FileName = filename:basename(FilePath), case filename:extension(FileName) == ?FILE_EXTENSION of true -> {Values, ChangedValues} = parse_file(FilePath, ExistingValues, RowFun), NewAccValues = maps:merge(AccValues, Values), NewAccChangedValues = maps:merge(AccChangedValues, ChangedValues), {NewAccValues, NewAccChangedValues, ExistingValues}; false -> {AccValues, AccChangedValues, ExistingValues} end end, {AccValuesMap, #{}, ExistingValuesMap}, FilePathList), {ValuesMap, ChangedValuesMap}. %%-------------------------------------------------------------------- %% @doc %% Generates object configs from files of given folder with default %% row function. %% %% @end %%-------------------------------------------------------------------- -spec traverse_files(FilePathList, AccMapFromFiles, AccChangedMapFromFiles) -> {MapFromFiles, ChangedMapFromFiles, DeletedFilesStruct} when FilePathList :: [file:name_all()], AccMapFromFiles :: csv_data(), MapFromFiles :: AccMapFromFiles, AccChangedMapFromFiles :: AccMapFromFiles, ChangedMapFromFiles :: AccMapFromFiles, DeletedFilesStruct :: [csv_data_struct()]. traverse_files(FilePathList, AccMapFromFiles, AccChangedMapFromFiles) -> traverse_files(FilePathList, AccMapFromFiles, AccChangedMapFromFiles, fun default_row_fun/1). %%-------------------------------------------------------------------- %% @doc %% Generates object configs from files of given folder. %% %% @end %%-------------------------------------------------------------------- -spec traverse_files(FilePathList, AccMapFromFiles, AccChangedMapFromFiles, RowFun) -> {MapFromFiles, ChangedMapFromFiles, DeletedFilesStruct} when FilePathList :: [file:name_all()], RowFun :: function(), AccMapFromFiles :: csv_data(), AccChangedMapFromFiles :: AccMapFromFiles, MapFromFiles :: AccMapFromFiles, ChangedMapFromFiles :: AccMapFromFiles, DeletedFilesStruct :: [csv_data_struct()]. traverse_files(FilePathList, AccMapFromFiles, AccChangedMapFromFiles, RowFun) -> {MapFromFiles, ChangedMapFromFiles, DeletedFilesStruct} = lists:foldl( fun(FilePath, {AccAccMapFromFiles, AccAccChangedMapFromFiles, AccDeletedFilesStruct}) -> FileName = filename:basename(FilePath), case filename:extension(FileName) == ?FILE_EXTENSION of true -> Key = list_to_atom(filename:rootname(FileName)), ExistingChangedValuesMap = maps:get(Key, AccMapFromFiles, #{}), {ValuesMap, ChangedValuesMap} = parse_file(FilePath, ExistingChangedValuesMap, RowFun), { AccAccMapFromFiles#{ Key => ValuesMap }, case maps:size(ChangedValuesMap) =:= 0 of true -> AccAccChangedMapFromFiles; false -> AccAccChangedMapFromFiles#{ Key => ChangedValuesMap } end, case maps:keys(maps:without(maps:keys(ValuesMap), ExistingChangedValuesMap)) of [] -> AccDeletedFilesStruct; DeletedRecordNames -> [{Key, DeletedRecordNames} | AccDeletedFilesStruct] end }; false -> {AccAccMapFromFiles, AccAccChangedMapFromFiles} end end, {AccMapFromFiles, AccChangedMapFromFiles, []}, FilePathList), {MapFromFiles, ChangedMapFromFiles, DeletedFilesStruct}. %%-------------------------------------------------------------------- %% @doc %% Generates object configs with default row function from file which %% the number of object configs equals to the number of rows. %% %% @end %%-------------------------------------------------------------------- -spec parse_file(FilePath, ExistingChangedValuesMap) -> {ValuesMap, ChangedValuesMap} when FilePath :: file:filename_all(), ValuesMap :: csv_data(), ChangedValuesMap :: ValuesMap, ExistingChangedValuesMap :: ValuesMap. parse_file(FilePath, ExistingChangedValuesMap) -> parse_file(FilePath, ExistingChangedValuesMap, fun default_row_fun/1). %%-------------------------------------------------------------------- %% @doc %% Generates object configs from file which the number of object %% configs equals to the number of rows. %% %% @end %%-------------------------------------------------------------------- -spec parse_file(FilePath, ExistingChangedValuesMap, RowFun) -> {ValuesMap, ChangedValuesMap} when FilePath :: file:filename(), RowFun :: function(), ValuesMap :: csv_data(), ExistingChangedValuesMap :: ValuesMap, ChangedValuesMap :: ValuesMap. parse_file(FilePath, ExistingChangedValuesMap, RowFun) -> {ok, File} = file:open(FilePath, [read]), RecordName = list_to_atom(filename:rootname(filename:basename(FilePath))), {ok, {ValuesMap, ChangedValuesMap}} = ecsv:process_csv_file_with(File, fun traverse_rows/2, {0, RowFun, RecordName, ExistingChangedValuesMap}), ok = file:close(File), {ValuesMap, ChangedValuesMap}. %%-------------------------------------------------------------------- %% @doc %% List changed priv file paths for hot code upgrade before committed. %% %% @end %%-------------------------------------------------------------------- -spec convert_priv_paths({ModifiedFiles, AddedFiles, DeletedFiles}) -> no_change | {ModifiedFilePaths, AddedFilePaths, DeletedFileNames} when ModifiedFiles :: [file:filename_all()], AddedFiles :: ModifiedFiles, DeletedFiles :: ModifiedFiles, ModifiedFilePaths :: ModifiedFiles, AddedFilePaths :: ModifiedFiles, DeletedFileNames :: [atom()]. % file name % generic atom convert_priv_paths({ModifiedFiles, AddedFiles, DeletedFiles}) -> BasePath = filename:dirname(code:priv_dir(elib:app_name())), if ModifiedFiles == [] andalso AddedFiles == [] andalso DeletedFiles == [] -> no_change; true -> ModifiedFilePaths = [filename:join(BasePath, ModifiedFile) || ModifiedFile <- ModifiedFiles], AddedFilePaths = [filename:join(BasePath, AddedFile) || AddedFile <- AddedFiles], DeletedFileNames = [list_to_atom(filename:basename(filename:rootname(DeletedFile))) || DeletedFile <- DeletedFiles], {ModifiedFilePaths, AddedFilePaths, DeletedFileNames} end. %%%=================================================================== Internal functions %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Reads line from csv file %% %% @end %%-------------------------------------------------------------------- -spec traverse_rows(NewRowData, State) -> {RowValuesMap, ChangedRowValuesMap} when NewRowData :: {newline, [csv_line()]} | {eof}, RowFun :: function(), RowValuesMap :: csv_data(), ChangedRowValuesMap :: RowValuesMap, Counter :: non_neg_integer(), % generic integer FieldInfos :: field_infos(), AccRowValuesMap :: RowValuesMap, AccChangedRowValuesMap :: RowValuesMap, RecordName :: atom(), % generic atom State :: {Counter, RowFun, FieldInfos, AccRowValuesMap, AccChangedRowValuesMap, ExistingChangedValuesMap, RecordName} | {0, RowFun, RecordName, ExistingChangedValuesMap}. traverse_rows({newline, NewRow}, {Counter, RowFun, FieldInfos, AccRowValuesMap, AccChangedRowValuesMap, ExistingChangedValuesMap, RecordName}) -> [_UselessHead, CurRowKey | _RestCurRowValues] = CurRowValues = traverse_column(NewRow, FieldInfos, [RecordName]), {UpdatedAccRowValuesMap, UpdatedAccChangedRowValuesMap} = case CurRowKey of undefined -> {AccRowValuesMap, AccChangedRowValuesMap}; _CurRowKey -> case RowFun(CurRowValues) of undefined -> {AccRowValuesMap, AccChangedRowValuesMap}; ConvertedCurRowValues -> ExistingRowValues = maps:get(CurRowKey, ExistingChangedValuesMap, undefined), { AccRowValuesMap#{ CurRowKey => ConvertedCurRowValues }, case ExistingRowValues == ConvertedCurRowValues of true -> AccChangedRowValuesMap; false -> AccChangedRowValuesMap#{ CurRowKey => ConvertedCurRowValues } end } end end, {Counter + 1, RowFun, FieldInfos, UpdatedAccRowValuesMap, UpdatedAccChangedRowValuesMap, ExistingChangedValuesMap, RecordName}; traverse_rows({newline, NewRow}, {0, RowFun, RecordName, ExistingChangedValuesMap}) -> FieldInfos = gen_fieldinfos(NewRow, []), {1, RowFun, FieldInfos, #{}, #{}, ExistingChangedValuesMap, RecordName}; traverse_rows({eof}, {_Counter, _RowFun, _FieldInfos, RowValuesMap, ChangedRowValuesMap, _ExistingChangedValuesMap, _RecordName}) -> {RowValuesMap, ChangedRowValuesMap}. %%-------------------------------------------------------------------- %% @doc Generates field infos from first row %% %% @end %%-------------------------------------------------------------------- -spec gen_fieldinfos(NewRow, AccFieldInfos) -> FieldInfos when NewRow :: [csv_line()], AccFieldInfos :: field_infos(), FieldInfos :: AccFieldInfos. gen_fieldinfos([], AccFieldInfos) -> lists:reverse(AccFieldInfos); gen_fieldinfos([RawFieldInfoStr | Tail], AccFieldInfos) -> FieldInfo = get_field_name_type(RawFieldInfoStr), gen_fieldinfos(Tail, [FieldInfo | AccFieldInfos]). %%-------------------------------------------------------------------- %% @doc %% Generates values map from rest of columns of current row. %% %% Supported types: %% integer, float, atom, string, and other terms %% %% @end %%-------------------------------------------------------------------- -spec traverse_column(RowData, FieldInfos, AccValues) -> FinalValues when RowData :: [csv_line()], FieldInfos :: field_infos(), AccValues :: [value()], FinalValues :: AccValues. traverse_column([RawValue0 | TailValues], [{_Key, FieldType} | TailFieldInfos], AccValues) -> eliminate new line genereated by Numbers.app replace special double quote with ' \ " ' from Numbers.app replace special double quote with ' \ " ' from Numbers.app Value = try case RawValue of [] -> undefined; _RawValue -> case FieldType of atom -> list_to_atom(RawValue); binary -> list_to_binary(RawValue); integer -> list_to_integer(RawValue); float -> list_to_float(RawValue); term -> {ok, Tokens, _EndLocation} = erl_scan:string(RawValue), {ok, Term} = erl_parse:parse_term(Tokens), Term; exprs -> {ok, Tokens, _EndLocation} = erl_scan:string(RawValue), {ok, Exprs} = erl_parse:parse_exprs(Tokens), Exprs; skill -> RawValueBin = list_to_binary(RawValue), FromValueNames = collect_formula_value_names(RawValueBin, <<"From">>), ToValueNames = collect_formula_value_names(RawValueBin, <<"To">>), {ok, Tokens, _EndLocation} = erl_scan:string(RawValue), {ok, Exprs} = erl_parse:parse_exprs(Tokens), #skill_formula{ formula = Exprs, from_var_names = FromValueNames, to_var_names = ToValueNames }; _FieldType -> RawValue end end catch Type:Reason:Stacktrace -> error_logger:error_msg("traverse_column failed~nRawValue:~tp~nType:~p~nReason:~p~nStackTrace:~p~n", [RawValue, Type, Reason, Stacktrace]), RawValue end, traverse_column(TailValues, TailFieldInfos, [Value | AccValues]); traverse_column([], _FieldInfos, AccValues) -> lists:reverse(AccValues). %%-------------------------------------------------------------------- %% @doc %% Collect value names form formula. %% %% @end %%-------------------------------------------------------------------- -spec collect_formula_value_names(RawValue, Prefix) -> ValueNames when RawValue :: binary(), Prefix :: binary(), ValueNames :: erl_eval:bindings(). collect_formula_value_names(RawValue, Prefix) -> MatchRE = <<"(", Prefix/binary, "_([A-z0-9]*))[\s|.|,]{1}">>, case re:run(RawValue, MatchRE, [global, {capture, all_but_first, binary}]) of {match, MatchedList} -> collect_formula_value_names_convert(MatchedList, erl_eval:new_bindings()); nomatch -> [] end. %%-------------------------------------------------------------------- %% @doc Convert matched value names to erl_eval bindings . %% %% @end %%-------------------------------------------------------------------- -spec collect_formula_value_names_convert(MatchedList, AccValueNames) -> ValueNames when MatchValue :: binary(), MatchedList :: [[MatchValue]], AccValueNames :: erl_eval:bindings(), ValueNames :: AccValueNames. collect_formula_value_names_convert([[RawBindingKey, RawStatusFieldName] | RestMatchedList], AccValueNames) -> UpdatedAccValueNames = case erl_eval:binding(RawBindingKey, AccValueNames) of unbound -> erl_eval:add_binding( binary_to_atom(RawStatusFieldName, utf8), binary_to_atom(RawBindingKey, utf8), AccValueNames ); _Exist -> AccValueNames end, collect_formula_value_names_convert(RestMatchedList, UpdatedAccValueNames); collect_formula_value_names_convert([], ValueNames) -> ValueNames. %%-------------------------------------------------------------------- %% @doc %% Default row function which directly return row values map. %% %% @end %%-------------------------------------------------------------------- -spec default_row_fun(RowValues) -> csv_row_data() when RowValues :: [value()]. default_row_fun(RowValues) -> list_to_tuple(RowValues). %%-------------------------------------------------------------------- %% @doc %% Get field name and field type from raw field name info string. " fieldname : fieldtype " = > { FieldName , FieldType } %% %% @end %%-------------------------------------------------------------------- -spec get_field_name_type(FieldNameInfoStr) -> FieldInfo when FieldNameInfoStr :: csv_line(), FieldInfo :: field_info(). get_field_name_type(FieldNameInfoStr) -> [FieldNameStr | TailFieldTypeStr] = string:tokens(FieldNameInfoStr, ?NAME_TYPE_SEPARATOR), FieldName = list_to_atom(FieldNameStr), FieldType = case TailFieldTypeStr of [] -> string; [FieldTypeStr | _RestFieldTypeStrs] -> list_to_atom(FieldTypeStr) end, {FieldName, FieldType}.
null
https://raw.githubusercontent.com/shuieryin/wechat_mud/b2a9251a9b208fee5cd8c4213759750b95c8b8aa/src/common/csv_to_object.erl
erlang
------------------------------------------------------------------- @doc Converts csv files to object configs according to function provided from caller. @end ------------------------------------------------------------------- API generic atom generic term generic atom generic tuple generic atom =================================================================== API =================================================================== -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Generates object configs from files of given folder with default row function. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Generates object configs from files of given folder. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Generates object configs with default row function from file which the number of object configs equals to the number of rows. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Generates object configs from file which the number of object configs equals to the number of rows. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc List changed priv file paths for hot code upgrade before committed. @end -------------------------------------------------------------------- file name % generic atom =================================================================== =================================================================== -------------------------------------------------------------------- @doc Reads line from csv file @end -------------------------------------------------------------------- generic integer generic atom -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Generates values map from rest of columns of current row. Supported types: integer, float, atom, string, and other terms @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Collect value names form formula. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Default row function which directly return row values map. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Get field name and field type from raw field name info string. @end --------------------------------------------------------------------
@author shuieryin ( C ) 2015 , Shuieryin Created : 04 . Nov 2015 9:13 PM -module(csv_to_object). -author("shuieryin"). -export([ traverse_merge_files/4, traverse_files/3, traverse_files/4, parse_file/2, parse_file/3, convert_priv_paths/1 ]). -define(FILE_EXTENSION, ".csv"). -define(NAME_TYPE_SEPARATOR, ":"). -type csv_line() :: string(). -type csv_data() :: #{key() => csv_row_data()}. -type field_info() :: {key(), field_type()}. -type field_infos() :: [field_info()]. -type csv_object() :: #{key() => csv_data()}. -include("../data_type/player_profile.hrl"). -export_type([ csv_data/0, csv_object/0, csv_data_struct/0 ]). Generates object configs from files of given folder and merge as one map . -spec traverse_merge_files(FilePathList, AccValuesMap, ExistingValuesMap, RowFun) -> {ValuesMap, ChangedValuesMap} when FilePathList :: [file:filename_all()], RowFun :: function(), ValuesMap :: csv_data(), AccValuesMap :: ValuesMap, ExistingValuesMap :: ValuesMap, ChangedValuesMap :: ValuesMap. traverse_merge_files(FilePathList, AccValuesMap, ExistingValuesMap, RowFun) -> {ValuesMap, ChangedValuesMap, _ExistingValuesMap} = lists:foldl( fun(FilePath, {AccValues, AccChangedValues, ExistingValues}) -> FileName = filename:basename(FilePath), case filename:extension(FileName) == ?FILE_EXTENSION of true -> {Values, ChangedValues} = parse_file(FilePath, ExistingValues, RowFun), NewAccValues = maps:merge(AccValues, Values), NewAccChangedValues = maps:merge(AccChangedValues, ChangedValues), {NewAccValues, NewAccChangedValues, ExistingValues}; false -> {AccValues, AccChangedValues, ExistingValues} end end, {AccValuesMap, #{}, ExistingValuesMap}, FilePathList), {ValuesMap, ChangedValuesMap}. -spec traverse_files(FilePathList, AccMapFromFiles, AccChangedMapFromFiles) -> {MapFromFiles, ChangedMapFromFiles, DeletedFilesStruct} when FilePathList :: [file:name_all()], AccMapFromFiles :: csv_data(), MapFromFiles :: AccMapFromFiles, AccChangedMapFromFiles :: AccMapFromFiles, ChangedMapFromFiles :: AccMapFromFiles, DeletedFilesStruct :: [csv_data_struct()]. traverse_files(FilePathList, AccMapFromFiles, AccChangedMapFromFiles) -> traverse_files(FilePathList, AccMapFromFiles, AccChangedMapFromFiles, fun default_row_fun/1). -spec traverse_files(FilePathList, AccMapFromFiles, AccChangedMapFromFiles, RowFun) -> {MapFromFiles, ChangedMapFromFiles, DeletedFilesStruct} when FilePathList :: [file:name_all()], RowFun :: function(), AccMapFromFiles :: csv_data(), AccChangedMapFromFiles :: AccMapFromFiles, MapFromFiles :: AccMapFromFiles, ChangedMapFromFiles :: AccMapFromFiles, DeletedFilesStruct :: [csv_data_struct()]. traverse_files(FilePathList, AccMapFromFiles, AccChangedMapFromFiles, RowFun) -> {MapFromFiles, ChangedMapFromFiles, DeletedFilesStruct} = lists:foldl( fun(FilePath, {AccAccMapFromFiles, AccAccChangedMapFromFiles, AccDeletedFilesStruct}) -> FileName = filename:basename(FilePath), case filename:extension(FileName) == ?FILE_EXTENSION of true -> Key = list_to_atom(filename:rootname(FileName)), ExistingChangedValuesMap = maps:get(Key, AccMapFromFiles, #{}), {ValuesMap, ChangedValuesMap} = parse_file(FilePath, ExistingChangedValuesMap, RowFun), { AccAccMapFromFiles#{ Key => ValuesMap }, case maps:size(ChangedValuesMap) =:= 0 of true -> AccAccChangedMapFromFiles; false -> AccAccChangedMapFromFiles#{ Key => ChangedValuesMap } end, case maps:keys(maps:without(maps:keys(ValuesMap), ExistingChangedValuesMap)) of [] -> AccDeletedFilesStruct; DeletedRecordNames -> [{Key, DeletedRecordNames} | AccDeletedFilesStruct] end }; false -> {AccAccMapFromFiles, AccAccChangedMapFromFiles} end end, {AccMapFromFiles, AccChangedMapFromFiles, []}, FilePathList), {MapFromFiles, ChangedMapFromFiles, DeletedFilesStruct}. -spec parse_file(FilePath, ExistingChangedValuesMap) -> {ValuesMap, ChangedValuesMap} when FilePath :: file:filename_all(), ValuesMap :: csv_data(), ChangedValuesMap :: ValuesMap, ExistingChangedValuesMap :: ValuesMap. parse_file(FilePath, ExistingChangedValuesMap) -> parse_file(FilePath, ExistingChangedValuesMap, fun default_row_fun/1). -spec parse_file(FilePath, ExistingChangedValuesMap, RowFun) -> {ValuesMap, ChangedValuesMap} when FilePath :: file:filename(), RowFun :: function(), ValuesMap :: csv_data(), ExistingChangedValuesMap :: ValuesMap, ChangedValuesMap :: ValuesMap. parse_file(FilePath, ExistingChangedValuesMap, RowFun) -> {ok, File} = file:open(FilePath, [read]), RecordName = list_to_atom(filename:rootname(filename:basename(FilePath))), {ok, {ValuesMap, ChangedValuesMap}} = ecsv:process_csv_file_with(File, fun traverse_rows/2, {0, RowFun, RecordName, ExistingChangedValuesMap}), ok = file:close(File), {ValuesMap, ChangedValuesMap}. -spec convert_priv_paths({ModifiedFiles, AddedFiles, DeletedFiles}) -> no_change | {ModifiedFilePaths, AddedFilePaths, DeletedFileNames} when ModifiedFiles :: [file:filename_all()], AddedFiles :: ModifiedFiles, DeletedFiles :: ModifiedFiles, ModifiedFilePaths :: ModifiedFiles, AddedFilePaths :: ModifiedFiles, convert_priv_paths({ModifiedFiles, AddedFiles, DeletedFiles}) -> BasePath = filename:dirname(code:priv_dir(elib:app_name())), if ModifiedFiles == [] andalso AddedFiles == [] andalso DeletedFiles == [] -> no_change; true -> ModifiedFilePaths = [filename:join(BasePath, ModifiedFile) || ModifiedFile <- ModifiedFiles], AddedFilePaths = [filename:join(BasePath, AddedFile) || AddedFile <- AddedFiles], DeletedFileNames = [list_to_atom(filename:basename(filename:rootname(DeletedFile))) || DeletedFile <- DeletedFiles], {ModifiedFilePaths, AddedFilePaths, DeletedFileNames} end. Internal functions -spec traverse_rows(NewRowData, State) -> {RowValuesMap, ChangedRowValuesMap} when NewRowData :: {newline, [csv_line()]} | {eof}, RowFun :: function(), RowValuesMap :: csv_data(), ChangedRowValuesMap :: RowValuesMap, FieldInfos :: field_infos(), AccRowValuesMap :: RowValuesMap, AccChangedRowValuesMap :: RowValuesMap, State :: {Counter, RowFun, FieldInfos, AccRowValuesMap, AccChangedRowValuesMap, ExistingChangedValuesMap, RecordName} | {0, RowFun, RecordName, ExistingChangedValuesMap}. traverse_rows({newline, NewRow}, {Counter, RowFun, FieldInfos, AccRowValuesMap, AccChangedRowValuesMap, ExistingChangedValuesMap, RecordName}) -> [_UselessHead, CurRowKey | _RestCurRowValues] = CurRowValues = traverse_column(NewRow, FieldInfos, [RecordName]), {UpdatedAccRowValuesMap, UpdatedAccChangedRowValuesMap} = case CurRowKey of undefined -> {AccRowValuesMap, AccChangedRowValuesMap}; _CurRowKey -> case RowFun(CurRowValues) of undefined -> {AccRowValuesMap, AccChangedRowValuesMap}; ConvertedCurRowValues -> ExistingRowValues = maps:get(CurRowKey, ExistingChangedValuesMap, undefined), { AccRowValuesMap#{ CurRowKey => ConvertedCurRowValues }, case ExistingRowValues == ConvertedCurRowValues of true -> AccChangedRowValuesMap; false -> AccChangedRowValuesMap#{ CurRowKey => ConvertedCurRowValues } end } end end, {Counter + 1, RowFun, FieldInfos, UpdatedAccRowValuesMap, UpdatedAccChangedRowValuesMap, ExistingChangedValuesMap, RecordName}; traverse_rows({newline, NewRow}, {0, RowFun, RecordName, ExistingChangedValuesMap}) -> FieldInfos = gen_fieldinfos(NewRow, []), {1, RowFun, FieldInfos, #{}, #{}, ExistingChangedValuesMap, RecordName}; traverse_rows({eof}, {_Counter, _RowFun, _FieldInfos, RowValuesMap, ChangedRowValuesMap, _ExistingChangedValuesMap, _RecordName}) -> {RowValuesMap, ChangedRowValuesMap}. Generates field infos from first row -spec gen_fieldinfos(NewRow, AccFieldInfos) -> FieldInfos when NewRow :: [csv_line()], AccFieldInfos :: field_infos(), FieldInfos :: AccFieldInfos. gen_fieldinfos([], AccFieldInfos) -> lists:reverse(AccFieldInfos); gen_fieldinfos([RawFieldInfoStr | Tail], AccFieldInfos) -> FieldInfo = get_field_name_type(RawFieldInfoStr), gen_fieldinfos(Tail, [FieldInfo | AccFieldInfos]). -spec traverse_column(RowData, FieldInfos, AccValues) -> FinalValues when RowData :: [csv_line()], FieldInfos :: field_infos(), AccValues :: [value()], FinalValues :: AccValues. traverse_column([RawValue0 | TailValues], [{_Key, FieldType} | TailFieldInfos], AccValues) -> eliminate new line genereated by Numbers.app replace special double quote with ' \ " ' from Numbers.app replace special double quote with ' \ " ' from Numbers.app Value = try case RawValue of [] -> undefined; _RawValue -> case FieldType of atom -> list_to_atom(RawValue); binary -> list_to_binary(RawValue); integer -> list_to_integer(RawValue); float -> list_to_float(RawValue); term -> {ok, Tokens, _EndLocation} = erl_scan:string(RawValue), {ok, Term} = erl_parse:parse_term(Tokens), Term; exprs -> {ok, Tokens, _EndLocation} = erl_scan:string(RawValue), {ok, Exprs} = erl_parse:parse_exprs(Tokens), Exprs; skill -> RawValueBin = list_to_binary(RawValue), FromValueNames = collect_formula_value_names(RawValueBin, <<"From">>), ToValueNames = collect_formula_value_names(RawValueBin, <<"To">>), {ok, Tokens, _EndLocation} = erl_scan:string(RawValue), {ok, Exprs} = erl_parse:parse_exprs(Tokens), #skill_formula{ formula = Exprs, from_var_names = FromValueNames, to_var_names = ToValueNames }; _FieldType -> RawValue end end catch Type:Reason:Stacktrace -> error_logger:error_msg("traverse_column failed~nRawValue:~tp~nType:~p~nReason:~p~nStackTrace:~p~n", [RawValue, Type, Reason, Stacktrace]), RawValue end, traverse_column(TailValues, TailFieldInfos, [Value | AccValues]); traverse_column([], _FieldInfos, AccValues) -> lists:reverse(AccValues). -spec collect_formula_value_names(RawValue, Prefix) -> ValueNames when RawValue :: binary(), Prefix :: binary(), ValueNames :: erl_eval:bindings(). collect_formula_value_names(RawValue, Prefix) -> MatchRE = <<"(", Prefix/binary, "_([A-z0-9]*))[\s|.|,]{1}">>, case re:run(RawValue, MatchRE, [global, {capture, all_but_first, binary}]) of {match, MatchedList} -> collect_formula_value_names_convert(MatchedList, erl_eval:new_bindings()); nomatch -> [] end. Convert matched value names to erl_eval bindings . -spec collect_formula_value_names_convert(MatchedList, AccValueNames) -> ValueNames when MatchValue :: binary(), MatchedList :: [[MatchValue]], AccValueNames :: erl_eval:bindings(), ValueNames :: AccValueNames. collect_formula_value_names_convert([[RawBindingKey, RawStatusFieldName] | RestMatchedList], AccValueNames) -> UpdatedAccValueNames = case erl_eval:binding(RawBindingKey, AccValueNames) of unbound -> erl_eval:add_binding( binary_to_atom(RawStatusFieldName, utf8), binary_to_atom(RawBindingKey, utf8), AccValueNames ); _Exist -> AccValueNames end, collect_formula_value_names_convert(RestMatchedList, UpdatedAccValueNames); collect_formula_value_names_convert([], ValueNames) -> ValueNames. -spec default_row_fun(RowValues) -> csv_row_data() when RowValues :: [value()]. default_row_fun(RowValues) -> list_to_tuple(RowValues). " fieldname : fieldtype " = > { FieldName , FieldType } -spec get_field_name_type(FieldNameInfoStr) -> FieldInfo when FieldNameInfoStr :: csv_line(), FieldInfo :: field_info(). get_field_name_type(FieldNameInfoStr) -> [FieldNameStr | TailFieldTypeStr] = string:tokens(FieldNameInfoStr, ?NAME_TYPE_SEPARATOR), FieldName = list_to_atom(FieldNameStr), FieldType = case TailFieldTypeStr of [] -> string; [FieldTypeStr | _RestFieldTypeStrs] -> list_to_atom(FieldTypeStr) end, {FieldName, FieldType}.
70b6bf6908ba4e3a6cdd9ef572cdbf645e12fe9151cbdbd4ec57e8008526f4d1
adaliu-gh/htdp
10-175.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname 10-175) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/batch-io) (define-struct wc [letters words lines]) ; (make-wc Number Number Number) where letters represents the number of 1Strings ; the words represents the number of words ; the lines represents the number of line in a given file ; String -> Wc ; counts the number of letters, words, and lines in a given file (define (count n) (make-wc (count-letters (read-words n)) (length (read-words n)) (length (read-lines n)))) ; Low -> Number counts the number of 1Strings in a given list of words (define (count-letters l) (cond [(empty? l) 0] [else (+ (string-length (first l)) (count-letters (rest l)))]))
null
https://raw.githubusercontent.com/adaliu-gh/htdp/a0fca8af2ae8bdcef40d56f6f45021dd92df2995/8-13%20Arbitrarily%20Large%20Data/10-175.rkt
racket
about the language level of this file in a form that our tools can easily process. (make-wc Number Number Number) where letters represents the number of 1Strings the words represents the number of words the lines represents the number of line in a given file String -> Wc counts the number of letters, words, and lines in a given file Low -> Number
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname 10-175) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/batch-io) (define-struct wc [letters words lines]) (define (count n) (make-wc (count-letters (read-words n)) (length (read-words n)) (length (read-lines n)))) counts the number of 1Strings in a given list of words (define (count-letters l) (cond [(empty? l) 0] [else (+ (string-length (first l)) (count-letters (rest l)))]))
2d1c98c0dc6aa00b3642e3be13fdabbe93ccf6574c9e23ae9a796ad0a9b64bc3
gedge-platform/gedge-platform
exometer_slide.erl
%% This file is a copy of exometer_slide.erl from , %% with the following modifications: %% 1 ) The elements are tuples of numbers %% 2 ) Only one element for each expected interval point is added , intermediate values are discarded . Thus , if we have a window of 60s and interval of 5s , at max 12 elements %% are stored. %% 3 ) Additions can be provided as increments to the last value stored %% 4 ) sum/1 implements the sum of several slides , generating a new timestamp sequence based %% on the given intervals. Elements on each window are added to the closest interval point. %% Original commit : %% %% ------------------------------------------------------------------- %% Copyright ( c ) 2014 Basho Technologies , Inc. All Rights Reserved . %% This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% %% ------------------------------------------------------------------- %% @author < > @author @author < > %% %% @doc Efficient sliding-window buffer %% Initial implementation : 29 Sep 2009 by %% %% This module implements an efficient sliding window, maintaining two lists - a primary and a secondary . Values are paired with a timestamp ( millisecond resolution , see ` timestamp/0 ' ) %% and prepended to the primary list. When the time span between the oldest %% and the newest entry in the primary list exceeds the given window size, %% the primary list is shifted into the secondary list position, and the %% new entry is added to a new (empty) primary list. %% %% The window can be converted to a list using `to_list/1'. %% @end %% %% All modifications are ( C ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . The Initial Developer of the Original Code is Basho Technologies , Inc. -module(exometer_slide). -export([new/2, new/3, reset/1, add_element/3, to_list/2, to_list/3, foldl/5, map/2, to_normalized_list/5]). -export([timestamp/0, last_two/1, last/1]). -export([sum/1, sum/2, sum/5, optimize/1]). %% For testing -export([buffer/1]). -compile(inline). -compile(inline_list_funcs). -type value() :: tuple(). -type internal_value() :: tuple() | drop. -type timestamp() :: non_neg_integer(). -type fold_acc() :: any(). -type fold_fun() :: fun(({timestamp(), internal_value()}, fold_acc()) -> fold_acc()). %% Fixed size event buffer -record(slide, {size = 0 :: integer(), % ms window n = 0 :: integer(), % number of elements in buf1 max_n :: infinity | integer(), % max no of elements incremental = false :: boolean(), interval :: integer(), last = 0 :: integer(), % millisecond timestamp first = undefined :: undefined | integer(), % millisecond timestamp buf1 = [] :: [internal_value()], buf2 = [] :: [internal_value()], total :: undefined | value()}). -opaque slide() :: #slide{}. -export_type([slide/0, timestamp/0]). -spec timestamp() -> timestamp(). %% @doc Generate a millisecond-resolution timestamp. %% %% This timestamp format is used e.g. by the `exometer_slide' and %% `exometer_histogram' implementations. %% @end timestamp() -> os:system_time(milli_seconds). -spec new(_Size::integer(), _Options::list()) -> slide(). %% @doc Create a new sliding-window buffer. %% %% `Size' determines the size in milliseconds of the sliding window. %% The implementation prepends values into a primary list until the oldest %% element in the list is `Size' ms older than the current value. It then %% swaps the primary list into a secondary list, and starts prepending to %% a new primary list. This means that more data than fits inside the window %% will be kept - upwards of twice as much. On the other hand, updating the %% buffer is very cheap. %% @end new(Size, Opts) -> new(timestamp(), Size, Opts). -spec new(Timestamp :: timestamp(), Size::integer(), Options::list()) -> slide(). new(TS, Size, Opts) -> #slide{size = Size, max_n = proplists:get_value(max_n, Opts, infinity), interval = proplists:get_value(interval, Opts, infinity), last = TS, first = undefined, incremental = proplists:get_value(incremental, Opts, false), buf1 = [], buf2 = []}. -spec reset(slide()) -> slide(). %% @doc Empty the buffer %% reset(Slide) -> Slide#slide{n = 0, buf1 = [], buf2 = [], last = 0, first = undefined}. %% @doc Add an element to the buffer, tagged with the given timestamp. %% %% Apart from the specified timestamp, this function works just like { @link add_element/2 } . %% @end -spec add_element(timestamp(), value(), slide()) -> slide(). add_element(_TS, _Evt, Slide) when Slide#slide.size == 0 -> Slide; add_element(TS, Evt, #slide{last = Last, interval = Interval, total = Total0, incremental = true} = Slide) when (TS - Last) < Interval -> Total = add_to_total(Evt, Total0), Slide#slide{total = Total}; add_element(TS, Evt, #slide{last = Last, interval = Interval} = Slide) when (TS - Last) < Interval -> Slide#slide{total = Evt}; add_element(TS, Evt, #slide{last = Last, size = Sz, incremental = true, n = N, max_n = MaxN, total = Total0, buf1 = Buf1} = Slide) -> N1 = N+1, Total = add_to_total(Evt, Total0), %% Total could be the same as the last sample, by adding and substracting %% the same amout to the totals. That is not strictly a drop, but should %% generate new samples. I.e. 0 , 0 , -14 , 14 ( total = 0 , samples = 14 , -14 , 0 , drop ) case {is_zeros(Evt), Buf1} of {_, []} -> Slide#slide{n = N1, first = TS, buf1 = [{TS, Total} | Buf1], last = TS, total = Total}; _ when TS - Last > Sz; N1 > MaxN -> %% swap Slide#slide{last = TS, n = 1, buf1 = [{TS, Total}], buf2 = Buf1, total = Total}; {true, [{_, Total}, {_, drop} = Drop | Tail]} -> %% Memory optimisation Slide#slide{buf1 = [{TS, Total}, Drop | Tail], n = N1, last = TS}; {true, [{DropTS, Total} | Tail]} -> %% Memory optimisation Slide#slide{buf1 = [{TS, Total}, {DropTS, drop} | Tail], n = N1, last = TS}; _ -> Slide#slide{n = N1, buf1 = [{TS, Total} | Buf1], last = TS, total = Total} end; add_element(TS, Evt, #slide{last = Last, size = Sz, n = N, max_n = MaxN, buf1 = Buf1} = Slide) when TS - Last > Sz; N + 1 > MaxN -> Slide#slide{last = TS, n = 1, buf1 = [{TS, Evt}], buf2 = Buf1, total = Evt}; add_element(TS, Evt, #slide{buf1 = [{_, Evt}, {_, drop} = Drop | Tail], n = N} = Slide) -> %% Memory optimisation Slide#slide{buf1 = [{TS, Evt}, Drop | Tail], n = N + 1, last = TS}; add_element(TS, Evt, #slide{buf1 = [{DropTS, Evt} | Tail], n = N} = Slide) -> %% Memory optimisation Slide#slide{buf1 = [{TS, Evt}, {DropTS, drop} | Tail], n = N + 1, last = TS}; add_element(TS, Evt, #slide{n = N, buf1 = Buf1} = Slide) -> N1 = N+1, case Buf1 of [] -> Slide#slide{n = N1, buf1 = [{TS, Evt} | Buf1], last = TS, first = TS, total = Evt}; _ -> Slide#slide{n = N1, buf1 = [{TS, Evt} | Buf1], last = TS, total = Evt} end. add_to_total(Evt, undefined) -> Evt; add_to_total({A0}, {B0}) -> {B0 + A0}; add_to_total({A0, A1}, {B0, B1}) -> {B0 + A0, B1 + A1}; add_to_total({A0, A1, A2}, {B0, B1, B2}) -> {B0 + A0, B1 + A1, B2 + A2}; add_to_total({A0, A1, A2, A3}, {B0, B1, B2, B3}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3}; add_to_total({A0, A1, A2, A3, A4}, {B0, B1, B2, B3, B4}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4}; add_to_total({A0, A1, A2, A3, A4, A5}, {B0, B1, B2, B3, B4, B5}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4, B5 + A5}; add_to_total({A0, A1, A2, A3, A4, A5, A6}, {B0, B1, B2, B3, B4, B5, B6}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4, B5 + A5, B6 + A6}; add_to_total({A0, A1, A2, A3, A4, A5, A6, A7}, {B0, B1, B2, B3, B4, B5, B6, B7}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4, B5 + A5, B6 + A6, B7 + A7}; add_to_total({A0, A1, A2, A3, A4, A5, A6, A7, A8}, {B0, B1, B2, B3, B4, B5, B6, B7, B8}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4, B5 + A5, B6 + A6, B7 + A7, B8 + A8}; add_to_total({A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19}, {B0, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, B13, B14, B15, B16, B17, B18, B19}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4, B5 + A5, B6 + A6, B7 + A7, B8 + A8, B9 + A9, B10 + A10, B11 + A11, B12 + A12, B13 + A13, B14 + A14, B15 + A15, B16 + A16, B17 + A17, B18 + A18, B19 + A19}. is_zeros({0}) -> true; is_zeros({0, 0}) -> true; is_zeros({0, 0, 0}) -> true; is_zeros({0, 0, 0, 0}) -> true; is_zeros({0, 0, 0, 0, 0}) -> true; is_zeros({0, 0, 0, 0, 0, 0}) -> true; is_zeros({0, 0, 0, 0, 0, 0, 0}) -> true; is_zeros({0, 0, 0, 0, 0, 0, 0, 0, 0}) -> true; is_zeros({0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) -> true; is_zeros(_) -> false. -spec optimize(slide()) -> slide(). optimize(#slide{buf2 = []} = Slide) -> Slide; optimize(#slide{buf1 = Buf1, buf2 = Buf2, max_n = MaxN, n = N} = Slide) when is_integer(MaxN) andalso length(Buf1) < MaxN -> Slide#slide{buf1 = Buf1, buf2 = lists:sublist(Buf2, n_diff(MaxN, N) + 1)}; optimize(Slide) -> Slide. snd(T) when is_tuple(T) -> element(2, T). -spec to_list(timestamp(), slide()) -> [{timestamp(), value()}]. %% @doc Convert the sliding window into a list of timestamped values. %% @end to_list(_Now, #slide{size = Sz}) when Sz == 0 -> []; to_list(Now, #slide{size = Sz} = Slide) -> snd(to_list_from(Now, Now - Sz, Slide)). to_list(Now, Start, Slide) -> snd(to_list_from(Now, Start, Slide)). to_list_from(Now, Start0, #slide{max_n = MaxN, buf2 = Buf2, first = FirstTS, interval = Interval} = Slide) -> {NewN, Buf1} = maybe_add_last_sample(Now, Slide), Start = first_max(FirstTS, Start0), {Prev0, Buf1_1} = take_since(Buf1, Now, Start, first_max(MaxN, NewN), [], Interval), case take_since(Buf2, Now, Start, first_max(MaxN, NewN), Buf1_1, Interval) of {undefined, Buf1_1} -> {Prev0, Buf1_1}; {_Prev, Buf1_1} = Res -> case Prev0 of undefined -> Res; _ -> %% If take_since returns the same buffer, that means we don't %% need Buf2 at all. We might be returning a too old sample %% in previous, so we must use the one from Buf1 {Prev0, Buf1_1} end; Res -> Res end. first_max(F, X) when is_integer(F) -> max(F, X); first_max(_, X) -> X. -spec last_two(slide()) -> [{timestamp(), value()}]. @doc Returns the newest 2 elements on the sample last_two(#slide{buf1 = [{TS, Evt} = H1, {_, drop} | _], interval = Interval}) -> [H1, {TS - Interval, Evt}]; last_two(#slide{buf1 = [H1, H2_0 | _], interval = Interval}) -> H2 = adjust_timestamp(H1, H2_0, Interval), [H1, H2]; last_two(#slide{buf1 = [H1], buf2 = [H2_0 | _], interval = Interval}) -> H2 = adjust_timestamp(H1, H2_0, Interval), [H1, H2]; last_two(#slide{buf1 = [H1], buf2 = []}) -> [H1]; last_two(_) -> []. adjust_timestamp({TS1, _}, {TS2, V2}, Interval) -> case TS1 - TS2 > Interval of true -> {TS1 - Interval, V2}; false -> {TS2, V2} end. -spec last(slide()) -> value() | undefined. last(#slide{total = T}) when T =/= undefined -> T; last(#slide{buf1 = [{_TS, T} | _]}) -> T; last(#slide{buf2 = [{_TS, T} | _]}) -> T; last(_) -> undefined. -spec foldl(timestamp(), timestamp(), fold_fun(), fold_acc(), slide()) -> fold_acc(). @doc Fold over the sliding window , starting from ` Timestamp ' . %% Now provides a reference point to evaluate whether to include partial , unrealised sample values in the sequence . Unrealised values will be %% appended to the sequence when Now >= LastTS + Interval %% The fun should as ` fun({Timestamp , Value } , Acc ) - > NewAcc ' . %% The values are processed in order from oldest to newest. %% @end foldl(_Now, _Timestamp, _Fun, _Acc, #slide{size = Sz}) when Sz == 0 -> []; foldl(Now, Start0, Fun, Acc, #slide{max_n = _MaxN, buf2 = _Buf2, interval = _Interval} = Slide) -> lists:foldl(Fun, Acc, element(2, to_list_from(Now, Start0, Slide)) ++ [last]). map(Fun, #slide{buf1 = Buf1, buf2 = Buf2, total = Total} = Slide) -> BufFun = fun({Timestamp, Value}) -> {Timestamp, Fun(Value)} end, MappedBuf1 = lists:map(BufFun, Buf1), MappedBuf2 = lists:map(BufFun, Buf2), MappedTotal = Fun(Total), Slide#slide{buf1 = MappedBuf1, buf2 = MappedBuf2, total = MappedTotal}. maybe_add_last_sample(_Now, #slide{total = T, n = N, buf1 = [{_, T} | _] = Buf1}) -> {N, Buf1}; maybe_add_last_sample(Now, #slide{total = T, n = N, last = Last, interval = I, buf1 = Buf1}) when T =/= undefined andalso Now >= Last + I -> {N + 1, [{Last + I, T} | Buf1]}; maybe_add_last_sample(_Now, #slide{buf1 = Buf1, n = N}) -> {N, Buf1}. create_normalized_lookup(Start, Interval, RoundFun, Samples) -> lists:foldl(fun({TS, Value}, Acc) when TS - Start >= 0 -> NewTS = map_timestamp(TS, Start, Interval, RoundFun), maps:update_with(NewTS, fun({T, V}) when T > TS -> {T, V}; (_) -> {TS, Value} end, {TS, Value}, Acc); (_, Acc) -> Acc end, #{}, Samples). -spec to_normalized_list(timestamp(), timestamp(), integer(), slide(), no_pad | tuple()) -> [tuple()]. to_normalized_list(Now, Start, Interval, Slide, Empty) -> to_normalized_list(Now, Start, Interval, Slide, Empty, fun ceil/1). to_normalized_list(Now, Start, Interval, #slide{first = FirstTS0, total = Total} = Slide, Empty, RoundFun) -> RoundTSFun = fun (TS) -> map_timestamp(TS, Start, Interval, RoundFun) end, % add interval as we don't want to miss a sample due to rounding {Prev, Samples} = to_list_from(Now + Interval, Start, Slide), Lookup = create_normalized_lookup(Start, Interval, RoundFun, Samples), NowRound = RoundTSFun(Now), Pad = case Samples of _ when Empty =:= no_pad -> []; [{TS, _} | _] when Prev =/= undefined, Start =< TS -> [{T, snd(Prev)} || T <- lists:seq(RoundTSFun(TS) - Interval, Start, -Interval)]; [{TS, _} | _] when is_number(FirstTS0) andalso Start < FirstTS0 -> % only if we know there is nothing in the past can we % generate a 0 pad [{T, Empty} || T <- lists:seq(RoundTSFun(TS) - Interval, Start, -Interval)]; _ when FirstTS0 =:= undefined andalso Total =:= undefined -> [{T, Empty} || T <- lists:seq(NowRound, Start, -Interval)]; [] -> % samples have been seen, use the total to pad [{T, Total} || T <- lists:seq(NowRound, Start, -Interval)]; _ -> [] end, {_, Res1} = lists:foldl( fun(T, {Last, Acc}) -> case maps:find(T, Lookup) of {ok, {_, V}} -> {V, [{T, V} | Acc]}; error when Last =:= undefined -> {Last, Acc}; error -> % this pads the last value into the future {Last, [{T, Last} | Acc]} end end, {undefined, []}, lists:seq(Start, NowRound, Interval)), Res1 ++ Pad. %% @doc Sums a list of slides %% %% Takes the last known timestamp and creates an template version of the %% sliding window. Timestamps are then truncated and summed with the value %% in the template slide. %% @end -spec sum([slide()]) -> slide(). sum(Slides) -> sum(Slides, no_pad). sum([#slide{size = Size, interval = Interval} | _] = Slides, Pad) -> % take the freshest timestamp as reference point for summing operation Now = lists:max([Last || #slide{last = Last} <- Slides]), Start = Now - Size, sum(Now, Start, Interval, Slides, Pad). sum(Now, Start, Interval, [Slide | _ ] = All, Pad) -> Fun = fun({TS, Value}, Acc) -> maps:update_with(TS, fun(V) -> add_to_total(V, Value) end, Value, Acc) end, {Total, Dict} = lists:foldl(fun(#slide{total = T} = S, {Tot, Acc}) -> Samples = to_normalized_list(Now, Start, Interval, S, Pad, fun ceil/1), Total = add_to_total(T, Tot), Folded = lists:foldl(Fun, Acc, Samples), {Total, Folded} end, {undefined, #{}}, All), {First, Buffer} = case lists:sort(maps:to_list(Dict)) of [] -> F = case [TS || #slide{first = TS} <- All, is_integer(TS)] of [] -> undefined; FS -> lists:min(FS) end, {F, []}; [{F, _} | _ ] = B -> {F, lists:reverse(B)} end, Slide#slide{buf1 = Buffer, buf2 = [], total = Total, n = length(Buffer), first = First, last = Now}. truncated_seq(_First, _Last, _Incr, 0) -> []; truncated_seq(TS, TS, _Incr, MaxN) when MaxN > 0 -> [TS]; truncated_seq(First, Last, Incr, MaxN) when First =< Last andalso MaxN > 0 -> End = min(Last, First + (MaxN * Incr) - Incr), lists:seq(First, End, Incr); truncated_seq(First, Last, Incr, MaxN) -> End = max(Last, First + (MaxN * Incr) - Incr), lists:seq(First, End, Incr). take_since([{DropTS, drop} | T], Now, Start, N, [{TS, Evt} | _] = Acc, Interval) -> case T of [] -> Fill = [{TS0, Evt} || TS0 <- truncated_seq(TS - Interval, max(DropTS, Start), -Interval, N)], {undefined, lists:reverse(Fill) ++ Acc}; [{TS0, _} = E | Rest] when TS0 >= Start, N > 0 -> Fill = [{TS1, Evt} || TS1 <- truncated_seq(TS0 + Interval, max(TS0 + Interval, TS - Interval), Interval, N)], take_since(Rest, Now, Start, decr(N), [E | Fill ++ Acc], Interval); [Prev | _] -> % next sample is out of range so needs to be filled from Start Fill = [{TS1, Evt} || TS1 <- truncated_seq(Start, max(Start, TS - Interval), Interval, N)], {Prev, Fill ++ Acc} end; take_since([{TS, V} = H | T], Now, Start, N, Acc, Interval) when TS >= Start, N > 0, TS =< Now, is_tuple(V) -> take_since(T, Now, Start, decr(N), [H|Acc], Interval); take_since([{TS,_} | T], Now, Start, N, Acc, Interval) when TS >= Start, N > 0 -> take_since(T, Now, Start, decr(N), Acc, Interval); take_since([Prev | _], _, _, _, Acc, _) -> {Prev, Acc}; take_since(_, _, _, _, Acc, _) -> %% Don't reverse; already the wanted order. {undefined, Acc}. decr(N) when is_integer(N) -> N-1; decr(N) -> N. n_diff(A, B) when is_integer(A) -> A - B. ceil(X) when X < 0 -> trunc(X); ceil(X) -> T = trunc(X), case X - T == 0 of true -> T; false -> T + 1 end. map_timestamp(TS, Start, Interval, Round) -> Factor = Round((TS - Start) / Interval), Start + Interval * Factor. buffer(#slide{buf1 = Buf1, buf2 = Buf2}) -> Buf1 ++ Buf2.
null
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbitmq_management_agent/src/exometer_slide.erl
erlang
This file is a copy of exometer_slide.erl from , with the following modifications: are stored. on the given intervals. Elements on each window are added to the closest interval point. ------------------------------------------------------------------- ------------------------------------------------------------------- @doc Efficient sliding-window buffer This module implements an efficient sliding window, maintaining and prepended to the primary list. When the time span between the oldest and the newest entry in the primary list exceeds the given window size, the primary list is shifted into the secondary list position, and the new entry is added to a new (empty) primary list. The window can be converted to a list using `to_list/1'. @end For testing Fixed size event buffer ms window number of elements in buf1 max no of elements millisecond timestamp millisecond timestamp @doc Generate a millisecond-resolution timestamp. This timestamp format is used e.g. by the `exometer_slide' and `exometer_histogram' implementations. @end @doc Create a new sliding-window buffer. `Size' determines the size in milliseconds of the sliding window. The implementation prepends values into a primary list until the oldest element in the list is `Size' ms older than the current value. It then swaps the primary list into a secondary list, and starts prepending to a new primary list. This means that more data than fits inside the window will be kept - upwards of twice as much. On the other hand, updating the buffer is very cheap. @end @doc Empty the buffer @doc Add an element to the buffer, tagged with the given timestamp. Apart from the specified timestamp, this function works just like @end Total could be the same as the last sample, by adding and substracting the same amout to the totals. That is not strictly a drop, but should generate new samples. swap Memory optimisation Memory optimisation Memory optimisation Memory optimisation @doc Convert the sliding window into a list of timestamped values. @end If take_since returns the same buffer, that means we don't need Buf2 at all. We might be returning a too old sample in previous, so we must use the one from Buf1 Now provides a reference point to evaluate whether to include appended to the sequence when Now >= LastTS + Interval The values are processed in order from oldest to newest. @end add interval as we don't want to miss a sample due to rounding only if we know there is nothing in the past can we generate a 0 pad samples have been seen, use the total to pad this pads the last value into the future @doc Sums a list of slides Takes the last known timestamp and creates an template version of the sliding window. Timestamps are then truncated and summed with the value in the template slide. @end take the freshest timestamp as reference point for summing operation next sample is out of range so needs to be filled from Start Don't reverse; already the wanted order.
1 ) The elements are tuples of numbers 2 ) Only one element for each expected interval point is added , intermediate values are discarded . Thus , if we have a window of 60s and interval of 5s , at max 12 elements 3 ) Additions can be provided as increments to the last value stored 4 ) sum/1 implements the sum of several slides , generating a new timestamp sequence based Original commit : Copyright ( c ) 2014 Basho Technologies , Inc. All Rights Reserved . This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. @author < > @author @author < > Initial implementation : 29 Sep 2009 by two lists - a primary and a secondary . Values are paired with a timestamp ( millisecond resolution , see ` timestamp/0 ' ) All modifications are ( C ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . The Initial Developer of the Original Code is Basho Technologies , Inc. -module(exometer_slide). -export([new/2, new/3, reset/1, add_element/3, to_list/2, to_list/3, foldl/5, map/2, to_normalized_list/5]). -export([timestamp/0, last_two/1, last/1]). -export([sum/1, sum/2, sum/5, optimize/1]). -export([buffer/1]). -compile(inline). -compile(inline_list_funcs). -type value() :: tuple(). -type internal_value() :: tuple() | drop. -type timestamp() :: non_neg_integer(). -type fold_acc() :: any(). -type fold_fun() :: fun(({timestamp(), internal_value()}, fold_acc()) -> fold_acc()). incremental = false :: boolean(), interval :: integer(), buf1 = [] :: [internal_value()], buf2 = [] :: [internal_value()], total :: undefined | value()}). -opaque slide() :: #slide{}. -export_type([slide/0, timestamp/0]). -spec timestamp() -> timestamp(). timestamp() -> os:system_time(milli_seconds). -spec new(_Size::integer(), _Options::list()) -> slide(). new(Size, Opts) -> new(timestamp(), Size, Opts). -spec new(Timestamp :: timestamp(), Size::integer(), Options::list()) -> slide(). new(TS, Size, Opts) -> #slide{size = Size, max_n = proplists:get_value(max_n, Opts, infinity), interval = proplists:get_value(interval, Opts, infinity), last = TS, first = undefined, incremental = proplists:get_value(incremental, Opts, false), buf1 = [], buf2 = []}. -spec reset(slide()) -> slide(). reset(Slide) -> Slide#slide{n = 0, buf1 = [], buf2 = [], last = 0, first = undefined}. { @link add_element/2 } . -spec add_element(timestamp(), value(), slide()) -> slide(). add_element(_TS, _Evt, Slide) when Slide#slide.size == 0 -> Slide; add_element(TS, Evt, #slide{last = Last, interval = Interval, total = Total0, incremental = true} = Slide) when (TS - Last) < Interval -> Total = add_to_total(Evt, Total0), Slide#slide{total = Total}; add_element(TS, Evt, #slide{last = Last, interval = Interval} = Slide) when (TS - Last) < Interval -> Slide#slide{total = Evt}; add_element(TS, Evt, #slide{last = Last, size = Sz, incremental = true, n = N, max_n = MaxN, total = Total0, buf1 = Buf1} = Slide) -> N1 = N+1, Total = add_to_total(Evt, Total0), I.e. 0 , 0 , -14 , 14 ( total = 0 , samples = 14 , -14 , 0 , drop ) case {is_zeros(Evt), Buf1} of {_, []} -> Slide#slide{n = N1, first = TS, buf1 = [{TS, Total} | Buf1], last = TS, total = Total}; _ when TS - Last > Sz; N1 > MaxN -> Slide#slide{last = TS, n = 1, buf1 = [{TS, Total}], buf2 = Buf1, total = Total}; {true, [{_, Total}, {_, drop} = Drop | Tail]} -> Slide#slide{buf1 = [{TS, Total}, Drop | Tail], n = N1, last = TS}; {true, [{DropTS, Total} | Tail]} -> Slide#slide{buf1 = [{TS, Total}, {DropTS, drop} | Tail], n = N1, last = TS}; _ -> Slide#slide{n = N1, buf1 = [{TS, Total} | Buf1], last = TS, total = Total} end; add_element(TS, Evt, #slide{last = Last, size = Sz, n = N, max_n = MaxN, buf1 = Buf1} = Slide) when TS - Last > Sz; N + 1 > MaxN -> Slide#slide{last = TS, n = 1, buf1 = [{TS, Evt}], buf2 = Buf1, total = Evt}; add_element(TS, Evt, #slide{buf1 = [{_, Evt}, {_, drop} = Drop | Tail], n = N} = Slide) -> Slide#slide{buf1 = [{TS, Evt}, Drop | Tail], n = N + 1, last = TS}; add_element(TS, Evt, #slide{buf1 = [{DropTS, Evt} | Tail], n = N} = Slide) -> Slide#slide{buf1 = [{TS, Evt}, {DropTS, drop} | Tail], n = N + 1, last = TS}; add_element(TS, Evt, #slide{n = N, buf1 = Buf1} = Slide) -> N1 = N+1, case Buf1 of [] -> Slide#slide{n = N1, buf1 = [{TS, Evt} | Buf1], last = TS, first = TS, total = Evt}; _ -> Slide#slide{n = N1, buf1 = [{TS, Evt} | Buf1], last = TS, total = Evt} end. add_to_total(Evt, undefined) -> Evt; add_to_total({A0}, {B0}) -> {B0 + A0}; add_to_total({A0, A1}, {B0, B1}) -> {B0 + A0, B1 + A1}; add_to_total({A0, A1, A2}, {B0, B1, B2}) -> {B0 + A0, B1 + A1, B2 + A2}; add_to_total({A0, A1, A2, A3}, {B0, B1, B2, B3}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3}; add_to_total({A0, A1, A2, A3, A4}, {B0, B1, B2, B3, B4}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4}; add_to_total({A0, A1, A2, A3, A4, A5}, {B0, B1, B2, B3, B4, B5}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4, B5 + A5}; add_to_total({A0, A1, A2, A3, A4, A5, A6}, {B0, B1, B2, B3, B4, B5, B6}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4, B5 + A5, B6 + A6}; add_to_total({A0, A1, A2, A3, A4, A5, A6, A7}, {B0, B1, B2, B3, B4, B5, B6, B7}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4, B5 + A5, B6 + A6, B7 + A7}; add_to_total({A0, A1, A2, A3, A4, A5, A6, A7, A8}, {B0, B1, B2, B3, B4, B5, B6, B7, B8}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4, B5 + A5, B6 + A6, B7 + A7, B8 + A8}; add_to_total({A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19}, {B0, B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, B13, B14, B15, B16, B17, B18, B19}) -> {B0 + A0, B1 + A1, B2 + A2, B3 + A3, B4 + A4, B5 + A5, B6 + A6, B7 + A7, B8 + A8, B9 + A9, B10 + A10, B11 + A11, B12 + A12, B13 + A13, B14 + A14, B15 + A15, B16 + A16, B17 + A17, B18 + A18, B19 + A19}. is_zeros({0}) -> true; is_zeros({0, 0}) -> true; is_zeros({0, 0, 0}) -> true; is_zeros({0, 0, 0, 0}) -> true; is_zeros({0, 0, 0, 0, 0}) -> true; is_zeros({0, 0, 0, 0, 0, 0}) -> true; is_zeros({0, 0, 0, 0, 0, 0, 0}) -> true; is_zeros({0, 0, 0, 0, 0, 0, 0, 0, 0}) -> true; is_zeros({0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) -> true; is_zeros(_) -> false. -spec optimize(slide()) -> slide(). optimize(#slide{buf2 = []} = Slide) -> Slide; optimize(#slide{buf1 = Buf1, buf2 = Buf2, max_n = MaxN, n = N} = Slide) when is_integer(MaxN) andalso length(Buf1) < MaxN -> Slide#slide{buf1 = Buf1, buf2 = lists:sublist(Buf2, n_diff(MaxN, N) + 1)}; optimize(Slide) -> Slide. snd(T) when is_tuple(T) -> element(2, T). -spec to_list(timestamp(), slide()) -> [{timestamp(), value()}]. to_list(_Now, #slide{size = Sz}) when Sz == 0 -> []; to_list(Now, #slide{size = Sz} = Slide) -> snd(to_list_from(Now, Now - Sz, Slide)). to_list(Now, Start, Slide) -> snd(to_list_from(Now, Start, Slide)). to_list_from(Now, Start0, #slide{max_n = MaxN, buf2 = Buf2, first = FirstTS, interval = Interval} = Slide) -> {NewN, Buf1} = maybe_add_last_sample(Now, Slide), Start = first_max(FirstTS, Start0), {Prev0, Buf1_1} = take_since(Buf1, Now, Start, first_max(MaxN, NewN), [], Interval), case take_since(Buf2, Now, Start, first_max(MaxN, NewN), Buf1_1, Interval) of {undefined, Buf1_1} -> {Prev0, Buf1_1}; {_Prev, Buf1_1} = Res -> case Prev0 of undefined -> Res; _ -> {Prev0, Buf1_1} end; Res -> Res end. first_max(F, X) when is_integer(F) -> max(F, X); first_max(_, X) -> X. -spec last_two(slide()) -> [{timestamp(), value()}]. @doc Returns the newest 2 elements on the sample last_two(#slide{buf1 = [{TS, Evt} = H1, {_, drop} | _], interval = Interval}) -> [H1, {TS - Interval, Evt}]; last_two(#slide{buf1 = [H1, H2_0 | _], interval = Interval}) -> H2 = adjust_timestamp(H1, H2_0, Interval), [H1, H2]; last_two(#slide{buf1 = [H1], buf2 = [H2_0 | _], interval = Interval}) -> H2 = adjust_timestamp(H1, H2_0, Interval), [H1, H2]; last_two(#slide{buf1 = [H1], buf2 = []}) -> [H1]; last_two(_) -> []. adjust_timestamp({TS1, _}, {TS2, V2}, Interval) -> case TS1 - TS2 > Interval of true -> {TS1 - Interval, V2}; false -> {TS2, V2} end. -spec last(slide()) -> value() | undefined. last(#slide{total = T}) when T =/= undefined -> T; last(#slide{buf1 = [{_TS, T} | _]}) -> T; last(#slide{buf2 = [{_TS, T} | _]}) -> T; last(_) -> undefined. -spec foldl(timestamp(), timestamp(), fold_fun(), fold_acc(), slide()) -> fold_acc(). @doc Fold over the sliding window , starting from ` Timestamp ' . partial , unrealised sample values in the sequence . Unrealised values will be The fun should as ` fun({Timestamp , Value } , Acc ) - > NewAcc ' . foldl(_Now, _Timestamp, _Fun, _Acc, #slide{size = Sz}) when Sz == 0 -> []; foldl(Now, Start0, Fun, Acc, #slide{max_n = _MaxN, buf2 = _Buf2, interval = _Interval} = Slide) -> lists:foldl(Fun, Acc, element(2, to_list_from(Now, Start0, Slide)) ++ [last]). map(Fun, #slide{buf1 = Buf1, buf2 = Buf2, total = Total} = Slide) -> BufFun = fun({Timestamp, Value}) -> {Timestamp, Fun(Value)} end, MappedBuf1 = lists:map(BufFun, Buf1), MappedBuf2 = lists:map(BufFun, Buf2), MappedTotal = Fun(Total), Slide#slide{buf1 = MappedBuf1, buf2 = MappedBuf2, total = MappedTotal}. maybe_add_last_sample(_Now, #slide{total = T, n = N, buf1 = [{_, T} | _] = Buf1}) -> {N, Buf1}; maybe_add_last_sample(Now, #slide{total = T, n = N, last = Last, interval = I, buf1 = Buf1}) when T =/= undefined andalso Now >= Last + I -> {N + 1, [{Last + I, T} | Buf1]}; maybe_add_last_sample(_Now, #slide{buf1 = Buf1, n = N}) -> {N, Buf1}. create_normalized_lookup(Start, Interval, RoundFun, Samples) -> lists:foldl(fun({TS, Value}, Acc) when TS - Start >= 0 -> NewTS = map_timestamp(TS, Start, Interval, RoundFun), maps:update_with(NewTS, fun({T, V}) when T > TS -> {T, V}; (_) -> {TS, Value} end, {TS, Value}, Acc); (_, Acc) -> Acc end, #{}, Samples). -spec to_normalized_list(timestamp(), timestamp(), integer(), slide(), no_pad | tuple()) -> [tuple()]. to_normalized_list(Now, Start, Interval, Slide, Empty) -> to_normalized_list(Now, Start, Interval, Slide, Empty, fun ceil/1). to_normalized_list(Now, Start, Interval, #slide{first = FirstTS0, total = Total} = Slide, Empty, RoundFun) -> RoundTSFun = fun (TS) -> map_timestamp(TS, Start, Interval, RoundFun) end, {Prev, Samples} = to_list_from(Now + Interval, Start, Slide), Lookup = create_normalized_lookup(Start, Interval, RoundFun, Samples), NowRound = RoundTSFun(Now), Pad = case Samples of _ when Empty =:= no_pad -> []; [{TS, _} | _] when Prev =/= undefined, Start =< TS -> [{T, snd(Prev)} || T <- lists:seq(RoundTSFun(TS) - Interval, Start, -Interval)]; [{TS, _} | _] when is_number(FirstTS0) andalso Start < FirstTS0 -> [{T, Empty} || T <- lists:seq(RoundTSFun(TS) - Interval, Start, -Interval)]; _ when FirstTS0 =:= undefined andalso Total =:= undefined -> [{T, Empty} || T <- lists:seq(NowRound, Start, -Interval)]; [{T, Total} || T <- lists:seq(NowRound, Start, -Interval)]; _ -> [] end, {_, Res1} = lists:foldl( fun(T, {Last, Acc}) -> case maps:find(T, Lookup) of {ok, {_, V}} -> {V, [{T, V} | Acc]}; error when Last =:= undefined -> {Last, Acc}; {Last, [{T, Last} | Acc]} end end, {undefined, []}, lists:seq(Start, NowRound, Interval)), Res1 ++ Pad. -spec sum([slide()]) -> slide(). sum(Slides) -> sum(Slides, no_pad). sum([#slide{size = Size, interval = Interval} | _] = Slides, Pad) -> Now = lists:max([Last || #slide{last = Last} <- Slides]), Start = Now - Size, sum(Now, Start, Interval, Slides, Pad). sum(Now, Start, Interval, [Slide | _ ] = All, Pad) -> Fun = fun({TS, Value}, Acc) -> maps:update_with(TS, fun(V) -> add_to_total(V, Value) end, Value, Acc) end, {Total, Dict} = lists:foldl(fun(#slide{total = T} = S, {Tot, Acc}) -> Samples = to_normalized_list(Now, Start, Interval, S, Pad, fun ceil/1), Total = add_to_total(T, Tot), Folded = lists:foldl(Fun, Acc, Samples), {Total, Folded} end, {undefined, #{}}, All), {First, Buffer} = case lists:sort(maps:to_list(Dict)) of [] -> F = case [TS || #slide{first = TS} <- All, is_integer(TS)] of [] -> undefined; FS -> lists:min(FS) end, {F, []}; [{F, _} | _ ] = B -> {F, lists:reverse(B)} end, Slide#slide{buf1 = Buffer, buf2 = [], total = Total, n = length(Buffer), first = First, last = Now}. truncated_seq(_First, _Last, _Incr, 0) -> []; truncated_seq(TS, TS, _Incr, MaxN) when MaxN > 0 -> [TS]; truncated_seq(First, Last, Incr, MaxN) when First =< Last andalso MaxN > 0 -> End = min(Last, First + (MaxN * Incr) - Incr), lists:seq(First, End, Incr); truncated_seq(First, Last, Incr, MaxN) -> End = max(Last, First + (MaxN * Incr) - Incr), lists:seq(First, End, Incr). take_since([{DropTS, drop} | T], Now, Start, N, [{TS, Evt} | _] = Acc, Interval) -> case T of [] -> Fill = [{TS0, Evt} || TS0 <- truncated_seq(TS - Interval, max(DropTS, Start), -Interval, N)], {undefined, lists:reverse(Fill) ++ Acc}; [{TS0, _} = E | Rest] when TS0 >= Start, N > 0 -> Fill = [{TS1, Evt} || TS1 <- truncated_seq(TS0 + Interval, max(TS0 + Interval, TS - Interval), Interval, N)], take_since(Rest, Now, Start, decr(N), [E | Fill ++ Acc], Interval); Fill = [{TS1, Evt} || TS1 <- truncated_seq(Start, max(Start, TS - Interval), Interval, N)], {Prev, Fill ++ Acc} end; take_since([{TS, V} = H | T], Now, Start, N, Acc, Interval) when TS >= Start, N > 0, TS =< Now, is_tuple(V) -> take_since(T, Now, Start, decr(N), [H|Acc], Interval); take_since([{TS,_} | T], Now, Start, N, Acc, Interval) when TS >= Start, N > 0 -> take_since(T, Now, Start, decr(N), Acc, Interval); take_since([Prev | _], _, _, _, Acc, _) -> {Prev, Acc}; take_since(_, _, _, _, Acc, _) -> {undefined, Acc}. decr(N) when is_integer(N) -> N-1; decr(N) -> N. n_diff(A, B) when is_integer(A) -> A - B. ceil(X) when X < 0 -> trunc(X); ceil(X) -> T = trunc(X), case X - T == 0 of true -> T; false -> T + 1 end. map_timestamp(TS, Start, Interval, Round) -> Factor = Round((TS - Start) / Interval), Start + Interval * Factor. buffer(#slide{buf1 = Buf1, buf2 = Buf2}) -> Buf1 ++ Buf2.
0915ec13ebe11ee341f24c20262b55e4b8cdb0db700caa2b108bad5bfc034a17
alx741/graphite
Generation.hs
# LANGUAGE ScopedTypeVariables # module Data.Graph.Generation ( * – Rényi model erdosRenyi , erdosRenyiU , erdosRenyiD -- * General Random graphs , rndGraph , rndGraph' -- * Random adjacency matrix , rndAdjacencyMatrix ) where import Control.Monad (replicateM) import Data.List (foldl') import System.Random import Data.Hashable import Data.Graph.DGraph import Data.Graph.Types import Data.Graph.UGraph | Generate a random – , p ) model graph erdosRenyi :: Graph g => Int -> Float -> IO (g Int ()) erdosRenyi n p = rndGraph' p [1..n] | ' erdosRenyi ' convinience ' UGraph ' generation function erdosRenyiU :: Int -> Float -> IO (UGraph Int ()) erdosRenyiU = erdosRenyi | ' erdosRenyi ' convinience ' ' generation function erdosRenyiD :: Int -> Float -> IO (DGraph Int ()) erdosRenyiD = erdosRenyi -- | Generate a random graph for all the vertices of type /v/ in the list, -- random edge attributes in /e/ within given bounds, and some existing probability for each possible edge as per the – Rényi model rndGraph :: forall g v e . (Graph g, Hashable v, Eq v, Random e) => (e, e) -> Float -> [v] -> IO (g v e) rndGraph edgeBounds p verts = go verts (probability p) empty where go :: [v] -> Float -> g v e -> IO (g v e) go [] _ g = return g go (v:vs) pv g = do rnds <- replicateM (length vs + 1) $ randomRIO (0.0, 1.0) flipDir <- randomRIO (True, False) edgeAttr <- randomRIO edgeBounds let vs' = zip rnds vs let g' = insertVertex v g go vs pv $! foldl' (insertFlippedEdge pv v edgeAttr flipDir) g' vs' -- | Same as 'rndGraph' but uses attributeless edges rndGraph' :: forall g v . (Graph g, Hashable v, Eq v) => Float -> [v] -> IO (g v ()) rndGraph' p verts = go verts (probability p) empty where go :: [v] -> Float -> g v () -> IO (g v ()) go [] _ g = return g go (v:vs) pv g = do rnds <- replicateM (length vs + 1) $ randomRIO (0.0, 1.0) flipDir <- randomRIO (True, False) let vs' = zip rnds vs let g' = insertVertex v g go vs pv $! foldl' (insertFlippedEdge pv v () flipDir) g' vs' -- | Generate a random adjacency matrix -- Useful for use with ' ' rndAdjacencyMatrix :: Int -> IO [[Int]] rndAdjacencyMatrix n = replicateM n randRow where randRow = replicateM n (randomRIO (0,1)) :: IO [Int] -- | Insert and edge between vertices if the probability is met insertFlippedEdge :: (Graph g, Hashable v, Eq v) => Float -> v -> e -> Bool -> g v e -> (Float, v) -> g v e insertFlippedEdge pv v edgeAttr flipDir g (p', v') | p' < pv = insertEdgeTriple triple g | otherwise = g where triple = if flipDir then (v', v, edgeAttr) else (v, v', edgeAttr) | Bound a real value as probability value [ 0.0 , 1.0 ] probability :: Float -> Float probability v | v >= 1 = 1 | v <= 0 = 0 | otherwise = v
null
https://raw.githubusercontent.com/alx741/graphite/c911d7dae2c17d20c70ad9b7da1a1f7b142cbb9a/src/Data/Graph/Generation.hs
haskell
* General Random graphs * Random adjacency matrix | Generate a random graph for all the vertices of type /v/ in the list, random edge attributes in /e/ within given bounds, and some existing | Same as 'rndGraph' but uses attributeless edges | Generate a random adjacency matrix | Insert and edge between vertices if the probability is met
# LANGUAGE ScopedTypeVariables # module Data.Graph.Generation ( * – Rényi model erdosRenyi , erdosRenyiU , erdosRenyiD , rndGraph , rndGraph' , rndAdjacencyMatrix ) where import Control.Monad (replicateM) import Data.List (foldl') import System.Random import Data.Hashable import Data.Graph.DGraph import Data.Graph.Types import Data.Graph.UGraph | Generate a random – , p ) model graph erdosRenyi :: Graph g => Int -> Float -> IO (g Int ()) erdosRenyi n p = rndGraph' p [1..n] | ' erdosRenyi ' convinience ' UGraph ' generation function erdosRenyiU :: Int -> Float -> IO (UGraph Int ()) erdosRenyiU = erdosRenyi | ' erdosRenyi ' convinience ' ' generation function erdosRenyiD :: Int -> Float -> IO (DGraph Int ()) erdosRenyiD = erdosRenyi probability for each possible edge as per the – Rényi model rndGraph :: forall g v e . (Graph g, Hashable v, Eq v, Random e) => (e, e) -> Float -> [v] -> IO (g v e) rndGraph edgeBounds p verts = go verts (probability p) empty where go :: [v] -> Float -> g v e -> IO (g v e) go [] _ g = return g go (v:vs) pv g = do rnds <- replicateM (length vs + 1) $ randomRIO (0.0, 1.0) flipDir <- randomRIO (True, False) edgeAttr <- randomRIO edgeBounds let vs' = zip rnds vs let g' = insertVertex v g go vs pv $! foldl' (insertFlippedEdge pv v edgeAttr flipDir) g' vs' rndGraph' :: forall g v . (Graph g, Hashable v, Eq v) => Float -> [v] -> IO (g v ()) rndGraph' p verts = go verts (probability p) empty where go :: [v] -> Float -> g v () -> IO (g v ()) go [] _ g = return g go (v:vs) pv g = do rnds <- replicateM (length vs + 1) $ randomRIO (0.0, 1.0) flipDir <- randomRIO (True, False) let vs' = zip rnds vs let g' = insertVertex v g go vs pv $! foldl' (insertFlippedEdge pv v () flipDir) g' vs' Useful for use with ' ' rndAdjacencyMatrix :: Int -> IO [[Int]] rndAdjacencyMatrix n = replicateM n randRow where randRow = replicateM n (randomRIO (0,1)) :: IO [Int] insertFlippedEdge :: (Graph g, Hashable v, Eq v) => Float -> v -> e -> Bool -> g v e -> (Float, v) -> g v e insertFlippedEdge pv v edgeAttr flipDir g (p', v') | p' < pv = insertEdgeTriple triple g | otherwise = g where triple = if flipDir then (v', v, edgeAttr) else (v, v', edgeAttr) | Bound a real value as probability value [ 0.0 , 1.0 ] probability :: Float -> Float probability v | v >= 1 = 1 | v <= 0 = 0 | otherwise = v
42df630f398c6d7788ff890399239a295f1fa19f9ced26286dbe824e587a621d
jaspervdj/hakyll
Tests.hs
-------------------------------------------------------------------------------- module Hakyll.Web.Html.Tests ( tests ) where -------------------------------------------------------------------------------- import Data.Char (toUpper) import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit ((@=?)) import qualified Text.HTML.TagSoup as TS -------------------------------------------------------------------------------- import Hakyll.Web.Html import TestSuite.Util -------------------------------------------------------------------------------- tests :: TestTree tests = testGroup "Hakyll.Web.Html.Tests" $ concat [ fromAssertions "demoteHeaders" [ "<h2>A h1 title</h2>" @=? Assert single - step demotion , "<h6>A h6 title</h6>" @=? Assert maximum demotion is h6 ] , fromAssertions "demoteHeadersBy" [ "<h3>A h1 title</h3>" @=? demoteHeadersBy 2 "<h1>A h1 title</h1>" , "<h6>A h5 title</h6>" @=? Assert that h6 is the lowest possible demoted header . , "<h4>A h4 title</h4>" @=? demoteHeadersBy 0 "<h4>A h4 title</h4>" -- Assert that a demotion of @N < 1@ is a no-op. ] , fromAssertions "getUrls" [ ["/image1.png", "/image2.jpeg", "", "/game.swf", "/poster.jpeg"] @=? getUrls [ TS.TagOpen "img" [("src", "/image1.png")] , TS.TagOpen "img" [("src", "/image2.jpeg")] , TS.TagOpen "a" [("href", "")] , TS.TagOpen "object" [("data", "/game.swf")] , TS.TagOpen "video" [("poster", "/poster.jpeg")] ] , ["/image1.png", "/image2.jpeg", "/image3.bmp"] @=? getUrls [ TS.TagOpen "img" [("srcset", "/image1.png 10w, /image2.jpeg, /image3.bmp 1.3x")] ] Invalid srcset specification means no URLs are extracted , [] @=? getUrls [ TS.TagOpen "img" [("srcset", "/image1.png 10wide, /image2.jpeg, /image3.bmp 1.3px")] ] ] , fromAssertions "withUrls" [ "<a href=\"FOO\">bar</a>" @=? withUrls (map toUpper) "<a href=\"foo\">bar</a>" , "<img src=\"OH BAR\" />" @=? withUrls (map toUpper) "<img src=\"oh bar\" />" -- Test escaping , "<script>\"sup\"</script>" @=? withUrls id "<script>\"sup\"</script>" , "<code>&lt;stdio&gt;</code>" @=? withUrls id "<code>&lt;stdio&gt;</code>" , "<style>body > p { line-height: 1.3 }</style>" @=? withUrls id "<style>body > p { line-height: 1.3 }</style>" -- Test minimizing elements , "<meta bar=\"foo\" />" @=? withUrls id "<meta bar=\"foo\" />" Test that URLs are extracted from 's srcset , "<img srcset=\"foo 200w\" />" @=? withUrls (const "foo") "<img srcset=\"/path/to/image.png 200w\" />" , "<img srcset=\"bar 200w, bar 400w\" />" @=? withUrls (const "bar") "<img srcset=\"/small.jpeg 200w, /img/large.jpeg 400w\" />" Invalid srcsets are left unchanged , "<img srcset=\"/image1.png 200px\" />" @=? withUrls (const "bar") "<img srcset=\"/image1.png 200px\" />" ] , fromAssertions "toUrl" [ "/foo/bar.html" @=? toUrl "foo/bar.html" , "/foo/bar.html" @=? toUrl "foo\\bar.html" -- Windows-specific , "/" @=? toUrl "/" , "/funny-pics.html" @=? toUrl "/funny-pics.html" , "/funny%20pics.html" @=? toUrl "funny pics.html" Test various reserved characters ( RFC 3986 , section 2.2 ) , "/%21%2A%27%28%29%3B%3A%40%26.html" @=? toUrl "/!*'();:@&.html" , "/%3D%2B%24%2C/%3F%23%5B%5D.html" @=? toUrl "=+$,/?#[].html" -- Test various characters that are nor reserved, nor unreserved. , "/%E3%81%82%F0%9D%90%87%E2%88%80" @=? toUrl "\12354\119815\8704" ] , fromAssertions "toSiteRoot" [ ".." @=? toSiteRoot "/foo/bar.html" , "." @=? toSiteRoot "index.html" , "." @=? toSiteRoot "/index.html" , "../.." @=? toSiteRoot "foo/bar/qux" , ".." @=? toSiteRoot "./foo/bar.html" , ".." @=? toSiteRoot "/foo/./bar.html" ] , fromAssertions "isExternal" [ True @=? isExternal "" , True @=? isExternal "" , True @=? isExternal "//ajax.googleapis.com" , False @=? isExternal "../header.png" , False @=? isExternal "/foo/index.html" ] , fromAssertions "stripTags" [ "foo" @=? stripTags "<p>foo</p>" , "foo bar" @=? stripTags "<p>foo</p> bar" , "foo" @=? stripTags "<p>foo</p" ] , fromAssertions "escapeHtml" [ "Me &amp; Dean" @=? escapeHtml "Me & Dean" , "&lt;img&gt;" @=? escapeHtml "<img>" ] ]
null
https://raw.githubusercontent.com/jaspervdj/hakyll/05070e8a2b025a625cca923d9438e4d647075646/tests/Hakyll/Web/Html/Tests.hs
haskell
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Assert that a demotion of @N < 1@ is a no-op. Test escaping Test minimizing elements Windows-specific Test various characters that are nor reserved, nor unreserved.
module Hakyll.Web.Html.Tests ( tests ) where import Data.Char (toUpper) import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit ((@=?)) import qualified Text.HTML.TagSoup as TS import Hakyll.Web.Html import TestSuite.Util tests :: TestTree tests = testGroup "Hakyll.Web.Html.Tests" $ concat [ fromAssertions "demoteHeaders" [ "<h2>A h1 title</h2>" @=? Assert single - step demotion , "<h6>A h6 title</h6>" @=? Assert maximum demotion is h6 ] , fromAssertions "demoteHeadersBy" [ "<h3>A h1 title</h3>" @=? demoteHeadersBy 2 "<h1>A h1 title</h1>" , "<h6>A h5 title</h6>" @=? Assert that h6 is the lowest possible demoted header . , "<h4>A h4 title</h4>" @=? ] , fromAssertions "getUrls" [ ["/image1.png", "/image2.jpeg", "", "/game.swf", "/poster.jpeg"] @=? getUrls [ TS.TagOpen "img" [("src", "/image1.png")] , TS.TagOpen "img" [("src", "/image2.jpeg")] , TS.TagOpen "a" [("href", "")] , TS.TagOpen "object" [("data", "/game.swf")] , TS.TagOpen "video" [("poster", "/poster.jpeg")] ] , ["/image1.png", "/image2.jpeg", "/image3.bmp"] @=? getUrls [ TS.TagOpen "img" [("srcset", "/image1.png 10w, /image2.jpeg, /image3.bmp 1.3x")] ] Invalid srcset specification means no URLs are extracted , [] @=? getUrls [ TS.TagOpen "img" [("srcset", "/image1.png 10wide, /image2.jpeg, /image3.bmp 1.3px")] ] ] , fromAssertions "withUrls" [ "<a href=\"FOO\">bar</a>" @=? withUrls (map toUpper) "<a href=\"foo\">bar</a>" , "<img src=\"OH BAR\" />" @=? withUrls (map toUpper) "<img src=\"oh bar\" />" , "<script>\"sup\"</script>" @=? withUrls id "<script>\"sup\"</script>" , "<code>&lt;stdio&gt;</code>" @=? withUrls id "<code>&lt;stdio&gt;</code>" , "<style>body > p { line-height: 1.3 }</style>" @=? withUrls id "<style>body > p { line-height: 1.3 }</style>" , "<meta bar=\"foo\" />" @=? withUrls id "<meta bar=\"foo\" />" Test that URLs are extracted from 's srcset , "<img srcset=\"foo 200w\" />" @=? withUrls (const "foo") "<img srcset=\"/path/to/image.png 200w\" />" , "<img srcset=\"bar 200w, bar 400w\" />" @=? withUrls (const "bar") "<img srcset=\"/small.jpeg 200w, /img/large.jpeg 400w\" />" Invalid srcsets are left unchanged , "<img srcset=\"/image1.png 200px\" />" @=? withUrls (const "bar") "<img srcset=\"/image1.png 200px\" />" ] , fromAssertions "toUrl" [ "/foo/bar.html" @=? toUrl "foo/bar.html" , "/" @=? toUrl "/" , "/funny-pics.html" @=? toUrl "/funny-pics.html" , "/funny%20pics.html" @=? toUrl "funny pics.html" Test various reserved characters ( RFC 3986 , section 2.2 ) , "/%21%2A%27%28%29%3B%3A%40%26.html" @=? toUrl "/!*'();:@&.html" , "/%3D%2B%24%2C/%3F%23%5B%5D.html" @=? toUrl "=+$,/?#[].html" , "/%E3%81%82%F0%9D%90%87%E2%88%80" @=? toUrl "\12354\119815\8704" ] , fromAssertions "toSiteRoot" [ ".." @=? toSiteRoot "/foo/bar.html" , "." @=? toSiteRoot "index.html" , "." @=? toSiteRoot "/index.html" , "../.." @=? toSiteRoot "foo/bar/qux" , ".." @=? toSiteRoot "./foo/bar.html" , ".." @=? toSiteRoot "/foo/./bar.html" ] , fromAssertions "isExternal" [ True @=? isExternal "" , True @=? isExternal "" , True @=? isExternal "//ajax.googleapis.com" , False @=? isExternal "../header.png" , False @=? isExternal "/foo/index.html" ] , fromAssertions "stripTags" [ "foo" @=? stripTags "<p>foo</p>" , "foo bar" @=? stripTags "<p>foo</p> bar" , "foo" @=? stripTags "<p>foo</p" ] , fromAssertions "escapeHtml" [ "Me &amp; Dean" @=? escapeHtml "Me & Dean" , "&lt;img&gt;" @=? escapeHtml "<img>" ] ]
140387c2f1a54722594882add369f4810142888826ab71949f05f357ba22bf23
uhc/uhc
Plugin.hs
{- A Plugin holds all info required for parsing from and formatting to a particular text format. -} ------------------------------------------------------------------------- -- Plugin structure ------------------------------------------------------------------------- module Plugin ( Plugin(..), defaultPlugin , PluginMp ) where import qualified Data.Map as Map import UU.Parsing import qualified EH.Util.FastSeq as Seq import Common import Text import Text.Parser.Common ------------------------------------------------------------------------- -- Plugin ------------------------------------------------------------------------- data Plugin = Plugin has a parser ( Maybe can not be used because parser type can not be type parameter in recent GHC versions ( > = 7 ) ) , plgParseTextItems :: Maybe (T2TPr (Seq.Seq TextItem)) -- parse text items , plgParseTextItems2 :: T2TPr ( (Seq.Seq TextItem)) -- parse text items , plgScanOptsMp :: ScanOptsMp -- scanner configuration , plgScanInitState :: ScState -- initial scanning state , plgToOutDoc :: Maybe (Opts -> AGItf -> OutDoc) -- generate output for format } defaultPlugin :: Plugin defaultPlugin = Plugin { plgHasParserTextItems = False , plgParseTextItems = Nothing , plgParseTextItems2 = pSucceed Seq.empty , plgScanOptsMp = Map.empty , plgScanInitState = defaultScState , plgToOutDoc = Nothing } type PluginMp = Map.Map TextType Plugin
null
https://raw.githubusercontent.com/uhc/uhc/8eb6914df3ba2ba43916a1a4956c6f25aa0e07c5/EHC/src/text2text/Plugin.hs
haskell
A Plugin holds all info required for parsing from and formatting to a particular text format. ----------------------------------------------------------------------- Plugin structure ----------------------------------------------------------------------- ----------------------------------------------------------------------- Plugin ----------------------------------------------------------------------- parse text items parse text items scanner configuration initial scanning state generate output for format
module Plugin ( Plugin(..), defaultPlugin , PluginMp ) where import qualified Data.Map as Map import UU.Parsing import qualified EH.Util.FastSeq as Seq import Common import Text import Text.Parser.Common data Plugin = Plugin has a parser ( Maybe can not be used because parser type can not be type parameter in recent GHC versions ( > = 7 ) ) } defaultPlugin :: Plugin defaultPlugin = Plugin { plgHasParserTextItems = False , plgParseTextItems = Nothing , plgParseTextItems2 = pSucceed Seq.empty , plgScanOptsMp = Map.empty , plgScanInitState = defaultScState , plgToOutDoc = Nothing } type PluginMp = Map.Map TextType Plugin
4e5dd8dbb7f67f72ad661d56fdc06897586afb4afb805572a303a2fce53c681f
LuisThiamNye/chic
svg.clj
(ns chic.ui.svg (:require [io.github.humbleui.core :as hui :refer [deftype+]] [io.github.humbleui.protocols :as huip :refer [IComponent]]) (:import [io.github.humbleui.skija Canvas Data] (io.github.humbleui.skija.svg SVGLengthContext SVGDOM SVGSVG SVGLengthType) [io.github.humbleui.types IPoint Point] [java.lang AutoCloseable])) (deftype+ Svg [^SVGDOM dom] IComponent (-measure [_ ctx cs] (let [root (.getRoot dom) lc (SVGLengthContext. (Point. (:x cs) (:y cs)))] (.getIntrinsicSize root lc))) (-draw [_ _ctx cs ^Canvas canvas] (let [root ^SVGSVG (.getRoot dom) lc (SVGLengthContext. (Point. (:width cs) (:height cs))) width (.resolve lc (.getWidth root) SVGLengthType/HORIZONTAL) height (.resolve lc (.getHeight root) SVGLengthType/VERTICAL) xscale (/ (:width cs) width) yscale (/ (:height cs) height) layer (.save canvas)] (.setContainerSize dom (Point. (:x cs) (:y cs))) (.scale canvas xscale yscale) (.render dom canvas) (.restoreToCount canvas layer))) (-event [_ _event]) AutoCloseable (close [_])) #_(defn file->svgdom [f] (let [data-bytes(fs/read-all-bytes f) data (Data/makeFromBytes data-bytes) svgdom (SVGDOM. data)] svgdom)) (defn make [^Data data] (->Svg (SVGDOM. data))) (comment #! )
null
https://raw.githubusercontent.com/LuisThiamNye/chic/813633a689f9080731613f788a295604d4d9a510/src/chic/ui/svg.clj
clojure
(ns chic.ui.svg (:require [io.github.humbleui.core :as hui :refer [deftype+]] [io.github.humbleui.protocols :as huip :refer [IComponent]]) (:import [io.github.humbleui.skija Canvas Data] (io.github.humbleui.skija.svg SVGLengthContext SVGDOM SVGSVG SVGLengthType) [io.github.humbleui.types IPoint Point] [java.lang AutoCloseable])) (deftype+ Svg [^SVGDOM dom] IComponent (-measure [_ ctx cs] (let [root (.getRoot dom) lc (SVGLengthContext. (Point. (:x cs) (:y cs)))] (.getIntrinsicSize root lc))) (-draw [_ _ctx cs ^Canvas canvas] (let [root ^SVGSVG (.getRoot dom) lc (SVGLengthContext. (Point. (:width cs) (:height cs))) width (.resolve lc (.getWidth root) SVGLengthType/HORIZONTAL) height (.resolve lc (.getHeight root) SVGLengthType/VERTICAL) xscale (/ (:width cs) width) yscale (/ (:height cs) height) layer (.save canvas)] (.setContainerSize dom (Point. (:x cs) (:y cs))) (.scale canvas xscale yscale) (.render dom canvas) (.restoreToCount canvas layer))) (-event [_ _event]) AutoCloseable (close [_])) #_(defn file->svgdom [f] (let [data-bytes(fs/read-all-bytes f) data (Data/makeFromBytes data-bytes) svgdom (SVGDOM. data)] svgdom)) (defn make [^Data data] (->Svg (SVGDOM. data))) (comment #! )
b9b455aace2e3e8c03bc72e39f816bb868fb01ae7129647fed684c60ca7be7cf
SKA-ScienceDataProcessor/RC
ddp-in-memory-cuda.hs
# LANGUAGE TemplateHaskell # module Main(main) where import DNA.Channel.File (readDataMMap) import DNA import DDP import DDP_Slice_CUDA ---------------------------------------------------------------- -- Distributed dot product -- -- Note that actors which do not spawn actors on other nodes do not -- receive CAD. ---------------------------------------------------------------- ddpCollector :: CollectActor Double Double ddpCollector = collectActor (\s a -> return $! s + a) (return 0) (return) remotable [ 'ddpCollector ] -- | Actor for calculating dot product ddpDotProduct :: Actor Slice Double ddpDotProduct = actor $ \size -> do res <- selectMany (Frac 1) (NNodes 1) [UseLocal] r <- select Local (N 0) shell <- startGroup res Failout $(mkStaticClosure 'ddpProductSlice) shCol <- startCollector r $(mkStaticClosure 'ddpCollector) sendParam size $ broadcast shell connect shell shCol res <- delay Remote shCol await res main :: IO () main = dnaRun rtable $ do let n = 10*1000*1000 expected = fromIntegral n*(fromIntegral n-1)/2 * 0.1 -- Show configuration nodes <- groupSize let size = n * 8; sizePerNode = size `div` fromIntegral nodes liftIO $ putStrLn $ concat [ "Data: ", show (size `div` 1000000), " MB total, " , show (sizePerNode `div` 1000000), " MB per node"] b <- eval ddpDotProduct (Slice 0 n) liftIO $ putStrLn $ concat [ "RESULT: ", show b , " EXPECTED: ", show expected , if b == expected then " -- ok" else " -- WRONG!" ] where rtable = DDP.__remoteTable . DDP_Slice_CUDA.__remoteTable . Main.__remoteTable
null
https://raw.githubusercontent.com/SKA-ScienceDataProcessor/RC/1b5e25baf9204a9f7ef40ed8ee94a86cc6c674af/MS2/dna-programs/ddp-in-memory-cuda.hs
haskell
-------------------------------------------------------------- Distributed dot product Note that actors which do not spawn actors on other nodes do not receive CAD. -------------------------------------------------------------- | Actor for calculating dot product Show configuration
# LANGUAGE TemplateHaskell # module Main(main) where import DNA.Channel.File (readDataMMap) import DNA import DDP import DDP_Slice_CUDA ddpCollector :: CollectActor Double Double ddpCollector = collectActor (\s a -> return $! s + a) (return 0) (return) remotable [ 'ddpCollector ] ddpDotProduct :: Actor Slice Double ddpDotProduct = actor $ \size -> do res <- selectMany (Frac 1) (NNodes 1) [UseLocal] r <- select Local (N 0) shell <- startGroup res Failout $(mkStaticClosure 'ddpProductSlice) shCol <- startCollector r $(mkStaticClosure 'ddpCollector) sendParam size $ broadcast shell connect shell shCol res <- delay Remote shCol await res main :: IO () main = dnaRun rtable $ do let n = 10*1000*1000 expected = fromIntegral n*(fromIntegral n-1)/2 * 0.1 nodes <- groupSize let size = n * 8; sizePerNode = size `div` fromIntegral nodes liftIO $ putStrLn $ concat [ "Data: ", show (size `div` 1000000), " MB total, " , show (sizePerNode `div` 1000000), " MB per node"] b <- eval ddpDotProduct (Slice 0 n) liftIO $ putStrLn $ concat [ "RESULT: ", show b , " EXPECTED: ", show expected , if b == expected then " -- ok" else " -- WRONG!" ] where rtable = DDP.__remoteTable . DDP_Slice_CUDA.__remoteTable . Main.__remoteTable
29c89cded809fb892cf2c704bc091f56b392712b15b17661ee952879c0985bd1
mbenke/zpf2013
SimpleCheck2.hs
module SimpleCheck1 where import System.Random ( StdGen -- :: * : : IO StdGen , Random(..) -- class : : ( RandomGen g , Random a ) = > ( a , a ) - > g - > ( a , g ) , split -- :: RandomGen g => g -> (g, g) rozdziela argument na instance RandomGen StdGen ) import Data.List( group, sort, intersperse ) import Control.Monad( liftM2, liftM3, liftM4 ) infix 1 ` classify ` newtype Gen a = Gen (Int -> StdGen -> a) sized :: (Int -> Gen a) -> Gen a sized fgen = Gen (\n r -> let Gen m = fgen n in m n r) resize :: Int -> Gen a -> Gen a resize n (Gen m) = Gen (\_ r -> m n r) instance Monad Gen where return a = Gen $ \n r -> a Gen m >>= k = Gen $ \n r0 -> let (r1,r2) = split r0 Gen m' = k (m n r1) in m' n r2 instance Functor Gen where fmap f m = m >>= return . f rand :: Gen StdGen rand = Gen (\n r -> r) chooseInt1 :: (Int,Int) -> Gen Int chooseInt1 bounds = Gen $ \n r -> fst (randomR bounds r) chooseInt :: (Int,Int) -> Gen Int chooseInt bounds = (fst . randomR bounds) `fmap` rand choose :: Random a => (a, a) -> Gen a choose bounds = (fst . randomR bounds) `fmap` rand elements :: [a] -> Gen a elements xs = (xs !!) `fmap` choose (0, length xs - 1) vector :: Arbitrary a => Int -> Gen [a] vector n = sequence [ arbitrary | i <- [1..n] ] sequence : : = > [ m a ] - > m [ a ] genOne :: Gen a -> IO a genOne (Gen m) = do rnd0 <- newStdGen return $ m 7 rnd0 -- * Arbitrary class Arbitrary a where arbitrary :: Gen a instance Arbitrary () where arbitrary = return () instance Arbitrary Bool where arbitrary = elements [True, False] instance Arbitrary a => Arbitrary [a] where arbitrary = sized (\n -> choose (0,n) >>= vector) instance Arbitrary Int where arbitrary = sized $ \n -> choose (-n,n) * promote :: (a -> Gen b) -> Gen (a -> b) promote f = Gen (\n r -> \a -> let Gen m = f a in m n r) class CoArbitrary a where coarbitrary :: a -> Gen b -> Gen b instance (CoArbitrary a, Arbitrary b) => Arbitrary(a->b) where arbitrary = promote $ \a -> coarbitrary a arbitrary variant :: Int -> Gen a -> Gen a variant v (Gen m) = Gen (\n r -> m n (rands r !! (v+1))) where rands r0 = r1 : rands r2 where (r1, r2) = split r0 instance CoArbitrary Bool where coarbitrary False = variant 0 coarbitrary True = variant 1 instance CoArbitrary Int where coarbitrary n = variant (if n >= 0 then 2*n else 2*(-n) + 1) genInt :: IO Int genInt = genOne arbitrary genInts :: IO [Int] genInts = genOne arbitrary generate :: Int -> StdGen -> Gen a -> a generate n rnd (Gen m) = m size rnd' where (size, rnd') = randomR (0, n) rnd data Result = Result { ok :: Maybe Bool, arguments :: [String] } nothing :: Result nothing = Result{ ok = Nothing, arguments = [] } newtype Property = Prop (Gen Result) class Testable a where property :: a -> Property result :: Result -> Property result res = Prop (return res) instance Testable () where property () = result nothing instance Testable Bool where property b = result (nothing { ok = Just b }) instance Testable Property where property prop = prop evaluate :: Testable a => a -> Gen Result evaluate a = gen where Prop gen = property a forAll :: (Show a, Testable b) => Gen a -> (a -> b) -> Property forAll gen body = Prop $ do a <- gen res <- evaluate (body a) return (argument a res) where argument a res = res{ arguments = show a : arguments res } instance (Arbitrary a, Show a, Testable b) => Testable (a -> b) where property f = forAll arbitrary f infixr 0 ==> (==>) :: Testable a => Bool -> a -> Property True ==> a = property a False ==> a = property () -- Driver check :: Testable prop => prop -> IO () check prop = do rnd <- newStdGen tests (evaluate prop) rnd 0 0 tests :: Gen Result -> StdGen -> Int -> Int -> IO () tests gen rnd0 ntest nfail | ntest == configMaxTest = do done "OK, passed" ntest | nfail == configMaxFail = do done "Arguments exhausted after" ntest | otherwise = do -- configEvery ntests (arguments result) case ok result of Nothing -> tests gen rnd1 ntest (nfail+1) Just True -> tests gen rnd1 (ntest+1) nfail Just False -> putStr ( "Falsifiable, after " ++ show ntest ++ " tests:\n" ++ unlines (arguments result) ) where result = generate (configSize ntest) rnd2 gen (rnd1,rnd2) = split rnd0 done :: String -> Int -> IO () done mesg ntest = do putStrLn ( mesg ++ " " ++ show ntest ++ " tests" ) configMaxTest = 100 configMaxFail = 500 configSize = (+ 3) . (`div` 2) configEvery = let s = show n in s + + [ ' \b ' | _ < - s ] propAddCom1 :: Property propAddCom1 = forAll (chooseInt (-100,100)) (\x -> x + 1 == 1 + x) propAddCom2 = forAll int (\x -> forAll int (\y -> x + y == y + x)) where int = chooseInt (-100,100) propAddCom3 :: Int -> Int -> Bool propAddCom3 x y = x + y == y + x propMul1 :: Int -> Property propMul1 x = (x>0) ==> (2*x > 0) propMul2 :: Int -> Int -> Property propMul2 x y = (x>0) ==> (x*y > 0) infix 4 === (===) f g x = f x == g x instance Show(a->b) where show f = "<function>" propCompAssoc f g h = (f . g) . h === f . (g . h) where types = [f,g,h::Int->Int]
null
https://raw.githubusercontent.com/mbenke/zpf2013/85f32747e17f07a74e1c3cb064b1d6acaca3f2f0/Slides/13QC/SimpleCheck2.hs
haskell
:: * class :: RandomGen g => g -> (g, g) * Arbitrary Driver configEvery ntests (arguments result)
module SimpleCheck1 where import System.Random : : IO StdGen : : ( RandomGen g , Random a ) = > ( a , a ) - > g - > ( a , g ) rozdziela argument na instance RandomGen StdGen ) import Data.List( group, sort, intersperse ) import Control.Monad( liftM2, liftM3, liftM4 ) infix 1 ` classify ` newtype Gen a = Gen (Int -> StdGen -> a) sized :: (Int -> Gen a) -> Gen a sized fgen = Gen (\n r -> let Gen m = fgen n in m n r) resize :: Int -> Gen a -> Gen a resize n (Gen m) = Gen (\_ r -> m n r) instance Monad Gen where return a = Gen $ \n r -> a Gen m >>= k = Gen $ \n r0 -> let (r1,r2) = split r0 Gen m' = k (m n r1) in m' n r2 instance Functor Gen where fmap f m = m >>= return . f rand :: Gen StdGen rand = Gen (\n r -> r) chooseInt1 :: (Int,Int) -> Gen Int chooseInt1 bounds = Gen $ \n r -> fst (randomR bounds r) chooseInt :: (Int,Int) -> Gen Int chooseInt bounds = (fst . randomR bounds) `fmap` rand choose :: Random a => (a, a) -> Gen a choose bounds = (fst . randomR bounds) `fmap` rand elements :: [a] -> Gen a elements xs = (xs !!) `fmap` choose (0, length xs - 1) vector :: Arbitrary a => Int -> Gen [a] vector n = sequence [ arbitrary | i <- [1..n] ] sequence : : = > [ m a ] - > m [ a ] genOne :: Gen a -> IO a genOne (Gen m) = do rnd0 <- newStdGen return $ m 7 rnd0 class Arbitrary a where arbitrary :: Gen a instance Arbitrary () where arbitrary = return () instance Arbitrary Bool where arbitrary = elements [True, False] instance Arbitrary a => Arbitrary [a] where arbitrary = sized (\n -> choose (0,n) >>= vector) instance Arbitrary Int where arbitrary = sized $ \n -> choose (-n,n) * promote :: (a -> Gen b) -> Gen (a -> b) promote f = Gen (\n r -> \a -> let Gen m = f a in m n r) class CoArbitrary a where coarbitrary :: a -> Gen b -> Gen b instance (CoArbitrary a, Arbitrary b) => Arbitrary(a->b) where arbitrary = promote $ \a -> coarbitrary a arbitrary variant :: Int -> Gen a -> Gen a variant v (Gen m) = Gen (\n r -> m n (rands r !! (v+1))) where rands r0 = r1 : rands r2 where (r1, r2) = split r0 instance CoArbitrary Bool where coarbitrary False = variant 0 coarbitrary True = variant 1 instance CoArbitrary Int where coarbitrary n = variant (if n >= 0 then 2*n else 2*(-n) + 1) genInt :: IO Int genInt = genOne arbitrary genInts :: IO [Int] genInts = genOne arbitrary generate :: Int -> StdGen -> Gen a -> a generate n rnd (Gen m) = m size rnd' where (size, rnd') = randomR (0, n) rnd data Result = Result { ok :: Maybe Bool, arguments :: [String] } nothing :: Result nothing = Result{ ok = Nothing, arguments = [] } newtype Property = Prop (Gen Result) class Testable a where property :: a -> Property result :: Result -> Property result res = Prop (return res) instance Testable () where property () = result nothing instance Testable Bool where property b = result (nothing { ok = Just b }) instance Testable Property where property prop = prop evaluate :: Testable a => a -> Gen Result evaluate a = gen where Prop gen = property a forAll :: (Show a, Testable b) => Gen a -> (a -> b) -> Property forAll gen body = Prop $ do a <- gen res <- evaluate (body a) return (argument a res) where argument a res = res{ arguments = show a : arguments res } instance (Arbitrary a, Show a, Testable b) => Testable (a -> b) where property f = forAll arbitrary f infixr 0 ==> (==>) :: Testable a => Bool -> a -> Property True ==> a = property a False ==> a = property () check :: Testable prop => prop -> IO () check prop = do rnd <- newStdGen tests (evaluate prop) rnd 0 0 tests :: Gen Result -> StdGen -> Int -> Int -> IO () tests gen rnd0 ntest nfail | ntest == configMaxTest = do done "OK, passed" ntest | nfail == configMaxFail = do done "Arguments exhausted after" ntest | otherwise = case ok result of Nothing -> tests gen rnd1 ntest (nfail+1) Just True -> tests gen rnd1 (ntest+1) nfail Just False -> putStr ( "Falsifiable, after " ++ show ntest ++ " tests:\n" ++ unlines (arguments result) ) where result = generate (configSize ntest) rnd2 gen (rnd1,rnd2) = split rnd0 done :: String -> Int -> IO () done mesg ntest = do putStrLn ( mesg ++ " " ++ show ntest ++ " tests" ) configMaxTest = 100 configMaxFail = 500 configSize = (+ 3) . (`div` 2) configEvery = let s = show n in s + + [ ' \b ' | _ < - s ] propAddCom1 :: Property propAddCom1 = forAll (chooseInt (-100,100)) (\x -> x + 1 == 1 + x) propAddCom2 = forAll int (\x -> forAll int (\y -> x + y == y + x)) where int = chooseInt (-100,100) propAddCom3 :: Int -> Int -> Bool propAddCom3 x y = x + y == y + x propMul1 :: Int -> Property propMul1 x = (x>0) ==> (2*x > 0) propMul2 :: Int -> Int -> Property propMul2 x y = (x>0) ==> (x*y > 0) infix 4 === (===) f g x = f x == g x instance Show(a->b) where show f = "<function>" propCompAssoc f g h = (f . g) . h === f . (g . h) where types = [f,g,h::Int->Int]
1237c9d86a72319ef98209af8109848f233e5b22c7b95822615fcde8507de335
yuriy-chumak/ol
loops-infinite.scm
; actually ca n't test because this is infinite task , so just do this one time (let loop () (print "SPAM") #|(loop)|#)
null
https://raw.githubusercontent.com/yuriy-chumak/ol/83dd03d311339763682eab02cbe0c1321daa25bc/tests/rosettacode/loops-infinite.scm
scheme
(loop)
actually ca n't test because this is infinite task , so just do this one time (let loop () (print "SPAM")
6cef7f9cb3f60c143a8db72492a7597fab9e39836acaa1470e1f24b0f538fca7
marick/fp-oo
t_pattern_text.clj
(ns sources.t-pattern-text (:use midje.sweet)) (load-file "sources/pattern-text.clj") (fact (add-points [1 2] [3 4]) => [4 6] (add-points-2 [1 2] [3 4]) => [4 6]) (fact (factorial 0) => 1 (factorial 1) => 1 (factorial 5) => 120 (factorial-2 0) => 1 (factorial-2 1) => 1 (factorial-2 5) => 120 (factorial-3 0) => 1 (factorial-3 1) => 1 (factorial-3 5) => 120 (factorial-4 -1) => :oops (factorial-4 0) => 1 (factorial-4 1) => 1 (factorial-4 5) => 120 (factorial-5 -1) => :oops (factorial-5 0) => 1 (factorial-5 1) => 1 (factorial-5 5) => 120) (fact (count-sequence [:a :b :c]) => 3)
null
https://raw.githubusercontent.com/marick/fp-oo/434937826d794d6fe02b3e9a62cf5b4fbc314412/test/sources/t_pattern_text.clj
clojure
(ns sources.t-pattern-text (:use midje.sweet)) (load-file "sources/pattern-text.clj") (fact (add-points [1 2] [3 4]) => [4 6] (add-points-2 [1 2] [3 4]) => [4 6]) (fact (factorial 0) => 1 (factorial 1) => 1 (factorial 5) => 120 (factorial-2 0) => 1 (factorial-2 1) => 1 (factorial-2 5) => 120 (factorial-3 0) => 1 (factorial-3 1) => 1 (factorial-3 5) => 120 (factorial-4 -1) => :oops (factorial-4 0) => 1 (factorial-4 1) => 1 (factorial-4 5) => 120 (factorial-5 -1) => :oops (factorial-5 0) => 1 (factorial-5 1) => 1 (factorial-5 5) => 120) (fact (count-sequence [:a :b :c]) => 3)
ffac158b7eeac8ecd6f98abbfa105f39cc0f2d18aabc4b6219b6540a9da36b95
hasura/graphql-data-specification
Definition.hs
module Schema.Model.Type.SelectionSetAggregate.Definition ( definition, ) where import DDL qualified import Language.GraphQL.Draft.Syntax as GraphQL import Schema.Context import Schema.Model.Type.SelectionSetAggregate.Name (name) import Schema.NamingConvention definition :: DDL.ModelDTO -> Generate (GraphQL.ObjectTypeDefinition GraphQL.InputValueDefinition) definition model = do aggregateFields <- mapM (aggregateField model.name . DDL.AggregationFunctionName) ["count", "sum", "avg"] nodes <- nodesField model pure $ GraphQL.ObjectTypeDefinition { _otdDescription = Nothing, _otdName = name model.name, _otdImplementsInterfaces = [], _otdDirectives = [], _otdFieldsDefinition = nodes : aggregateFields } nodesField :: DDL.ModelDTO -> Generate (GraphQL.FieldDefinition GraphQL.InputValueDefinition) nodesField model = do selectionSetTypeName <- getTypeName $ TGRSelectionSetFields model.name let fieldType = GraphQL.TypeList (GraphQL.Nullability False) $ GraphQL.TypeNamed (GraphQL.Nullability False) selectionSetTypeName pure $ GraphQL.FieldDefinition { _fldDescription = Nothing, _fldName = fieldName, _fldArgumentsDefinition = [], _fldType = fieldType, _fldDirectives = [] } where fieldName = mkFieldName "nodes" aggregateField :: DDL.ModelName -> DDL.AggregationFunctionName -> Generate (GraphQL.FieldDefinition GraphQL.InputValueDefinition) aggregateField modelName functionName = do selectionSetTypeName <- getTypeName $ TGRSelectionSetAggregateFunctionFields modelName functionName let fieldType = GraphQL.TypeNamed (GraphQL.Nullability True) selectionSetTypeName pure $ GraphQL.FieldDefinition { _fldDescription = Nothing, _fldName = fieldName, _fldArgumentsDefinition = [], _fldType = fieldType, _fldDirectives = [] } where fieldName = mkFieldName functionName.wrapped
null
https://raw.githubusercontent.com/hasura/graphql-data-specification/b82b899a7d015c810a571d31322619aff2154b81/tooling/lib/Schema/Model/Type/SelectionSetAggregate/Definition.hs
haskell
module Schema.Model.Type.SelectionSetAggregate.Definition ( definition, ) where import DDL qualified import Language.GraphQL.Draft.Syntax as GraphQL import Schema.Context import Schema.Model.Type.SelectionSetAggregate.Name (name) import Schema.NamingConvention definition :: DDL.ModelDTO -> Generate (GraphQL.ObjectTypeDefinition GraphQL.InputValueDefinition) definition model = do aggregateFields <- mapM (aggregateField model.name . DDL.AggregationFunctionName) ["count", "sum", "avg"] nodes <- nodesField model pure $ GraphQL.ObjectTypeDefinition { _otdDescription = Nothing, _otdName = name model.name, _otdImplementsInterfaces = [], _otdDirectives = [], _otdFieldsDefinition = nodes : aggregateFields } nodesField :: DDL.ModelDTO -> Generate (GraphQL.FieldDefinition GraphQL.InputValueDefinition) nodesField model = do selectionSetTypeName <- getTypeName $ TGRSelectionSetFields model.name let fieldType = GraphQL.TypeList (GraphQL.Nullability False) $ GraphQL.TypeNamed (GraphQL.Nullability False) selectionSetTypeName pure $ GraphQL.FieldDefinition { _fldDescription = Nothing, _fldName = fieldName, _fldArgumentsDefinition = [], _fldType = fieldType, _fldDirectives = [] } where fieldName = mkFieldName "nodes" aggregateField :: DDL.ModelName -> DDL.AggregationFunctionName -> Generate (GraphQL.FieldDefinition GraphQL.InputValueDefinition) aggregateField modelName functionName = do selectionSetTypeName <- getTypeName $ TGRSelectionSetAggregateFunctionFields modelName functionName let fieldType = GraphQL.TypeNamed (GraphQL.Nullability True) selectionSetTypeName pure $ GraphQL.FieldDefinition { _fldDescription = Nothing, _fldName = fieldName, _fldArgumentsDefinition = [], _fldType = fieldType, _fldDirectives = [] } where fieldName = mkFieldName functionName.wrapped
19ef1d0866cc5abc5becee8ead94dd40d00005562077f164d24a0e7abd310810
ocaml/ocaml
build_as_type.ml
(* TEST * expect *) let f = function | ([] : int list) as x -> x | _ :: _ -> assert false;; [%%expect{| val f : int list -> int list = <fun> |}] let f = let f' = function | ([] : 'a list) as x -> x | _ :: _ -> assert false in f', f';; [%%expect{| val f : ('a list -> 'a list) * ('a list -> 'a list) = (<fun>, <fun>) |}] let f = let f' = function | ([] : _ list) as x -> x | _ :: _ -> assert false in f', f';; [%%expect{| val f : ('a list -> 'b list) * ('c list -> 'd list) = (<fun>, <fun>) |}] let f = let f' (type a) = function | ([] : a list) as x -> x | _ :: _ -> assert false in f', f';; [%%expect{| val f : ('a list -> 'a list) * ('b list -> 'b list) = (<fun>, <fun>) |}] type t = [ `A | `B ];; [%%expect{| type t = [ `A | `B ] |}] let f = function `A as x -> x | `B -> `A;; [%%expect{| val f : [< `A | `B ] -> [> `A ] = <fun> |}] let f = function (`A : t) as x -> x | `B -> `A;; [%%expect{| val f : t -> t = <fun> |}] let f : t -> _ = function `A as x -> x | `B -> `A;; [%%expect{| val f : t -> [> `A ] = <fun> |}] let f = function | (`A : t) as x -> (* This should be flagged as non-exhaustive: because of the constraint [x] is of type [t]. *) begin match x with | `A -> () end | `B -> ();; [%%expect{| Lines 5-7, characters 4-7: 5 | ....begin match x with 6 | | `A -> () 7 | end Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `B val f : t -> unit = <fun> |}] let f = function | (`A : t) as x -> begin match x with | `A -> () | `B -> () end | `B -> ();; [%%expect{| val f : t -> unit = <fun> |}] let f = function | (`A : t) as x -> begin match x with | `A -> () | `B -> () | `C -> () end | `B -> ();; [%%expect{| Line 6, characters 6-8: 6 | | `C -> () ^^ Error: This pattern matches values of type [? `C ] but a pattern was expected which matches values of type t The second variant type does not allow tag(s) `C |}] let f = function (`A, _ : _ * int) as x -> x;; [%%expect{| val f : [< `A ] * int -> [> `A ] * int = <fun> |}] (* Make sure *all* the constraints are respected: *) let f = function | ((`A : _) : t) as x -> (* This should be flagged as non-exhaustive: because of the constraint [x] is of type [t]. *) begin match x with | `A -> () end | `B -> ();; [%%expect{| Lines 5-7, characters 4-7: 5 | ....begin match x with 6 | | `A -> () 7 | end Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `B val f : t -> unit = <fun> |}] let f = function | ((`A : t) : _) as x -> (* This should be flagged as non-exhaustive: because of the constraint [x] is of type [t]. *) begin match x with | `A -> () end | `B -> ();; [%%expect{| Lines 5-7, characters 4-7: 5 | ....begin match x with 6 | | `A -> () 7 | end Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `B val f : t -> unit = <fun> |}]
null
https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/testsuite/tests/typing-misc/build_as_type.ml
ocaml
TEST * expect This should be flagged as non-exhaustive: because of the constraint [x] is of type [t]. Make sure *all* the constraints are respected: This should be flagged as non-exhaustive: because of the constraint [x] is of type [t]. This should be flagged as non-exhaustive: because of the constraint [x] is of type [t].
let f = function | ([] : int list) as x -> x | _ :: _ -> assert false;; [%%expect{| val f : int list -> int list = <fun> |}] let f = let f' = function | ([] : 'a list) as x -> x | _ :: _ -> assert false in f', f';; [%%expect{| val f : ('a list -> 'a list) * ('a list -> 'a list) = (<fun>, <fun>) |}] let f = let f' = function | ([] : _ list) as x -> x | _ :: _ -> assert false in f', f';; [%%expect{| val f : ('a list -> 'b list) * ('c list -> 'd list) = (<fun>, <fun>) |}] let f = let f' (type a) = function | ([] : a list) as x -> x | _ :: _ -> assert false in f', f';; [%%expect{| val f : ('a list -> 'a list) * ('b list -> 'b list) = (<fun>, <fun>) |}] type t = [ `A | `B ];; [%%expect{| type t = [ `A | `B ] |}] let f = function `A as x -> x | `B -> `A;; [%%expect{| val f : [< `A | `B ] -> [> `A ] = <fun> |}] let f = function (`A : t) as x -> x | `B -> `A;; [%%expect{| val f : t -> t = <fun> |}] let f : t -> _ = function `A as x -> x | `B -> `A;; [%%expect{| val f : t -> [> `A ] = <fun> |}] let f = function | (`A : t) as x -> begin match x with | `A -> () end | `B -> ();; [%%expect{| Lines 5-7, characters 4-7: 5 | ....begin match x with 6 | | `A -> () 7 | end Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `B val f : t -> unit = <fun> |}] let f = function | (`A : t) as x -> begin match x with | `A -> () | `B -> () end | `B -> ();; [%%expect{| val f : t -> unit = <fun> |}] let f = function | (`A : t) as x -> begin match x with | `A -> () | `B -> () | `C -> () end | `B -> ();; [%%expect{| Line 6, characters 6-8: 6 | | `C -> () ^^ Error: This pattern matches values of type [? `C ] but a pattern was expected which matches values of type t The second variant type does not allow tag(s) `C |}] let f = function (`A, _ : _ * int) as x -> x;; [%%expect{| val f : [< `A ] * int -> [> `A ] * int = <fun> |}] let f = function | ((`A : _) : t) as x -> begin match x with | `A -> () end | `B -> ();; [%%expect{| Lines 5-7, characters 4-7: 5 | ....begin match x with 6 | | `A -> () 7 | end Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `B val f : t -> unit = <fun> |}] let f = function | ((`A : t) : _) as x -> begin match x with | `A -> () end | `B -> ();; [%%expect{| Lines 5-7, characters 4-7: 5 | ....begin match x with 6 | | `A -> () 7 | end Warning 8 [partial-match]: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `B val f : t -> unit = <fun> |}]
42996e98f3b68f41cdb410f7daa327f6c87c9bde660da3deb410fed62b33466d
AccelerationNet/symbol-munger
symbol-munger.lisp
(defpackage :symbol-munger (:use :cl :cl-user :iter) (:export :normalize-capitalization-and-spacing :english->lisp-symbol :english->lisp-name :english->keyword :english->camel-case :english->studly-case :english->underscores :lisp->english :lisp->keyword :lisp->camel-case :lisp->underscores :lisp->studly-caps :combine-symbols :reintern :qualified-symbol-string :camel-case->english :camel-case->lisp-name :camel-case->lisp-symbol :camel-case->keyword :camel-case->underscores :underscores->english :underscores->lisp-name :underscores->lisp-symbol :underscores->keyword :underscores->camel-case :underscores->studly-caps )) (in-package :symbol-munger) (defgeneric %coerce-to-string (s) (:documentation "This method can be specialized to help turn objects into strings so they can be combined and normalized correctly") (:method (s) (typecase s (symbol (symbol-name s)) (string s) (float (format nil "~F" s)) (t (princ-to-string s))))) (defmacro ensure-list! (place) `(setf ,place (alexandria:ensure-list ,place))) (defmacro ensure-flat-list! (place) `(setf ,place (alexandria:flatten ,place))) (defun qualified-symbol-string (sym) (let ((*package* (find-package :keyword)) (*print-pretty* nil)) (format nil "~S" sym))) (defun normalize-capitalization-and-spacing (s &key (capitalize :each-word) (word-separators #\space) word-separators-to-replace stream in-place) "Will recapitalize a string and replace word-separators with a standard one (in-place if desired and possible) If s is a lisp tree, then each part will be %coerce-to-string'ed and treated as a separate part of the phrase being normalized Will write to a stream if given otherwise it. Defaults to capitalizing each word but can be any of {:each-word :first-word T (:all is an alias for T) nil :but-first-word (likeJavaScript) } word-separators are used to distinguish new words for the purposes of capitalization The first of these will be used to replace word-separators-to-replace (auto flattened) word-separators-to-replace helps normalize word separators so that spaces or underscores become the appropriate word-separator. If this eql :capitals it assumes capital letters indicate a new word separation (auto flattened) returns a string (new or the one passed in if in-place) unless :stream is provided" ;; Check and enforce our assumptions (ecase capitalize ((:each-word :first-word :but-first-word T :all nil) T)) (when (and in-place (member :capitals word-separators-to-replace)) (error "in-place replacement is not available for word separators which take no space (such as :capitals)")) (ensure-flat-list! word-separators) (ensure-flat-list! word-separators-to-replace) (let ((str (or stream (unless in-place (make-string-output-stream)))) (replacement-sep (let ((it (first word-separators))) (typecase it (string (if (= 1 (length it)) (elt it 0) it)) (t it)))) (just-wrote-separator? nil)) (labels ((%write (c) (etypecase c (character (write-char c str)) (string (write-string c str)) (symbol (write-string (symbol-name c) str)))) (write-c (c) (cond ((string= c replacement-sep) (unless just-wrote-separator? (setf just-wrote-separator? t) (%write c))) (t (setf just-wrote-separator? nil) (%write c))))) (iter (for part in (alexandria:flatten s)) (for source-string = (%coerce-to-string part)) (for start-of-phrase? = (first-iteration-p)) (iter (for c in-string source-string) (for last-c previous c) (for i from 0) (for is-cap? = (eql c (char-upcase c))) (setf start-of-phrase? (and start-of-phrase? (first-iteration-p))) (for start-of-word? = (or (first-iteration-p) (and is-cap? (member :capitals word-separators-to-replace)) (and is-cap? (member :capitals word-separators)) ;; the last char we wrote was some kind of separator (member last-c word-separators-to-replace :test #'string-equal) (member last-c word-separators :test #'string-equal))) ;; handle capital letters as word-separators (when (and str ;; in-place will not work replacement-sep ;; need to have a separator (not start-of-phrase?) ;; dont start a string with a sep ;; put separators before new words start-of-word?) (write-c replacement-sep)) (for should-cap? = (or (eq capitalize :all) (eq capitalize T) (and start-of-word? (or (eq capitalize :each-word) (if (first-iteration-p) (eq capitalize :first-word) (eq capitalize :but-first-word)))))) (for char = (cond ((member c word-separators-to-replace :test #'string-equal) (or replacement-sep (next-iteration))) (should-cap? (char-upcase c)) (T (char-downcase c)))) (when in-place (setf (elt source-string i) char)) (when str (write-c char))))) (cond ((not stream) (get-output-stream-string str)) (in-place s)))) (defun english->lisp-name (phrase &key stream capitalize) "Turns an english phrase into a string containing a common lisp style symbol-name" (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators (list #\-) :word-separators-to-replace (list #\_ #\space #\newline #\tab))) (defun english->lisp-symbol (phrase &optional (package *package*)) "Turns an english phrase into a common lisp symbol in the specified package" (intern (english->lisp-name phrase :capitalize T) package)) (defun english->keyword (phrase) "Turns an english phrase into a common lisp keyword" (english->lisp-symbol phrase :keyword)) (defun english->camel-case (phrase &key stream (capitalize :but-first-word)) "Turns an english phrase into a camelCasePhraseLikeThis " (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators nil :word-separators-to-replace (list #\_ #\space))) (defun english->studly-case (phrase &key stream) "Turns an english phrase into a CamelCasePhraseLikeThis" (english->camel-case phrase :stream stream :capitalize :each-word)) (defun english->underscores (phrase &key stream capitalize) "Turns an english phrase into a a_phrase_like_this" (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\_ :word-separators-to-replace (list #\space))) (defun lisp->english (phrase &key stream (capitalize :each-word) (word-separator #\space)) "Converts a common lisp symbol (or symbol-name) into an english phrase" (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators word-separator :word-separators-to-replace (list #\-))) (defun lisp->keyword (phrase) (combine-symbols phrase :package :keyword)) (defun reintern (phrase &optional (package *package*)) ;; never reintern nil (when phrase (combine-symbols phrase :package package))) (defun combine-symbols (phrase &key (package *package*) (separator #\-)) ;; never reintern nil (when phrase (intern (normalize-capitalization-and-spacing phrase :capitalize T ;; these are flattened so if nil it will just use #\- :word-separators separator :word-separators-to-replace nil) package))) (defun lisp->camel-case (phrase &key stream) (normalize-capitalization-and-spacing phrase :stream stream :capitalize :but-first-word :word-separators nil :word-separators-to-replace (list #\-))) (defun lisp->studly-caps (phrase &key stream) (normalize-capitalization-and-spacing phrase :stream stream :capitalize :each-word :word-separators nil :word-separators-to-replace (list #\-))) (defun lisp->underscores (phrase &key stream capitalize) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\_ :word-separators-to-replace (list #\-))) (defun camel-case->english (phrase &key stream (capitalize :each-word)) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\space :word-separators-to-replace (list :capitals #\_))) (defun camel-case->lisp-name (phrase &key stream (capitalize nil)) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\- :word-separators-to-replace (list :capitals #\_))) (defun camel-case->lisp-symbol (phrase &optional (package *package*)) (intern (camel-case->lisp-name phrase :capitalize T) package)) (defun camel-case->keyword (phrase) (camel-case->lisp-symbol phrase :keyword)) (defun camel-case->underscores (phrase &key stream capitalize) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\_ :word-separators-to-replace (list :capitals #\space))) ;;;;; (defun underscores->english (phrase &key stream (capitalize :each-word)) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\space :word-separators-to-replace (list #\_))) (defun underscores->lisp-name (phrase &key stream (capitalize nil)) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\- :word-separators-to-replace (list #\_))) (defun underscores->lisp-symbol (phrase &optional (package *package*)) "Turns a_phrase_with_underscores into a-phrase-with-underscores lisp symbol" (intern (underscores->lisp-name phrase :capitalize T) package)) (defun underscores->keyword (phrase) "Converts and underscores name to a common lisp keyword" (underscores->lisp-symbol phrase :keyword)) (defun underscores->camel-case (phrase &key stream) (normalize-capitalization-and-spacing phrase :stream stream :capitalize :but-first-word :word-separators nil :word-separators-to-replace (list #\_))) (defun underscores->studly-caps (phrase &key stream) (normalize-capitalization-and-spacing phrase :stream stream :capitalize :each-word :word-separators nil :word-separators-to-replace (list #\_)))
null
https://raw.githubusercontent.com/AccelerationNet/symbol-munger/e96558e8315b8eef3822be713354787b2348b25e/symbol-munger.lisp
lisp
Check and enforce our assumptions the last char we wrote was some kind of separator handle capital letters as word-separators in-place will not work need to have a separator dont start a string with a sep put separators before new words never reintern nil never reintern nil these are flattened so if nil it will just use #\-
(defpackage :symbol-munger (:use :cl :cl-user :iter) (:export :normalize-capitalization-and-spacing :english->lisp-symbol :english->lisp-name :english->keyword :english->camel-case :english->studly-case :english->underscores :lisp->english :lisp->keyword :lisp->camel-case :lisp->underscores :lisp->studly-caps :combine-symbols :reintern :qualified-symbol-string :camel-case->english :camel-case->lisp-name :camel-case->lisp-symbol :camel-case->keyword :camel-case->underscores :underscores->english :underscores->lisp-name :underscores->lisp-symbol :underscores->keyword :underscores->camel-case :underscores->studly-caps )) (in-package :symbol-munger) (defgeneric %coerce-to-string (s) (:documentation "This method can be specialized to help turn objects into strings so they can be combined and normalized correctly") (:method (s) (typecase s (symbol (symbol-name s)) (string s) (float (format nil "~F" s)) (t (princ-to-string s))))) (defmacro ensure-list! (place) `(setf ,place (alexandria:ensure-list ,place))) (defmacro ensure-flat-list! (place) `(setf ,place (alexandria:flatten ,place))) (defun qualified-symbol-string (sym) (let ((*package* (find-package :keyword)) (*print-pretty* nil)) (format nil "~S" sym))) (defun normalize-capitalization-and-spacing (s &key (capitalize :each-word) (word-separators #\space) word-separators-to-replace stream in-place) "Will recapitalize a string and replace word-separators with a standard one (in-place if desired and possible) If s is a lisp tree, then each part will be %coerce-to-string'ed and treated as a separate part of the phrase being normalized Will write to a stream if given otherwise it. Defaults to capitalizing each word but can be any of {:each-word :first-word T (:all is an alias for T) nil :but-first-word (likeJavaScript) } word-separators are used to distinguish new words for the purposes of capitalization The first of these will be used to replace word-separators-to-replace (auto flattened) word-separators-to-replace helps normalize word separators so that spaces or underscores become the appropriate word-separator. If this eql :capitals it assumes capital letters indicate a new word separation (auto flattened) returns a string (new or the one passed in if in-place) unless :stream is provided" (ecase capitalize ((:each-word :first-word :but-first-word T :all nil) T)) (when (and in-place (member :capitals word-separators-to-replace)) (error "in-place replacement is not available for word separators which take no space (such as :capitals)")) (ensure-flat-list! word-separators) (ensure-flat-list! word-separators-to-replace) (let ((str (or stream (unless in-place (make-string-output-stream)))) (replacement-sep (let ((it (first word-separators))) (typecase it (string (if (= 1 (length it)) (elt it 0) it)) (t it)))) (just-wrote-separator? nil)) (labels ((%write (c) (etypecase c (character (write-char c str)) (string (write-string c str)) (symbol (write-string (symbol-name c) str)))) (write-c (c) (cond ((string= c replacement-sep) (unless just-wrote-separator? (setf just-wrote-separator? t) (%write c))) (t (setf just-wrote-separator? nil) (%write c))))) (iter (for part in (alexandria:flatten s)) (for source-string = (%coerce-to-string part)) (for start-of-phrase? = (first-iteration-p)) (iter (for c in-string source-string) (for last-c previous c) (for i from 0) (for is-cap? = (eql c (char-upcase c))) (setf start-of-phrase? (and start-of-phrase? (first-iteration-p))) (for start-of-word? = (or (first-iteration-p) (and is-cap? (member :capitals word-separators-to-replace)) (and is-cap? (member :capitals word-separators)) (member last-c word-separators-to-replace :test #'string-equal) (member last-c word-separators :test #'string-equal))) start-of-word?) (write-c replacement-sep)) (for should-cap? = (or (eq capitalize :all) (eq capitalize T) (and start-of-word? (or (eq capitalize :each-word) (if (first-iteration-p) (eq capitalize :first-word) (eq capitalize :but-first-word)))))) (for char = (cond ((member c word-separators-to-replace :test #'string-equal) (or replacement-sep (next-iteration))) (should-cap? (char-upcase c)) (T (char-downcase c)))) (when in-place (setf (elt source-string i) char)) (when str (write-c char))))) (cond ((not stream) (get-output-stream-string str)) (in-place s)))) (defun english->lisp-name (phrase &key stream capitalize) "Turns an english phrase into a string containing a common lisp style symbol-name" (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators (list #\-) :word-separators-to-replace (list #\_ #\space #\newline #\tab))) (defun english->lisp-symbol (phrase &optional (package *package*)) "Turns an english phrase into a common lisp symbol in the specified package" (intern (english->lisp-name phrase :capitalize T) package)) (defun english->keyword (phrase) "Turns an english phrase into a common lisp keyword" (english->lisp-symbol phrase :keyword)) (defun english->camel-case (phrase &key stream (capitalize :but-first-word)) "Turns an english phrase into a camelCasePhraseLikeThis " (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators nil :word-separators-to-replace (list #\_ #\space))) (defun english->studly-case (phrase &key stream) "Turns an english phrase into a CamelCasePhraseLikeThis" (english->camel-case phrase :stream stream :capitalize :each-word)) (defun english->underscores (phrase &key stream capitalize) "Turns an english phrase into a a_phrase_like_this" (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\_ :word-separators-to-replace (list #\space))) (defun lisp->english (phrase &key stream (capitalize :each-word) (word-separator #\space)) "Converts a common lisp symbol (or symbol-name) into an english phrase" (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators word-separator :word-separators-to-replace (list #\-))) (defun lisp->keyword (phrase) (combine-symbols phrase :package :keyword)) (defun reintern (phrase &optional (package *package*)) (when phrase (combine-symbols phrase :package package))) (defun combine-symbols (phrase &key (package *package*) (separator #\-)) (when phrase (intern (normalize-capitalization-and-spacing phrase :capitalize T :word-separators separator :word-separators-to-replace nil) package))) (defun lisp->camel-case (phrase &key stream) (normalize-capitalization-and-spacing phrase :stream stream :capitalize :but-first-word :word-separators nil :word-separators-to-replace (list #\-))) (defun lisp->studly-caps (phrase &key stream) (normalize-capitalization-and-spacing phrase :stream stream :capitalize :each-word :word-separators nil :word-separators-to-replace (list #\-))) (defun lisp->underscores (phrase &key stream capitalize) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\_ :word-separators-to-replace (list #\-))) (defun camel-case->english (phrase &key stream (capitalize :each-word)) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\space :word-separators-to-replace (list :capitals #\_))) (defun camel-case->lisp-name (phrase &key stream (capitalize nil)) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\- :word-separators-to-replace (list :capitals #\_))) (defun camel-case->lisp-symbol (phrase &optional (package *package*)) (intern (camel-case->lisp-name phrase :capitalize T) package)) (defun camel-case->keyword (phrase) (camel-case->lisp-symbol phrase :keyword)) (defun camel-case->underscores (phrase &key stream capitalize) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\_ :word-separators-to-replace (list :capitals #\space))) (defun underscores->english (phrase &key stream (capitalize :each-word)) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\space :word-separators-to-replace (list #\_))) (defun underscores->lisp-name (phrase &key stream (capitalize nil)) (normalize-capitalization-and-spacing phrase :stream stream :capitalize capitalize :word-separators #\- :word-separators-to-replace (list #\_))) (defun underscores->lisp-symbol (phrase &optional (package *package*)) "Turns a_phrase_with_underscores into a-phrase-with-underscores lisp symbol" (intern (underscores->lisp-name phrase :capitalize T) package)) (defun underscores->keyword (phrase) "Converts and underscores name to a common lisp keyword" (underscores->lisp-symbol phrase :keyword)) (defun underscores->camel-case (phrase &key stream) (normalize-capitalization-and-spacing phrase :stream stream :capitalize :but-first-word :word-separators nil :word-separators-to-replace (list #\_))) (defun underscores->studly-caps (phrase &key stream) (normalize-capitalization-and-spacing phrase :stream stream :capitalize :each-word :word-separators nil :word-separators-to-replace (list #\_)))
7590fe96dc8ddd4493e409baac74b98a6789b9e6b16541771695c4493af9c445
Torvaney/flow-solver
sat.clj
(ns flow-solver.sat (:require [clojure.math.combinatorics :as combo] [rolling-stones.core :as sat] [ubergraph.core :as uber])) (defn get-graph-colours [g] (->> g :attrs vals (map :color) distinct)) (defn get-node-colour [g node] (-> g :attrs (get node) :color)) (defn edge->sat "Converts an edge to a SAT symbol" ([edge] {:<-> #{(uber/src edge) (uber/dest edge)}}) ([edge colour] {:<-> #{(uber/src edge) (uber/dest edge)} :colour colour})) (defn edge-colours "Enumerate all the possible colours that an edge could have" [colours edge] (->> (map #(edge->sat edge %) colours) (cons (edge->sat edge)))) (defn drop-nth [n xs] (concat (take n xs) (drop (inc n) xs))) (defn partition-each-element "Returns a list of all the distinct one-element partitions of xs. For example: (partition-each-element [:a :b :c :d :e]) => ([:a (:b :c :d :e)] [:b (:a :c :d :e)] [:c (:a :b :d :e)] [:d (:a :b :c :e)] [:e (:a :b :c :d)])" [xs] (map-indexed (fn [i x] [x (drop-nth i xs)]) xs)) (defn one-hot "One-hot encodes a variable as a SAT expression" [variants] (->> variants partition-each-element (map (fn [[x xs]] (apply sat/AND x (map sat/negate xs)))) (apply sat/OR))) (defn one-hot-edge-colour "One-hot encodes an edge's colour" [colours edge] (->> edge (edge-colours colours) one-hot)) (defn edges-such-that "Find all possible edge combinations that satisfy predicate function p" [p all-colours edges] (let [possible-edges (map #(edge-colours all-colours %) edges) edge-combinations (apply combo/cartesian-product possible-edges)] (->> edge-combinations (filter p) (mapv #(apply sat/AND %)) one-hot))) (defn exactly-one-colour "Each terminal (coloured) node must have exactly one coloured edge, of a pre-specified colour." [colour edges] (let [coloured-edges (keep :colour edges)] (and (= 1 (count coloured-edges)) (= colour (first coloured-edges))))) (defn exactly-two-colours "Each connector node must have exactly two coloured edges (of the same colour)" [edges] (let [edge-colours (keep :colour edges)] (and (= 2 (count edge-colours)) (apply = edge-colours)))) (defn node-has-valid-connections "Creates a SAT expression for the edges connected to a given node. Each terminal (coloured) node must have exactly one coloured edge. Each connector node must have exactly two coloured edges (of the same colour)" [colours g node] (let [edges (uber/find-edges g {:src node})] (if-let [colour (get-node-colour g node)] (edges-such-that #(exactly-one-colour colour %) colours edges) (edges-such-that exactly-two-colours colours edges)))) (defn graph->sat "Convert a graph to a SAT expression" [g] (let [colours (get-graph-colours g)] (apply sat/AND (concat (map #(one-hot-edge-colour colours %) (uber/edges g)) (map #(node-has-valid-connections colours g %) (uber/nodes g)))))) (defn sat->edge "Converts an edge to a SAT symbol" [{nodes :<-> colour :colour :as edge}] [(first nodes) (second nodes) {:color colour}]) (defn sat->graph "Convert a solved SAT into a graph" [solution] (->> solution (filter sat/positive?) (map sat->edge) (apply uber/graph)))
null
https://raw.githubusercontent.com/Torvaney/flow-solver/e215f93a293a493eb193fde52d27fa4ff88bf191/src/flow_solver/sat.clj
clojure
(ns flow-solver.sat (:require [clojure.math.combinatorics :as combo] [rolling-stones.core :as sat] [ubergraph.core :as uber])) (defn get-graph-colours [g] (->> g :attrs vals (map :color) distinct)) (defn get-node-colour [g node] (-> g :attrs (get node) :color)) (defn edge->sat "Converts an edge to a SAT symbol" ([edge] {:<-> #{(uber/src edge) (uber/dest edge)}}) ([edge colour] {:<-> #{(uber/src edge) (uber/dest edge)} :colour colour})) (defn edge-colours "Enumerate all the possible colours that an edge could have" [colours edge] (->> (map #(edge->sat edge %) colours) (cons (edge->sat edge)))) (defn drop-nth [n xs] (concat (take n xs) (drop (inc n) xs))) (defn partition-each-element "Returns a list of all the distinct one-element partitions of xs. For example: (partition-each-element [:a :b :c :d :e]) => ([:a (:b :c :d :e)] [:b (:a :c :d :e)] [:c (:a :b :d :e)] [:d (:a :b :c :e)] [:e (:a :b :c :d)])" [xs] (map-indexed (fn [i x] [x (drop-nth i xs)]) xs)) (defn one-hot "One-hot encodes a variable as a SAT expression" [variants] (->> variants partition-each-element (map (fn [[x xs]] (apply sat/AND x (map sat/negate xs)))) (apply sat/OR))) (defn one-hot-edge-colour "One-hot encodes an edge's colour" [colours edge] (->> edge (edge-colours colours) one-hot)) (defn edges-such-that "Find all possible edge combinations that satisfy predicate function p" [p all-colours edges] (let [possible-edges (map #(edge-colours all-colours %) edges) edge-combinations (apply combo/cartesian-product possible-edges)] (->> edge-combinations (filter p) (mapv #(apply sat/AND %)) one-hot))) (defn exactly-one-colour "Each terminal (coloured) node must have exactly one coloured edge, of a pre-specified colour." [colour edges] (let [coloured-edges (keep :colour edges)] (and (= 1 (count coloured-edges)) (= colour (first coloured-edges))))) (defn exactly-two-colours "Each connector node must have exactly two coloured edges (of the same colour)" [edges] (let [edge-colours (keep :colour edges)] (and (= 2 (count edge-colours)) (apply = edge-colours)))) (defn node-has-valid-connections "Creates a SAT expression for the edges connected to a given node. Each terminal (coloured) node must have exactly one coloured edge. Each connector node must have exactly two coloured edges (of the same colour)" [colours g node] (let [edges (uber/find-edges g {:src node})] (if-let [colour (get-node-colour g node)] (edges-such-that #(exactly-one-colour colour %) colours edges) (edges-such-that exactly-two-colours colours edges)))) (defn graph->sat "Convert a graph to a SAT expression" [g] (let [colours (get-graph-colours g)] (apply sat/AND (concat (map #(one-hot-edge-colour colours %) (uber/edges g)) (map #(node-has-valid-connections colours g %) (uber/nodes g)))))) (defn sat->edge "Converts an edge to a SAT symbol" [{nodes :<-> colour :colour :as edge}] [(first nodes) (second nodes) {:color colour}]) (defn sat->graph "Convert a solved SAT into a graph" [solution] (->> solution (filter sat/positive?) (map sat->edge) (apply uber/graph)))
85d9005b320610f15b59b48b00f85c48779f46b878626bfa26b5ae968bf8c974
dwayne/eopl3
env.rkt
#lang eopl (require "./parser.rkt") (provide ;; Build empty-env extend-env extend-env-rec ;; Query env? apply-env identifier? identifier=?) (define-datatype env env? [empty] [extend (var identifier?) (val any?) (saved-env env?)] [extend-rec (p-names (list-of identifier?)) (b-vars (list-of identifier?)) (p-bodies (list-of expression?)) (saved-env env?)]) (define (empty-env) (empty)) (define (extend-env var val env) (extend var val env)) (define (extend-env-rec proc-names vars proc-bodies env) (extend-rec proc-names vars proc-bodies env)) (define (apply-env env1 search-var construct-proc-val) (define (find-rec-proc p-names b-vars p-bodies) (if (null? p-names) #f (if (identifier=? search-var (car p-names)) (list (car b-vars) (car p-bodies)) (find-rec-proc (cdr p-names) (cdr b-vars) (cdr p-bodies))))) (cases env env1 [empty () (eopl:error 'apply-env "No binding for ~s" search-var)] [extend (saved-var saved-val saved-env) (if (identifier=? search-var saved-var) saved-val (apply-env saved-env search-var construct-proc-val))] [extend-rec (p-names b-vars p-bodies saved-env) (let ([result (find-rec-proc p-names b-vars p-bodies)]) (if result (let ([b-var (car result)] [p-body (cadr result)]) (construct-proc-val b-var p-body env1)) (apply-env saved-env search-var construct-proc-val)))])) (define identifier? symbol?) (define identifier=? eq?) (define (any? v) #t)
null
https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/04-ch4/interpreters/racket/EXPLICIT-REFS-4.12/env.rkt
racket
Build Query
#lang eopl (require "./parser.rkt") (provide empty-env extend-env extend-env-rec env? apply-env identifier? identifier=?) (define-datatype env env? [empty] [extend (var identifier?) (val any?) (saved-env env?)] [extend-rec (p-names (list-of identifier?)) (b-vars (list-of identifier?)) (p-bodies (list-of expression?)) (saved-env env?)]) (define (empty-env) (empty)) (define (extend-env var val env) (extend var val env)) (define (extend-env-rec proc-names vars proc-bodies env) (extend-rec proc-names vars proc-bodies env)) (define (apply-env env1 search-var construct-proc-val) (define (find-rec-proc p-names b-vars p-bodies) (if (null? p-names) #f (if (identifier=? search-var (car p-names)) (list (car b-vars) (car p-bodies)) (find-rec-proc (cdr p-names) (cdr b-vars) (cdr p-bodies))))) (cases env env1 [empty () (eopl:error 'apply-env "No binding for ~s" search-var)] [extend (saved-var saved-val saved-env) (if (identifier=? search-var saved-var) saved-val (apply-env saved-env search-var construct-proc-val))] [extend-rec (p-names b-vars p-bodies saved-env) (let ([result (find-rec-proc p-names b-vars p-bodies)]) (if result (let ([b-var (car result)] [p-body (cadr result)]) (construct-proc-val b-var p-body env1)) (apply-env saved-env search-var construct-proc-val)))])) (define identifier? symbol?) (define identifier=? eq?) (define (any? v) #t)
74070b22fbc9c03145b534a692ed8d70a85d1f65216c24bfceb5fb9be2dd0571
algoriffic/lsa4solr
hierarchical_clustering.clj
(ns lsa4solr.hierarchical-clustering (:use [lsa4solr mahout-matrix dendrogram]) (:require [clojure [zip :as z]]) (:require [clojure.contrib [combinatorics :as combine] [zip-filter :as zf] [seq-utils :as seq-utils]]) (:import (org.apache.mahout.math SparseMatrix RandomAccessSparseVector VectorWritable Matrix DenseMatrix) (org.apache.mahout.math.hadoop DistributedRowMatrix))) (defn get-count [cluster] (:count (meta cluster))) (defn get-centroid [cluster] (:centroid (meta cluster))) (defn merge-centroids [c1 c2] (add (mult (get-centroid c1) (double (/ 1 (get-count c1)))) (mult (get-centroid c2) (double (/ 1 (get-count c2)))))) (defn get-vecs [mat idxs] (map #(.getRow mat %) idxs)) (defn average-dispersion [mat group centroid dist] (/ (reduce + (map #(dist centroid %) (get-vecs mat group))) (count group))) (defn average-intercluster-dispersion [mat clusters dist] (let [centroids (map #(apply centroid (get-vecs mat %)) clusters) combos (combine/combinations centroids 2)] (/ (reduce + (map #(apply dist %) combos)) (count combos)))) (defn hclust "Hierarchical clustering of the rows of mat. Returns a dendrogram and a merge sequence. The dendrogram is a tree with doc ids as leaf nodes and meta data in the branch nodes indicating the number of children and the centroid of the branch." [mat] (let [dend (dendrogram (map #(with-meta {:id %} (hash-map :centroid (.getRow mat %) :count 1)) (range 0 (.numRows mat)))) get-distance (memoize euclidean-distance)] (take (- (.numRows mat) 1) (iterate (fn [[dend merge-sequence]] (let [clusters (z/children dend) dists (map #(list % (get-distance (get-centroid (nth clusters (first %))) (get-centroid (nth clusters (second %))))) (combine/combinations (range 0 (count clusters)) 2)) closest-pair (first (reduce #(if (< (second %1) (second %2)) %1 %2) (first dists) (rest dists)))] (list (merge-nodes dend closest-pair (fn [n1 n2] (with-meta (list (with-meta n1 (meta n1)) (with-meta n2 (meta n2))) (hash-map :count (apply + (map get-count [n1 n2])) :centroid (merge-centroids n1 n2))))) (conj merge-sequence closest-pair)))) (list dend '())))))
null
https://raw.githubusercontent.com/algoriffic/lsa4solr/93231caff612d0a0bf3c418523385af674adae4e/src/lsa4solr/hierarchical_clustering.clj
clojure
(ns lsa4solr.hierarchical-clustering (:use [lsa4solr mahout-matrix dendrogram]) (:require [clojure [zip :as z]]) (:require [clojure.contrib [combinatorics :as combine] [zip-filter :as zf] [seq-utils :as seq-utils]]) (:import (org.apache.mahout.math SparseMatrix RandomAccessSparseVector VectorWritable Matrix DenseMatrix) (org.apache.mahout.math.hadoop DistributedRowMatrix))) (defn get-count [cluster] (:count (meta cluster))) (defn get-centroid [cluster] (:centroid (meta cluster))) (defn merge-centroids [c1 c2] (add (mult (get-centroid c1) (double (/ 1 (get-count c1)))) (mult (get-centroid c2) (double (/ 1 (get-count c2)))))) (defn get-vecs [mat idxs] (map #(.getRow mat %) idxs)) (defn average-dispersion [mat group centroid dist] (/ (reduce + (map #(dist centroid %) (get-vecs mat group))) (count group))) (defn average-intercluster-dispersion [mat clusters dist] (let [centroids (map #(apply centroid (get-vecs mat %)) clusters) combos (combine/combinations centroids 2)] (/ (reduce + (map #(apply dist %) combos)) (count combos)))) (defn hclust "Hierarchical clustering of the rows of mat. Returns a dendrogram and a merge sequence. The dendrogram is a tree with doc ids as leaf nodes and meta data in the branch nodes indicating the number of children and the centroid of the branch." [mat] (let [dend (dendrogram (map #(with-meta {:id %} (hash-map :centroid (.getRow mat %) :count 1)) (range 0 (.numRows mat)))) get-distance (memoize euclidean-distance)] (take (- (.numRows mat) 1) (iterate (fn [[dend merge-sequence]] (let [clusters (z/children dend) dists (map #(list % (get-distance (get-centroid (nth clusters (first %))) (get-centroid (nth clusters (second %))))) (combine/combinations (range 0 (count clusters)) 2)) closest-pair (first (reduce #(if (< (second %1) (second %2)) %1 %2) (first dists) (rest dists)))] (list (merge-nodes dend closest-pair (fn [n1 n2] (with-meta (list (with-meta n1 (meta n1)) (with-meta n2 (meta n2))) (hash-map :count (apply + (map get-count [n1 n2])) :centroid (merge-centroids n1 n2))))) (conj merge-sequence closest-pair)))) (list dend '())))))
9b57bfd8bfe3e8015ad92095870db0d3c74bc86abcd4bb47bb12576d5fedf4a1
stuhlmueller/jschurch
index.html.scm
(html-doctype) (html (head (title "BiwaScheme : Scheme interpreter for browsers") (meta :http-equiv "Content-Type" :content "text/html; charset=utf-8" ) (link :href "css/screen.css" :rel "stylesheet" :type "text/css") (link :href "css/jquery.terminal.css" :rel "stylesheet" :type "text/css") (script :src "js/jquery-1.4.4.min.js" :type "text/javascript") (script :type "text/javascript" "jQuery.noConflict();") (script :src "js/jquery.mousewheel.min.js" :type "text/javascript") (script :src "js/jquery.timers.min.js" :type "text/javascript") (script :src "js/jquery.cookie.min.js" :type "text/javascript") (script :src "js/jquery.terminal-0.2.3.min.js" :type "text/javascript") (script :src "repos/lib/biwascheme.js" :type "text/javascript") (script :src "js/biwascheme_terminal.js" :type "text/javascript")) (body (convert-file "_header.html.scm") (div :id "content" (h2 "About") (p "BiwaScheme is a Scheme interpreter written in JavaScript.") (h2 "Try it now") (div :id "term") (h2 "Download") (ul (li (link-to "biwascheme.js" "repos/lib/biwascheme.js") " (version " (span :id "ver" "--") ")")) (script :type "text/javascript" "jQuery('#ver').html(BiwaScheme.Version)") (p (link-to "Older versions" "") " and the " (link-to "latest version" "") " are on github.") (h2 "Example") (pre "<font color='purple'>&lt;script src=\"biwascheme.js\"&gt;</font> <font color='purple'>(</font><font color=blue>display</font> <font color=red>\"hello, world!\"</font><font color='purple'>)</font> <font color='purple'>&lt;/script&gt;</font>") (h2 "Demo") (ul (link-list '(("repos/repl.html" . "REPL") ("repos/demo/pictlang.html" . "SICP's picture language") ("/" . "Hockey (pong-like game)") ("/" . "Dobon (a card game)")))) (h2 "Features") (ul (li "Most syntax/base library of R6RS (see " (a :href "status.html" "Status") ")") (li "Support for" (a :title "Wikipedia article about Lisp Macros" :href "#Lisp_macros" "Lisp Macros") " and Quasiquotation") (li "Functions for web application (Ajax, DOM manipulation, etc.)") (li "Calling JavaScript functions from Scheme and Scheme from JavaScript") (li "Extending scheme interpreter in Javascipt") (li "Comprehensive " (link-to "unit test" "repos/test/spec.html")) (li "Tiny " (link-to "interpreter debugger" "repos/test/tracer.html"))) (h2 "Links") (ul (li (a :href "/" "R6RS") " (" (a :href "-Z-H-2.html#node_toc_start" "Language") " / " (a :href "-lib/r6rs-lib-Z-H-1.html#node_toc_start" "Library") ")" )) (h2 "Licence") (ul (li "BiwaScheme: " (link-to "MIT License" "-LICENSE.txt")) (li "BiwaScheme Logo" " (by " (link-to "Jakub Jankiewicz" "/") "): " (link-to "Creative Commons Attribution 3.0" "/") )) (h2 "Contact") (p "see " (link-to "Development" "development.html") " for ITS and mailing lists.") (p "Yutaka HARA (yutaka.hara.gmail.com)" (br) (link-to "/#!/yhara_en")) (convert-file "_footer.html.scm") )))
null
https://raw.githubusercontent.com/stuhlmueller/jschurch/58a94802ba987c92cb81e556341f86dba66a8fd1/external/biwascheme/website/index.html.scm
scheme
</font> /script&gt;</font>")
(html-doctype) (html (head (title "BiwaScheme : Scheme interpreter for browsers") (meta :http-equiv "Content-Type" :content "text/html; charset=utf-8" ) (link :href "css/screen.css" :rel "stylesheet" :type "text/css") (link :href "css/jquery.terminal.css" :rel "stylesheet" :type "text/css") (script :src "js/jquery-1.4.4.min.js" :type "text/javascript") (script :type "text/javascript" "jQuery.noConflict();") (script :src "js/jquery.mousewheel.min.js" :type "text/javascript") (script :src "js/jquery.timers.min.js" :type "text/javascript") (script :src "js/jquery.cookie.min.js" :type "text/javascript") (script :src "js/jquery.terminal-0.2.3.min.js" :type "text/javascript") (script :src "repos/lib/biwascheme.js" :type "text/javascript") (script :src "js/biwascheme_terminal.js" :type "text/javascript")) (body (convert-file "_header.html.scm") (div :id "content" (h2 "About") (p "BiwaScheme is a Scheme interpreter written in JavaScript.") (h2 "Try it now") (div :id "term") (h2 "Download") (ul (li (link-to "biwascheme.js" "repos/lib/biwascheme.js") " (version " (span :id "ver" "--") ")")) (script :type "text/javascript" "jQuery('#ver').html(BiwaScheme.Version)") (p (link-to "Older versions" "") " and the " (link-to "latest version" "") " are on github.") (h2 "Example") <font color='purple'>(</font><font color=blue>display</font> <font color=red>\"hello, world!\"</font><font color='purple'>)</font> (h2 "Demo") (ul (link-list '(("repos/repl.html" . "REPL") ("repos/demo/pictlang.html" . "SICP's picture language") ("/" . "Hockey (pong-like game)") ("/" . "Dobon (a card game)")))) (h2 "Features") (ul (li "Most syntax/base library of R6RS (see " (a :href "status.html" "Status") ")") (li "Support for" (a :title "Wikipedia article about Lisp Macros" :href "#Lisp_macros" "Lisp Macros") " and Quasiquotation") (li "Functions for web application (Ajax, DOM manipulation, etc.)") (li "Calling JavaScript functions from Scheme and Scheme from JavaScript") (li "Extending scheme interpreter in Javascipt") (li "Comprehensive " (link-to "unit test" "repos/test/spec.html")) (li "Tiny " (link-to "interpreter debugger" "repos/test/tracer.html"))) (h2 "Links") (ul (li (a :href "/" "R6RS") " (" (a :href "-Z-H-2.html#node_toc_start" "Language") " / " (a :href "-lib/r6rs-lib-Z-H-1.html#node_toc_start" "Library") ")" )) (h2 "Licence") (ul (li "BiwaScheme: " (link-to "MIT License" "-LICENSE.txt")) (li "BiwaScheme Logo" " (by " (link-to "Jakub Jankiewicz" "/") "): " (link-to "Creative Commons Attribution 3.0" "/") )) (h2 "Contact") (p "see " (link-to "Development" "development.html") " for ITS and mailing lists.") (p "Yutaka HARA (yutaka.hara.gmail.com)" (br) (link-to "/#!/yhara_en")) (convert-file "_footer.html.scm") )))
0f48a4b1a67dbaf32a26c1db28839f1121d36dd0b0e692aa75f8d3ed27625df9
catseye/Emmental
HasteMain.hs
{-# LANGUAGE OverloadedStrings #-} module Main where import Haste.DOM (withElems, getValue, setProp) import Haste.Events (onEvent, MouseEvent(Click)) import Haste.Foreign (ffi) import Language.Emmental (emmentalWithIO) getCh :: IO Char getCh = ffi "(function() {var i=document.getElementById('prog-input'); var s=i.value; i.value=s.substring(1); return s.charCodeAt(0);})" putCh :: Char -> IO () putCh = ffi "(function(c) {var o=document.getElementById('prog-output'); o.textContent += String.fromCharCode(c);})" clearOutput :: IO () clearOutput = ffi "(function(c) {var o=document.getElementById('prog-output'); o.textContent = '';})" main = withElems ["prog", "result", "run-button"] driver driver [progElem, resultElem, runButtonElem] = onEvent runButtonElem Click $ \_ -> do Just prog <- getValue progElem clearOutput r <- emmentalWithIO (getCh) (putCh) prog setProp resultElem "textContent" $ show $ r
null
https://raw.githubusercontent.com/catseye/Emmental/98f5c00f3d04adf557644f9fc5ebaf600a1f8458/src/HasteMain.hs
haskell
# LANGUAGE OverloadedStrings #
module Main where import Haste.DOM (withElems, getValue, setProp) import Haste.Events (onEvent, MouseEvent(Click)) import Haste.Foreign (ffi) import Language.Emmental (emmentalWithIO) getCh :: IO Char getCh = ffi "(function() {var i=document.getElementById('prog-input'); var s=i.value; i.value=s.substring(1); return s.charCodeAt(0);})" putCh :: Char -> IO () putCh = ffi "(function(c) {var o=document.getElementById('prog-output'); o.textContent += String.fromCharCode(c);})" clearOutput :: IO () clearOutput = ffi "(function(c) {var o=document.getElementById('prog-output'); o.textContent = '';})" main = withElems ["prog", "result", "run-button"] driver driver [progElem, resultElem, runButtonElem] = onEvent runButtonElem Click $ \_ -> do Just prog <- getValue progElem clearOutput r <- emmentalWithIO (getCh) (putCh) prog setProp resultElem "textContent" $ show $ r
0d5959f35977fe3fcd814aca3d25ae0865faf44b4dc32a664fcd28e18cf12cd4
acl2/acl2
boot-strap-pass-2-a.lisp
ACL2 Version 8.5 -- A Computational Logic for Applicative Common Lisp Copyright ( C ) 2023 , Regents of the University of Texas This version of ACL2 is a descendent of ACL2 Version 1.9 , Copyright ( C ) 1997 Computational Logic , Inc. See the documentation topic NOTE-2 - 0 . ; This program is free software; you can redistribute it and/or modify ; it under the terms of the LICENSE file distributed with ACL2. ; 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 ; LICENSE for more details. Written by : and J Strother Moore email : and Department of Computer Science University of Texas at Austin Austin , TX 78712 U.S.A. (in-package "ACL2") This file is the first of a pair of files , boot-strap-pass-2-a.lisp and ; boot-strap-pass-2-b.lisp. They are compiled and loaded; but they are only processed during the second pass of the boot - strap process , not the first . We introduce proper defattach events , i.e. , without : skip - checks t. Here are ; some guiding principles for making system functions available for attachment ; by users. ; - The initial attachment is named by adding the suffix -builtin. For ; example, worse-than is a constrained function initially attached to ; worse-than-builtin. ; - Use the weakest logical specs we can (even if T), without getting ; distracted by names. For example, we do not specify a relationship between ; worse-than-or-equal and worse-than. ; - Only make functions attachable if they are used in our sources somewhere ; outside their definitions. So for example, we do not introduce ; worse-than-list as a constrained function, since its only use is in the ; mutual-recursion event that defines worse-than. ; We conclude by defining some theories, near the end so that they pick up much ; of the rest of this file. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Miscellaneous verify-termination and guard verification ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; cons - term and symbol - class -- at one point during development , used in ; fncall-term, but anyhow, generally useful to have in logic mode (verify-termination-boot-strap quote-listp) ; and guards (verify-termination-boot-strap cons-term1) ; and guards (verify-termination-boot-strap cons-term) ; and guards (verify-termination-boot-strap symbol-class) ; and guards packn1 , packn , and pack - to - string (verify-termination-boot-strap packn1) ; and guards (encapsulate () (local (defthm character-listp-explode-nonnegative-integer (implies (character-listp z) (character-listp (explode-nonnegative-integer x y z))) :rule-classes ((:forward-chaining :trigger-terms ((explode-nonnegative-integer x y z)))))) (local (defthm character-listp-explode-atom (character-listp (explode-atom x y)) :rule-classes ((:forward-chaining :trigger-terms ((explode-atom x y)))))) (verify-termination-boot-strap packn-pos) ; and guards (verify-termination-boot-strap find-first-non-cl-symbol) ; and guards (verify-termination-boot-strap packn) ; and guards (verify-termination-boot-strap pack-to-string) ; and guards ) (verify-termination-boot-strap read-file-into-string1) ; and guards ; miscellaneous (verify-termination-boot-strap guard-theorem-simplify-msg) ; and guards (verify-termination-boot-strap guard-or-termination-theorem-msg) ; and guards (verify-termination-boot-strap alist-keys-subsetp) ; and guards (verify-termination-boot-strap keyword-listp) ; and guards (verify-termination-boot-strap pairlis-x1) ; and guards (verify-termination-boot-strap pairlis-x2) ; and guards (verify-termination-boot-strap first-keyword) ; and guards (verify-termination-boot-strap symbol-name-lst) ; and guards ; for case-match expansions: (verify-termination-boot-strap symbol-name-equal) ; and guards (verify-termination-boot-strap fix-pkg) ; and guards (verify-termination-boot-strap unmake-true-list-cons-nest) ; and guards (verify-termination-boot-strap dumb-negate-lit) ; and guards (verify-termination-boot-strap flatten-ands-in-lit) ; and guards (verify-termination-boot-strap union-equal-to-end) ; and guards (verify-termination-boot-strap flatten-ands-in-lit!) ; and guards (verify-termination-boot-strap remove-lisp-suffix) ; and guards (verify-guards warranted-fns-of-world) ; Convert defproxy events to :logic mode. (defstub initialize-event-user (* * state) => state) (defstub finalize-event-user (* * state) => state) (defstub acl2x-expansion-alist (* state) => *) (defstub set-ld-history-entry-user-data (* * * state) => *) #+acl2-loop-only (partial-encapsulate (((canonical-pathname * * state) => *)) ; Supporters = nil since each missing axiom equates a call of ; canonical-pathname on explicit arguments with its result. nil (local (defun canonical-pathname (x dir-p state) (declare (xargs :mode :logic)) (declare (ignore dir-p state)) (if (stringp x) x nil))) (defthm canonical-pathname-is-idempotent (equal (canonical-pathname (canonical-pathname x dir-p state) dir-p state) (canonical-pathname x dir-p state))) (defthm canonical-pathname-type (or (equal (canonical-pathname x dir-p state) nil) (stringp (canonical-pathname x dir-p state))) :rule-classes :type-prescription)) #+acl2-loop-only (partial-encapsulate (((magic-ev-fncall * * state * *) => (mv * *))) ; Supporters = nil since each missing axiom equates a call of ; magic-ev-fncall on explicit arguments with its result. nil (logic) (local (defun magic-ev-fncall (fn args state hard-error-returns-nilp aok) (declare (xargs :mode :logic) (ignore fn args state hard-error-returns-nilp aok)) (mv nil nil)))) #+acl2-loop-only (partial-encapsulate (((mfc-ap-fn * * state *) => *) ((mfc-relieve-hyp-fn * * * * * * state *) => *) ((mfc-relieve-hyp-ttree * * * * * * state *) => (mv * *)) ((mfc-rw+-fn * * * * * state *) => *) ((mfc-rw+-ttree * * * * * state *) => (mv * *)) ((mfc-rw-fn * * * * state *) => *) ((mfc-rw-ttree * * * * state *) => (mv * *)) ((mfc-ts-fn * * state *) => *) ((mfc-ts-ttree * * state *) => (mv * *))) Supporters = nil since each missing axiom equates a call of one of the ; signature functions (above) on explicit arguments with its result. nil (logic) (set-ignore-ok t) (set-irrelevant-formals-ok t) (local (defun mfc-ts-fn (term mfc state forcep) t)) (local (defun mfc-ts-ttree (term mfc state forcep) (mv t t))) (local (defun mfc-rw-fn (term obj equiv-info mfc state forcep) t)) (local (defun mfc-rw-ttree (term obj equiv-info mfc state forcep) (mv t t))) (local (defun mfc-rw+-fn (term alist obj equiv-info mfc state forcep) t)) (local (defun mfc-rw+-ttree (term alist obj equiv-info mfc state forcep) (mv t t))) (local (defun mfc-relieve-hyp-fn (hyp alist rune target bkptr mfc state forcep) t)) (local (defun mfc-relieve-hyp-ttree (hyp alist rune target bkptr mfc state forcep) (mv t t))) (local (defun mfc-ap-fn (term mfc state forcep) t))) (verify-termination-boot-strap print-object$-fn) ; and guards (verify-termination-boot-strap print-object$) ; and guards (verify-termination-boot-strap print-object$-preserving-case) ; and guards (verify-termination-boot-strap set-fmt-hard-right-margin) ; and guards (verify-termination-boot-strap set-fmt-soft-right-margin) ; and guards (verify-termination-boot-strap bounded-integer-listp) ; and guards (verify-termination-boot-strap project-dir-alist) ; and guards (verify-termination-boot-strap project-dir-lookup) ; and guards (verify-termination-boot-strap project-dir) ; and guards (verify-termination-boot-strap system-books-dir) ; and guards (verify-termination-boot-strap sysfile-p) ; and guards (verify-termination-boot-strap sysfile-key) ; and guards (verify-termination-boot-strap sysfile-filename) ; and guards (verify-termination-boot-strap book-name-p) ; and guards (verify-termination-boot-strap book-name-listp) ; and guards (verify-termination-boot-strap book-name-to-filename-1) ; and guards (verify-termination-boot-strap book-name-to-filename) ; and guards (verify-termination-boot-strap book-name-lst-to-filename-lst) ; and guards ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Attachment: too-many-ifs-post-rewrite and too-many-ifs-pre-rewrite ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #+acl2-loop-only The above readtime conditional avoids a CLISP warning , and lets the defproxy ; for print-clause-id-okp provide the raw Lisp definition. (encapsulate ((too-many-ifs-post-rewrite (args val) t :guard (and (pseudo-term-listp args) (pseudo-termp val)))) (local (defun too-many-ifs-post-rewrite (args val) (list args val)))) ; The following events are derived from the original version of community book ; books/system/too-many-ifs.lisp. But here we provide a proof that does not ; depend on books. Our approach was to take the proof in the above book, ; eliminate the unnecessary use of an arithmetic book, expand away all uses of ; macros and make-events, avoid use of (theory 'minimal-theory) since that ; theory didn't yet exist (where these events were originally placed), and ; apply some additional hand-editing in order (for example) to remove hints ; depending on the tools/flag community book. We have left original events ; from the book as comments. (encapsulate () (logic) ;;; (include-book "tools/flag" :dir :system) ; In the original book, but not needed for its certification: ; (include-book "arithmetic/top-with-meta" :dir :system) ; Comments like the following show events from the original book. ;;; (make-flag pseudo-termp-flg ;;; pseudo-termp : flag - var flg ;;; :flag-mapping ((pseudo-termp term) ;;; (pseudo-term-listp list)) ;;; :defthm-macro-name defthm-pseudo-termp ;;; :local t) (local (defun-nx pseudo-termp-flg (flg x lst) (declare (xargs :verify-guards nil :normalize nil :measure (case flg (term (acl2-count x)) (otherwise (acl2-count lst))))) (case flg (term (if (consp x) (cond ((equal (car x) 'quote) (and (consp (cdr x)) (equal (cddr x) nil))) ((true-listp x) (and (pseudo-termp-flg 'list nil (cdr x)) (cond ((symbolp (car x)) t) ((true-listp (car x)) (and (equal (length (car x)) 3) (equal (caar x) 'lambda) (symbol-listp (cadar x)) (pseudo-termp-flg 'term (caddar x) nil) (equal (length (cadar x)) (length (cdr x))))) (t nil)))) (t nil)) (symbolp x))) (otherwise (if (consp lst) (and (pseudo-termp-flg 'term (car lst) nil) (pseudo-termp-flg 'list nil (cdr lst))) (equal lst nil)))))) (local (defthm pseudo-termp-flg-equivalences (equal (pseudo-termp-flg flg x lst) (case flg (term (pseudo-termp x)) (otherwise (pseudo-term-listp lst)))) :hints (("goal" :induct (pseudo-termp-flg flg x lst))))) (local (in-theory (disable (:definition pseudo-termp-flg)))) ; Added here (not present or needed in the certified book): (verify-termination-boot-strap max) ; and guards (verify-termination-boot-strap var-counts1) ;;; (make-flag var-counts1-flg ;;; var-counts1 : flag - var flg ;;; :flag-mapping ((var-counts1 term) ;;; (var-counts1-lst list)) ;;; :defthm-macro-name defthm-var-counts1 ;;; :local t) (local (defun-nx var-counts1-flg (flg rhs arg lst acc) (declare (xargs :verify-guards nil :normalize nil :measure (case flg (term (acl2-count rhs)) (otherwise (acl2-count lst))) :hints nil :well-founded-relation o< :mode :logic) (ignorable rhs arg lst acc)) (case flg (term (cond ((equal arg rhs) (+ 1 acc)) ((consp rhs) (cond ((equal 'quote (car rhs)) acc) ((equal (car rhs) 'if) (max (var-counts1-flg 'term (caddr rhs) arg nil acc) (var-counts1-flg 'term (cadddr rhs) arg nil acc))) (t (var-counts1-flg 'list nil arg (cdr rhs) acc)))) (t acc))) (otherwise (if (consp lst) (var-counts1-flg 'list nil arg (cdr lst) (var-counts1-flg 'term (car lst) arg nil acc)) acc))))) (local (defthm var-counts1-flg-equivalences (equal (var-counts1-flg flg rhs arg lst acc) (case flg (term (var-counts1 arg rhs acc)) (otherwise (var-counts1-lst arg lst acc)))))) (local (in-theory (disable (:definition var-counts1-flg)))) ;;; (defthm-var-counts1 natp-var-counts1 ;;; (term ( implies ( natp acc ) ( natp ( var - counts1 arg rhs acc ) ) ) ;;; :rule-classes :type-prescription) ;;; (list ( implies ( natp acc ) ( natp ( var - counts1 - lst arg lst acc ) ) ) ;;; :rule-classes :type-prescription) : hints ( ( " Goal " : induct ( var - counts1 - flg flg rhs arg lst acc ) ) ) ) (local (defthm natp-var-counts1 (case flg (term (implies (natp acc) (natp (var-counts1 arg rhs acc)))) (otherwise (implies (natp acc) (natp (var-counts1-lst arg lst acc))))) :hints (("Goal" :induct (var-counts1-flg flg rhs arg lst acc))) :rule-classes nil)) (local (defthm natp-var-counts1-term (implies (natp acc) (natp (var-counts1 arg rhs acc))) :hints (("Goal" ; :in-theory (theory 'minimal-theory) :use ((:instance natp-var-counts1 (flg 'term))))) :rule-classes :type-prescription)) (local (defthm natp-var-counts1-list (implies (natp acc) (natp (var-counts1-lst arg lst acc))) :hints (("Goal" ; :in-theory (theory 'minimal-theory) :use ((:instance natp-var-counts1 (flg 'list))))) :rule-classes :type-prescription)) (verify-guards var-counts1) (verify-termination-boot-strap var-counts) ; and guards ;;; Since the comment about var-counts says that var-counts returns a list of nats as long as lhs - args , I prove those facts , speculatively . ; Except, we reason instead about integer-listp. See the comment just above the commented - out definition of nat - listp in the source code ( file ; rewrite.lisp). ( verify - termination nat - listp ) (local (defthm integer-listp-var-counts (integer-listp (var-counts lhs-args rhs)))) (local (defthm len-var-counts (equal (len (var-counts lhs-args rhs)) (len lhs-args)))) (verify-termination-boot-strap count-ifs) ; and guards ; Added here (not present or needed in the certified book): (verify-termination-boot-strap ifix) ; and guards ; Added here (not present or needed in the certified book): (verify-termination-boot-strap abs) ; and guards ; Added here (not present or needed in the certified book): (verify-termination-boot-strap expt) ; and guards ; Added here (not present or needed in the certified book): (local (defthm natp-expt (implies (and (integerp base) (integerp n) (<= 0 n)) (integerp (expt base n))) :rule-classes :type-prescription)) ; Added here (not present or needed in the certified book): (verify-termination-boot-strap signed-byte-p) ; and guards (verify-termination-boot-strap too-many-ifs0) ; and guards (verify-termination-boot-strap too-many-ifs-pre-rewrite-builtin) ; and guards (verify-termination-boot-strap occur-cnt-bounded) ;;; (make-flag occur-cnt-bounded-flg ;;; occur-cnt-bounded : flag - var flg ;;; :flag-mapping ((occur-cnt-bounded term) ;;; (occur-cnt-bounded-lst list)) ;;; :defthm-macro-name defthm-occur-cnt-bounded ;;; :local t) (local (defun-nx occur-cnt-bounded-flg (flg term2 term1 lst a m bound-m) (declare (xargs :verify-guards nil :normalize nil :measure (case flg (term (acl2-count term2)) (otherwise (acl2-count lst)))) (ignorable term2 term1 lst a m bound-m)) (case flg (term (cond ((equal term1 term2) (if (< bound-m a) -1 (+ a m))) ((consp term2) (if (equal 'quote (car term2)) a (occur-cnt-bounded-flg 'list nil term1 (cdr term2) a m bound-m))) (t a))) (otherwise (if (consp lst) (let ((new (occur-cnt-bounded-flg 'term (car lst) term1 nil a m bound-m))) (if (equal new -1) -1 (occur-cnt-bounded-flg 'list nil term1 (cdr lst) new m bound-m))) a))))) (local (defthm occur-cnt-bounded-flg-equivalences (equal (occur-cnt-bounded-flg flg term2 term1 lst a m bound-m) (case flg (term (occur-cnt-bounded term1 term2 a m bound-m)) (otherwise (occur-cnt-bounded-lst term1 lst a m bound-m)))))) (local (in-theory (disable (:definition occur-cnt-bounded-flg)))) ( defthm - occur - cnt - bounded integerp - occur - cnt - bounded ;;; (term ;;; (implies (and (integerp a) ;;; (integerp m)) ( integerp ( occur - cnt - bounded a m bound - m ) ) ) ;;; :rule-classes :type-prescription) ;;; (list ;;; (implies (and (integerp a) ;;; (integerp m)) ( integerp ( occur - cnt - bounded - lst term1 lst a m bound - m ) ) ) ;;; :rule-classes :type-prescription) : hints ( ( " Goal " : induct ( occur - cnt - bounded - flg flg lst a m ;;; bound-m)))) (local (defthm integerp-occur-cnt-bounded (case flg (term (implies (and (integerp a) (integerp m)) (integerp (occur-cnt-bounded term1 term2 a m bound-m)))) (otherwise (implies (and (integerp a) (integerp m)) (integerp (occur-cnt-bounded-lst term1 lst a m bound-m))))) :rule-classes nil :hints (("Goal" :induct (occur-cnt-bounded-flg flg term2 term1 lst a m bound-m))))) (local (defthm integerp-occur-cnt-bounded-term (implies (and (integerp a) (integerp m)) (integerp (occur-cnt-bounded term1 term2 a m bound-m))) :rule-classes :type-prescription :hints (("goal" ; :in-theory (theory 'minimal-theory) :use ((:instance integerp-occur-cnt-bounded (flg 'term))))))) (local (defthm integerp-occur-cnt-bounded-list (implies (and (integerp a) (integerp m)) (integerp (occur-cnt-bounded-lst term1 lst a m bound-m))) :rule-classes :type-prescription :hints (("goal" ; :in-theory (theory 'minimal-theory) :use ((:instance integerp-occur-cnt-bounded (flg 'list))))))) ;;; (defthm-occur-cnt-bounded signed-byte-p-30-occur-cnt-bounded-flg ;;; (term ;;; (implies (and (force (signed-byte-p 30 a)) ;;; (signed-byte-p 30 m) ;;; (signed-byte-p 30 (+ bound-m m)) ;;; (force (<= 0 a)) ;;; (<= 0 m) ;;; (<= 0 bound-m) ;;; (<= a (+ bound-m m))) ( and ( < = -1 ( occur - cnt - bounded a m bound - m ) ) ( < = ( occur - cnt - bounded a m bound - m ) ( + bound - m m ) ) ) ) ;;; :rule-classes :linear) ;;; (list ;;; (implies (and (force (signed-byte-p 30 a)) ;;; (signed-byte-p 30 m) ;;; (signed-byte-p 30 (+ bound-m m)) ;;; (force (<= 0 a)) ;;; (<= 0 m) ;;; (<= 0 bound-m) ;;; (<= a (+ bound-m m))) ;;; (and (<= -1 (occur-cnt-bounded-lst term1 lst a m bound-m)) ;;; (<= (occur-cnt-bounded-lst term1 lst a m bound-m) (+ bound-m m)))) ;;; :rule-classes :linear) : hints ( ( " Goal " : induct ( occur - cnt - bounded - flg flg lst a m ;;; bound-m)))) (local (defthm signed-byte-p-30-occur-cnt-bounded-flg (case flg (term (implies (and (force (signed-byte-p 30 a)) (signed-byte-p 30 m) (signed-byte-p 30 (+ bound-m m)) (force (<= 0 a)) (<= 0 m) (<= 0 bound-m) (<= a (+ bound-m m))) (and (<= -1 (occur-cnt-bounded term1 term2 a m bound-m)) (<= (occur-cnt-bounded term1 term2 a m bound-m) (+ bound-m m))))) (otherwise (implies (and (force (signed-byte-p 30 a)) (signed-byte-p 30 m) (signed-byte-p 30 (+ bound-m m)) (force (<= 0 a)) (<= 0 m) (<= 0 bound-m) (<= a (+ bound-m m))) (and (<= -1 (occur-cnt-bounded-lst term1 lst a m bound-m)) (<= (occur-cnt-bounded-lst term1 lst a m bound-m) (+ bound-m m)))))) :rule-classes nil :hints (("Goal" :induct (occur-cnt-bounded-flg flg term2 term1 lst a m bound-m))))) (local (defthm signed-byte-p-30-occur-cnt-bounded-flg-term (implies (and (force (signed-byte-p 30 a)) (signed-byte-p 30 m) (signed-byte-p 30 (+ bound-m m)) (force (<= 0 a)) (<= 0 m) (<= 0 bound-m) (<= a (+ bound-m m))) (and (<= -1 (occur-cnt-bounded term1 term2 a m bound-m)) (<= (occur-cnt-bounded term1 term2 a m bound-m) (+ bound-m m)))) :rule-classes :linear :hints (("Goal" ; :in-theory (theory 'minimal-theory) :use ((:instance signed-byte-p-30-occur-cnt-bounded-flg (flg 'term))))))) (local (defthm signed-byte-p-30-occur-cnt-bounded-flg-list (implies (and (force (signed-byte-p 30 a)) (signed-byte-p 30 m) (signed-byte-p 30 (+ bound-m m)) (force (<= 0 a)) (<= 0 m) (<= 0 bound-m) (<= a (+ bound-m m))) (and (<= -1 (occur-cnt-bounded-lst term1 lst a m bound-m)) (<= (occur-cnt-bounded-lst term1 lst a m bound-m) (+ bound-m m)))) :rule-classes :linear :hints (("Goal" ; :in-theory (theory 'minimal-theory) :use ((:instance signed-byte-p-30-occur-cnt-bounded-flg (flg 'list))))))) (verify-guards occur-cnt-bounded) (verify-termination-boot-strap too-many-ifs1) ; and guards (verify-termination-boot-strap too-many-ifs-post-rewrite-builtin) ; and guards ) (defattach too-many-ifs-post-rewrite too-many-ifs-post-rewrite-builtin) ; Complete too-many-ifs-pre-rewrite. #+acl2-loop-only The above readtime conditional avoids a CLISP warning , and lets the defproxy ; for print-clause-id-okp provide the raw Lisp definition. (encapsulate ((too-many-ifs-pre-rewrite (args counts) t :guard (and (pseudo-term-listp args) (integer-listp counts) (equal (len args) (len counts))))) (local (defun too-many-ifs-pre-rewrite (args counts) (list args counts)))) (defattach (too-many-ifs-pre-rewrite too-many-ifs-pre-rewrite-builtin)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Attachment: ancestors-check, worse-than, worse-than-or-equal ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (verify-termination-boot-strap pseudo-variantp) (verify-termination-boot-strap member-char-stringp) (verify-termination-boot-strap terminal-substringp1) (verify-termination-boot-strap terminal-substringp) (verify-termination-boot-strap evg-occur) (verify-termination-boot-strap min-fixnum) (verify-termination-boot-strap fn-count-evg-rec ; but not guards (declare (xargs :verify-guards nil))) (defthm fn-count-evg-rec-type-prescription (implies (natp acc) (natp (fn-count-evg-rec evg acc calls))) :rule-classes :type-prescription) (defthm fn-count-evg-rec-bound (< (fn-count-evg-rec evg acc calls) ( expt 2 29 ) :rule-classes :linear) (verify-guards fn-count-evg-rec) (verify-termination-boot-strap occur) and mut - rec nest (verify-termination-boot-strap worse-than-builtin) (verify-termination-boot-strap worse-than-or-equal-builtin) (verify-termination-boot-strap ancestor-listp) (verify-termination-boot-strap earlier-ancestor-biggerp) (verify-termination-boot-strap fn-count-1) ; but not guards (defthm fn-count-1-type (implies (and (integerp fn-count-acc) (integerp p-fn-count-acc)) (and (integerp (car (fn-count-1 flag term fn-count-acc p-fn-count-acc))) (integerp (mv-nth 0 (fn-count-1 flag term fn-count-acc p-fn-count-acc))) (integerp (mv-nth 1 (fn-count-1 flag term fn-count-acc p-fn-count-acc))) (integerp (nth 0 (fn-count-1 flag term fn-count-acc p-fn-count-acc))) (integerp (nth 1 (fn-count-1 flag term fn-count-acc p-fn-count-acc))))) :rule-classes ((:forward-chaining :trigger-terms ((fn-count-1 flag term fn-count-acc p-fn-count-acc))))) (verify-guards fn-count-1) (verify-termination-boot-strap var-fn-count-1) ; but not guards (defthm symbol-listp-cdr-assoc-equal (implies (symbol-list-listp x) (symbol-listp (cdr (assoc-equal key x))))) We state the following three rules in all forms that we think might be useful ; to those who want to reason about var-fn-count-1, for example if they are ; developing attachments to ancestors-check. (defthm integerp-nth-0-var-fn-count-1 (implies (integerp var-count-acc) (integerp (nth 0 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))) :rule-classes ((:forward-chaining :trigger-terms ((var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)) :corollary (implies (integerp var-count-acc) (and (integerp (nth 0 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table))) (integerp (mv-nth 0 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table))) (integerp (car (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))))))) (defthm integerp-nth-1-var-fn-count-1 (implies (integerp fn-count-acc) (integerp (nth 1 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))) :rule-classes ((:forward-chaining :trigger-terms ((var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)) :corollary (implies (integerp fn-count-acc) (and (integerp (nth 1 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table))) (integerp (mv-nth 1 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))))))) (defthm integerp-nth-2-var-fn-count-1 (implies (integerp p-fn-count-acc) (integerp (nth 2 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))) :rule-classes ((:forward-chaining :trigger-terms ((var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)) :corollary (implies (integerp p-fn-count-acc) (and (integerp (nth 2 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table))) (integerp (mv-nth 2 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))))))) (verify-guards var-fn-count-1) (verify-termination-boot-strap equal-mod-commuting) ; and guards (verify-termination-boot-strap ancestors-check1) (verify-termination-boot-strap ancestors-check-builtin) (defun member-equal-mod-commuting (x lst wrld) (declare (xargs :guard (and (pseudo-termp x) (pseudo-term-listp lst) (plist-worldp wrld)))) (cond ((endp lst) nil) ((equal-mod-commuting x (car lst) wrld) lst) (t (member-equal-mod-commuting x (cdr lst) wrld)))) In the following , terms ( nth 0 ... ) and ( nth 1 ... ) in the hints were originally ( car ... ) and ( mv - nth 1 ... ) , respectively , but those did n't ; work. It would be good at some point to explore why not, given that the ; original versions worked outside the build. (defun strip-ancestor-literals (ancestors) (declare (xargs :guard (ancestor-listp ancestors))) (cond ((endp ancestors) nil) (t (cons (access ancestor (car ancestors) :lit) (strip-ancestor-literals (cdr ancestors)))))) (encapsulate () (local (defthm ancestors-check1-property (mv-let (on-ancestors assumed-true) (ancestors-check1 lit-atm lit var-cnt fn-cnt p-fn-cnt ancestors tokens) (implies (and on-ancestors assumed-true) (member-equal-mod-commuting lit (strip-ancestor-literals ancestors) nil))) :rule-classes nil)) (defthmd ancestors-check-builtin-property (mv-let (on-ancestors assumed-true) (ancestors-check-builtin lit ancestors tokens) (implies (and on-ancestors assumed-true) (member-equal-mod-commuting lit (strip-ancestor-literals ancestors) nil))) :hints (("Goal" :use ((:instance ancestors-check1-property (lit-atm lit) (var-cnt 0) (fn-cnt 0) (p-fn-cnt 0)) (:instance ancestors-check1-property (lit-atm lit) (var-cnt (nth 0 (var-fn-count-1 nil lit 0 0 0 nil nil))) (fn-cnt (nth 1 (var-fn-count-1 nil lit 0 0 0 nil nil))) (p-fn-cnt (nth 2 (var-fn-count-1 nil lit 0 0 0 nil nil)))) (:instance ancestors-check1-property (lit-atm (cadr lit)) (var-cnt (nth 0 (var-fn-count-1 nil (cadr lit) 0 0 0 nil nil))) (fn-cnt (nth 1 (var-fn-count-1 nil (cadr lit) 0 0 0 nil nil))) (p-fn-cnt (nth 2 (var-fn-count-1 nil (cadr lit) 0 0 0 nil nil))))))))) #+acl2-loop-only The above readtime conditional avoids a CLISP warning , and lets the defproxy ; for print-clause-id-okp provide the raw Lisp definition. (encapsulate ((ancestors-check (lit ancestors tokens) (mv t t) :guard (and (pseudo-termp lit) (ancestor-listp ancestors) (true-listp tokens)))) (local (defun ancestors-check (lit ancestors tokens) (ancestors-check-builtin lit ancestors tokens))) (defthmd ancestors-check-constraint (implies (and (pseudo-termp lit) (ancestor-listp ancestors) (true-listp tokens)) (mv-let (on-ancestors assumed-true) (ancestors-check lit ancestors tokens) (implies (and on-ancestors assumed-true) (member-equal-mod-commuting lit (strip-ancestor-literals ancestors) nil)))) :hints (("Goal" :use ancestors-check-builtin-property)))) (defattach (ancestors-check ancestors-check-builtin) :hints (("Goal" :by ancestors-check-builtin-property))) (defattach worse-than worse-than-builtin) (defattach worse-than-or-equal worse-than-or-equal-builtin) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Attachment: acl2x-expansion-alist ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (verify-termination-boot-strap hons-copy-with-state) ; and guards (verify-termination-boot-strap identity-with-state) ; and guards (defattach (acl2x-expansion-alist ; User-modifiable; see comment in the defstub introducing ; acl2x-expansion-alist. identity-with-state)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Attachments: rw-cache utilities ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (verify-termination-boot-strap rw-cache-debug-builtin) ; and guards (defattach rw-cache-debug rw-cache-debug-builtin) (verify-termination-boot-strap rw-cache-debug-action-builtin) ; and guards (defattach rw-cache-debug-action rw-cache-debug-action-builtin) (verify-termination-boot-strap rw-cacheable-failure-reason-builtin) ; and guards (defattach rw-cacheable-failure-reason rw-cacheable-failure-reason-builtin) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Attachments: print-clause-id-okp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (verify-termination-boot-strap all-digits-p) ; and guards (verify-termination-boot-strap ; and guards (d-pos-listp (declare (xargs :guard-hints (("Goal" :use ((:instance coerce-inverse-2 (x (symbol-name (car lst)))) (:instance character-listp-coerce (str (symbol-name (car lst))))) :expand ((len (coerce (symbol-name (car lst)) 'list))) :in-theory (disable coerce-inverse-2 character-listp-coerce))))))) (verify-termination-boot-strap pos-listp) (verify-guards pos-listp) (defthm d-pos-listp-forward-to-true-listp (implies (d-pos-listp x) (true-listp x)) :rule-classes :forward-chaining) (verify-termination-boot-strap clause-id-p) ; and guards #+acl2-loop-only The above readtime conditional avoids a CLISP warning , and lets the defproxy ; for print-clause-id-okp provide the raw Lisp definition. (encapsulate (((print-clause-id-okp *) => * :formals (cl-id) :guard (clause-id-p cl-id))) (local (defun print-clause-id-okp (x) x))) (verify-termination-boot-strap print-clause-id-okp-builtin) ; and guards (defattach print-clause-id-okp print-clause-id-okp-builtin) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Attachments: oncep-tp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; We could avoid the forms below by replacing the earlier forms ( defproxy oncep - tp ( * * ) = > * ) ; (defun oncep-tp-builtin ...) ; :guard t ; (defattach (oncep-tp oncep-tp-builtin) :skip-checks t) ; in place, by changing defproxy to defstub and removing :skip-checks t. ; However, the guard on once-tp would then be left with a guard of t, which ; might be stronger than we'd like. #+acl2-loop-only The above readtime conditional avoids a CLISP warning , and lets the defproxy ; for print-clause-id-okp provide the raw Lisp definition. (encapsulate (((oncep-tp * *) => * :formals (rune wrld) :guard (and (plist-worldp wrld) ; Although (runep rune wrld) is appropriate here, we don't want to fight the ; battle yet of putting runep into :logic mode. So we just lay down the ; syntactic part of its code, which should suffice for user-defined attachments ; to oncep-tp. (and (consp rune) (consp (cdr rune)) (symbolp (cadr rune)))))) (logic) (local (defun oncep-tp (rune wrld) (oncep-tp-builtin rune wrld)))) (defattach oncep-tp oncep-tp-builtin) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; verify-termination and guard verification: ; string-for-tilde-@-clause-id-phrase and some subsidiary functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; proved termination and guards for ; string-for-tilde-@-clause-id-phrase, with a proof that included community ; books unicode/explode-atom and unicode/explode-nonnegative-integer. Here, we ; rework that proof a bit to avoid those dependencies. Note that this proof ; depends on d-pos-listp, whose termination and guard verification are ; performed above. ; We proved true-listp-explode-nonnegative-integer here, but then found it was already proved locally in axioms.lisp . So we made that defthm non - local ( and ; strengthened it to its current form). (verify-termination-boot-strap chars-for-tilde-@-clause-id-phrase/periods) (verify-termination-boot-strap chars-for-tilde-@-clause-id-phrase/primes) (defthm pos-listp-forward-to-integer-listp (implies (pos-listp x) (integer-listp x)) :rule-classes :forward-chaining) (verify-termination-boot-strap chars-for-tilde-@-clause-id-phrase) (defthm true-listp-chars-for-tilde-@-clause-id-phrase/periods (true-listp (chars-for-tilde-@-clause-id-phrase/periods lst)) :rule-classes :type-prescription) (defthm true-listp-explode-atom (true-listp (explode-atom n print-base)) :rule-classes :type-prescription) (encapsulate () ; The following local events create perfectly good rewrite rules, but we avoid ; the possibility of namespace clashes for existing books by making them local ; as we add them after Version_4.3. (local (defthm character-listp-explode-nonnegative-integer (implies (character-listp ans) (character-listp (explode-nonnegative-integer n print-base ans))))) (local (defthm character-listp-explode-atom (character-listp (explode-atom n print-base)) need to disable this local lemma from axioms.lisp (("Goal" :in-theory (disable character-listp-cdr))))) (local (defthm character-listp-chars-for-tilde-@-clause-id-phrase/periods (character-listp (chars-for-tilde-@-clause-id-phrase/periods lst)))) (verify-termination-boot-strap string-for-tilde-@-clause-id-phrase)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; verify-termination and guard verification: ; strict-merge-symbol<, strict-merge-sort-symbol<, strict-symbol<-sortedp, ; and sort-symbol-listp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (verify-termination-boot-strap strict-merge-symbol< (declare (xargs :measure (+ (len l1) (len l2))))) (encapsulate () (local (defthm len-strict-merge-symbol< (<= (len (strict-merge-symbol< l1 l2 acc)) (+ (len l1) (len l2) (len acc))) :rule-classes :linear)) (local (defthm len-evens (equal (len l) (+ (len (evens l)) (len (odds l)))) :rule-classes :linear)) (local (defthm symbol-listp-evens (implies (symbol-listp x) (symbol-listp (evens x))) :hints (("Goal" :induct (evens x))))) (local (defthm symbol-listp-odds (implies (symbol-listp x) (symbol-listp (odds x))))) (local (defthm symbol-listp-strict-merge-symbol< (implies (and (symbol-listp l1) (symbol-listp l2) (symbol-listp acc)) (symbol-listp (strict-merge-symbol< l1 l2 acc))))) (verify-termination-boot-strap strict-merge-sort-symbol< (declare (xargs :measure (len l) :verify-guards nil))) (defthm symbol-listp-strict-merge-sort-symbol< ; This lemma is non-local because it is needed for "make proofs", for ; guard-verification for new-verify-guards-fns1. (implies (symbol-listp x) (symbol-listp (strict-merge-sort-symbol< x)))) (verify-guards strict-merge-sort-symbol<) (verify-termination-boot-strap sort-symbol-listp) ; and guards ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; verify-termination and guard verification: ; ld-history and associated functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (verify-termination-boot-strap ld-history) ; and guards (verify-termination-boot-strap ld-history-entry-input) ; and guards (verify-termination-boot-strap ld-history-entry-error-flg) ; and guards (verify-termination-boot-strap ld-history-entry-stobjs-out/value) ; and guards (verify-termination-boot-strap ld-history-entry-stobjs-out) ; and guards (verify-termination-boot-strap ld-history-entry-value) ; and guards (verify-termination-boot-strap ld-history-entry-user-data) ; and guards (verify-termination-boot-strap set-ld-history-entry-user-data-default) (defattach set-ld-history-entry-user-data set-ld-history-entry-user-data-default) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Theories ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (deftheory definition-minimal-theory (definition-runes *definition-minimal-theory* nil world)) (deftheory executable-counterpart-minimal-theory (definition-runes *built-in-executable-counterparts* t world)) (deftheory minimal-theory ; Warning: The resulting value must be a runic-theoryp. See ; theory-fn-callp. ; Keep this definition in sync with translate-in-theory-hint. (union-theories (theory 'definition-minimal-theory) (union-theories ; Without the :executable-counterpart of force, the use of (theory ; 'minimal-theory) will produce the warning "Forcing has transitioned from ; enabled to disabled", at least if forcing is enabled (as is the default). ; Moreover, it's not unreasonable to leave forcing on in the minimal-theory, for example in case it 's useful for linear arithmetic . '((:executable-counterpart force)) (theory 'executable-counterpart-minimal-theory)))) (defconst *acl2-primitives* (strip-cars *primitive-formals-and-guards*)) (deftheory acl2-primitives (definition-runes *acl2-primitives* nil world)) ; See the Essay on the Status of the Tau System During and After Bootstrapping in axioms.lisp where we discuss choices ( 1.a ) , ( 1.b ) , ( 2.a ) and ( 2.b ) ; related to the status of the tau system. Here is where we implement ; (2.a). (in-theory (if (cadr *tau-status-boot-strap-settings*) ; (2.a) (enable (:executable-counterpart tau-system)) (disable (:executable-counterpart tau-system)))) Avoid ugly output from , e.g. , ( thm ( equal ( print - call - history ) 3 ) ) . (in-theory (disable (:e print-call-history))) observed significant speed - up from the following disable . (in-theory (disable ctxp)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; meta-extract support ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (verify-termination-boot-strap formals) ; and guards (verify-termination-boot-strap constraint-info) ; and guards (verify-termination-boot-strap unknown-constraints-p) ; and guards (defund meta-extract-formula (name state) ; This function supports meta-extract-global-fact+. It needs to be executable ; and in :logic mode (hence, as required by the ACL2 build process, ; guard-verified), since it may be called by meta functions. ; While this function can be viewed as a version of formula, it applies only to ; symbols (not runes), it is in :logic mode, and there are a few other ; differences as well. The present function requires name to be a symbol and ; only returns a normalp=nil form of body. (Otherwise, in order to put body in ; :logic mode, body would need to be guard-verified, which would probably take ; considerable effort.) (declare (xargs :stobjs state :guard (symbolp name))) (let ((wrld (w state))) (or (getpropc name 'theorem nil wrld) (cond ((logicp name wrld) (mv-let (flg prop) (constraint-info name wrld) (cond ((unknown-constraints-p prop) *t*) (flg (ec-call (conjoin prop))) (t prop)))) (t *t*))))) (verify-termination-boot-strap type-set-quote) (verify-guards type-set-quote) (defun typespec-check (ts x) (declare (xargs :guard (integerp ts))) (if (bad-atom x) (< ts 0) ; bad-atom type intersects every complement type ; We would like to write ; (ts-subsetp (type-set-quote x) ts) here , but for that we need a stronger guard than ( integerp ts ) , and we prefer ; to keep this simple. (not (eql 0 (logand (type-set-quote x) ts))))) (defun meta-extract-rw+-term (term alist equiv rhs state) ; This function supports the function meta-extract-contextual-fact. Neither of ; these functions is intended to be executed. Meta - extract - rw+-term creates ( logically ) a term claiming that term under ; alist is equiv to rhs, where equiv=nil represents 'equal and equiv=t ; represents 'iff. If equiv is not t, nil, or an equivalence relation, then ; *t* is returned. ; Note that this function does not support the use of a geneqv for the equiv ; argument. (declare (xargs :mode :program ; becomes :logic with system-verify-guards :stobjs state :guard (and (symbol-alistp alist) (pseudo-term-listp (strip-cdrs alist)) (pseudo-termp term)))) (non-exec (let ((lhs (sublis-var alist term))) (case equiv ((nil) `(equal ,lhs ,rhs)) ((t) `(iff ,lhs ,rhs)) (otherwise (if (symbolp equiv) (if (equivalence-relationp equiv (w state)) `(,equiv ,lhs ,rhs) ; else bad equivalence relation *t*) *t*)))))) (defun meta-extract-contextual-fact (obj mfc state) ; This function is not intended to be executed. ; This function may be called in the hypothesis of a meta rule, because we know it always produces a term that evaluates to non - nil under the where the ; metafunction is called, using the specific alist A for which we're proving ( evl x a ) = ( evl ( ) a ) . The terms it produces reflect the ; correctness of certain prover operations -- currently, accessing type-alist and typeset information , rewriting , and linear arithmetic . See the Essay on ; Correctness of Meta Reasoning. Note that these operations use the state for ; heuristic purposes, and get their logical information from the world stored in ( not in state ) . ; This function avoids forcing and does not return a tag-tree. (declare (xargs :mode :program ; becomes :logic with system-verify-guards :stobjs state)) (non-exec (case-match obj ((':typeset term . &) ; mfc-ts produces correct results `(typespec-check ',(mfc-ts term mfc state :forcep nil :ttreep nil) ,term)) ((':rw+ term alist obj equiv . &) ; result is equiv to term/alist. (meta-extract-rw+-term term alist equiv (mfc-rw+ term alist obj equiv mfc state :forcep nil :ttreep nil) state)) ((':rw term obj equiv . &) ; as for :rw+, with alist of nil (meta-extract-rw+-term term nil equiv (mfc-rw term obj equiv mfc state :forcep nil :ttreep nil) state)) ((':ap term . &) ; Can linear arithmetic can falsify term? (if (mfc-ap term mfc state :forcep nil) `(not ,term) *t*)) ((':relieve-hyp hyp alist rune target bkptr . &) ; hyp/alist proved? (if (mfc-relieve-hyp hyp alist rune target bkptr mfc state :forcep nil :ttreep nil) (sublis-var alist hyp) *t*)) (& *t*)))) (defun rewrite-rule-term-exec (x) (declare (xargs :guard (and (weak-rewrite-rule-p x) (or (eq (access rewrite-rule x :subclass) 'meta) (true-listp (access rewrite-rule x :hyps)))))) (if (eq (access rewrite-rule x :subclass) 'meta) *t* `(implies ,(conjoin (access rewrite-rule x :hyps)) (,(access rewrite-rule x :equiv) ,(access rewrite-rule x :lhs) ,(access rewrite-rule x :rhs))))) (defun rewrite-rule-term (x) ; This function turns a rewrite-rule record into a term. Consider using ; rewrite-rule-term-exec instead when its guard doesn't cause problems. (declare (xargs :guard t)) (ec-call (rewrite-rule-term-exec x))) (defun linear-lemma-term-exec (x) (declare (xargs :guard (and (weak-linear-lemma-p x) (true-listp (access linear-lemma x :hyps))))) `(implies ,(conjoin (access linear-lemma x :hyps)) ,(access linear-lemma x :concl))) (defun linear-lemma-term (x) ; This function turns a linear-lemma record into a term. Consider using ; linear-lemma-term-exec instead when its guard doesn't cause problems. (declare (xargs :guard t)) (ec-call (linear-lemma-term-exec x))) (defmacro meta-extract-global-fact (obj state) ; See meta-extract-global-fact+. `(meta-extract-global-fact+ ,obj ,state ,state)) (defun fncall-term (fn arglist state) (declare (xargs :stobjs state :guard (and (symbolp fn) (true-listp arglist)))) (cond ((logicp fn (w state)) (mv-let (erp val) (magic-ev-fncall fn arglist state t ; hard-error-returns-nilp nil ; aok ) (cond (erp *t*) (t (fcons-term* 'equal As suggested by , we use fcons - term below in order to avoid having ; to reason about the application of an evaluator to (cons-term fn ...). (fcons-term fn (kwote-lst arglist)) (kwote val)))))) (t *t*))) (defun logically-equivalent-states (st1 st2) (declare (xargs :guard t)) (non-exec (equal (w st1) (w st2)))) (defun meta-extract-global-fact+ (obj st state) ; This function is not intended to be executed. ; This function may be called in the hypothesis of a meta rule, because we know ; it always produces a term that evaluates to non-nil for any alist. The terms ; it produces reflect the correctness of certain facts stored in the world. ; See the Essay on Correctness of Meta Reasoning. (declare (xargs :mode :program ; becomes :logic with system-verify-guards :stobjs state)) (non-exec (cond ((logically-equivalent-states st state) (case-match obj ((':formula name) (meta-extract-formula name st)) ((':lemma fn n) (let* ((lemmas (getpropc fn 'lemmas nil (w st))) (rule (nth n lemmas))) The use of rewrite - rule - term below relies on the fact that the ' LEMMAS ; property of a symbol in the ACL2 world is a list of rewrite-rule records that ; reflect known facts. (if (< (nfix n) (len lemmas)) (rewrite-rule-term rule) *t*))) ; Fn doesn't exist or n is too big. ((':linear-lemma fn n) (let* ((lemmas (getpropc fn 'linear-lemmas nil (w st))) (rule (nth n lemmas))) ; The use of linear-lemma-term below relies on the fact that the 'LINEAR-LEMMAS ; property of a symbol in the ACL2 world is a list of linear-lemma records that ; reflect known facts. (if (< (nfix n) (len lemmas)) (linear-lemma-term rule) *t*))) ((':fncall fn arglist) (non-exec ; avoid guard check (fncall-term fn arglist st))) (& *t*))) (t *t*)))) (add-macro-alias meta-extract-global-fact meta-extract-global-fact+) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; {read/write}-user-stobj-alist ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; It would be more natural to define these in axioms.lisp , but the defun - nx ; calls expand to include calls of push-inhibit-output-lst-stack, which isn't ; defined until basis-b.lisp. (defun-nx read-user-stobj-alist (st state) ; Warning: Keep this in sync with the definition of read-user-stobj-alist in ; (defxdoc with-global-stobj ...) in community book ; books/system/doc/acl2-doc.lisp. (declare (xargs :guard (symbolp st) :stobjs state)) (cdr (assoc-eq st (user-stobj-alist1 state)))) #-acl2-loop-only (defun read-user-stobj-alist-raw (st state) (cond ((live-state-p state) (cdr (assoc-eq st *user-stobj-alist*))) (t ; should be impossible coming from ACL2 loop evaluation (error "Illegal call of read-user-stobj-alist: State argument is not ~ the `live' ACL2 state.")))) (defun-nx write-user-stobj-alist (st val state) ; Warning: Keep this in sync with the definition of write-user-stobj-alist in ; (defxdoc with-global-stobj ...) in community book ; books/system/doc/acl2-doc.lisp. ; If you give this raw Lisp code, consider removing it from the list in ; check-invariant-risk. (declare (xargs :guard (symbolp st) :stobjs state)) (update-user-stobj-alist1 (put-assoc-eq st val (user-stobj-alist1 state)) state)) #-acl2-loop-only (defun write-user-stobj-alist-raw (st val state) (cond (*wormholep* (wormhole-er 'write-user-stobj-alist (list st val 'state))) ((live-state-p state) (loop for pair of-type cons in *user-stobj-alist* when (eq (car pair) st) do (progn (or (eq (cdr pair) val) (setf (cdr pair) val)) (return state)) finally (error "Unknown stobj, ~s" st))) (t (error "Illegal call of write-user-stobj-alist: State argument is not the ~ `live' ACL2 state.")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
null
https://raw.githubusercontent.com/acl2/acl2/65a46d5c1128cbecb9903bfee4192bb5daf7c036/boot-strap-pass-2-a.lisp
lisp
This program is free software; you can redistribute it and/or modify it under the terms of the LICENSE file distributed with ACL2. 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 LICENSE for more details. boot-strap-pass-2-b.lisp. They are compiled and loaded; but they are only some guiding principles for making system functions available for attachment by users. - The initial attachment is named by adding the suffix -builtin. For example, worse-than is a constrained function initially attached to worse-than-builtin. - Use the weakest logical specs we can (even if T), without getting distracted by names. For example, we do not specify a relationship between worse-than-or-equal and worse-than. - Only make functions attachable if they are used in our sources somewhere outside their definitions. So for example, we do not introduce worse-than-list as a constrained function, since its only use is in the mutual-recursion event that defines worse-than. We conclude by defining some theories, near the end so that they pick up much of the rest of this file. Miscellaneous verify-termination and guard verification fncall-term, but anyhow, generally useful to have in logic mode and guards and guards and guards and guards and guards and guards and guards and guards and guards and guards miscellaneous and guards and guards and guards and guards and guards and guards and guards and guards for case-match expansions: and guards and guards and guards and guards and guards and guards and guards and guards Convert defproxy events to :logic mode. Supporters = nil since each missing axiom equates a call of canonical-pathname on explicit arguments with its result. Supporters = nil since each missing axiom equates a call of magic-ev-fncall on explicit arguments with its result. signature functions (above) on explicit arguments with its result. and guards and guards and guards and guards and guards and guards and guards and guards and guards and guards and guards and guards and guards and guards and guards and guards and guards and guards Attachment: too-many-ifs-post-rewrite and too-many-ifs-pre-rewrite for print-clause-id-okp provide the raw Lisp definition. The following events are derived from the original version of community book books/system/too-many-ifs.lisp. But here we provide a proof that does not depend on books. Our approach was to take the proof in the above book, eliminate the unnecessary use of an arithmetic book, expand away all uses of macros and make-events, avoid use of (theory 'minimal-theory) since that theory didn't yet exist (where these events were originally placed), and apply some additional hand-editing in order (for example) to remove hints depending on the tools/flag community book. We have left original events from the book as comments. (include-book "tools/flag" :dir :system) In the original book, but not needed for its certification: (include-book "arithmetic/top-with-meta" :dir :system) Comments like the following show events from the original book. (make-flag pseudo-termp-flg pseudo-termp :flag-mapping ((pseudo-termp term) (pseudo-term-listp list)) :defthm-macro-name defthm-pseudo-termp :local t) Added here (not present or needed in the certified book): and guards (make-flag var-counts1-flg var-counts1 :flag-mapping ((var-counts1 term) (var-counts1-lst list)) :defthm-macro-name defthm-var-counts1 :local t) (defthm-var-counts1 natp-var-counts1 (term :rule-classes :type-prescription) (list :rule-classes :type-prescription) :in-theory (theory 'minimal-theory) :in-theory (theory 'minimal-theory) and guards Since the comment about var-counts says that var-counts returns a list of Except, we reason instead about integer-listp. See the comment just above rewrite.lisp). and guards Added here (not present or needed in the certified book): and guards Added here (not present or needed in the certified book): and guards Added here (not present or needed in the certified book): and guards Added here (not present or needed in the certified book): Added here (not present or needed in the certified book): and guards and guards and guards (make-flag occur-cnt-bounded-flg occur-cnt-bounded :flag-mapping ((occur-cnt-bounded term) (occur-cnt-bounded-lst list)) :defthm-macro-name defthm-occur-cnt-bounded :local t) (term (implies (and (integerp a) (integerp m)) :rule-classes :type-prescription) (list (implies (and (integerp a) (integerp m)) :rule-classes :type-prescription) bound-m)))) :in-theory (theory 'minimal-theory) :in-theory (theory 'minimal-theory) (defthm-occur-cnt-bounded signed-byte-p-30-occur-cnt-bounded-flg (term (implies (and (force (signed-byte-p 30 a)) (signed-byte-p 30 m) (signed-byte-p 30 (+ bound-m m)) (force (<= 0 a)) (<= 0 m) (<= 0 bound-m) (<= a (+ bound-m m))) :rule-classes :linear) (list (implies (and (force (signed-byte-p 30 a)) (signed-byte-p 30 m) (signed-byte-p 30 (+ bound-m m)) (force (<= 0 a)) (<= 0 m) (<= 0 bound-m) (<= a (+ bound-m m))) (and (<= -1 (occur-cnt-bounded-lst term1 lst a m bound-m)) (<= (occur-cnt-bounded-lst term1 lst a m bound-m) (+ bound-m m)))) :rule-classes :linear) bound-m)))) :in-theory (theory 'minimal-theory) :in-theory (theory 'minimal-theory) and guards and guards Complete too-many-ifs-pre-rewrite. for print-clause-id-okp provide the raw Lisp definition. Attachment: ancestors-check, worse-than, worse-than-or-equal but not guards but not guards but not guards to those who want to reason about var-fn-count-1, for example if they are developing attachments to ancestors-check. and guards work. It would be good at some point to explore why not, given that the original versions worked outside the build. for print-clause-id-okp provide the raw Lisp definition. Attachment: acl2x-expansion-alist and guards and guards User-modifiable; see comment in the defstub introducing acl2x-expansion-alist. Attachments: rw-cache utilities and guards and guards and guards Attachments: print-clause-id-okp and guards and guards and guards for print-clause-id-okp provide the raw Lisp definition. and guards Attachments: oncep-tp We could avoid the forms below by replacing the earlier forms (defun oncep-tp-builtin ...) ; :guard t (defattach (oncep-tp oncep-tp-builtin) :skip-checks t) in place, by changing defproxy to defstub and removing :skip-checks t. However, the guard on once-tp would then be left with a guard of t, which might be stronger than we'd like. for print-clause-id-okp provide the raw Lisp definition. Although (runep rune wrld) is appropriate here, we don't want to fight the battle yet of putting runep into :logic mode. So we just lay down the syntactic part of its code, which should suffice for user-defined attachments to oncep-tp. verify-termination and guard verification: string-for-tilde-@-clause-id-phrase and some subsidiary functions string-for-tilde-@-clause-id-phrase, with a proof that included community books unicode/explode-atom and unicode/explode-nonnegative-integer. Here, we rework that proof a bit to avoid those dependencies. Note that this proof depends on d-pos-listp, whose termination and guard verification are performed above. We proved true-listp-explode-nonnegative-integer here, but then found it was strengthened it to its current form). The following local events create perfectly good rewrite rules, but we avoid the possibility of namespace clashes for existing books by making them local as we add them after Version_4.3. verify-termination and guard verification: strict-merge-symbol<, strict-merge-sort-symbol<, strict-symbol<-sortedp, and sort-symbol-listp This lemma is non-local because it is needed for "make proofs", for guard-verification for new-verify-guards-fns1. and guards verify-termination and guard verification: ld-history and associated functions and guards and guards and guards and guards and guards and guards and guards Theories Warning: The resulting value must be a runic-theoryp. See theory-fn-callp. Keep this definition in sync with translate-in-theory-hint. Without the :executable-counterpart of force, the use of (theory 'minimal-theory) will produce the warning "Forcing has transitioned from enabled to disabled", at least if forcing is enabled (as is the default). Moreover, it's not unreasonable to leave forcing on in the minimal-theory, See the Essay on the Status of the Tau System During and After Bootstrapping related to the status of the tau system. Here is where we implement (2.a). (2.a) meta-extract support and guards and guards and guards This function supports meta-extract-global-fact+. It needs to be executable and in :logic mode (hence, as required by the ACL2 build process, guard-verified), since it may be called by meta functions. While this function can be viewed as a version of formula, it applies only to symbols (not runes), it is in :logic mode, and there are a few other differences as well. The present function requires name to be a symbol and only returns a normalp=nil form of body. (Otherwise, in order to put body in :logic mode, body would need to be guard-verified, which would probably take considerable effort.) bad-atom type intersects every complement type We would like to write (ts-subsetp (type-set-quote x) ts) to keep this simple. This function supports the function meta-extract-contextual-fact. Neither of these functions is intended to be executed. alist is equiv to rhs, where equiv=nil represents 'equal and equiv=t represents 'iff. If equiv is not t, nil, or an equivalence relation, then *t* is returned. Note that this function does not support the use of a geneqv for the equiv argument. becomes :logic with system-verify-guards else bad equivalence relation This function is not intended to be executed. This function may be called in the hypothesis of a meta rule, because we know metafunction is called, using the specific alist A for which we're proving correctness of certain prover operations -- currently, accessing type-alist Correctness of Meta Reasoning. Note that these operations use the state for heuristic purposes, and get their logical information from the world stored This function avoids forcing and does not return a tag-tree. becomes :logic with system-verify-guards mfc-ts produces correct results result is equiv to term/alist. as for :rw+, with alist of nil Can linear arithmetic can falsify term? hyp/alist proved? This function turns a rewrite-rule record into a term. Consider using rewrite-rule-term-exec instead when its guard doesn't cause problems. This function turns a linear-lemma record into a term. Consider using linear-lemma-term-exec instead when its guard doesn't cause problems. See meta-extract-global-fact+. hard-error-returns-nilp aok to reason about the application of an evaluator to (cons-term fn ...). This function is not intended to be executed. This function may be called in the hypothesis of a meta rule, because we know it always produces a term that evaluates to non-nil for any alist. The terms it produces reflect the correctness of certain facts stored in the world. See the Essay on Correctness of Meta Reasoning. becomes :logic with system-verify-guards property of a symbol in the ACL2 world is a list of rewrite-rule records that reflect known facts. Fn doesn't exist or n is too big. The use of linear-lemma-term below relies on the fact that the 'LINEAR-LEMMAS property of a symbol in the ACL2 world is a list of linear-lemma records that reflect known facts. avoid guard check {read/write}-user-stobj-alist calls expand to include calls of push-inhibit-output-lst-stack, which isn't defined until basis-b.lisp. Warning: Keep this in sync with the definition of read-user-stobj-alist in (defxdoc with-global-stobj ...) in community book books/system/doc/acl2-doc.lisp. should be impossible coming from ACL2 loop evaluation Warning: Keep this in sync with the definition of write-user-stobj-alist in (defxdoc with-global-stobj ...) in community book books/system/doc/acl2-doc.lisp. If you give this raw Lisp code, consider removing it from the list in check-invariant-risk.
ACL2 Version 8.5 -- A Computational Logic for Applicative Common Lisp Copyright ( C ) 2023 , Regents of the University of Texas This version of ACL2 is a descendent of ACL2 Version 1.9 , Copyright ( C ) 1997 Computational Logic , Inc. See the documentation topic NOTE-2 - 0 . Written by : and J Strother Moore email : and Department of Computer Science University of Texas at Austin Austin , TX 78712 U.S.A. (in-package "ACL2") This file is the first of a pair of files , boot-strap-pass-2-a.lisp and processed during the second pass of the boot - strap process , not the first . We introduce proper defattach events , i.e. , without : skip - checks t. Here are cons - term and symbol - class -- at one point during development , used in packn1 , packn , and pack - to - string (encapsulate () (local (defthm character-listp-explode-nonnegative-integer (implies (character-listp z) (character-listp (explode-nonnegative-integer x y z))) :rule-classes ((:forward-chaining :trigger-terms ((explode-nonnegative-integer x y z)))))) (local (defthm character-listp-explode-atom (character-listp (explode-atom x y)) :rule-classes ((:forward-chaining :trigger-terms ((explode-atom x y)))))) ) (verify-guards warranted-fns-of-world) (defstub initialize-event-user (* * state) => state) (defstub finalize-event-user (* * state) => state) (defstub acl2x-expansion-alist (* state) => *) (defstub set-ld-history-entry-user-data (* * * state) => *) #+acl2-loop-only (partial-encapsulate (((canonical-pathname * * state) => *)) nil (local (defun canonical-pathname (x dir-p state) (declare (xargs :mode :logic)) (declare (ignore dir-p state)) (if (stringp x) x nil))) (defthm canonical-pathname-is-idempotent (equal (canonical-pathname (canonical-pathname x dir-p state) dir-p state) (canonical-pathname x dir-p state))) (defthm canonical-pathname-type (or (equal (canonical-pathname x dir-p state) nil) (stringp (canonical-pathname x dir-p state))) :rule-classes :type-prescription)) #+acl2-loop-only (partial-encapsulate (((magic-ev-fncall * * state * *) => (mv * *))) nil (logic) (local (defun magic-ev-fncall (fn args state hard-error-returns-nilp aok) (declare (xargs :mode :logic) (ignore fn args state hard-error-returns-nilp aok)) (mv nil nil)))) #+acl2-loop-only (partial-encapsulate (((mfc-ap-fn * * state *) => *) ((mfc-relieve-hyp-fn * * * * * * state *) => *) ((mfc-relieve-hyp-ttree * * * * * * state *) => (mv * *)) ((mfc-rw+-fn * * * * * state *) => *) ((mfc-rw+-ttree * * * * * state *) => (mv * *)) ((mfc-rw-fn * * * * state *) => *) ((mfc-rw-ttree * * * * state *) => (mv * *)) ((mfc-ts-fn * * state *) => *) ((mfc-ts-ttree * * state *) => (mv * *))) Supporters = nil since each missing axiom equates a call of one of the nil (logic) (set-ignore-ok t) (set-irrelevant-formals-ok t) (local (defun mfc-ts-fn (term mfc state forcep) t)) (local (defun mfc-ts-ttree (term mfc state forcep) (mv t t))) (local (defun mfc-rw-fn (term obj equiv-info mfc state forcep) t)) (local (defun mfc-rw-ttree (term obj equiv-info mfc state forcep) (mv t t))) (local (defun mfc-rw+-fn (term alist obj equiv-info mfc state forcep) t)) (local (defun mfc-rw+-ttree (term alist obj equiv-info mfc state forcep) (mv t t))) (local (defun mfc-relieve-hyp-fn (hyp alist rune target bkptr mfc state forcep) t)) (local (defun mfc-relieve-hyp-ttree (hyp alist rune target bkptr mfc state forcep) (mv t t))) (local (defun mfc-ap-fn (term mfc state forcep) t))) #+acl2-loop-only The above readtime conditional avoids a CLISP warning , and lets the defproxy (encapsulate ((too-many-ifs-post-rewrite (args val) t :guard (and (pseudo-term-listp args) (pseudo-termp val)))) (local (defun too-many-ifs-post-rewrite (args val) (list args val)))) (encapsulate () (logic) : flag - var flg (local (defun-nx pseudo-termp-flg (flg x lst) (declare (xargs :verify-guards nil :normalize nil :measure (case flg (term (acl2-count x)) (otherwise (acl2-count lst))))) (case flg (term (if (consp x) (cond ((equal (car x) 'quote) (and (consp (cdr x)) (equal (cddr x) nil))) ((true-listp x) (and (pseudo-termp-flg 'list nil (cdr x)) (cond ((symbolp (car x)) t) ((true-listp (car x)) (and (equal (length (car x)) 3) (equal (caar x) 'lambda) (symbol-listp (cadar x)) (pseudo-termp-flg 'term (caddar x) nil) (equal (length (cadar x)) (length (cdr x))))) (t nil)))) (t nil)) (symbolp x))) (otherwise (if (consp lst) (and (pseudo-termp-flg 'term (car lst) nil) (pseudo-termp-flg 'list nil (cdr lst))) (equal lst nil)))))) (local (defthm pseudo-termp-flg-equivalences (equal (pseudo-termp-flg flg x lst) (case flg (term (pseudo-termp x)) (otherwise (pseudo-term-listp lst)))) :hints (("goal" :induct (pseudo-termp-flg flg x lst))))) (local (in-theory (disable (:definition pseudo-termp-flg)))) (verify-termination-boot-strap var-counts1) : flag - var flg (local (defun-nx var-counts1-flg (flg rhs arg lst acc) (declare (xargs :verify-guards nil :normalize nil :measure (case flg (term (acl2-count rhs)) (otherwise (acl2-count lst))) :hints nil :well-founded-relation o< :mode :logic) (ignorable rhs arg lst acc)) (case flg (term (cond ((equal arg rhs) (+ 1 acc)) ((consp rhs) (cond ((equal 'quote (car rhs)) acc) ((equal (car rhs) 'if) (max (var-counts1-flg 'term (caddr rhs) arg nil acc) (var-counts1-flg 'term (cadddr rhs) arg nil acc))) (t (var-counts1-flg 'list nil arg (cdr rhs) acc)))) (t acc))) (otherwise (if (consp lst) (var-counts1-flg 'list nil arg (cdr lst) (var-counts1-flg 'term (car lst) arg nil acc)) acc))))) (local (defthm var-counts1-flg-equivalences (equal (var-counts1-flg flg rhs arg lst acc) (case flg (term (var-counts1 arg rhs acc)) (otherwise (var-counts1-lst arg lst acc)))))) (local (in-theory (disable (:definition var-counts1-flg)))) ( implies ( natp acc ) ( natp ( var - counts1 arg rhs acc ) ) ) ( implies ( natp acc ) ( natp ( var - counts1 - lst arg lst acc ) ) ) : hints ( ( " Goal " : induct ( var - counts1 - flg flg rhs arg lst acc ) ) ) ) (local (defthm natp-var-counts1 (case flg (term (implies (natp acc) (natp (var-counts1 arg rhs acc)))) (otherwise (implies (natp acc) (natp (var-counts1-lst arg lst acc))))) :hints (("Goal" :induct (var-counts1-flg flg rhs arg lst acc))) :rule-classes nil)) (local (defthm natp-var-counts1-term (implies (natp acc) (natp (var-counts1 arg rhs acc))) :use ((:instance natp-var-counts1 (flg 'term))))) :rule-classes :type-prescription)) (local (defthm natp-var-counts1-list (implies (natp acc) (natp (var-counts1-lst arg lst acc))) :use ((:instance natp-var-counts1 (flg 'list))))) :rule-classes :type-prescription)) (verify-guards var-counts1) nats as long as lhs - args , I prove those facts , speculatively . the commented - out definition of nat - listp in the source code ( file ( verify - termination nat - listp ) (local (defthm integer-listp-var-counts (integer-listp (var-counts lhs-args rhs)))) (local (defthm len-var-counts (equal (len (var-counts lhs-args rhs)) (len lhs-args)))) (local (defthm natp-expt (implies (and (integerp base) (integerp n) (<= 0 n)) (integerp (expt base n))) :rule-classes :type-prescription)) (verify-termination-boot-strap occur-cnt-bounded) : flag - var flg (local (defun-nx occur-cnt-bounded-flg (flg term2 term1 lst a m bound-m) (declare (xargs :verify-guards nil :normalize nil :measure (case flg (term (acl2-count term2)) (otherwise (acl2-count lst)))) (ignorable term2 term1 lst a m bound-m)) (case flg (term (cond ((equal term1 term2) (if (< bound-m a) -1 (+ a m))) ((consp term2) (if (equal 'quote (car term2)) a (occur-cnt-bounded-flg 'list nil term1 (cdr term2) a m bound-m))) (t a))) (otherwise (if (consp lst) (let ((new (occur-cnt-bounded-flg 'term (car lst) term1 nil a m bound-m))) (if (equal new -1) -1 (occur-cnt-bounded-flg 'list nil term1 (cdr lst) new m bound-m))) a))))) (local (defthm occur-cnt-bounded-flg-equivalences (equal (occur-cnt-bounded-flg flg term2 term1 lst a m bound-m) (case flg (term (occur-cnt-bounded term1 term2 a m bound-m)) (otherwise (occur-cnt-bounded-lst term1 lst a m bound-m)))))) (local (in-theory (disable (:definition occur-cnt-bounded-flg)))) ( defthm - occur - cnt - bounded integerp - occur - cnt - bounded ( integerp ( occur - cnt - bounded a m bound - m ) ) ) ( integerp ( occur - cnt - bounded - lst term1 lst a m bound - m ) ) ) : hints ( ( " Goal " : induct ( occur - cnt - bounded - flg flg lst a m (local (defthm integerp-occur-cnt-bounded (case flg (term (implies (and (integerp a) (integerp m)) (integerp (occur-cnt-bounded term1 term2 a m bound-m)))) (otherwise (implies (and (integerp a) (integerp m)) (integerp (occur-cnt-bounded-lst term1 lst a m bound-m))))) :rule-classes nil :hints (("Goal" :induct (occur-cnt-bounded-flg flg term2 term1 lst a m bound-m))))) (local (defthm integerp-occur-cnt-bounded-term (implies (and (integerp a) (integerp m)) (integerp (occur-cnt-bounded term1 term2 a m bound-m))) :rule-classes :type-prescription :use ((:instance integerp-occur-cnt-bounded (flg 'term))))))) (local (defthm integerp-occur-cnt-bounded-list (implies (and (integerp a) (integerp m)) (integerp (occur-cnt-bounded-lst term1 lst a m bound-m))) :rule-classes :type-prescription :use ((:instance integerp-occur-cnt-bounded (flg 'list))))))) ( and ( < = -1 ( occur - cnt - bounded a m bound - m ) ) ( < = ( occur - cnt - bounded a m bound - m ) ( + bound - m m ) ) ) ) : hints ( ( " Goal " : induct ( occur - cnt - bounded - flg flg lst a m (local (defthm signed-byte-p-30-occur-cnt-bounded-flg (case flg (term (implies (and (force (signed-byte-p 30 a)) (signed-byte-p 30 m) (signed-byte-p 30 (+ bound-m m)) (force (<= 0 a)) (<= 0 m) (<= 0 bound-m) (<= a (+ bound-m m))) (and (<= -1 (occur-cnt-bounded term1 term2 a m bound-m)) (<= (occur-cnt-bounded term1 term2 a m bound-m) (+ bound-m m))))) (otherwise (implies (and (force (signed-byte-p 30 a)) (signed-byte-p 30 m) (signed-byte-p 30 (+ bound-m m)) (force (<= 0 a)) (<= 0 m) (<= 0 bound-m) (<= a (+ bound-m m))) (and (<= -1 (occur-cnt-bounded-lst term1 lst a m bound-m)) (<= (occur-cnt-bounded-lst term1 lst a m bound-m) (+ bound-m m)))))) :rule-classes nil :hints (("Goal" :induct (occur-cnt-bounded-flg flg term2 term1 lst a m bound-m))))) (local (defthm signed-byte-p-30-occur-cnt-bounded-flg-term (implies (and (force (signed-byte-p 30 a)) (signed-byte-p 30 m) (signed-byte-p 30 (+ bound-m m)) (force (<= 0 a)) (<= 0 m) (<= 0 bound-m) (<= a (+ bound-m m))) (and (<= -1 (occur-cnt-bounded term1 term2 a m bound-m)) (<= (occur-cnt-bounded term1 term2 a m bound-m) (+ bound-m m)))) :rule-classes :linear :use ((:instance signed-byte-p-30-occur-cnt-bounded-flg (flg 'term))))))) (local (defthm signed-byte-p-30-occur-cnt-bounded-flg-list (implies (and (force (signed-byte-p 30 a)) (signed-byte-p 30 m) (signed-byte-p 30 (+ bound-m m)) (force (<= 0 a)) (<= 0 m) (<= 0 bound-m) (<= a (+ bound-m m))) (and (<= -1 (occur-cnt-bounded-lst term1 lst a m bound-m)) (<= (occur-cnt-bounded-lst term1 lst a m bound-m) (+ bound-m m)))) :rule-classes :linear :use ((:instance signed-byte-p-30-occur-cnt-bounded-flg (flg 'list))))))) (verify-guards occur-cnt-bounded) ) (defattach too-many-ifs-post-rewrite too-many-ifs-post-rewrite-builtin) #+acl2-loop-only The above readtime conditional avoids a CLISP warning , and lets the defproxy (encapsulate ((too-many-ifs-pre-rewrite (args counts) t :guard (and (pseudo-term-listp args) (integer-listp counts) (equal (len args) (len counts))))) (local (defun too-many-ifs-pre-rewrite (args counts) (list args counts)))) (defattach (too-many-ifs-pre-rewrite too-many-ifs-pre-rewrite-builtin)) (verify-termination-boot-strap pseudo-variantp) (verify-termination-boot-strap member-char-stringp) (verify-termination-boot-strap terminal-substringp1) (verify-termination-boot-strap terminal-substringp) (verify-termination-boot-strap evg-occur) (verify-termination-boot-strap min-fixnum) (declare (xargs :verify-guards nil))) (defthm fn-count-evg-rec-type-prescription (implies (natp acc) (natp (fn-count-evg-rec evg acc calls))) :rule-classes :type-prescription) (defthm fn-count-evg-rec-bound (< (fn-count-evg-rec evg acc calls) ( expt 2 29 ) :rule-classes :linear) (verify-guards fn-count-evg-rec) (verify-termination-boot-strap occur) and mut - rec nest (verify-termination-boot-strap worse-than-builtin) (verify-termination-boot-strap worse-than-or-equal-builtin) (verify-termination-boot-strap ancestor-listp) (verify-termination-boot-strap earlier-ancestor-biggerp) (defthm fn-count-1-type (implies (and (integerp fn-count-acc) (integerp p-fn-count-acc)) (and (integerp (car (fn-count-1 flag term fn-count-acc p-fn-count-acc))) (integerp (mv-nth 0 (fn-count-1 flag term fn-count-acc p-fn-count-acc))) (integerp (mv-nth 1 (fn-count-1 flag term fn-count-acc p-fn-count-acc))) (integerp (nth 0 (fn-count-1 flag term fn-count-acc p-fn-count-acc))) (integerp (nth 1 (fn-count-1 flag term fn-count-acc p-fn-count-acc))))) :rule-classes ((:forward-chaining :trigger-terms ((fn-count-1 flag term fn-count-acc p-fn-count-acc))))) (verify-guards fn-count-1) (defthm symbol-listp-cdr-assoc-equal (implies (symbol-list-listp x) (symbol-listp (cdr (assoc-equal key x))))) We state the following three rules in all forms that we think might be useful (defthm integerp-nth-0-var-fn-count-1 (implies (integerp var-count-acc) (integerp (nth 0 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))) :rule-classes ((:forward-chaining :trigger-terms ((var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)) :corollary (implies (integerp var-count-acc) (and (integerp (nth 0 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table))) (integerp (mv-nth 0 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table))) (integerp (car (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))))))) (defthm integerp-nth-1-var-fn-count-1 (implies (integerp fn-count-acc) (integerp (nth 1 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))) :rule-classes ((:forward-chaining :trigger-terms ((var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)) :corollary (implies (integerp fn-count-acc) (and (integerp (nth 1 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table))) (integerp (mv-nth 1 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))))))) (defthm integerp-nth-2-var-fn-count-1 (implies (integerp p-fn-count-acc) (integerp (nth 2 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))) :rule-classes ((:forward-chaining :trigger-terms ((var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)) :corollary (implies (integerp p-fn-count-acc) (and (integerp (nth 2 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table))) (integerp (mv-nth 2 (var-fn-count-1 flg x var-count-acc fn-count-acc p-fn-count-acc invisible-fns invisible-fns-table)))))))) (verify-guards var-fn-count-1) (verify-termination-boot-strap ancestors-check1) (verify-termination-boot-strap ancestors-check-builtin) (defun member-equal-mod-commuting (x lst wrld) (declare (xargs :guard (and (pseudo-termp x) (pseudo-term-listp lst) (plist-worldp wrld)))) (cond ((endp lst) nil) ((equal-mod-commuting x (car lst) wrld) lst) (t (member-equal-mod-commuting x (cdr lst) wrld)))) In the following , terms ( nth 0 ... ) and ( nth 1 ... ) in the hints were originally ( car ... ) and ( mv - nth 1 ... ) , respectively , but those did n't (defun strip-ancestor-literals (ancestors) (declare (xargs :guard (ancestor-listp ancestors))) (cond ((endp ancestors) nil) (t (cons (access ancestor (car ancestors) :lit) (strip-ancestor-literals (cdr ancestors)))))) (encapsulate () (local (defthm ancestors-check1-property (mv-let (on-ancestors assumed-true) (ancestors-check1 lit-atm lit var-cnt fn-cnt p-fn-cnt ancestors tokens) (implies (and on-ancestors assumed-true) (member-equal-mod-commuting lit (strip-ancestor-literals ancestors) nil))) :rule-classes nil)) (defthmd ancestors-check-builtin-property (mv-let (on-ancestors assumed-true) (ancestors-check-builtin lit ancestors tokens) (implies (and on-ancestors assumed-true) (member-equal-mod-commuting lit (strip-ancestor-literals ancestors) nil))) :hints (("Goal" :use ((:instance ancestors-check1-property (lit-atm lit) (var-cnt 0) (fn-cnt 0) (p-fn-cnt 0)) (:instance ancestors-check1-property (lit-atm lit) (var-cnt (nth 0 (var-fn-count-1 nil lit 0 0 0 nil nil))) (fn-cnt (nth 1 (var-fn-count-1 nil lit 0 0 0 nil nil))) (p-fn-cnt (nth 2 (var-fn-count-1 nil lit 0 0 0 nil nil)))) (:instance ancestors-check1-property (lit-atm (cadr lit)) (var-cnt (nth 0 (var-fn-count-1 nil (cadr lit) 0 0 0 nil nil))) (fn-cnt (nth 1 (var-fn-count-1 nil (cadr lit) 0 0 0 nil nil))) (p-fn-cnt (nth 2 (var-fn-count-1 nil (cadr lit) 0 0 0 nil nil))))))))) #+acl2-loop-only The above readtime conditional avoids a CLISP warning , and lets the defproxy (encapsulate ((ancestors-check (lit ancestors tokens) (mv t t) :guard (and (pseudo-termp lit) (ancestor-listp ancestors) (true-listp tokens)))) (local (defun ancestors-check (lit ancestors tokens) (ancestors-check-builtin lit ancestors tokens))) (defthmd ancestors-check-constraint (implies (and (pseudo-termp lit) (ancestor-listp ancestors) (true-listp tokens)) (mv-let (on-ancestors assumed-true) (ancestors-check lit ancestors tokens) (implies (and on-ancestors assumed-true) (member-equal-mod-commuting lit (strip-ancestor-literals ancestors) nil)))) :hints (("Goal" :use ancestors-check-builtin-property)))) (defattach (ancestors-check ancestors-check-builtin) :hints (("Goal" :by ancestors-check-builtin-property))) (defattach worse-than worse-than-builtin) (defattach worse-than-or-equal worse-than-or-equal-builtin) (defattach (acl2x-expansion-alist identity-with-state)) (defattach rw-cache-debug rw-cache-debug-builtin) (defattach rw-cache-debug-action rw-cache-debug-action-builtin) (defattach rw-cacheable-failure-reason rw-cacheable-failure-reason-builtin) (d-pos-listp (declare (xargs :guard-hints (("Goal" :use ((:instance coerce-inverse-2 (x (symbol-name (car lst)))) (:instance character-listp-coerce (str (symbol-name (car lst))))) :expand ((len (coerce (symbol-name (car lst)) 'list))) :in-theory (disable coerce-inverse-2 character-listp-coerce))))))) (verify-termination-boot-strap pos-listp) (verify-guards pos-listp) (defthm d-pos-listp-forward-to-true-listp (implies (d-pos-listp x) (true-listp x)) :rule-classes :forward-chaining) #+acl2-loop-only The above readtime conditional avoids a CLISP warning , and lets the defproxy (encapsulate (((print-clause-id-okp *) => * :formals (cl-id) :guard (clause-id-p cl-id))) (local (defun print-clause-id-okp (x) x))) (defattach print-clause-id-okp print-clause-id-okp-builtin) ( defproxy oncep - tp ( * * ) = > * ) #+acl2-loop-only The above readtime conditional avoids a CLISP warning , and lets the defproxy (encapsulate (((oncep-tp * *) => * :formals (rune wrld) :guard (and (plist-worldp wrld) (and (consp rune) (consp (cdr rune)) (symbolp (cadr rune)))))) (logic) (local (defun oncep-tp (rune wrld) (oncep-tp-builtin rune wrld)))) (defattach oncep-tp oncep-tp-builtin) proved termination and guards for already proved locally in axioms.lisp . So we made that defthm non - local ( and (verify-termination-boot-strap chars-for-tilde-@-clause-id-phrase/periods) (verify-termination-boot-strap chars-for-tilde-@-clause-id-phrase/primes) (defthm pos-listp-forward-to-integer-listp (implies (pos-listp x) (integer-listp x)) :rule-classes :forward-chaining) (verify-termination-boot-strap chars-for-tilde-@-clause-id-phrase) (defthm true-listp-chars-for-tilde-@-clause-id-phrase/periods (true-listp (chars-for-tilde-@-clause-id-phrase/periods lst)) :rule-classes :type-prescription) (defthm true-listp-explode-atom (true-listp (explode-atom n print-base)) :rule-classes :type-prescription) (encapsulate () (local (defthm character-listp-explode-nonnegative-integer (implies (character-listp ans) (character-listp (explode-nonnegative-integer n print-base ans))))) (local (defthm character-listp-explode-atom (character-listp (explode-atom n print-base)) need to disable this local lemma from axioms.lisp (("Goal" :in-theory (disable character-listp-cdr))))) (local (defthm character-listp-chars-for-tilde-@-clause-id-phrase/periods (character-listp (chars-for-tilde-@-clause-id-phrase/periods lst)))) (verify-termination-boot-strap string-for-tilde-@-clause-id-phrase)) (verify-termination-boot-strap strict-merge-symbol< (declare (xargs :measure (+ (len l1) (len l2))))) (encapsulate () (local (defthm len-strict-merge-symbol< (<= (len (strict-merge-symbol< l1 l2 acc)) (+ (len l1) (len l2) (len acc))) :rule-classes :linear)) (local (defthm len-evens (equal (len l) (+ (len (evens l)) (len (odds l)))) :rule-classes :linear)) (local (defthm symbol-listp-evens (implies (symbol-listp x) (symbol-listp (evens x))) :hints (("Goal" :induct (evens x))))) (local (defthm symbol-listp-odds (implies (symbol-listp x) (symbol-listp (odds x))))) (local (defthm symbol-listp-strict-merge-symbol< (implies (and (symbol-listp l1) (symbol-listp l2) (symbol-listp acc)) (symbol-listp (strict-merge-symbol< l1 l2 acc))))) (verify-termination-boot-strap strict-merge-sort-symbol< (declare (xargs :measure (len l) :verify-guards nil))) (defthm symbol-listp-strict-merge-sort-symbol< (implies (symbol-listp x) (symbol-listp (strict-merge-sort-symbol< x)))) (verify-guards strict-merge-sort-symbol<) ) (verify-termination-boot-strap set-ld-history-entry-user-data-default) (defattach set-ld-history-entry-user-data set-ld-history-entry-user-data-default) (deftheory definition-minimal-theory (definition-runes *definition-minimal-theory* nil world)) (deftheory executable-counterpart-minimal-theory (definition-runes *built-in-executable-counterparts* t world)) (deftheory minimal-theory (union-theories (theory 'definition-minimal-theory) (union-theories for example in case it 's useful for linear arithmetic . '((:executable-counterpart force)) (theory 'executable-counterpart-minimal-theory)))) (defconst *acl2-primitives* (strip-cars *primitive-formals-and-guards*)) (deftheory acl2-primitives (definition-runes *acl2-primitives* nil world)) in axioms.lisp where we discuss choices ( 1.a ) , ( 1.b ) , ( 2.a ) and ( 2.b ) (enable (:executable-counterpart tau-system)) (disable (:executable-counterpart tau-system)))) Avoid ugly output from , e.g. , ( thm ( equal ( print - call - history ) 3 ) ) . (in-theory (disable (:e print-call-history))) observed significant speed - up from the following disable . (in-theory (disable ctxp)) (defund meta-extract-formula (name state) (declare (xargs :stobjs state :guard (symbolp name))) (let ((wrld (w state))) (or (getpropc name 'theorem nil wrld) (cond ((logicp name wrld) (mv-let (flg prop) (constraint-info name wrld) (cond ((unknown-constraints-p prop) *t*) (flg (ec-call (conjoin prop))) (t prop)))) (t *t*))))) (verify-termination-boot-strap type-set-quote) (verify-guards type-set-quote) (defun typespec-check (ts x) (declare (xargs :guard (integerp ts))) (if (bad-atom x) here , but for that we need a stronger guard than ( integerp ts ) , and we prefer (not (eql 0 (logand (type-set-quote x) ts))))) (defun meta-extract-rw+-term (term alist equiv rhs state) Meta - extract - rw+-term creates ( logically ) a term claiming that term under :stobjs state :guard (and (symbol-alistp alist) (pseudo-term-listp (strip-cdrs alist)) (pseudo-termp term)))) (non-exec (let ((lhs (sublis-var alist term))) (case equiv ((nil) `(equal ,lhs ,rhs)) ((t) `(iff ,lhs ,rhs)) (otherwise (if (symbolp equiv) (if (equivalence-relationp equiv (w state)) `(,equiv ,lhs ,rhs) *t*) *t*)))))) (defun meta-extract-contextual-fact (obj mfc state) it always produces a term that evaluates to non - nil under the where the ( evl x a ) = ( evl ( ) a ) . The terms it produces reflect the and typeset information , rewriting , and linear arithmetic . See the Essay on in ( not in state ) . :stobjs state)) (non-exec (case-match obj `(typespec-check ',(mfc-ts term mfc state :forcep nil :ttreep nil) ,term)) (meta-extract-rw+-term term alist equiv (mfc-rw+ term alist obj equiv mfc state :forcep nil :ttreep nil) state)) (meta-extract-rw+-term term nil equiv (mfc-rw term obj equiv mfc state :forcep nil :ttreep nil) state)) (if (mfc-ap term mfc state :forcep nil) `(not ,term) *t*)) (if (mfc-relieve-hyp hyp alist rune target bkptr mfc state :forcep nil :ttreep nil) (sublis-var alist hyp) *t*)) (& *t*)))) (defun rewrite-rule-term-exec (x) (declare (xargs :guard (and (weak-rewrite-rule-p x) (or (eq (access rewrite-rule x :subclass) 'meta) (true-listp (access rewrite-rule x :hyps)))))) (if (eq (access rewrite-rule x :subclass) 'meta) *t* `(implies ,(conjoin (access rewrite-rule x :hyps)) (,(access rewrite-rule x :equiv) ,(access rewrite-rule x :lhs) ,(access rewrite-rule x :rhs))))) (defun rewrite-rule-term (x) (declare (xargs :guard t)) (ec-call (rewrite-rule-term-exec x))) (defun linear-lemma-term-exec (x) (declare (xargs :guard (and (weak-linear-lemma-p x) (true-listp (access linear-lemma x :hyps))))) `(implies ,(conjoin (access linear-lemma x :hyps)) ,(access linear-lemma x :concl))) (defun linear-lemma-term (x) (declare (xargs :guard t)) (ec-call (linear-lemma-term-exec x))) (defmacro meta-extract-global-fact (obj state) `(meta-extract-global-fact+ ,obj ,state ,state)) (defun fncall-term (fn arglist state) (declare (xargs :stobjs state :guard (and (symbolp fn) (true-listp arglist)))) (cond ((logicp fn (w state)) (mv-let (erp val) (magic-ev-fncall fn arglist state ) (cond (erp *t*) (t (fcons-term* 'equal As suggested by , we use fcons - term below in order to avoid having (fcons-term fn (kwote-lst arglist)) (kwote val)))))) (t *t*))) (defun logically-equivalent-states (st1 st2) (declare (xargs :guard t)) (non-exec (equal (w st1) (w st2)))) (defun meta-extract-global-fact+ (obj st state) :stobjs state)) (non-exec (cond ((logically-equivalent-states st state) (case-match obj ((':formula name) (meta-extract-formula name st)) ((':lemma fn n) (let* ((lemmas (getpropc fn 'lemmas nil (w st))) (rule (nth n lemmas))) The use of rewrite - rule - term below relies on the fact that the ' LEMMAS (if (< (nfix n) (len lemmas)) (rewrite-rule-term rule) ((':linear-lemma fn n) (let* ((lemmas (getpropc fn 'linear-lemmas nil (w st))) (rule (nth n lemmas))) (if (< (nfix n) (len lemmas)) (linear-lemma-term rule) *t*))) ((':fncall fn arglist) (fncall-term fn arglist st))) (& *t*))) (t *t*)))) (add-macro-alias meta-extract-global-fact meta-extract-global-fact+) It would be more natural to define these in axioms.lisp , but the defun - nx (defun-nx read-user-stobj-alist (st state) (declare (xargs :guard (symbolp st) :stobjs state)) (cdr (assoc-eq st (user-stobj-alist1 state)))) #-acl2-loop-only (defun read-user-stobj-alist-raw (st state) (cond ((live-state-p state) (cdr (assoc-eq st *user-stobj-alist*))) (error "Illegal call of read-user-stobj-alist: State argument is not ~ the `live' ACL2 state.")))) (defun-nx write-user-stobj-alist (st val state) (declare (xargs :guard (symbolp st) :stobjs state)) (update-user-stobj-alist1 (put-assoc-eq st val (user-stobj-alist1 state)) state)) #-acl2-loop-only (defun write-user-stobj-alist-raw (st val state) (cond (*wormholep* (wormhole-er 'write-user-stobj-alist (list st val 'state))) ((live-state-p state) (loop for pair of-type cons in *user-stobj-alist* when (eq (car pair) st) do (progn (or (eq (cdr pair) val) (setf (cdr pair) val)) (return state)) finally (error "Unknown stobj, ~s" st))) (t (error "Illegal call of write-user-stobj-alist: State argument is not the ~ `live' ACL2 state."))))
1e20129470381ed8ee87a24b0f0dd3b41135c83b90fb79aa6d201f8daee43709
ruisb/LambdaPi
Parser.hs
module LambdaPi.Parser where import LambdaPi.Types import LambdaPi.Functions import Interpreter.Types import Data.List -- parser imports import Text.ParserCombinators.Parsec hiding (parse, State) import qualified Text.ParserCombinators.Parsec as P import Text.ParserCombinators.Parsec.Token import Text.ParserCombinators.Parsec.Language ------------------------------------------------------------------------------- -- Parse the core language. ------------------------------------------------------------------------------- lambdaPi = makeTokenParser (haskellStyle { identStart = letter <|> P.char '_', reservedNames = ["forall" , "let" , "assume" , "putStrLn" , "out" , "data" -- data declaration. FIXME needed ? ] }) parseStmt :: [String] -> CharParser () (Stmt ITerm CTerm) parseStmt e = do reserved lambdaPi "data" name <- identifier lambdaPi -- name of the data reserved lambdaPi "::" FIXME this ok ? reserved lambdaPi "where" ctors <- parseDataCtors e return (DataDecl (DataInfo name t ctors)) <|> do reserved lambdaPi "let" x <- identifier lambdaPi -- name of the var reserved lambdaPi "=" t <- parseITerm 0 e return (Let x t) <|> do reserved lambdaPi "assume" (xs, ts) <- parseBindings False [] return (Assume (reverse (zip xs ts))) <|> do reserved lambdaPi "putStrLn" x <- stringLiteral lambdaPi return (PutStrLn x) <|> do reserved lambdaPi "out" x <- option "" (stringLiteral lambdaPi) return (Out x) <|> fmap Eval (parseITerm 0 e) Parse the constructors of a data type . parseDataCtors :: [String] -> CharParser () [(String,CTerm)] parseDataCtors e = do m <- sepBy ( do name <- identifier lambdaPi -- name of the data reserved lambdaPi "::" FIXME this ok ? return (name, t)) FIXME temp with , seperated return m parseBindings :: Bool -> [String] -> CharParser () ([String], [CTerm]) parseBindings b e = (let rec :: [String] -> [CTerm] -> CharParser () ([String], [CTerm]) rec e ts = do (x,t) <- parens lambdaPi (do x <- identifier lambdaPi reserved lambdaPi "::" t <- parseCTerm 0 (if b then e else []) return (x,t)) (rec (x : e) (t : ts) <|> return (x : e, t : ts)) in rec e []) <|> do x <- identifier lambdaPi reserved lambdaPi "::" t <- parseCTerm 0 e return (x : e, [t]) parseITerm :: Int -> [String] -> CharParser () ITerm parseITerm 0 e = do reserved lambdaPi "forall" (vn:vns,t:ts) <- parseBindings True e reserved lambdaPi "." t' <- parseCTerm 0 (vn:vns) return (foldl (\ p (vn,t) -> Pi vn t (Inf p)) (Pi vn t t') (zip vns ts)) <|> try (do t <- parseITerm 1 e rest (Inf t) <|> return t) <|> do t <- parens lambdaPi (parseLam e) rest t where rest t = do reserved lambdaPi "->" t' <- parseCTerm 0 ([]:e) return (Pi "_" t t') parseITerm 1 e = try (do t <- parseITerm 2 e rest (Inf t) <|> return t) <|> do t <- parens lambdaPi (parseLam e) rest t where rest t = do reserved lambdaPi "::" t' <- parseCTerm 0 e return (Ann t t') parseITerm 2 e = do t <- parseITerm 3 e ts <- many (parseCTerm 3 e) return (foldl (:$:) t ts) parseITerm 3 e = do reserved lambdaPi "*" return Star <|> do n <- natural lambdaPi return (toNat n) <|> do x <- identifier lambdaPi case findIndex (== x) e of Just n -> return (Bound n) Nothing -> return (Free x) <|> parens lambdaPi (parseITerm 0 e) parseCTerm :: Int -> [String] -> CharParser () CTerm parseCTerm 0 e = parseLam e <|> fmap Inf (parseITerm 0 e) parseCTerm p e = try (parens lambdaPi (parseLam e)) <|> fmap Inf (parseITerm p e) parseLam :: [String] -> CharParser () CTerm parseLam e = do reservedOp lambdaPi "\\" xs <- many1 (identifier lambdaPi) reservedOp lambdaPi "->" t <- parseCTerm 0 (reverse xs ++ e) -- reserved lambdaPi "." CHANGED return ( iterate t ! ! length xs ) return (foldr ($) t (map Lam xs)) toNat :: Integer -> ITerm toNat 0 = Free zeronm toNat n = Free succnm :$: Inf (toNat (n - 1)) parseIO :: String -> CharParser () a -> String -> IO (Maybe a) parseIO f p x = case P.parse (whiteSpace lambdaPi >> p >>= \ x -> eof >> return x) f x of Left e -> putStrLn (show e) >> return Nothing Right r -> return (Just r)
null
https://raw.githubusercontent.com/ruisb/LambdaPi/e8aea47b7098407f6ec3abb8ad65ac0c70729bf8/LambdaPi/Parser.hs
haskell
parser imports ----------------------------------------------------------------------------- Parse the core language. ----------------------------------------------------------------------------- data declaration. name of the data name of the var name of the data reserved lambdaPi "."
module LambdaPi.Parser where import LambdaPi.Types import LambdaPi.Functions import Interpreter.Types import Data.List import Text.ParserCombinators.Parsec hiding (parse, State) import qualified Text.ParserCombinators.Parsec as P import Text.ParserCombinators.Parsec.Token import Text.ParserCombinators.Parsec.Language lambdaPi = makeTokenParser (haskellStyle { identStart = letter <|> P.char '_', reservedNames = ["forall" , "let" , "assume" , "putStrLn" , "out" FIXME needed ? ] }) parseStmt :: [String] -> CharParser () (Stmt ITerm CTerm) parseStmt e = do reserved lambdaPi "data" reserved lambdaPi "::" FIXME this ok ? reserved lambdaPi "where" ctors <- parseDataCtors e return (DataDecl (DataInfo name t ctors)) <|> do reserved lambdaPi "let" reserved lambdaPi "=" t <- parseITerm 0 e return (Let x t) <|> do reserved lambdaPi "assume" (xs, ts) <- parseBindings False [] return (Assume (reverse (zip xs ts))) <|> do reserved lambdaPi "putStrLn" x <- stringLiteral lambdaPi return (PutStrLn x) <|> do reserved lambdaPi "out" x <- option "" (stringLiteral lambdaPi) return (Out x) <|> fmap Eval (parseITerm 0 e) Parse the constructors of a data type . parseDataCtors :: [String] -> CharParser () [(String,CTerm)] parseDataCtors e = do m <- sepBy ( do reserved lambdaPi "::" FIXME this ok ? return (name, t)) FIXME temp with , seperated return m parseBindings :: Bool -> [String] -> CharParser () ([String], [CTerm]) parseBindings b e = (let rec :: [String] -> [CTerm] -> CharParser () ([String], [CTerm]) rec e ts = do (x,t) <- parens lambdaPi (do x <- identifier lambdaPi reserved lambdaPi "::" t <- parseCTerm 0 (if b then e else []) return (x,t)) (rec (x : e) (t : ts) <|> return (x : e, t : ts)) in rec e []) <|> do x <- identifier lambdaPi reserved lambdaPi "::" t <- parseCTerm 0 e return (x : e, [t]) parseITerm :: Int -> [String] -> CharParser () ITerm parseITerm 0 e = do reserved lambdaPi "forall" (vn:vns,t:ts) <- parseBindings True e reserved lambdaPi "." t' <- parseCTerm 0 (vn:vns) return (foldl (\ p (vn,t) -> Pi vn t (Inf p)) (Pi vn t t') (zip vns ts)) <|> try (do t <- parseITerm 1 e rest (Inf t) <|> return t) <|> do t <- parens lambdaPi (parseLam e) rest t where rest t = do reserved lambdaPi "->" t' <- parseCTerm 0 ([]:e) return (Pi "_" t t') parseITerm 1 e = try (do t <- parseITerm 2 e rest (Inf t) <|> return t) <|> do t <- parens lambdaPi (parseLam e) rest t where rest t = do reserved lambdaPi "::" t' <- parseCTerm 0 e return (Ann t t') parseITerm 2 e = do t <- parseITerm 3 e ts <- many (parseCTerm 3 e) return (foldl (:$:) t ts) parseITerm 3 e = do reserved lambdaPi "*" return Star <|> do n <- natural lambdaPi return (toNat n) <|> do x <- identifier lambdaPi case findIndex (== x) e of Just n -> return (Bound n) Nothing -> return (Free x) <|> parens lambdaPi (parseITerm 0 e) parseCTerm :: Int -> [String] -> CharParser () CTerm parseCTerm 0 e = parseLam e <|> fmap Inf (parseITerm 0 e) parseCTerm p e = try (parens lambdaPi (parseLam e)) <|> fmap Inf (parseITerm p e) parseLam :: [String] -> CharParser () CTerm parseLam e = do reservedOp lambdaPi "\\" xs <- many1 (identifier lambdaPi) reservedOp lambdaPi "->" t <- parseCTerm 0 (reverse xs ++ e) CHANGED return ( iterate t ! ! length xs ) return (foldr ($) t (map Lam xs)) toNat :: Integer -> ITerm toNat 0 = Free zeronm toNat n = Free succnm :$: Inf (toNat (n - 1)) parseIO :: String -> CharParser () a -> String -> IO (Maybe a) parseIO f p x = case P.parse (whiteSpace lambdaPi >> p >>= \ x -> eof >> return x) f x of Left e -> putStrLn (show e) >> return Nothing Right r -> return (Just r)
b754219cb3f6a73ed05f5d0e2fe487607b1dcd72ab3983a1e09c41703a1bd9b6
clojure-interop/java-jdk
BasicIconFactory.clj
(ns javax.swing.plaf.basic.BasicIconFactory "Factory object that can vend Icons appropriate for the basic L & F. Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans™ has been added to the java.beans package. Please see XMLEncoder." (:refer-clojure :only [require comment defn ->]) (:import [javax.swing.plaf.basic BasicIconFactory])) (defn ->basic-icon-factory "Constructor." (^BasicIconFactory [] (new BasicIconFactory ))) (defn *get-menu-item-check-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getMenuItemCheckIcon ))) (defn *get-menu-item-arrow-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getMenuItemArrowIcon ))) (defn *get-menu-arrow-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getMenuArrowIcon ))) (defn *get-check-box-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getCheckBoxIcon ))) (defn *get-radio-button-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getRadioButtonIcon ))) (defn *get-check-box-menu-item-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getCheckBoxMenuItemIcon ))) (defn *get-radio-button-menu-item-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getRadioButtonMenuItemIcon ))) (defn *create-empty-frame-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/createEmptyFrameIcon )))
null
https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.swing/src/javax/swing/plaf/basic/BasicIconFactory.clj
clojure
(ns javax.swing.plaf.basic.BasicIconFactory "Factory object that can vend Icons appropriate for the basic L & F. Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans™ has been added to the java.beans package. Please see XMLEncoder." (:refer-clojure :only [require comment defn ->]) (:import [javax.swing.plaf.basic BasicIconFactory])) (defn ->basic-icon-factory "Constructor." (^BasicIconFactory [] (new BasicIconFactory ))) (defn *get-menu-item-check-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getMenuItemCheckIcon ))) (defn *get-menu-item-arrow-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getMenuItemArrowIcon ))) (defn *get-menu-arrow-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getMenuArrowIcon ))) (defn *get-check-box-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getCheckBoxIcon ))) (defn *get-radio-button-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getRadioButtonIcon ))) (defn *get-check-box-menu-item-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getCheckBoxMenuItemIcon ))) (defn *get-radio-button-menu-item-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/getRadioButtonMenuItemIcon ))) (defn *create-empty-frame-icon "returns: `javax.swing.Icon`" (^javax.swing.Icon [] (BasicIconFactory/createEmptyFrameIcon )))
3fed10a9fd52d246c993ca948ba35e85075909a49ddb3ad1c6ec9e1f00ef2a78
MyDataFlow/ttalk-server
ct_expand.erl
The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %%% compliance with the License. You may obtain a copy of the License at %%% %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% The Original Code is exprecs-0.2 . %% The Initial Developer of the Original Code is Ericsson AB . Portions created by Ericsson are Copyright ( C ) , 2006 , Ericsson AB . All Rights Reserved . %% %% Contributor(s): ______________________________________. %%------------------------------------------------------------------- %% File : ct_expand.erl @author : %% @end %% Description : %% Created : 7 Apr 2010 by %%------------------------------------------------------------------- %% @doc Compile-time expansion utility %% %% This module serves as an example of parse_trans-based transforms, %% but might also be a useful utility in its own right. %% The transform searches for calls to the pseudo-function ` ct_expand : ) ' , and then replaces the call site with the result of evaluating ' at compile - time . %% %% For example, the line %% %% `ct_expand:term(lists:sort([3,5,2,1,4]))' %% would be expanded at compile - time to ` [ 1,2,3,4,5 ] ' . %% %% ct_expand has now been extended to also evaluate calls to local functions. %% See examples/ct_expand_test.erl for some examples. %% %% A debugging facility exists: passing the option {ct_expand_trace, Flags} as an option, %% or adding a compiler attribute -ct_expand_trace(Flags) will enable a form of call trace. %% %% `Flags' can be `[]' (no trace) or `[F]', where `F' is `c' (call trace), %% `r' (return trace), or `x' (exception trace)'. %% %% @end -module(ct_expand). -export([parse_transform/2]). -export([extract_fun/3, lfun_rewrite/2]). -type form() :: any(). -type forms() :: [form()]. -type options() :: [{atom(), any()}]. -spec parse_transform(forms(), options()) -> forms(). parse_transform(Forms, Options) -> Trace = ct_trace_opt(Options, Forms), case parse_trans:depth_first(fun(T,F,C,A) -> xform_fun(T,F,C,A,Forms, Trace) end, [], Forms, Options) of {error, Es} -> Es ++ Forms; {NewForms, _} -> parse_trans:revert(NewForms) end. ct_trace_opt(Options, Forms) -> case proplists:get_value(ct_expand_trace, Options) of undefined -> case [Opt || {attribute,_,ct_expand_trace,Opt} <- Forms] of [] -> []; [_|_] = L -> lists:last(L) end; Flags when is_list(Flags) -> Flags end. xform_fun(application, Form, _Ctxt, Acc, Forms, Trace) -> MFA = erl_syntax_lib:analyze_application(Form), case MFA of {?MODULE, {term, 1}} -> LFH = fun(Name, Args, Bs) -> eval_lfun( extract_fun(Name, length(Args), Forms), Args, Bs, Forms, Trace) end, Args = erl_syntax:application_arguments(Form), RevArgs = parse_trans:revert(Args), case erl_eval:exprs(RevArgs, [], {eval, LFH}) of {value, Value,[]} -> {abstract(Value), Acc}; Other -> parse_trans:error(cannot_evaluate,?LINE, [{expr, RevArgs}, {error, Other}]) end; _ -> {Form, Acc} end; xform_fun(_, Form, _Ctxt, Acc, _, _) -> {Form, Acc}. extract_fun(Name, Arity, Forms) -> case [F_ || {function,_,N_,A_,_Cs} = F_ <- Forms, N_ == Name, A_ == Arity] of [] -> erlang:error({undef, [{Name, Arity}]}); [FForm] -> FForm end. eval_lfun({function,L,F,_,Clauses}, Args, Bs, Forms, Trace) -> try begin {ArgsV, Bs1} = lists:mapfoldl( fun(A, Bs_) -> {value,AV,Bs1_} = erl_eval:expr(A, Bs_, lfh(Forms, Trace)), {abstract(AV), Bs1_} end, Bs, Args), Expr = {call, L, {'fun', L, {clauses, lfun_rewrite(Clauses, Forms)}}, ArgsV}, call_trace(Trace =/= [], L, F, ArgsV), {value, Ret, _} = erl_eval:expr(Expr, erl_eval:new_bindings(), lfh(Forms, Trace)), ret_trace(lists:member(r, Trace) orelse lists:member(x, Trace), L, F, Args, Ret), %% restore bindings {value, Ret, Bs1} end catch error:Err -> exception_trace(lists:member(x, Trace), L, F, Args, Err), error(Err) end. lfh(Forms, Trace) -> {eval, fun(Name, As, Bs1) -> eval_lfun( extract_fun(Name, length(As), Forms), As, Bs1, Forms, Trace) end}. call_trace(false, _, _, _) -> ok; call_trace(true, L, F, As) -> io:fwrite("ct_expand (~w): call ~s~n", [L, pp_function(F, As)]). pp_function(F, []) -> atom_to_list(F) ++ "()"; pp_function(F, [A|As]) -> lists:flatten([atom_to_list(F), "(", [io_lib:fwrite("~w", [erl_parse:normalise(A)]) | [[",", io_lib:fwrite("~w", [erl_parse:normalise(A_)])] || A_ <- As]], ")"]). ret_trace(false, _, _, _, _) -> ok; ret_trace(true, L, F, Args, Res) -> io:fwrite("ct_expand (~w): returned from ~w/~w: ~w~n", [L, F, length(Args), Res]). exception_trace(false, _, _, _, _) -> ok; exception_trace(true, L, F, Args, Err) -> io:fwrite("ct_expand (~w): exception from ~w/~w: ~p~n", [L, F, length(Args), Err]). lfun_rewrite(Exprs, Forms) -> parse_trans:plain_transform( fun({'fun',L,{function,F,A}}) -> {function,_,_,_,Cs} = extract_fun(F, A, Forms), {'fun',L,{clauses, Cs}}; (_) -> continue end, Exprs). %% abstract/1 - modified from erl_eval:abstract/1: -type abstract_expr() :: term(). -spec abstract(Data) -> AbsTerm when Data :: term(), AbsTerm :: abstract_expr(). abstract(T) when is_function(T) -> case erlang:fun_info(T, module) of {module, erl_eval} -> case erl_eval:fun_data(T) of {fun_data, _Imports, Clauses} -> {'fun', 0, {clauses, Clauses}}; false -> mimicking erl_parse : ) end; _ -> erlang:error(function_clause) end; abstract(T) when is_integer(T) -> {integer,0,T}; abstract(T) when is_float(T) -> {float,0,T}; abstract(T) when is_atom(T) -> {atom,0,T}; abstract([]) -> {nil,0}; abstract(B) when is_bitstring(B) -> {bin, 0, [abstract_byte(Byte, 0) || Byte <- bitstring_to_list(B)]}; abstract([C|T]) when is_integer(C), 0 =< C, C < 256 -> abstract_string(T, [C]); abstract([H|T]) -> {cons,0,abstract(H),abstract(T)}; abstract(Tuple) when is_tuple(Tuple) -> {tuple,0,abstract_list(tuple_to_list(Tuple))}. abstract_string([C|T], String) when is_integer(C), 0 =< C, C < 256 -> abstract_string(T, [C|String]); abstract_string([], String) -> {string, 0, lists:reverse(String)}; abstract_string(T, String) -> not_string(String, abstract(T)). not_string([C|T], Result) -> not_string(T, {cons, 0, {integer, 0, C}, Result}); not_string([], Result) -> Result. abstract_list([H|T]) -> [abstract(H)|abstract_list(T)]; abstract_list([]) -> []. abstract_byte(Byte, Line) when is_integer(Byte) -> {bin_element, Line, {integer, Line, Byte}, default, default}; abstract_byte(Bits, Line) -> Sz = bit_size(Bits), <<Val:Sz>> = Bits, {bin_element, Line, {integer, Line, Val}, {integer, Line, Sz}, default}.
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/parse_trans/src/ct_expand.erl
erlang
compliance with the License. You may obtain a copy of the License at basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Contributor(s): ______________________________________. ------------------------------------------------------------------- File : ct_expand.erl @end Description : ------------------------------------------------------------------- @doc Compile-time expansion utility This module serves as an example of parse_trans-based transforms, but might also be a useful utility in its own right. The transform searches for calls to the pseudo-function For example, the line `ct_expand:term(lists:sort([3,5,2,1,4]))' ct_expand has now been extended to also evaluate calls to local functions. See examples/ct_expand_test.erl for some examples. A debugging facility exists: passing the option {ct_expand_trace, Flags} as an option, or adding a compiler attribute -ct_expand_trace(Flags) will enable a form of call trace. `Flags' can be `[]' (no trace) or `[F]', where `F' is `c' (call trace), `r' (return trace), or `x' (exception trace)'. @end restore bindings abstract/1 - modified from erl_eval:abstract/1:
The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " The Original Code is exprecs-0.2 . The Initial Developer of the Original Code is Ericsson AB . Portions created by Ericsson are Copyright ( C ) , 2006 , Ericsson AB . All Rights Reserved . @author : Created : 7 Apr 2010 by ` ct_expand : ) ' , and then replaces the call site with the result of evaluating ' at compile - time . would be expanded at compile - time to ` [ 1,2,3,4,5 ] ' . -module(ct_expand). -export([parse_transform/2]). -export([extract_fun/3, lfun_rewrite/2]). -type form() :: any(). -type forms() :: [form()]. -type options() :: [{atom(), any()}]. -spec parse_transform(forms(), options()) -> forms(). parse_transform(Forms, Options) -> Trace = ct_trace_opt(Options, Forms), case parse_trans:depth_first(fun(T,F,C,A) -> xform_fun(T,F,C,A,Forms, Trace) end, [], Forms, Options) of {error, Es} -> Es ++ Forms; {NewForms, _} -> parse_trans:revert(NewForms) end. ct_trace_opt(Options, Forms) -> case proplists:get_value(ct_expand_trace, Options) of undefined -> case [Opt || {attribute,_,ct_expand_trace,Opt} <- Forms] of [] -> []; [_|_] = L -> lists:last(L) end; Flags when is_list(Flags) -> Flags end. xform_fun(application, Form, _Ctxt, Acc, Forms, Trace) -> MFA = erl_syntax_lib:analyze_application(Form), case MFA of {?MODULE, {term, 1}} -> LFH = fun(Name, Args, Bs) -> eval_lfun( extract_fun(Name, length(Args), Forms), Args, Bs, Forms, Trace) end, Args = erl_syntax:application_arguments(Form), RevArgs = parse_trans:revert(Args), case erl_eval:exprs(RevArgs, [], {eval, LFH}) of {value, Value,[]} -> {abstract(Value), Acc}; Other -> parse_trans:error(cannot_evaluate,?LINE, [{expr, RevArgs}, {error, Other}]) end; _ -> {Form, Acc} end; xform_fun(_, Form, _Ctxt, Acc, _, _) -> {Form, Acc}. extract_fun(Name, Arity, Forms) -> case [F_ || {function,_,N_,A_,_Cs} = F_ <- Forms, N_ == Name, A_ == Arity] of [] -> erlang:error({undef, [{Name, Arity}]}); [FForm] -> FForm end. eval_lfun({function,L,F,_,Clauses}, Args, Bs, Forms, Trace) -> try begin {ArgsV, Bs1} = lists:mapfoldl( fun(A, Bs_) -> {value,AV,Bs1_} = erl_eval:expr(A, Bs_, lfh(Forms, Trace)), {abstract(AV), Bs1_} end, Bs, Args), Expr = {call, L, {'fun', L, {clauses, lfun_rewrite(Clauses, Forms)}}, ArgsV}, call_trace(Trace =/= [], L, F, ArgsV), {value, Ret, _} = erl_eval:expr(Expr, erl_eval:new_bindings(), lfh(Forms, Trace)), ret_trace(lists:member(r, Trace) orelse lists:member(x, Trace), L, F, Args, Ret), {value, Ret, Bs1} end catch error:Err -> exception_trace(lists:member(x, Trace), L, F, Args, Err), error(Err) end. lfh(Forms, Trace) -> {eval, fun(Name, As, Bs1) -> eval_lfun( extract_fun(Name, length(As), Forms), As, Bs1, Forms, Trace) end}. call_trace(false, _, _, _) -> ok; call_trace(true, L, F, As) -> io:fwrite("ct_expand (~w): call ~s~n", [L, pp_function(F, As)]). pp_function(F, []) -> atom_to_list(F) ++ "()"; pp_function(F, [A|As]) -> lists:flatten([atom_to_list(F), "(", [io_lib:fwrite("~w", [erl_parse:normalise(A)]) | [[",", io_lib:fwrite("~w", [erl_parse:normalise(A_)])] || A_ <- As]], ")"]). ret_trace(false, _, _, _, _) -> ok; ret_trace(true, L, F, Args, Res) -> io:fwrite("ct_expand (~w): returned from ~w/~w: ~w~n", [L, F, length(Args), Res]). exception_trace(false, _, _, _, _) -> ok; exception_trace(true, L, F, Args, Err) -> io:fwrite("ct_expand (~w): exception from ~w/~w: ~p~n", [L, F, length(Args), Err]). lfun_rewrite(Exprs, Forms) -> parse_trans:plain_transform( fun({'fun',L,{function,F,A}}) -> {function,_,_,_,Cs} = extract_fun(F, A, Forms), {'fun',L,{clauses, Cs}}; (_) -> continue end, Exprs). -type abstract_expr() :: term(). -spec abstract(Data) -> AbsTerm when Data :: term(), AbsTerm :: abstract_expr(). abstract(T) when is_function(T) -> case erlang:fun_info(T, module) of {module, erl_eval} -> case erl_eval:fun_data(T) of {fun_data, _Imports, Clauses} -> {'fun', 0, {clauses, Clauses}}; false -> mimicking erl_parse : ) end; _ -> erlang:error(function_clause) end; abstract(T) when is_integer(T) -> {integer,0,T}; abstract(T) when is_float(T) -> {float,0,T}; abstract(T) when is_atom(T) -> {atom,0,T}; abstract([]) -> {nil,0}; abstract(B) when is_bitstring(B) -> {bin, 0, [abstract_byte(Byte, 0) || Byte <- bitstring_to_list(B)]}; abstract([C|T]) when is_integer(C), 0 =< C, C < 256 -> abstract_string(T, [C]); abstract([H|T]) -> {cons,0,abstract(H),abstract(T)}; abstract(Tuple) when is_tuple(Tuple) -> {tuple,0,abstract_list(tuple_to_list(Tuple))}. abstract_string([C|T], String) when is_integer(C), 0 =< C, C < 256 -> abstract_string(T, [C|String]); abstract_string([], String) -> {string, 0, lists:reverse(String)}; abstract_string(T, String) -> not_string(String, abstract(T)). not_string([C|T], Result) -> not_string(T, {cons, 0, {integer, 0, C}, Result}); not_string([], Result) -> Result. abstract_list([H|T]) -> [abstract(H)|abstract_list(T)]; abstract_list([]) -> []. abstract_byte(Byte, Line) when is_integer(Byte) -> {bin_element, Line, {integer, Line, Byte}, default, default}; abstract_byte(Bits, Line) -> Sz = bit_size(Bits), <<Val:Sz>> = Bits, {bin_element, Line, {integer, Line, Val}, {integer, Line, Sz}, default}.
bd5f5cac7f3bb94db4f43ea6b0731a23b6cf3c0f660e13167bfd8a4daf85bb43
fimad/prometheus-haskell
Info.hs
module Prometheus.Info ( Info (..) , checkInfo ) where import Data.Text (Text) import qualified Data.Text as T -- | Meta data about a metric including its name and a help string that -- describes the value that the metric is measuring. data Info = Info { metricName :: Text , metricHelp :: Text } deriving (Read, Show, Eq, Ord) checkInfo :: Info -> a -> a checkInfo info a | (x:_) <- T.unpack name, not $ validStart x = errorInvalid | (_:xs) <- T.unpack name, not $ all validRest xs = errorInvalid | ('_':'_':_) <- T.unpack name = errorPrefix | [] <- T.unpack name = errorEmpty | otherwise = a where name = metricName info errorInvalid = error $ concat [ "The metric '", T.unpack name, "' contains invalid characters." ] errorPrefix = error $ concat [ "The metric '", T.unpack name, "' cannot start with '__'." ] errorEmpty = error "Empty metric names are not allowed." validStart c = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_' || c == ':' validRest c = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '_' || c == ':'
null
https://raw.githubusercontent.com/fimad/prometheus-haskell/4e2c2f1da1f891e9de3ce5a5260ae92882a9f35e/prometheus-client/src/Prometheus/Info.hs
haskell
| Meta data about a metric including its name and a help string that describes the value that the metric is measuring.
module Prometheus.Info ( Info (..) , checkInfo ) where import Data.Text (Text) import qualified Data.Text as T data Info = Info { metricName :: Text , metricHelp :: Text } deriving (Read, Show, Eq, Ord) checkInfo :: Info -> a -> a checkInfo info a | (x:_) <- T.unpack name, not $ validStart x = errorInvalid | (_:xs) <- T.unpack name, not $ all validRest xs = errorInvalid | ('_':'_':_) <- T.unpack name = errorPrefix | [] <- T.unpack name = errorEmpty | otherwise = a where name = metricName info errorInvalid = error $ concat [ "The metric '", T.unpack name, "' contains invalid characters." ] errorPrefix = error $ concat [ "The metric '", T.unpack name, "' cannot start with '__'." ] errorEmpty = error "Empty metric names are not allowed." validStart c = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_' || c == ':' validRest c = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '_' || c == ':'
878caeb2e0fd4d581a7e268078512253c8fe5eceb7522242750ba68cafd0b018
psibi/fb
FQL.hs
# LANGUAGE CPP # # LANGUAGE FlexibleContexts # {-# LANGUAGE OverloadedStrings #-} module Facebook.FQL ( fqlQuery , FQLTime(..) , FQLList(..) , FQLObject(..) ) where import Control.Applicative ((<$>)) import Data.Monoid (mempty) import Data.Text (Text) import Data.Time (UTCTime) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import qualified Control.Monad.Trans.Resource as R import qualified Data.Aeson as A #if MIN_VERSION_aeson(2,0,0) import qualified Data.Aeson.KeyMap as Keys #else import qualified Data.HashMap.Strict as Keys #endif import Facebook.Types import Facebook.Monad import Facebook.Base import Facebook.Graph import Facebook.Pager | Query the Facebook Graph using FQL . fqlQuery :: (R.MonadResource m, R.MonadUnliftIO m, R.MonadThrow m, A.FromJSON a) => Text -- ^ FQL Query -> Maybe (AccessToken anyKind) -- ^ Optional access token -> FacebookT anyAuth m (Pager a) fqlQuery fql mtoken = runResourceInFb $ do let query = ["q" #= fql] asJson =<< fbhttp =<< fbreq "/fql" mtoken query -- | @newtype@ wrapper around 'UTCTime' that is able to parse FQL 's time representation as seconds since the Unix epoch . newtype FQLTime = FQLTime { unFQLTime :: UTCTime } deriving (Eq, Ord, Show) instance A.FromJSON FQLTime where parseJSON = fmap (FQLTime . posixSecondsToUTCTime . fromInteger) . A.parseJSON # DEPRECATED FQLTime " Deprecated since fb 0.14.7 , please use FbUTCTime instead . " # FQLTime "Deprecated since fb 0.14.7, please use FbUTCTime instead." #-} | @newtype@ wrapper around lists that works around FQL 's -- strange lists. -- For example , if you fetch the @tagged_uids@ field from @location_post@ , you 'll find that Facebook 's FQL represents an empty list of tagged UIDs as plain JSON array ( @[]@ ) . -- However, it represents a singleton list as an object @{\"1234\ " : 1234}@ instead of the much more correct @[1234]@. -- -- On the other hand, not all FQL arrays are represented in this bogus manner . Also , some so - called arrays by FQL 's documentation are actually objects , see ' ' . newtype FQLList a = FQLList { unFQLList :: [a] } deriving (Eq, Ord, Show) instance A.FromJSON a => A.FromJSON (FQLList a) where parseJSON (A.Object o) = FQLList <$> mapM A.parseJSON (Keys.elems o) parseJSON v = FQLList <$> A.parseJSON v | @newtype@ wrapper around any object that works around FQL 's -- strange objects. -- For example , if you fetch the @app_data@ field from @stream@ , -- you'll find that empty objects are actually represented as empty lists @[]@ instead of a proper empty object @{}@. Also note that FQL 's documentation says that @app_data@ is an array , which it clear is not . See also ' FQLList ' . newtype FQLObject a = FQLObject { unFQLObject :: a } deriving (Eq, Ord, Show) instance A.FromJSON a => A.FromJSON (FQLObject a) where parseJSON (A.Array a) | a == mempty = FQLObject <$> A.parseJSON (A.Object mempty) parseJSON v = FQLObject <$> A.parseJSON v
null
https://raw.githubusercontent.com/psibi/fb/bb87e714b22f244e1fda3af85f041a3331639e9f/src/Facebook/FQL.hs
haskell
# LANGUAGE OverloadedStrings # ^ FQL Query ^ Optional access token | @newtype@ wrapper around 'UTCTime' that is able to parse strange lists. However, it represents a singleton list as an object On the other hand, not all FQL arrays are represented in this strange objects. you'll find that empty objects are actually represented as
# LANGUAGE CPP # # LANGUAGE FlexibleContexts # module Facebook.FQL ( fqlQuery , FQLTime(..) , FQLList(..) , FQLObject(..) ) where import Control.Applicative ((<$>)) import Data.Monoid (mempty) import Data.Text (Text) import Data.Time (UTCTime) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import qualified Control.Monad.Trans.Resource as R import qualified Data.Aeson as A #if MIN_VERSION_aeson(2,0,0) import qualified Data.Aeson.KeyMap as Keys #else import qualified Data.HashMap.Strict as Keys #endif import Facebook.Types import Facebook.Monad import Facebook.Base import Facebook.Graph import Facebook.Pager | Query the Facebook Graph using FQL . fqlQuery :: (R.MonadResource m, R.MonadUnliftIO m, R.MonadThrow m, A.FromJSON a) -> FacebookT anyAuth m (Pager a) fqlQuery fql mtoken = runResourceInFb $ do let query = ["q" #= fql] asJson =<< fbhttp =<< fbreq "/fql" mtoken query FQL 's time representation as seconds since the Unix epoch . newtype FQLTime = FQLTime { unFQLTime :: UTCTime } deriving (Eq, Ord, Show) instance A.FromJSON FQLTime where parseJSON = fmap (FQLTime . posixSecondsToUTCTime . fromInteger) . A.parseJSON # DEPRECATED FQLTime " Deprecated since fb 0.14.7 , please use FbUTCTime instead . " # FQLTime "Deprecated since fb 0.14.7, please use FbUTCTime instead." #-} | @newtype@ wrapper around lists that works around FQL 's For example , if you fetch the @tagged_uids@ field from @location_post@ , you 'll find that Facebook 's FQL represents an empty list of tagged UIDs as plain JSON array ( @[]@ ) . @{\"1234\ " : 1234}@ instead of the much more correct @[1234]@. bogus manner . Also , some so - called arrays by FQL 's documentation are actually objects , see ' ' . newtype FQLList a = FQLList { unFQLList :: [a] } deriving (Eq, Ord, Show) instance A.FromJSON a => A.FromJSON (FQLList a) where parseJSON (A.Object o) = FQLList <$> mapM A.parseJSON (Keys.elems o) parseJSON v = FQLList <$> A.parseJSON v | @newtype@ wrapper around any object that works around FQL 's For example , if you fetch the @app_data@ field from @stream@ , empty lists @[]@ instead of a proper empty object @{}@. Also note that FQL 's documentation says that @app_data@ is an array , which it clear is not . See also ' FQLList ' . newtype FQLObject a = FQLObject { unFQLObject :: a } deriving (Eq, Ord, Show) instance A.FromJSON a => A.FromJSON (FQLObject a) where parseJSON (A.Array a) | a == mempty = FQLObject <$> A.parseJSON (A.Object mempty) parseJSON v = FQLObject <$> A.parseJSON v
2cb0f12524fb245e45bd1dd0b97c1df95495724d24011de05e102a1a946e307e
cdinger/rasql
core_test.clj
(ns rasql.core-test (:require [clojure.test :refer :all] [rasql.core :refer :all])) (defrelation posts :posts_tbl) (defrelation comments :comments_tbl) ;; Projection (deftest projection-test (let [p (->Projection [:a :b]) actual (to-sql p) expected "SELECT a, b"] (is (= expected actual)))) (deftest empty-projection-test (let [p (->Projection []) actual (to-sql p) expected "SELECT *"] (is (= expected actual)))) (deftest relation-projection-test (let [p (->Projection [(:a posts)]) actual (to-sql p) expected "SELECT \"posts\".a"] (is (= expected actual)))) ;; Predicates (deftest predicate-test (let [p [:= (:id posts) (:posts_id comments)] actual (to-sql p) expected "(\"posts\".id = \"comments\".posts_id)"] (is (= expected actual)))) (deftest relation-predicate-test (let [p [:= (:a posts) (:b posts)] actual (to-sql p) expected "(\"posts\".a = \"posts\".b)"] (is (= expected actual)))) ;; Joins (deftest join-test (let [j (->Join comments [:= (:id posts) (:posts_id comments)]) actual (to-sql j) expected " JOIN (SELECT * FROM comments_tbl \"comments\") \"comments\" ON (\"posts\".id = \"comments\".posts_id)"] (is (= expected actual)))) ;; Relation (deftest relation-test (let [actual (to-sql posts) expected "(SELECT * FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest empty-project-test (let [r (project posts []) actual (to-sql r) expected "(SELECT * FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest all-project-test (let [r (project posts [:*]) actual (to-sql r) expected "(SELECT * FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest relation-all-project-test (let [r (project posts [(:* posts)]) actual (to-sql r) expected "(SELECT \"posts\".* FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest multiple-project-test (let [r (project posts [:a :b :c]) actual (to-sql r) expected "(SELECT a, b, c FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest multiple-relation-column-project-test (let [r (project posts [(:a posts) (:b posts) :c]) actual (to-sql r) expected "(SELECT \"posts\".a, \"posts\".b, c FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest relation-select-test (let [r (select posts [:= :title "An awesome posts"]) actual (to-sql r) expected "(SELECT * FROM posts_tbl \"posts\" WHERE (title = 'An awesome posts'))"] (is (= expected actual)))) (deftest relation-qualified-select-test (let [r (select posts [:= (:author_id posts) 123]) actual (to-sql r) expected "(SELECT * FROM posts_tbl \"posts\" WHERE (\"posts\".author_id = 123))"] (is (= expected actual)))) Grouping (deftest group-by-test (let [r (project posts [(maximum :id :max_id) (:blah posts)]) actual (to-sql r) expected "(SELECT max(id) AS max_id, \"posts\".blah FROM posts_tbl \"posts\" GROUP BY \"posts\".blah)"] (is (= expected actual)))) (deftest exclude-group-by-when-single-aggregate-test (let [r (project posts [(maximum :id :max_id)]) actual (to-sql r) expected "(SELECT max(id) AS max_id FROM posts_tbl \"posts\")"] (is (= expected actual))))
null
https://raw.githubusercontent.com/cdinger/rasql/ed8cb378a403a86096924669068d785dde07b8f5/test/rasql/core_test.clj
clojure
Projection Predicates Joins Relation
(ns rasql.core-test (:require [clojure.test :refer :all] [rasql.core :refer :all])) (defrelation posts :posts_tbl) (defrelation comments :comments_tbl) (deftest projection-test (let [p (->Projection [:a :b]) actual (to-sql p) expected "SELECT a, b"] (is (= expected actual)))) (deftest empty-projection-test (let [p (->Projection []) actual (to-sql p) expected "SELECT *"] (is (= expected actual)))) (deftest relation-projection-test (let [p (->Projection [(:a posts)]) actual (to-sql p) expected "SELECT \"posts\".a"] (is (= expected actual)))) (deftest predicate-test (let [p [:= (:id posts) (:posts_id comments)] actual (to-sql p) expected "(\"posts\".id = \"comments\".posts_id)"] (is (= expected actual)))) (deftest relation-predicate-test (let [p [:= (:a posts) (:b posts)] actual (to-sql p) expected "(\"posts\".a = \"posts\".b)"] (is (= expected actual)))) (deftest join-test (let [j (->Join comments [:= (:id posts) (:posts_id comments)]) actual (to-sql j) expected " JOIN (SELECT * FROM comments_tbl \"comments\") \"comments\" ON (\"posts\".id = \"comments\".posts_id)"] (is (= expected actual)))) (deftest relation-test (let [actual (to-sql posts) expected "(SELECT * FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest empty-project-test (let [r (project posts []) actual (to-sql r) expected "(SELECT * FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest all-project-test (let [r (project posts [:*]) actual (to-sql r) expected "(SELECT * FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest relation-all-project-test (let [r (project posts [(:* posts)]) actual (to-sql r) expected "(SELECT \"posts\".* FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest multiple-project-test (let [r (project posts [:a :b :c]) actual (to-sql r) expected "(SELECT a, b, c FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest multiple-relation-column-project-test (let [r (project posts [(:a posts) (:b posts) :c]) actual (to-sql r) expected "(SELECT \"posts\".a, \"posts\".b, c FROM posts_tbl \"posts\")"] (is (= expected actual)))) (deftest relation-select-test (let [r (select posts [:= :title "An awesome posts"]) actual (to-sql r) expected "(SELECT * FROM posts_tbl \"posts\" WHERE (title = 'An awesome posts'))"] (is (= expected actual)))) (deftest relation-qualified-select-test (let [r (select posts [:= (:author_id posts) 123]) actual (to-sql r) expected "(SELECT * FROM posts_tbl \"posts\" WHERE (\"posts\".author_id = 123))"] (is (= expected actual)))) Grouping (deftest group-by-test (let [r (project posts [(maximum :id :max_id) (:blah posts)]) actual (to-sql r) expected "(SELECT max(id) AS max_id, \"posts\".blah FROM posts_tbl \"posts\" GROUP BY \"posts\".blah)"] (is (= expected actual)))) (deftest exclude-group-by-when-single-aggregate-test (let [r (project posts [(maximum :id :max_id)]) actual (to-sql r) expected "(SELECT max(id) AS max_id FROM posts_tbl \"posts\")"] (is (= expected actual))))
23e5f96f9bf6993017330e39a9e2271ae01731bcdd1fadbfc4e7c4a42926b354
tahnik/graphqlx
NonNullArguments.ml
open Types open Printf let error: bool ref = ref false;; let rec read_doc definitions = (match definitions with | [] -> () | def::defs -> read_definition def; read_doc defs); and read_definition def = match def with | Operation op -> read_operation op | Fragment fr -> read_fragment fr and read_fragment fr = match fr with | { name; type_condition; directives; selection_set; } -> read_directives directives; read_selection_set selection_set; and read_operation op = match op with | { optype; name; variable_definitions; directives; selection_set; } -> (match optype with | Query -> () | Mutation -> () | Subscription -> ()); (match name with | None -> () | Some value -> ()); read_directives directives; read_selection_set selection_set; and read_selection_set selection_set = match selection_set with | [] -> () | selection::sel_sets -> (match selection with | Field field -> read_field field | FragmentSpread spread -> read_frag_spread spread | InlineFragment frag -> read_inline_frag frag); read_selection_set sel_sets; and read_frag_spread spread = match spread with | { name; directives; } -> read_directives directives; and read_inline_frag frag = match frag with | { type_condition; directives; selection_set; } -> (match type_condition with | None -> () | Some typ -> ()); read_directives directives; read_selection_set selection_set; and read_field field = match field with | { alias; name; arguments; directives; selection_set; } -> (match alias with | None -> () | Some alias -> ()); read_arguments arguments 0; read_selection_set selection_set; and read_directives directives = match directives with | [] -> () | direc::direcs -> match direc with | { name; arguments } -> read_arguments arguments 0; read_directives direcs; and read_arguments arguments i = let length = List.length arguments in match arguments with | [] -> () | arg::args -> match arg with | (key, value) -> (match value with | `Null -> ( error := true; printf "\nvalidation error: argument value cannot be null\n"; ) | _ -> () ); read_arguments args (i + 1);; let validate definitions = error := false; read_doc definitions; !error
null
https://raw.githubusercontent.com/tahnik/graphqlx/4a3dea80891c0f8aa16a98485f5c9a3b6d0fe88c/src/validation/src/NonNullArguments.ml
ocaml
open Types open Printf let error: bool ref = ref false;; let rec read_doc definitions = (match definitions with | [] -> () | def::defs -> read_definition def; read_doc defs); and read_definition def = match def with | Operation op -> read_operation op | Fragment fr -> read_fragment fr and read_fragment fr = match fr with | { name; type_condition; directives; selection_set; } -> read_directives directives; read_selection_set selection_set; and read_operation op = match op with | { optype; name; variable_definitions; directives; selection_set; } -> (match optype with | Query -> () | Mutation -> () | Subscription -> ()); (match name with | None -> () | Some value -> ()); read_directives directives; read_selection_set selection_set; and read_selection_set selection_set = match selection_set with | [] -> () | selection::sel_sets -> (match selection with | Field field -> read_field field | FragmentSpread spread -> read_frag_spread spread | InlineFragment frag -> read_inline_frag frag); read_selection_set sel_sets; and read_frag_spread spread = match spread with | { name; directives; } -> read_directives directives; and read_inline_frag frag = match frag with | { type_condition; directives; selection_set; } -> (match type_condition with | None -> () | Some typ -> ()); read_directives directives; read_selection_set selection_set; and read_field field = match field with | { alias; name; arguments; directives; selection_set; } -> (match alias with | None -> () | Some alias -> ()); read_arguments arguments 0; read_selection_set selection_set; and read_directives directives = match directives with | [] -> () | direc::direcs -> match direc with | { name; arguments } -> read_arguments arguments 0; read_directives direcs; and read_arguments arguments i = let length = List.length arguments in match arguments with | [] -> () | arg::args -> match arg with | (key, value) -> (match value with | `Null -> ( error := true; printf "\nvalidation error: argument value cannot be null\n"; ) | _ -> () ); read_arguments args (i + 1);; let validate definitions = error := false; read_doc definitions; !error
9e99725495d2bcf0e687a32e818bb6fe231980571025f6cf19a0abba50936b38
conal/TypeCompose
Instances.hs
---------------------------------------------------------------------- -- | -- Module : Control.Instances Copyright : ( c ) Conal Elliott 2007 -- License : BSD3 -- -- Maintainer : -- Stability : experimental -- Portability : portable -- -- Some (orphan) instances that belong elsewhere (where they wouldn't be orphans). -- Add the following line to get these instances -- -- > import Control.Instances () -- ---------------------------------------------------------------------- module Control.Instances () where import Data.Orphans ()
null
https://raw.githubusercontent.com/conal/TypeCompose/5100cd68b68382b6b65c8c0598a3f34dc9481db3/src/Control/Instances.hs
haskell
-------------------------------------------------------------------- | Module : Control.Instances License : BSD3 Maintainer : Stability : experimental Portability : portable Some (orphan) instances that belong elsewhere (where they wouldn't be orphans). Add the following line to get these instances > import Control.Instances () --------------------------------------------------------------------
Copyright : ( c ) Conal Elliott 2007 module Control.Instances () where import Data.Orphans ()
12884cbf376886fe8f2b503c867d88e7c4304a4452820e5583b03cf975f40d90
GaloisInc/daedalus
Position.hs
{-# LANGUAGE RankNTypes #-} # LANGUAGE ViewPatterns # {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE BlockArguments # -- --------------------------------------------------------------------------------------- -- Mapping positions to things module Daedalus.LSP.Position where import Data.Monoid import Control.Monad(guard) import Data.Parameterized.Some import qualified Data.Text as Text import qualified Language.LSP.Types as J import Daedalus.PP import Daedalus.SourceRange import Daedalus.Type.AST import Data.Maybe (maybeToList, fromMaybe) import Daedalus.Type.Traverse import Daedalus.Rec (forgetRecs) import Data.Foldable import Daedalus.LSP.Diagnostics (sourceRangeToRange, jSourceColumn, jSourceLine) data NameRefClass = NameDef | NameUse deriving Eq data NameInfo = NameInfo { niNameRefClass :: NameRefClass , niName :: Name , niType :: Type -- result type for function calls } instance HasRange NameInfo where range = range . niName -- We can't use the free vars stuff here as we want each occurrence of -- a name, while that will just tell which vars are used (the free -- functions ignore source ranges). declToNames :: TCDecl SourceRange -> [NameInfo] declToNames d@TCDecl { tcDeclName = n, tcDeclParams = ps, tcDeclDef = def } = fdef n (typeOf d) : map paramName ps ++ case def of ExternDecl _ -> [] Defined tc -> go tc where paramName p = case p of ValParam v -> vdef v ClassParam v -> vdef v GrammarParam v -> vdef v vdef :: forall k. TCName k -> NameInfo vdef v = NameInfo NameDef (tcName v) (typeOf v) vuse :: forall k. TCName k -> NameInfo vuse v = NameInfo NameUse (tcName v) (typeOf v) fdef :: Name -> Type -> NameInfo fdef = NameInfo NameDef fuse :: forall k. TCName k -> NameInfo fuse v = NameInfo NameUse (tcName v) (typeOf v) go :: forall k. TC SourceRange k -> [NameInfo] go tc = case texprValue tc of TCVar v -> [vuse v] TCDo (Just v) _ _ -> vdef v : goBody tc TCFor l -> case loopFlav l of Fold v _ c -> vdef v : vDefCol c LoopMany _ v _ -> [vdef v] LoopMap c -> vDefCol c ++ goBody tc TCCall v _ _ -> fuse v : goBody tc TCCase _ alts _ -> (vdef <$> foldMap altBinds alts) ++ goBody tc _ -> goBody tc vDefCol c = maybeToList (vdef <$> lcKName c) ++ [ vdef (lcElName c) ] goBody = foldMapTC go data TypeInfo = TypeInfo { nameOfDecl :: Name , typeOfDecl :: Poly RuleType , typeLoc :: SourceRange , typeOfExpr :: Maybe Type } typeAtModule :: J.Position -> TCModule SourceRange -> Maybe TypeInfo typeAtModule pos m = msum (map (typeAtDecl pos) (forgetRecs (tcModuleDecls m))) typeAtDecl :: J.Position -> TCDecl SourceRange -> Maybe TypeInfo typeAtDecl pos d@TCDecl { tcDeclName = n, tcDeclParams = ps, tcDeclDef = def , tcDeclAnnot = r } | not (positionInRange pos (tcDeclAnnot d)) = Nothing | otherwise = msum (inName : map inParam ps ++ [ inBody, Just here ]) where here = TypeInfo { nameOfDecl = n , typeOfDecl = declTypeOf d , typeLoc = r , typeOfExpr = Nothing } inName = do guard (positionInRange pos n) pure here { typeLoc = range n } inParam p = do guard (positionInRange pos p) pure here { typeLoc = range p, typeOfExpr = Just (typeOf p) } inBody = case def of Defined tc -> do (ty,rng) <- getAlt (typeAtTC pos tc) pure here { typeLoc = rng, typeOfExpr = Just ty } ExternDecl {} -> Nothing declAtPos :: J.Position -> TCModule SourceRange -> Maybe (TCDecl SourceRange) declAtPos pos m = find (positionInRange pos . tcDeclAnnot) (forgetRecs (tcModuleDecls m)) typeAtTC :: J.Position -> TC SourceRange k -> Alt Maybe (Type, SourceRange) typeAtTC pos tc = do exprs <- positionToExprs pos tc Alt $ case reverse exprs of [] -> Nothing -- means the position isn't inside tc -- We need to 'fixup' the results of exprs at, as we may be looking at e.g. a binder Some tc' : _ -> case texprValue tc' of TCDo (Just n) _ _ | positionInRange pos n -> Just (typeOf n, range n) TCCall fn _ _ | positionInRange pos fn -> Just (typeOf fn, range fn) -- FIXME: this just returns the result type, not the fn type TCFor (loopFlav -> Fold n _ c) | positionInRange pos n -> Just (typeOf n, range n) | Just yes <- colNames c -> Just yes TCFor (loopFlav -> LoopMany _ n _) | positionInRange pos n -> Just (typeOf n, range n) TCFor (loopFlav -> LoopMap c) | Just yes <- colNames c -> Just yes , at least return something . where colNames col = msum [ do guard (positionInRange pos x) pure (typeOf x, range x) | x <- maybeToList (lcKName col) ++ [lcElName col] ] exprTree :: TCDecl SourceRange -> Doc exprTree TCDecl { tcDeclDef = ExternDecl _ } = "external" exprTree TCDecl { tcDeclDef = Defined def } = bullets (go def) where go :: forall k. TC SourceRange k -> [Doc] go tc = let kids = foldMapTC go tc in [ hang (text (prettySourceRange (range tc)) $$ pp tc) 4 (bullets kids) ] -- This assumes that a position cannot be in sibling expressions positionToExprs :: J.Position -> TC SourceRange k -> Alt Maybe [Some (TC SourceRange)] positionToExprs pos = go where go :: forall k. TC SourceRange k -> Alt Maybe [Some (TC SourceRange)] go tc | not (positionInRange pos tc) = mempty -- Nothing means either no matches, or no children. We know _we_ match , so either some child also matches , or no TC child -- matches (but some non-tc type may match, e.g. the variable in a -- do). go tc = Alt (Just (Some tc : fromMaybe [] (getAlt $ foldMapTC go tc))) positionInRange :: HasRange a => J.Position -> a -> Bool positionInRange (J.Position line0 col0) (range -> SourceRange start end) = (jSourceLine start < line || (jSourceLine start == line && jSourceColumn start <= col)) && (jSourceLine end > line || (jSourceLine end == line && jSourceColumn end >= col)) where line = line0 + 1 col = col0 + 1 sourceRangeToLocation :: SourceRange -> J.Location sourceRangeToLocation pos = J.Location (J.filePathToUri (Text.unpack $ sourceFile (sourceFrom pos))) (sourceRangeToRange pos)
null
https://raw.githubusercontent.com/GaloisInc/daedalus/76baf11113cc4a0b4ad06faba898a97e42a92e7a/daedalus-language-server/src/Daedalus/LSP/Position.hs
haskell
# LANGUAGE RankNTypes # # LANGUAGE GADTs # # LANGUAGE OverloadedStrings # --------------------------------------------------------------------------------------- Mapping positions to things result type for function calls We can't use the free vars stuff here as we want each occurrence of a name, while that will just tell which vars are used (the free functions ignore source ranges). means the position isn't inside tc We need to 'fixup' the results of exprs at, as we may be looking at e.g. a binder FIXME: this just returns the result type, not the fn type This assumes that a position cannot be in sibling expressions Nothing means either no matches, or no children. We know _we_ matches (but some non-tc type may match, e.g. the variable in a do).
# LANGUAGE ViewPatterns # # LANGUAGE BlockArguments # module Daedalus.LSP.Position where import Data.Monoid import Control.Monad(guard) import Data.Parameterized.Some import qualified Data.Text as Text import qualified Language.LSP.Types as J import Daedalus.PP import Daedalus.SourceRange import Daedalus.Type.AST import Data.Maybe (maybeToList, fromMaybe) import Daedalus.Type.Traverse import Daedalus.Rec (forgetRecs) import Data.Foldable import Daedalus.LSP.Diagnostics (sourceRangeToRange, jSourceColumn, jSourceLine) data NameRefClass = NameDef | NameUse deriving Eq data NameInfo = NameInfo { niNameRefClass :: NameRefClass , niName :: Name } instance HasRange NameInfo where range = range . niName declToNames :: TCDecl SourceRange -> [NameInfo] declToNames d@TCDecl { tcDeclName = n, tcDeclParams = ps, tcDeclDef = def } = fdef n (typeOf d) : map paramName ps ++ case def of ExternDecl _ -> [] Defined tc -> go tc where paramName p = case p of ValParam v -> vdef v ClassParam v -> vdef v GrammarParam v -> vdef v vdef :: forall k. TCName k -> NameInfo vdef v = NameInfo NameDef (tcName v) (typeOf v) vuse :: forall k. TCName k -> NameInfo vuse v = NameInfo NameUse (tcName v) (typeOf v) fdef :: Name -> Type -> NameInfo fdef = NameInfo NameDef fuse :: forall k. TCName k -> NameInfo fuse v = NameInfo NameUse (tcName v) (typeOf v) go :: forall k. TC SourceRange k -> [NameInfo] go tc = case texprValue tc of TCVar v -> [vuse v] TCDo (Just v) _ _ -> vdef v : goBody tc TCFor l -> case loopFlav l of Fold v _ c -> vdef v : vDefCol c LoopMany _ v _ -> [vdef v] LoopMap c -> vDefCol c ++ goBody tc TCCall v _ _ -> fuse v : goBody tc TCCase _ alts _ -> (vdef <$> foldMap altBinds alts) ++ goBody tc _ -> goBody tc vDefCol c = maybeToList (vdef <$> lcKName c) ++ [ vdef (lcElName c) ] goBody = foldMapTC go data TypeInfo = TypeInfo { nameOfDecl :: Name , typeOfDecl :: Poly RuleType , typeLoc :: SourceRange , typeOfExpr :: Maybe Type } typeAtModule :: J.Position -> TCModule SourceRange -> Maybe TypeInfo typeAtModule pos m = msum (map (typeAtDecl pos) (forgetRecs (tcModuleDecls m))) typeAtDecl :: J.Position -> TCDecl SourceRange -> Maybe TypeInfo typeAtDecl pos d@TCDecl { tcDeclName = n, tcDeclParams = ps, tcDeclDef = def , tcDeclAnnot = r } | not (positionInRange pos (tcDeclAnnot d)) = Nothing | otherwise = msum (inName : map inParam ps ++ [ inBody, Just here ]) where here = TypeInfo { nameOfDecl = n , typeOfDecl = declTypeOf d , typeLoc = r , typeOfExpr = Nothing } inName = do guard (positionInRange pos n) pure here { typeLoc = range n } inParam p = do guard (positionInRange pos p) pure here { typeLoc = range p, typeOfExpr = Just (typeOf p) } inBody = case def of Defined tc -> do (ty,rng) <- getAlt (typeAtTC pos tc) pure here { typeLoc = rng, typeOfExpr = Just ty } ExternDecl {} -> Nothing declAtPos :: J.Position -> TCModule SourceRange -> Maybe (TCDecl SourceRange) declAtPos pos m = find (positionInRange pos . tcDeclAnnot) (forgetRecs (tcModuleDecls m)) typeAtTC :: J.Position -> TC SourceRange k -> Alt Maybe (Type, SourceRange) typeAtTC pos tc = do exprs <- positionToExprs pos tc Alt $ case reverse exprs of Some tc' : _ -> case texprValue tc' of TCDo (Just n) _ _ | positionInRange pos n -> Just (typeOf n, range n) TCFor (loopFlav -> Fold n _ c) | positionInRange pos n -> Just (typeOf n, range n) | Just yes <- colNames c -> Just yes TCFor (loopFlav -> LoopMany _ n _) | positionInRange pos n -> Just (typeOf n, range n) TCFor (loopFlav -> LoopMap c) | Just yes <- colNames c -> Just yes , at least return something . where colNames col = msum [ do guard (positionInRange pos x) pure (typeOf x, range x) | x <- maybeToList (lcKName col) ++ [lcElName col] ] exprTree :: TCDecl SourceRange -> Doc exprTree TCDecl { tcDeclDef = ExternDecl _ } = "external" exprTree TCDecl { tcDeclDef = Defined def } = bullets (go def) where go :: forall k. TC SourceRange k -> [Doc] go tc = let kids = foldMapTC go tc in [ hang (text (prettySourceRange (range tc)) $$ pp tc) 4 (bullets kids) ] positionToExprs :: J.Position -> TC SourceRange k -> Alt Maybe [Some (TC SourceRange)] positionToExprs pos = go where go :: forall k. TC SourceRange k -> Alt Maybe [Some (TC SourceRange)] go tc | not (positionInRange pos tc) = mempty match , so either some child also matches , or no TC child go tc = Alt (Just (Some tc : fromMaybe [] (getAlt $ foldMapTC go tc))) positionInRange :: HasRange a => J.Position -> a -> Bool positionInRange (J.Position line0 col0) (range -> SourceRange start end) = (jSourceLine start < line || (jSourceLine start == line && jSourceColumn start <= col)) && (jSourceLine end > line || (jSourceLine end == line && jSourceColumn end >= col)) where line = line0 + 1 col = col0 + 1 sourceRangeToLocation :: SourceRange -> J.Location sourceRangeToLocation pos = J.Location (J.filePathToUri (Text.unpack $ sourceFile (sourceFrom pos))) (sourceRangeToRange pos)
a1c293ce735a2eaf22f7d8f8cc886072374e2c8444e20f3a236495366458212e
TrustInSoft/tis-interpreter
Model.ml
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of WP plug - in of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (* -------------------------------------------------------------------------- *) (* --- Model Registry --- *) (* -------------------------------------------------------------------------- *) type model = { Identifier Basename for Model ( unique ) descr : string ; (* Title of the Model (for pretty) *) emitter : Emitter.t ; separation : separation ; mutable tuning : tuning list ; } and tuning = unit -> unit and separation = Kernel_function.t -> Separation.clause list let nosep (_kf) = [] let repr = { id = "?model" ; descr = "?model" ; emitter = Emitter.kernel ; tuning = [ fun () -> () ] ; separation = nosep ; } module D = Datatype.Make_with_collections(struct type t = model let name = "WP.Model" let rehash = Datatype.identity (** TODO: register and find below? *) let structural_descr = let open Structural_descr in t_record [| p_string; p_string; pack (t_option t_string) ; Emitter.packed_descr; pack (t_list t_unknown) |] let reprs = [repr] let equal x y = Datatype.String.equal x.id y.id let compare x y = Datatype.String.compare x.id y.id let hash x = Datatype.String.hash x.id let copy = Datatype.identity let internal_pretty_code _ fmt x = Format.pp_print_string fmt x.id let pretty fmt x = Format.pp_print_string fmt x.descr let mem_project = Datatype.never_any_project let varname _ = "m" end) module MODELS = struct module H = Datatype.String.Map let h = ref H.empty (* NOT PROJECTIFIED : Models are defined at Plugin load-time, for all projects *) let mem id = H.mem id !h let add m = h := H.add m.id m !h let find id = H.find id !h let iter f = H.iter (fun _ m -> f m) !h end let find ~id = MODELS.find id let iter f = MODELS.iter f let register ~id ?(descr=id) ?(tuning=[]) ?(separation=nosep) () = if MODELS.mem id then Wp_parameters.fatal "Duplicate model '%s'" id ; let emitter = let e_name = "Wp." ^ id in let correctness = [ ] in let tuning = [ Wp_parameters.Provers.parameter ] in Emitter.create e_name [ Emitter.Property_status ] ~correctness ~tuning in let model = { id = id ; descr ; emitter ; tuning ; separation ; } in MODELS.add model ; model let get_id m = m.id let get_descr m = m.descr let get_separation m = m.separation type scope = Kernel_function.t option let scope : scope Context.value = Context.create "Wp.Scope" let model : model Context.value = Context.create "Wp.Model" let rec bind = function [] -> () | f::fs -> f () ; bind fs let back = function None -> () | Some c -> bind c.tuning let with_model m f x = let current = Context.push model m in try bind m.tuning ; let result = f x in Context.pop model current ; back current ; result with err -> Context.pop model current ; back current ; raise err let on_model m f = with_model m f () let on_scope s f a = Context.bind scope s f a let on_kf kf f = on_scope (Some kf) f () let on_global f = on_scope None f () let get_scope () = Context.get scope let get_model () = Context.get model let get_emitter model = model.emitter let is_model_defined () = Context.defined model let directory () = Wp_parameters.get_output_dir (Context.get model).id module type Entries = sig type key type data val name : string val compare : key -> key -> int val pretty : Format.formatter -> key -> unit end module type Registry = sig module E : Entries type key = E.key type data = E.data val mem : key -> bool val find : key -> data val get : key -> data option val define : key -> data -> unit val update : key -> data -> unit val memoize : (key -> data) -> key -> data val compile : (key -> data) -> key -> unit val callback : (key -> data -> unit) -> unit val iter : (key -> data -> unit) -> unit val iter_sorted : (key -> data -> unit) -> unit end module Index(E : Entries) = struct module E = E type key = E.key type data = E.data module KEY = struct type t = E.key let compare = E.compare end module MAP = FCMap.Make(KEY) module SET = FCSet.Make(KEY) let demon = ref [] type entries = { mutable index : E.data MAP.t ; mutable lock : SET.t ; } module ENTRIES : Datatype.S with type t = entries = Datatype.Make (struct type t = entries include Datatype.Serializable_undefined let reprs = [{index=MAP.empty;lock=SET.empty}] let name = "Wp.Model.Index." ^ E.name end) module REGISTRY = State_builder.Hashtbl (Datatype.String.Hashtbl) (ENTRIES) (struct let name = "Wp.Model." ^ E.name let dependencies = [Ast.self] let size = 32 end) Projectified entry map , indexed by model let entries () : entries = let mid = (Context.get model).id in try REGISTRY.find mid with Not_found -> let e = { index=MAP.empty ; lock=SET.empty } in REGISTRY.add mid e ; e let mem k = let e = entries () in MAP.mem k e.index || SET.mem k e.lock let find k = let e = entries () in MAP.find k e.index let get k = try Some (find k) with Not_found -> None let fire k d = List.iter (fun f -> f k d) !demon let callback f = demon := !demon @ [f] let define k d = begin let e = entries () in if MAP.mem k e.index then Wp_parameters.fatal "Duplicate definition (%s:%a)" E.name E.pretty k ; if SET.mem k e.lock then Wp_parameters.fatal "Locked definition (%s:%a)" E.name E.pretty k ; e.index <- MAP.add k d e.index ; fire k d ; end let update k d = begin let e = entries () in e.index <- MAP.add k d e.index ; fire k d ; end let memoize f k = let e = entries () in try MAP.find k e.index with Not_found -> let lock = e.lock in e.lock <- SET.add k e.lock ; let d = f k in e.index <- MAP.add k d e.index ; fire k d ; e.lock <- lock ; d (* in case of exception, the entry remains intentionally locked *) let compile f k = ignore (memoize f k) let iter f = MAP.iter f (entries()).index let iter_sorted f = let e = entries () in let s = MAP.fold (fun k _ s -> SET.add k s) e.index SET.empty in SET.iter (fun k -> f k (MAP.find k e.index)) s end module Static(E : Entries) = struct module E = E type key = E.key type data = E.data module KEY = struct type t = E.key let compare = E.compare end module MAP = FCMap.Make(KEY) module SET = FCSet.Make(KEY) let demon = ref [] type entries = { mutable index : E.data MAP.t ; mutable lock : SET.t ; } module ENTRIES : Datatype.S with type t = entries = Datatype.Make (struct type t = entries include Datatype.Serializable_undefined let reprs = [{index=MAP.empty;lock=SET.empty}] let name = "Wp.Model.Index." ^ E.name end) module REGISTRY = State_builder.Ref (ENTRIES) (struct let name = "Wp.Model." ^ E.name let dependencies = [Ast.self] let default () = { index=MAP.empty ; lock=SET.empty } end) Projectified entry map , indexed by model let entries () : entries = REGISTRY.get () let mem k = let e = entries () in MAP.mem k e.index || SET.mem k e.lock let find k = let e = entries () in MAP.find k e.index let get k = try Some (find k) with Not_found -> None let fire k d = List.iter (fun f -> f k d) !demon let callback f = demon := !demon @ [f] let define k d = begin let e = entries () in if MAP.mem k e.index then Wp_parameters.fatal "Duplicate definition (%s:%a)" E.name E.pretty k ; if SET.mem k e.lock then Wp_parameters.fatal "Locked definition (%s:%a)" E.name E.pretty k ; e.index <- MAP.add k d e.index ; fire k d ; end let update k d = begin let e = entries () in e.index <- MAP.add k d e.index ; fire k d ; end let memoize f k = let e = entries () in try MAP.find k e.index with Not_found -> let lock = e.lock in e.lock <- SET.add k e.lock ; let d = f k in e.index <- MAP.add k d e.index ; fire k d ; e.lock <- lock ; d (* in case of exception, the entry remains intentionally locked *) let compile f k = ignore (memoize f k) let iter f = MAP.iter f (entries()).index let iter_sorted f = let e = entries () in let s = MAP.fold (fun k _ s -> SET.add k s) e.index SET.empty in SET.iter (fun k -> f k (MAP.find k e.index)) s end module type Key = sig type t val compare : t -> t -> int val pretty : Format.formatter -> t -> unit end module type Data = sig type key type data val name : string val compile : key -> data end module type Generator = sig type key type data val get : key -> data end module StaticGenerator(K : Key)(D : Data with type key = K.t) = struct module G = Static (struct include K include D end) type key = D.key type data = D.data let get = G.memoize D.compile end module Generator(K : Key)(D : Data with type key = K.t) = struct module G = Index (struct include K include D end) type key = D.key type data = D.data let get = G.memoize D.compile end module S = D type t = S.t (* Local Variables: compile-command: "make -C ../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/wp/Model.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ -------------------------------------------------------------------------- --- Model Registry --- -------------------------------------------------------------------------- Title of the Model (for pretty) * TODO: register and find below? NOT PROJECTIFIED : Models are defined at Plugin load-time, for all projects in case of exception, the entry remains intentionally locked in case of exception, the entry remains intentionally locked Local Variables: compile-command: "make -C ../../.." End:
Modified by TrustInSoft This file is part of WP plug - in of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . type model = { Identifier Basename for Model ( unique ) emitter : Emitter.t ; separation : separation ; mutable tuning : tuning list ; } and tuning = unit -> unit and separation = Kernel_function.t -> Separation.clause list let nosep (_kf) = [] let repr = { id = "?model" ; descr = "?model" ; emitter = Emitter.kernel ; tuning = [ fun () -> () ] ; separation = nosep ; } module D = Datatype.Make_with_collections(struct type t = model let name = "WP.Model" let structural_descr = let open Structural_descr in t_record [| p_string; p_string; pack (t_option t_string) ; Emitter.packed_descr; pack (t_list t_unknown) |] let reprs = [repr] let equal x y = Datatype.String.equal x.id y.id let compare x y = Datatype.String.compare x.id y.id let hash x = Datatype.String.hash x.id let copy = Datatype.identity let internal_pretty_code _ fmt x = Format.pp_print_string fmt x.id let pretty fmt x = Format.pp_print_string fmt x.descr let mem_project = Datatype.never_any_project let varname _ = "m" end) module MODELS = struct module H = Datatype.String.Map let h = ref H.empty let mem id = H.mem id !h let add m = h := H.add m.id m !h let find id = H.find id !h let iter f = H.iter (fun _ m -> f m) !h end let find ~id = MODELS.find id let iter f = MODELS.iter f let register ~id ?(descr=id) ?(tuning=[]) ?(separation=nosep) () = if MODELS.mem id then Wp_parameters.fatal "Duplicate model '%s'" id ; let emitter = let e_name = "Wp." ^ id in let correctness = [ ] in let tuning = [ Wp_parameters.Provers.parameter ] in Emitter.create e_name [ Emitter.Property_status ] ~correctness ~tuning in let model = { id = id ; descr ; emitter ; tuning ; separation ; } in MODELS.add model ; model let get_id m = m.id let get_descr m = m.descr let get_separation m = m.separation type scope = Kernel_function.t option let scope : scope Context.value = Context.create "Wp.Scope" let model : model Context.value = Context.create "Wp.Model" let rec bind = function [] -> () | f::fs -> f () ; bind fs let back = function None -> () | Some c -> bind c.tuning let with_model m f x = let current = Context.push model m in try bind m.tuning ; let result = f x in Context.pop model current ; back current ; result with err -> Context.pop model current ; back current ; raise err let on_model m f = with_model m f () let on_scope s f a = Context.bind scope s f a let on_kf kf f = on_scope (Some kf) f () let on_global f = on_scope None f () let get_scope () = Context.get scope let get_model () = Context.get model let get_emitter model = model.emitter let is_model_defined () = Context.defined model let directory () = Wp_parameters.get_output_dir (Context.get model).id module type Entries = sig type key type data val name : string val compare : key -> key -> int val pretty : Format.formatter -> key -> unit end module type Registry = sig module E : Entries type key = E.key type data = E.data val mem : key -> bool val find : key -> data val get : key -> data option val define : key -> data -> unit val update : key -> data -> unit val memoize : (key -> data) -> key -> data val compile : (key -> data) -> key -> unit val callback : (key -> data -> unit) -> unit val iter : (key -> data -> unit) -> unit val iter_sorted : (key -> data -> unit) -> unit end module Index(E : Entries) = struct module E = E type key = E.key type data = E.data module KEY = struct type t = E.key let compare = E.compare end module MAP = FCMap.Make(KEY) module SET = FCSet.Make(KEY) let demon = ref [] type entries = { mutable index : E.data MAP.t ; mutable lock : SET.t ; } module ENTRIES : Datatype.S with type t = entries = Datatype.Make (struct type t = entries include Datatype.Serializable_undefined let reprs = [{index=MAP.empty;lock=SET.empty}] let name = "Wp.Model.Index." ^ E.name end) module REGISTRY = State_builder.Hashtbl (Datatype.String.Hashtbl) (ENTRIES) (struct let name = "Wp.Model." ^ E.name let dependencies = [Ast.self] let size = 32 end) Projectified entry map , indexed by model let entries () : entries = let mid = (Context.get model).id in try REGISTRY.find mid with Not_found -> let e = { index=MAP.empty ; lock=SET.empty } in REGISTRY.add mid e ; e let mem k = let e = entries () in MAP.mem k e.index || SET.mem k e.lock let find k = let e = entries () in MAP.find k e.index let get k = try Some (find k) with Not_found -> None let fire k d = List.iter (fun f -> f k d) !demon let callback f = demon := !demon @ [f] let define k d = begin let e = entries () in if MAP.mem k e.index then Wp_parameters.fatal "Duplicate definition (%s:%a)" E.name E.pretty k ; if SET.mem k e.lock then Wp_parameters.fatal "Locked definition (%s:%a)" E.name E.pretty k ; e.index <- MAP.add k d e.index ; fire k d ; end let update k d = begin let e = entries () in e.index <- MAP.add k d e.index ; fire k d ; end let memoize f k = let e = entries () in try MAP.find k e.index with Not_found -> let lock = e.lock in e.lock <- SET.add k e.lock ; let d = f k in e.index <- MAP.add k d e.index ; fire k d ; e.lock <- lock ; let compile f k = ignore (memoize f k) let iter f = MAP.iter f (entries()).index let iter_sorted f = let e = entries () in let s = MAP.fold (fun k _ s -> SET.add k s) e.index SET.empty in SET.iter (fun k -> f k (MAP.find k e.index)) s end module Static(E : Entries) = struct module E = E type key = E.key type data = E.data module KEY = struct type t = E.key let compare = E.compare end module MAP = FCMap.Make(KEY) module SET = FCSet.Make(KEY) let demon = ref [] type entries = { mutable index : E.data MAP.t ; mutable lock : SET.t ; } module ENTRIES : Datatype.S with type t = entries = Datatype.Make (struct type t = entries include Datatype.Serializable_undefined let reprs = [{index=MAP.empty;lock=SET.empty}] let name = "Wp.Model.Index." ^ E.name end) module REGISTRY = State_builder.Ref (ENTRIES) (struct let name = "Wp.Model." ^ E.name let dependencies = [Ast.self] let default () = { index=MAP.empty ; lock=SET.empty } end) Projectified entry map , indexed by model let entries () : entries = REGISTRY.get () let mem k = let e = entries () in MAP.mem k e.index || SET.mem k e.lock let find k = let e = entries () in MAP.find k e.index let get k = try Some (find k) with Not_found -> None let fire k d = List.iter (fun f -> f k d) !demon let callback f = demon := !demon @ [f] let define k d = begin let e = entries () in if MAP.mem k e.index then Wp_parameters.fatal "Duplicate definition (%s:%a)" E.name E.pretty k ; if SET.mem k e.lock then Wp_parameters.fatal "Locked definition (%s:%a)" E.name E.pretty k ; e.index <- MAP.add k d e.index ; fire k d ; end let update k d = begin let e = entries () in e.index <- MAP.add k d e.index ; fire k d ; end let memoize f k = let e = entries () in try MAP.find k e.index with Not_found -> let lock = e.lock in e.lock <- SET.add k e.lock ; let d = f k in e.index <- MAP.add k d e.index ; fire k d ; e.lock <- lock ; let compile f k = ignore (memoize f k) let iter f = MAP.iter f (entries()).index let iter_sorted f = let e = entries () in let s = MAP.fold (fun k _ s -> SET.add k s) e.index SET.empty in SET.iter (fun k -> f k (MAP.find k e.index)) s end module type Key = sig type t val compare : t -> t -> int val pretty : Format.formatter -> t -> unit end module type Data = sig type key type data val name : string val compile : key -> data end module type Generator = sig type key type data val get : key -> data end module StaticGenerator(K : Key)(D : Data with type key = K.t) = struct module G = Static (struct include K include D end) type key = D.key type data = D.data let get = G.memoize D.compile end module Generator(K : Key)(D : Data with type key = K.t) = struct module G = Index (struct include K include D end) type key = D.key type data = D.data let get = G.memoize D.compile end module S = D type t = S.t
fee97a1b91cc23237dcfaa33344d7842af047db4cfb67cc43c7b9f9eea31d156
landakram/kiwi-desktop
subs.cljs
(ns kiwi.search.subs (:require [kiwi.utils :as utils] [re-frame.core :as re-frame :refer [reg-sub]] [clojure.string :as string])) (reg-sub :all-pages (fn [db _] (get-in db [:route-state :pages]))) (reg-sub :search-filter (fn [db ] (get-in db [:route-state :filter]))) (def lunr (js/require "lunr")) (set! (.-lunr js/window) lunr) (defn- build-index [pages] (let [index (lunr (fn [] (this-as ^js/lunr.Index this (.ref this "permalink") (.field this "title") (.field this "contents") (.field this "tags") (doseq [page pages] (.add this (clj->js page))))))] (print "rebuilding index") index)) (reg-sub :search-index :<- [:all-pages] (fn [pages _] (build-index pages))) (defn- valid-filter? [filter] (and (> (.-length (string/trim filter)) 0) (not (.endsWith (string/trim filter) ":")))) (defn- search [index filter] (if (valid-filter? filter) (js->clj (.search index (str filter))) [])) (defn- filter-pages [[ index pages filter-str] _] (if (valid-filter? filter-str) (let [results (search index filter-str) permalinks (map #(get % "ref") results) filtered-pages (filter #(utils/in? permalinks (:permalink %)) pages)] filtered-pages) pages)) (reg-sub :filtered-pages :<- [:search-index] :<- [:all-pages] :<- [:search-filter] filter-pages)
null
https://raw.githubusercontent.com/landakram/kiwi-desktop/cc7d0a5f28430f39d43dffb26850183601fd28f9/src/cljs/kiwi/search/subs.cljs
clojure
(ns kiwi.search.subs (:require [kiwi.utils :as utils] [re-frame.core :as re-frame :refer [reg-sub]] [clojure.string :as string])) (reg-sub :all-pages (fn [db _] (get-in db [:route-state :pages]))) (reg-sub :search-filter (fn [db ] (get-in db [:route-state :filter]))) (def lunr (js/require "lunr")) (set! (.-lunr js/window) lunr) (defn- build-index [pages] (let [index (lunr (fn [] (this-as ^js/lunr.Index this (.ref this "permalink") (.field this "title") (.field this "contents") (.field this "tags") (doseq [page pages] (.add this (clj->js page))))))] (print "rebuilding index") index)) (reg-sub :search-index :<- [:all-pages] (fn [pages _] (build-index pages))) (defn- valid-filter? [filter] (and (> (.-length (string/trim filter)) 0) (not (.endsWith (string/trim filter) ":")))) (defn- search [index filter] (if (valid-filter? filter) (js->clj (.search index (str filter))) [])) (defn- filter-pages [[ index pages filter-str] _] (if (valid-filter? filter-str) (let [results (search index filter-str) permalinks (map #(get % "ref") results) filtered-pages (filter #(utils/in? permalinks (:permalink %)) pages)] filtered-pages) pages)) (reg-sub :filtered-pages :<- [:search-index] :<- [:all-pages] :<- [:search-filter] filter-pages)
2a0098c0ca2251245d88e1b06df65311504b4bcb6e93dda978a382ee562fc06d
patricoferris/oodtty
build.ml
let time = {|Last built: 16:50:22 24/07/21 |}
null
https://raw.githubusercontent.com/patricoferris/oodtty/4fe0348e1e9d686136c0794bebe205f807bf386c/src/lib/build.ml
ocaml
let time = {|Last built: 16:50:22 24/07/21 |}
290ca8038e4ac791aa7cdd31cc597de492c36826a3d42f4d39bff69da5813979
armedbear/abcl
class-file.lisp
compiler-tests.lisp ;;; Copyright ( C ) 2010 ;;; $ Id$ ;;; ;;; 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 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 program; if not, write to the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . #+abcl (require '#:jvm) (in-package #:abcl.test.lisp) (deftest fieldtype.1a (string= (jvm::internal-field-type :int) "I") T) (deftest fieldtype.1b (string= (jvm::internal-field-type :long) "J") T) (deftest fieldtype.1c (string= (jvm::internal-field-type :float) "F") T) (deftest fieldtype.1d (string= (jvm::internal-field-type :double) "D") T) (deftest fieldtype.1e (string= (jvm::internal-field-type :boolean) "Z") T) (deftest fieldtype.1f (string= (jvm::internal-field-type :char) "C") T) (deftest fieldtype.1g (string= (jvm::internal-field-type :byte) "B") T) (deftest fieldtype.1h (string= (jvm::internal-field-type :short) "S") T) (deftest fieldtype.1i (string= (jvm::internal-field-type :void) "V") T) (deftest fieldtype.1j (string= (jvm::internal-field-type nil) "V") T) (deftest fieldtype.2 (string= (jvm::internal-field-type jvm::+lisp-object+) "org/armedbear/lisp/LispObject") T) (deftest fieldref.1a (string= (jvm::internal-field-ref :int) "I") T) (deftest fieldref.1b (string= (jvm::internal-field-ref :long) "J") T) (deftest fieldref.1c (string= (jvm::internal-field-ref :float) "F") T) (deftest fieldref.1d (string= (jvm::internal-field-ref :double) "D") T) (deftest fieldref.1e (string= (jvm::internal-field-ref :boolean) "Z") T) (deftest fieldref.1f (string= (jvm::internal-field-ref :char) "C") T) (deftest fieldref.1g (string= (jvm::internal-field-ref :byte) "B") T) (deftest fieldref.1h (string= (jvm::internal-field-ref :short) "S") T) (deftest fieldref.1i (string= (jvm::internal-field-ref :void) "V") T) (deftest fieldref.1j (string= (jvm::internal-field-ref nil) "V") T) (deftest fieldref.2 (string= (jvm::internal-field-ref jvm::+lisp-object+) "Lorg/armedbear/lisp/LispObject;") T) (deftest descriptor.1 (and (string= (jvm::descriptor :void :int :long :boolean) "(IJZ)V") (string= (jvm::descriptor nil :int :long :boolean) "(IJZ)V")) T) (deftest descriptor.2 (string= (jvm::descriptor jvm::+lisp-object+ jvm::+lisp-object+) "(Lorg/armedbear/lisp/LispObject;)Lorg/armedbear/lisp/LispObject;") T) (deftest map-flags.1 (eql (jvm::map-flags '(:public)) #x0001) T) (deftest pool.1 (let* ((pool (jvm::make-pool))) (jvm::pool-add-class pool jvm::+lisp-readtable+) (jvm::pool-add-field-ref pool jvm::+lisp-readtable+ "ABC" :int) (jvm::pool-add-field-ref pool jvm::+lisp-readtable+ "ABD" jvm::+lisp-readtable+) (jvm::pool-add-method-ref pool jvm::+lisp-readtable+ "MBC" :int) (jvm::pool-add-method-ref pool jvm::+lisp-readtable+ "MBD" jvm::+lisp-readtable+) (jvm::pool-add-interface-method-ref pool jvm::+lisp-readtable+ "MBD" :int) (jvm::pool-add-interface-method-ref pool jvm::+lisp-readtable+ "MBD" jvm::+lisp-readtable+) (jvm::pool-add-string pool "string") (jvm::pool-add-int pool 1) (jvm::pool-add-float pool 1.0f0) (jvm::pool-add-long pool 1) (jvm::pool-add-double pool 1.0d0) (jvm::pool-add-name/type pool "name1" :int) (jvm::pool-add-name/type pool "name2" jvm::+lisp-object+) (jvm::pool-add-utf8 pool "utf8") T) T) (deftest make-class-file.1 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/mcf_1")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public)))) (jvm::class-add-field file (jvm::make-field "ABC" :int)) (jvm::class-add-field file (jvm::make-field "ABD" jvm::+lisp-object+)) (jvm::class-add-method file (jvm::make-jvm-method "MBC" nil :int)) (jvm::class-add-method file (jvm::make-jvm-method "MBD" nil jvm::+lisp-object+)) (jvm::class-add-method file (jvm::make-jvm-method :constructor :void nil)) (jvm::class-add-method file (jvm::make-jvm-method :static-initializer :void nil)) T) T) (deftest finalize-class-file.1 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/fcf_1")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public)))) (jvm::class-add-field file (jvm::make-field "ABC" :int)) (jvm::class-add-field file (jvm::make-field "ABD" jvm::+lisp-object+)) (jvm::class-add-method file (jvm::make-jvm-method "MBC" nil '(:int))) (jvm::class-add-method file (jvm::make-jvm-method "MBD" nil (list jvm::+lisp-object+))) (jvm::finalize-class-file file) file T) T) (deftest generate-method.1 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/gm_1")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public))) (method (jvm::make-jvm-method :static-initializer :void nil :flags '(:static)))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit 'return)) (jvm::finalize-class-file file) (with-open-stream (stream (sys::%make-byte-array-output-stream)) (jvm::write-class-file file stream) (sys::load-compiled-function (sys::%get-output-stream-bytes stream))) T) T) (deftest generate-method.2 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/gm_2")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public))) (method (jvm::make-jvm-method "doNothing" :void nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (let ((label1 (gensym)) (label2 (gensym)) (label3 (gensym))) (jvm::label label1) (jvm::emit 'jvm::iconst_1) (jvm::label label2) (jvm::emit 'return) (jvm::label label3) (jvm::code-add-exception-handler (jvm::method-attribute method "Code") label1 label2 label3 nil)) (jvm::emit 'return)) (jvm::finalize-class-file file) (with-open-stream (stream (sys::%make-byte-array-output-stream)) (jvm::write-class-file file stream) (sys::load-compiled-function (sys::%get-output-stream-bytes stream))) T) T) generation of an ABCL - like function class (deftest generate-method.3 (let* ((class (jvm::make-jvm-class-name "org.armedbear.lisp.gm_3")) (file (jvm::make-class-file class jvm::+lisp-primitive+ '(:public))) ) (let ((method (jvm::make-jvm-method :constructor :void nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit 'aload 0) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit-invokespecial-init jvm::+lisp-primitive+ (list jvm::+lisp-object+ jvm::+lisp-object+)) (jvm::emit 'return))) (let ((method (jvm::make-jvm-method "execute" jvm::+lisp-object+ nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit 'jvm::areturn))) (jvm::finalize-class-file file) (with-open-stream (stream (sys::%make-byte-array-output-stream)) (jvm::write-class-file file stream) (funcall (sys::load-compiled-function (sys::%get-output-stream-bytes stream))))) NIL) generation of an ABCL - like function class with static init function and ;; static field (deftest generate-method.4 (let* ((class (jvm::make-jvm-class-name "org.armedbear.lisp.gm_4")) (file (jvm::make-class-file class jvm::+lisp-primitive+ '(:public))) ) (jvm::class-add-field file (jvm::make-field "N1" jvm::+lisp-object+ :flags '(:static :private))) (let ((method (jvm::make-jvm-method :static-initializer :void nil :flags '(:static)))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit-putstatic class "N1" jvm::+lisp-object+) (jvm::emit 'return))) (let ((method (jvm::make-jvm-method :constructor :void nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit 'aload 0) (jvm::emit-getstatic class "N1" jvm::+lisp-object+) (jvm::emit-getstatic class "N1" jvm::+lisp-object+) (jvm::emit-invokespecial-init jvm::+lisp-primitive+ (list jvm::+lisp-object+ jvm::+lisp-object+)) (jvm::emit 'return))) (let ((method (jvm::make-jvm-method "execute" jvm::+lisp-object+ nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic class "N1" jvm::+lisp-object+) (jvm::emit 'jvm::areturn))) (jvm::finalize-class-file file) (with-open-stream (stream (sys::%make-byte-array-output-stream)) (jvm::write-class-file file stream) (funcall (sys::load-compiled-function (sys::%get-output-stream-bytes stream))))) NIL) generation of ABCL - like function class with multiple ' execute ' methods (deftest generate-method.5 (let* ((class (jvm::make-jvm-class-name "org.armedbear.lisp.gm_5")) (file (jvm::make-class-file class jvm::+lisp-primitive+ '(:public))) ) (let ((method (jvm::make-jvm-method :constructor :void nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit 'aload 0) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit-invokespecial-init jvm::+lisp-primitive+ (list jvm::+lisp-object+ jvm::+lisp-object+)) (jvm::emit 'return))) (let ((method (jvm::make-jvm-method "execute" jvm::+lisp-object+ nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit 'jvm::areturn))) (let ((method (jvm::make-jvm-method "execute" jvm::+lisp-object+ (list jvm::+lisp-object+)))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic jvm::+lisp+ "T" jvm::+lisp-symbol+) (jvm::emit 'jvm::areturn))) (jvm::finalize-class-file file) (with-open-stream (stream (sys::%make-byte-array-output-stream)) (jvm::write-class-file file stream) (let* ((bytes (sys::%get-output-stream-bytes stream)) (fn (sys::load-compiled-function bytes))) (values (funcall fn) (funcall fn NIL))))) NIL T) ;;Nested with-code-to-method (deftest with-code-to-method.1 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/gm_6")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public))) (method (jvm::make-jvm-method :static-initializer :void nil :flags '(:static))) (registers nil)) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::with-code-to-method (file method) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::with-code-to-method (file method) (jvm::allocate-register :int) (push jvm::*register* registers)) (jvm::allocate-register :int) (push jvm::*register* registers)) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::emit 'return)) (jvm::finalize-class-file file) (nreverse registers)) (1 2 3 4 5)) (deftest with-code-to-method.2 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/gm_7")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public))) (method1 (jvm::make-jvm-method :static-initializer :void nil :flags '(:static))) (method2 (jvm::make-jvm-method "method2" :void nil)) (registers nil)) (jvm::class-add-method file method1) (jvm::class-add-method file method2) (jvm::with-code-to-method (file method1) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::with-code-to-method (file method2) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::with-code-to-method (file method1) (jvm::allocate-register :int) (push jvm::*register* registers)) (jvm::allocate-register :int) (push jvm::*register* registers)) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::emit 'return)) (jvm::finalize-class-file file) (nreverse registers)) (1 1 2 2 3)) ; ; generation of an ABCL - like function , with mixed output to constructor , ;; ;; static initializer and function method(s) ;; (deftest generate-method.6 ;; (let* ((class (jvm::make-jvm-class-name "org.armedbear.lisp.gm_6")) ;; (file (jvm::make-class-file class jvm::+lisp-primitive+ '(:public))) ;; ) ;; (let ((method (jvm::make-method :constructor :void nil))) ;; (jvm::class-add-method file method) ;; (jvm::with-code-to-method (file method) ( jvm::emit ' aload 0 ) ;; (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-object+) ;; (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-object+) ;; (jvm::emit-invokespecial-init jvm::+lisp-primitive+ ( list ;; jvm::+lisp-object+)) ;; (jvm::emit 'return))) ;; (let ((method (jvm::make-method "execute" jvm::+lisp-object+ nil))) ;; (jvm::class-add-method file method) ;; (jvm::with-code-to-method (file method) ;; (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-object+) ;; (jvm::emit 'jvm::areturn))) ;; (jvm::finalize-class-file file) ;; (with-open-stream (stream (sys::%make-byte-array-output-stream)) ;; (jvm::write-class-file file stream) ;; (ignore-errors (sys::load-compiled-function nil)) ;; (funcall (sys::load-compiled-function (sys::%get-output-stream-bytes stream)))) ;; T ;; ) ;; T)
null
https://raw.githubusercontent.com/armedbear/abcl/36a4b5994227d768882ff6458b3df9f79caac664/test/lisp/abcl/class-file.lisp
lisp
This program is free software; you can redistribute it and/or either version 2 This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, write to the Free Software static field Nested with-code-to-method ; generation of an ABCL - like function , with mixed output to constructor , ;; static initializer and function method(s) (deftest generate-method.6 (let* ((class (jvm::make-jvm-class-name "org.armedbear.lisp.gm_6")) (file (jvm::make-class-file class jvm::+lisp-primitive+ '(:public))) ) (let ((method (jvm::make-method :constructor :void nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-object+) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-object+) (jvm::emit-invokespecial-init jvm::+lisp-primitive+ jvm::+lisp-object+)) (jvm::emit 'return))) (let ((method (jvm::make-method "execute" jvm::+lisp-object+ nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-object+) (jvm::emit 'jvm::areturn))) (jvm::finalize-class-file file) (with-open-stream (stream (sys::%make-byte-array-output-stream)) (jvm::write-class-file file stream) (ignore-errors (sys::load-compiled-function nil)) (funcall (sys::load-compiled-function (sys::%get-output-stream-bytes stream)))) T ) T)
compiler-tests.lisp Copyright ( C ) 2010 $ Id$ modify it under the terms of the GNU General Public License of the License , or ( at your option ) any later version . You should have received a copy of the GNU General Public License Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . #+abcl (require '#:jvm) (in-package #:abcl.test.lisp) (deftest fieldtype.1a (string= (jvm::internal-field-type :int) "I") T) (deftest fieldtype.1b (string= (jvm::internal-field-type :long) "J") T) (deftest fieldtype.1c (string= (jvm::internal-field-type :float) "F") T) (deftest fieldtype.1d (string= (jvm::internal-field-type :double) "D") T) (deftest fieldtype.1e (string= (jvm::internal-field-type :boolean) "Z") T) (deftest fieldtype.1f (string= (jvm::internal-field-type :char) "C") T) (deftest fieldtype.1g (string= (jvm::internal-field-type :byte) "B") T) (deftest fieldtype.1h (string= (jvm::internal-field-type :short) "S") T) (deftest fieldtype.1i (string= (jvm::internal-field-type :void) "V") T) (deftest fieldtype.1j (string= (jvm::internal-field-type nil) "V") T) (deftest fieldtype.2 (string= (jvm::internal-field-type jvm::+lisp-object+) "org/armedbear/lisp/LispObject") T) (deftest fieldref.1a (string= (jvm::internal-field-ref :int) "I") T) (deftest fieldref.1b (string= (jvm::internal-field-ref :long) "J") T) (deftest fieldref.1c (string= (jvm::internal-field-ref :float) "F") T) (deftest fieldref.1d (string= (jvm::internal-field-ref :double) "D") T) (deftest fieldref.1e (string= (jvm::internal-field-ref :boolean) "Z") T) (deftest fieldref.1f (string= (jvm::internal-field-ref :char) "C") T) (deftest fieldref.1g (string= (jvm::internal-field-ref :byte) "B") T) (deftest fieldref.1h (string= (jvm::internal-field-ref :short) "S") T) (deftest fieldref.1i (string= (jvm::internal-field-ref :void) "V") T) (deftest fieldref.1j (string= (jvm::internal-field-ref nil) "V") T) (deftest fieldref.2 (string= (jvm::internal-field-ref jvm::+lisp-object+) "Lorg/armedbear/lisp/LispObject;") T) (deftest descriptor.1 (and (string= (jvm::descriptor :void :int :long :boolean) "(IJZ)V") (string= (jvm::descriptor nil :int :long :boolean) "(IJZ)V")) T) (deftest descriptor.2 (string= (jvm::descriptor jvm::+lisp-object+ jvm::+lisp-object+) "(Lorg/armedbear/lisp/LispObject;)Lorg/armedbear/lisp/LispObject;") T) (deftest map-flags.1 (eql (jvm::map-flags '(:public)) #x0001) T) (deftest pool.1 (let* ((pool (jvm::make-pool))) (jvm::pool-add-class pool jvm::+lisp-readtable+) (jvm::pool-add-field-ref pool jvm::+lisp-readtable+ "ABC" :int) (jvm::pool-add-field-ref pool jvm::+lisp-readtable+ "ABD" jvm::+lisp-readtable+) (jvm::pool-add-method-ref pool jvm::+lisp-readtable+ "MBC" :int) (jvm::pool-add-method-ref pool jvm::+lisp-readtable+ "MBD" jvm::+lisp-readtable+) (jvm::pool-add-interface-method-ref pool jvm::+lisp-readtable+ "MBD" :int) (jvm::pool-add-interface-method-ref pool jvm::+lisp-readtable+ "MBD" jvm::+lisp-readtable+) (jvm::pool-add-string pool "string") (jvm::pool-add-int pool 1) (jvm::pool-add-float pool 1.0f0) (jvm::pool-add-long pool 1) (jvm::pool-add-double pool 1.0d0) (jvm::pool-add-name/type pool "name1" :int) (jvm::pool-add-name/type pool "name2" jvm::+lisp-object+) (jvm::pool-add-utf8 pool "utf8") T) T) (deftest make-class-file.1 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/mcf_1")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public)))) (jvm::class-add-field file (jvm::make-field "ABC" :int)) (jvm::class-add-field file (jvm::make-field "ABD" jvm::+lisp-object+)) (jvm::class-add-method file (jvm::make-jvm-method "MBC" nil :int)) (jvm::class-add-method file (jvm::make-jvm-method "MBD" nil jvm::+lisp-object+)) (jvm::class-add-method file (jvm::make-jvm-method :constructor :void nil)) (jvm::class-add-method file (jvm::make-jvm-method :static-initializer :void nil)) T) T) (deftest finalize-class-file.1 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/fcf_1")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public)))) (jvm::class-add-field file (jvm::make-field "ABC" :int)) (jvm::class-add-field file (jvm::make-field "ABD" jvm::+lisp-object+)) (jvm::class-add-method file (jvm::make-jvm-method "MBC" nil '(:int))) (jvm::class-add-method file (jvm::make-jvm-method "MBD" nil (list jvm::+lisp-object+))) (jvm::finalize-class-file file) file T) T) (deftest generate-method.1 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/gm_1")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public))) (method (jvm::make-jvm-method :static-initializer :void nil :flags '(:static)))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit 'return)) (jvm::finalize-class-file file) (with-open-stream (stream (sys::%make-byte-array-output-stream)) (jvm::write-class-file file stream) (sys::load-compiled-function (sys::%get-output-stream-bytes stream))) T) T) (deftest generate-method.2 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/gm_2")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public))) (method (jvm::make-jvm-method "doNothing" :void nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (let ((label1 (gensym)) (label2 (gensym)) (label3 (gensym))) (jvm::label label1) (jvm::emit 'jvm::iconst_1) (jvm::label label2) (jvm::emit 'return) (jvm::label label3) (jvm::code-add-exception-handler (jvm::method-attribute method "Code") label1 label2 label3 nil)) (jvm::emit 'return)) (jvm::finalize-class-file file) (with-open-stream (stream (sys::%make-byte-array-output-stream)) (jvm::write-class-file file stream) (sys::load-compiled-function (sys::%get-output-stream-bytes stream))) T) T) generation of an ABCL - like function class (deftest generate-method.3 (let* ((class (jvm::make-jvm-class-name "org.armedbear.lisp.gm_3")) (file (jvm::make-class-file class jvm::+lisp-primitive+ '(:public))) ) (let ((method (jvm::make-jvm-method :constructor :void nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit 'aload 0) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit-invokespecial-init jvm::+lisp-primitive+ (list jvm::+lisp-object+ jvm::+lisp-object+)) (jvm::emit 'return))) (let ((method (jvm::make-jvm-method "execute" jvm::+lisp-object+ nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit 'jvm::areturn))) (jvm::finalize-class-file file) (with-open-stream (stream (sys::%make-byte-array-output-stream)) (jvm::write-class-file file stream) (funcall (sys::load-compiled-function (sys::%get-output-stream-bytes stream))))) NIL) generation of an ABCL - like function class with static init function and (deftest generate-method.4 (let* ((class (jvm::make-jvm-class-name "org.armedbear.lisp.gm_4")) (file (jvm::make-class-file class jvm::+lisp-primitive+ '(:public))) ) (jvm::class-add-field file (jvm::make-field "N1" jvm::+lisp-object+ :flags '(:static :private))) (let ((method (jvm::make-jvm-method :static-initializer :void nil :flags '(:static)))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit-putstatic class "N1" jvm::+lisp-object+) (jvm::emit 'return))) (let ((method (jvm::make-jvm-method :constructor :void nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit 'aload 0) (jvm::emit-getstatic class "N1" jvm::+lisp-object+) (jvm::emit-getstatic class "N1" jvm::+lisp-object+) (jvm::emit-invokespecial-init jvm::+lisp-primitive+ (list jvm::+lisp-object+ jvm::+lisp-object+)) (jvm::emit 'return))) (let ((method (jvm::make-jvm-method "execute" jvm::+lisp-object+ nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic class "N1" jvm::+lisp-object+) (jvm::emit 'jvm::areturn))) (jvm::finalize-class-file file) (with-open-stream (stream (sys::%make-byte-array-output-stream)) (jvm::write-class-file file stream) (funcall (sys::load-compiled-function (sys::%get-output-stream-bytes stream))))) NIL) generation of ABCL - like function class with multiple ' execute ' methods (deftest generate-method.5 (let* ((class (jvm::make-jvm-class-name "org.armedbear.lisp.gm_5")) (file (jvm::make-class-file class jvm::+lisp-primitive+ '(:public))) ) (let ((method (jvm::make-jvm-method :constructor :void nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit 'aload 0) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit-invokespecial-init jvm::+lisp-primitive+ (list jvm::+lisp-object+ jvm::+lisp-object+)) (jvm::emit 'return))) (let ((method (jvm::make-jvm-method "execute" jvm::+lisp-object+ nil))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic jvm::+lisp+ "NIL" jvm::+lisp-symbol+) (jvm::emit 'jvm::areturn))) (let ((method (jvm::make-jvm-method "execute" jvm::+lisp-object+ (list jvm::+lisp-object+)))) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::emit-getstatic jvm::+lisp+ "T" jvm::+lisp-symbol+) (jvm::emit 'jvm::areturn))) (jvm::finalize-class-file file) (with-open-stream (stream (sys::%make-byte-array-output-stream)) (jvm::write-class-file file stream) (let* ((bytes (sys::%get-output-stream-bytes stream)) (fn (sys::load-compiled-function bytes))) (values (funcall fn) (funcall fn NIL))))) NIL T) (deftest with-code-to-method.1 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/gm_6")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public))) (method (jvm::make-jvm-method :static-initializer :void nil :flags '(:static))) (registers nil)) (jvm::class-add-method file method) (jvm::with-code-to-method (file method) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::with-code-to-method (file method) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::with-code-to-method (file method) (jvm::allocate-register :int) (push jvm::*register* registers)) (jvm::allocate-register :int) (push jvm::*register* registers)) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::emit 'return)) (jvm::finalize-class-file file) (nreverse registers)) (1 2 3 4 5)) (deftest with-code-to-method.2 (let* ((class (jvm::make-jvm-class-name "org/armedbear/lisp/gm_7")) (file (jvm::make-class-file class jvm::+lisp-object+ '(:public))) (method1 (jvm::make-jvm-method :static-initializer :void nil :flags '(:static))) (method2 (jvm::make-jvm-method "method2" :void nil)) (registers nil)) (jvm::class-add-method file method1) (jvm::class-add-method file method2) (jvm::with-code-to-method (file method1) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::with-code-to-method (file method2) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::with-code-to-method (file method1) (jvm::allocate-register :int) (push jvm::*register* registers)) (jvm::allocate-register :int) (push jvm::*register* registers)) (jvm::allocate-register :int) (push jvm::*register* registers) (jvm::emit 'return)) (jvm::finalize-class-file file) (nreverse registers)) (1 1 2 2 3)) ( jvm::emit ' aload 0 ) ( list
d85c750935b95c0384a571fcf1022f41b85b6cdd49c747d7576cac0ae3e0a7f4
ocaml-multicore/eio
zzz.mli
(** A set of timers. *) (** A handle to a registered timer. *) module Key : sig type t end type t (** A set of timers (implemented as a priority queue). *) val create : unit -> t (** [create ()] is a fresh empty queue. *) val add : t -> Mtime.t -> unit Suspended.t -> Key.t (** [add t time thread] adds a new event, due at [time], and returns its ID. You must use {!Eio.Private.Fiber_context.set_cancel_fn} on [thread] before calling {!pop}. Your cancel function should call {!remove} (in addition to resuming [thread]). *) val remove : t -> Key.t -> unit (** [remove t key] removes an event previously added with [add]. *) val pop : t -> now:Mtime.t -> [`Due of unit Suspended.t | `Wait_until of Mtime.t | `Nothing] (** [pop ~now t] removes and returns the earliest thread due by [now]. It also clears the thread's cancel function. If no thread is due yet, it returns the time the earliest thread becomes due. *)
null
https://raw.githubusercontent.com/ocaml-multicore/eio/35feb3aaa83a47d43658b05ebc9819549593a18d/lib_eio/utils/zzz.mli
ocaml
* A set of timers. * A handle to a registered timer. * A set of timers (implemented as a priority queue). * [create ()] is a fresh empty queue. * [add t time thread] adds a new event, due at [time], and returns its ID. You must use {!Eio.Private.Fiber_context.set_cancel_fn} on [thread] before calling {!pop}. Your cancel function should call {!remove} (in addition to resuming [thread]). * [remove t key] removes an event previously added with [add]. * [pop ~now t] removes and returns the earliest thread due by [now]. It also clears the thread's cancel function. If no thread is due yet, it returns the time the earliest thread becomes due.
module Key : sig type t end type t val create : unit -> t val add : t -> Mtime.t -> unit Suspended.t -> Key.t val remove : t -> Key.t -> unit val pop : t -> now:Mtime.t -> [`Due of unit Suspended.t | `Wait_until of Mtime.t | `Nothing]
f013c971e4b1dd832a3b51d610348656032d9747fc6bbf7a73e8b942cc06d543
kana/sicp
ex-2.64.scm
(load "./sec-2.3.3-sets-as-binary-trees.scm") Exercise 2.64 . ;;; The following procedure list->tree converts an ordered list to a balanced ;;; binary tree. The helper procedure partial-tree takes as arguments an ;;; integer n and list of at least n elements and constructs a balanced tree containing the first n elements of the list . The result returned by ;;; partial-tree is a pair (formed with cons) whose car is the constructed tree ;;; and whose cdr is the list of elements not included in the tree. (define (list->tree elements) (car (partial-tree elements (length elements)))) (define (partial-tree elts n) (if (= n 0) (cons '() elts) (let ((left-size (quotient (- n 1) 2))) (let ((left-result (partial-tree elts left-size))) (let ((left-tree (car left-result)) (non-left-elts (cdr left-result)) (right-size (- n (+ left-size 1)))) (let ((this-entry (car non-left-elts)) (right-result (partial-tree (cdr non-left-elts) right-size))) (let ((right-tree (car right-result)) (remaining-elts (cdr right-result))) (cons (make-tree this-entry left-tree right-tree) remaining-elts)))))))) ;;; a. Write a short paragraph explaining as clearly as you can how ;;; partial-tree works. To simplify description , suppose that a list given to partial - tree has 2N+1 elements . At first , partial - tree divides a given list into three segments ; a left part ( N elements ) , a center part ( 1 element ) and a right part ( N ; elements). Then it converts the left and the right parts into balanced ; trees. Finally, it makes a root node which has the center part as its entry ; and the partial trees as left and right branches. Draw the tree produced by list->tree for the list ( 1 3 5 7 9 11 ) . ( list->tree ' ( 1 3 5 7 9 11 ) ) = ( car ( partial - tree ' ( 1 3 5 7 9 11 ) 6 ) ) left - size = 2 left - result = ( partial - tree ' ( 1 3 5 7 9 11 ) 2 ) = = > left - size = 0 ; left-result = (() (1 3 5 7 9 11)) right - size = 1 this - entry = 1 right - result = ( partial - tree ' ( 3 5 7 9 11 ) 1 ) = = > left - size = 0 left - result = ( ( ) ( 3 5 7 9 11 ) ) right - size = 0 this - entry = 3 ; right-result = (() (5 7 9 11)) ( ( 3 ( ) ( ) ) ( 5 7 9 11 ) ) ( ( 1 ( ) ( 3 ( ) ( ) ) ) ( 5 7 9 11 ) ) right - size = 3 this - entry = 5 right - result = ( partial - tree ' ( 7 9 11 ) 3 ) = = > left - size = 1 left - result = ( partial - tree ' ( 7 9 11 ) 1 ) = = > left - size = 0 left - result = ( ( ) ( 7 9 11 ) ) right - size = 0 this - entry = 7 right - result = ( ( ) ( 9 11 ) ) ( ( 7 ( ) ( ) ) ( 9 11 ) ) right - size = 1 this - entry = 9 right - result = ( partial - tree ' ( 11 ) 1 ) = = > left - size = 0 left - result = ( ( ) ' ( 11 ) ) right - size = 0 this - entry = 11 ; right-result = (() ()) ( ( 11 ( ) ( ) ) ( ) ) ( ( 9 ( 7 ( ) ( ) ) ( 11 ( ) ( ) ) ) ( ) ) ( ( 5 ( 1 ( ) ( 3 ( ) ( ) ) ) ( 9 ( 7 ( ) ( ) ) ( 11 ( ) ( ) ) ) ) ( ) ) = ( 5 ( 1 ( ) ( 3 ( ) ( ) ) ) ( 9 ( 7 ( ) ( ) ) ( 11 ( ) ( ) ) ) ) ; _ _ 5 _ _ ; / \ ; 1 9 ; \ / \ 3 7 11 ;;; b. What is the order of growth in the number of steps required by ;;; list->tree to convert a list of n elements? Like tree->list-2 in Exercise 2.63 , list->tree is O(N ) . Because ; * list->tree scans each element in a given list only once . * list->tree makes a tree by constructing nodes from left to right . * partial - tree uses only operations which are O(1 ) .
null
https://raw.githubusercontent.com/kana/sicp/912bda4276995492ffc2ec971618316701e196f6/ex-2.64.scm
scheme
binary tree. The helper procedure partial-tree takes as arguments an integer n and list of at least n elements and constructs a balanced tree partial-tree is a pair (formed with cons) whose car is the constructed tree and whose cdr is the list of elements not included in the tree. a. Write a short paragraph explaining as clearly as you can how partial-tree works. elements). Then it converts the left and the right parts into balanced trees. Finally, it makes a root node which has the center part as its entry and the partial trees as left and right branches. left-result = (() (1 3 5 7 9 11)) right-result = (() (5 7 9 11)) right-result = (() ()) / \ 1 9 \ / \ b. What is the order of growth in the number of steps required by list->tree to convert a list of n elements?
(load "./sec-2.3.3-sets-as-binary-trees.scm") Exercise 2.64 . The following procedure list->tree converts an ordered list to a balanced containing the first n elements of the list . The result returned by (define (list->tree elements) (car (partial-tree elements (length elements)))) (define (partial-tree elts n) (if (= n 0) (cons '() elts) (let ((left-size (quotient (- n 1) 2))) (let ((left-result (partial-tree elts left-size))) (let ((left-tree (car left-result)) (non-left-elts (cdr left-result)) (right-size (- n (+ left-size 1)))) (let ((this-entry (car non-left-elts)) (right-result (partial-tree (cdr non-left-elts) right-size))) (let ((right-tree (car right-result)) (remaining-elts (cdr right-result))) (cons (make-tree this-entry left-tree right-tree) remaining-elts)))))))) To simplify description , suppose that a list given to partial - tree has 2N+1 a left part ( N elements ) , a center part ( 1 element ) and a right part ( N Draw the tree produced by list->tree for the list ( 1 3 5 7 9 11 ) . ( list->tree ' ( 1 3 5 7 9 11 ) ) = ( car ( partial - tree ' ( 1 3 5 7 9 11 ) 6 ) ) left - size = 2 left - result = ( partial - tree ' ( 1 3 5 7 9 11 ) 2 ) = = > left - size = 0 right - size = 1 this - entry = 1 right - result = ( partial - tree ' ( 3 5 7 9 11 ) 1 ) = = > left - size = 0 left - result = ( ( ) ( 3 5 7 9 11 ) ) right - size = 0 this - entry = 3 ( ( 3 ( ) ( ) ) ( 5 7 9 11 ) ) ( ( 1 ( ) ( 3 ( ) ( ) ) ) ( 5 7 9 11 ) ) right - size = 3 this - entry = 5 right - result = ( partial - tree ' ( 7 9 11 ) 3 ) = = > left - size = 1 left - result = ( partial - tree ' ( 7 9 11 ) 1 ) = = > left - size = 0 left - result = ( ( ) ( 7 9 11 ) ) right - size = 0 this - entry = 7 right - result = ( ( ) ( 9 11 ) ) ( ( 7 ( ) ( ) ) ( 9 11 ) ) right - size = 1 this - entry = 9 right - result = ( partial - tree ' ( 11 ) 1 ) = = > left - size = 0 left - result = ( ( ) ' ( 11 ) ) right - size = 0 this - entry = 11 ( ( 11 ( ) ( ) ) ( ) ) ( ( 9 ( 7 ( ) ( ) ) ( 11 ( ) ( ) ) ) ( ) ) ( ( 5 ( 1 ( ) ( 3 ( ) ( ) ) ) ( 9 ( 7 ( ) ( ) ) ( 11 ( ) ( ) ) ) ) ( ) ) = ( 5 ( 1 ( ) ( 3 ( ) ( ) ) ) ( 9 ( 7 ( ) ( ) ) ( 11 ( ) ( ) ) ) ) _ _ 5 _ _ 3 7 11 Like tree->list-2 in Exercise 2.63 , list->tree is O(N ) . Because * list->tree scans each element in a given list only once . * list->tree makes a tree by constructing nodes from left to right . * partial - tree uses only operations which are O(1 ) .
2ff5eeb078a36334909c22381776df9adc275e5f10bcdfb3cfd663bd978d4d99
facebook/duckling
Rules.hs
Copyright ( c ) 2016 - present , Facebook , Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.TimeGrain.FI.Rules ( rules ) where import Data.String import Data.Text (Text) import Prelude import Duckling.Dimensions.Types import Duckling.Types import qualified Duckling.TimeGrain.Types as TG grains :: [(Text, String, TG.Grain)] grains = [ ("second (grain) ", "sekuntia?|s", TG.Second) , ("minute (grain)" , "minuuttia?|min", TG.Minute) , ("hour (grain)" , "tuntia?|h", TG.Hour) , ("day (grain)" , "päivä(ä)?|vuorokau(si|tta)|vrk|d", TG.Day) , ("week (grain)" , "viikkoa?|vko?", TG.Week) , ("month (grain)" , "kuukau(si|tta)|kk", TG.Month) , ("quarter (grain)", "kvartaali(a)?|neljännesvuo(si|tta)", TG.Quarter) , ("year (grain)" , "vuo(si|tta)|v\\.?|a", TG.Year) ] rules :: [Rule] rules = map go grains where go (name, regexPattern, grain) = Rule { name = name , pattern = [regex regexPattern] , prod = \_ -> Just $ Token TimeGrain grain }
null
https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/TimeGrain/FI/Rules.hs
haskell
All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. # LANGUAGE OverloadedStrings #
Copyright ( c ) 2016 - present , Facebook , Inc. module Duckling.TimeGrain.FI.Rules ( rules ) where import Data.String import Data.Text (Text) import Prelude import Duckling.Dimensions.Types import Duckling.Types import qualified Duckling.TimeGrain.Types as TG grains :: [(Text, String, TG.Grain)] grains = [ ("second (grain) ", "sekuntia?|s", TG.Second) , ("minute (grain)" , "minuuttia?|min", TG.Minute) , ("hour (grain)" , "tuntia?|h", TG.Hour) , ("day (grain)" , "päivä(ä)?|vuorokau(si|tta)|vrk|d", TG.Day) , ("week (grain)" , "viikkoa?|vko?", TG.Week) , ("month (grain)" , "kuukau(si|tta)|kk", TG.Month) , ("quarter (grain)", "kvartaali(a)?|neljännesvuo(si|tta)", TG.Quarter) , ("year (grain)" , "vuo(si|tta)|v\\.?|a", TG.Year) ] rules :: [Rule] rules = map go grains where go (name, regexPattern, grain) = Rule { name = name , pattern = [regex regexPattern] , prod = \_ -> Just $ Token TimeGrain grain }
fbf305e016b18c5838c8a3ccc838f0b54c52cbbd89721d2ee2bf1e19f1e44b7f
gregorycollins/hashtables
CheapPseudoRandomBitStream.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE CPP # module Data.HashTable.Internal.CheapPseudoRandomBitStream ( BitStream , newBitStream , getNextBit , getNBits ) where import Control.Applicative import Control.Monad.ST import Data.Bits ((.&.)) import Data.STRef import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as V import Data.Word (Word32, Word64) #if !MIN_VERSION_base(4,8,0) import Data.Word (Word) #endif import Data.HashTable.Internal.Utils ------------------------------------------------------------------------------ -- Chosen by fair dice roll. Guaranteed random. More importantly, there are an equal number of 0 and 1 bits in both of these vectors . random32s :: Vector Word32 random32s = V.fromList [ 0xe293c315 , 0x82e2ff62 , 0xcb1ef9ae , 0x78850172 , 0x551ee1ce , 0x59d6bfd1 , 0xb717ec44 , 0xe7a3024e , 0x02bb8976 , 0x87e2f94f , 0xfa156372 , 0xe1325b17 , 0xe005642a , 0xc8d02eb3 , 0xe90c0a87 , 0x4cb9e6e2 ] ------------------------------------------------------------------------------ random64s :: Vector Word64 random64s = V.fromList [ 0x62ef447e007e8732 , 0x149d6acb499feef8 , 0xca7725f9b404fbf8 , 0x4b5dfad194e626a9 , 0x6d76f2868359491b , 0x6b2284e3645dcc87 , 0x5b89b485013eaa16 , 0x6e2d4308250c435b , 0xc31e641a659e0013 , 0xe237b85e9dc7276d , 0x0b3bb7fa40d94f3f , 0x4da446874d4ca023 , 0x69240623fedbd26b , 0x76fb6810dcf894d3 , 0xa0da4e0ce57c8ea7 , 0xeb76b84453dc3873 ] ------------------------------------------------------------------------------ numRandoms :: Int numRandoms = 16 ------------------------------------------------------------------------------ randoms :: Vector Word randoms | wordSize == 32 = V.map fromIntegral random32s | otherwise = V.map fromIntegral random64s ------------------------------------------------------------------------------ data BitStream s = BitStream { _curRandom :: !(STRef s Word) , _bitsLeft :: !(STRef s Int ) , _randomPos :: !(STRef s Int ) } ------------------------------------------------------------------------------ newBitStream :: ST s (BitStream s) newBitStream = unwrapMonad $ BitStream <$> (WrapMonad $ newSTRef $ V.unsafeIndex randoms 0) <*> (WrapMonad $ newSTRef wordSize) <*> (WrapMonad $ newSTRef 1) ------------------------------------------------------------------------------ getNextBit :: BitStream s -> ST s Word getNextBit = getNBits 1 ------------------------------------------------------------------------------ getNBits :: Int -> BitStream s -> ST s Word getNBits nbits (BitStream crRef blRef rpRef) = do !bl <- readSTRef blRef if bl < nbits then newWord else nextBits bl where newWord = do !rp <- readSTRef rpRef let r = V.unsafeIndex randoms rp writeSTRef blRef $! wordSize - nbits writeSTRef rpRef $! if rp == (numRandoms-1) then 0 else rp + 1 extractBits r extractBits r = do let !b = r .&. ((1 `shiftL` nbits) - 1) writeSTRef crRef $! (r `shiftRL` nbits) return b nextBits bl = do !r <- readSTRef crRef writeSTRef blRef $! bl - nbits extractBits r
null
https://raw.githubusercontent.com/gregorycollins/hashtables/a48b589a3266be10921ad15c3b9e65d7fb7fc535/src/Data/HashTable/Internal/CheapPseudoRandomBitStream.hs
haskell
# LANGUAGE BangPatterns # ---------------------------------------------------------------------------- Chosen by fair dice roll. Guaranteed random. More importantly, there are an ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ----------------------------------------------------------------------------
# LANGUAGE CPP # module Data.HashTable.Internal.CheapPseudoRandomBitStream ( BitStream , newBitStream , getNextBit , getNBits ) where import Control.Applicative import Control.Monad.ST import Data.Bits ((.&.)) import Data.STRef import Data.Vector.Unboxed (Vector) import qualified Data.Vector.Unboxed as V import Data.Word (Word32, Word64) #if !MIN_VERSION_base(4,8,0) import Data.Word (Word) #endif import Data.HashTable.Internal.Utils equal number of 0 and 1 bits in both of these vectors . random32s :: Vector Word32 random32s = V.fromList [ 0xe293c315 , 0x82e2ff62 , 0xcb1ef9ae , 0x78850172 , 0x551ee1ce , 0x59d6bfd1 , 0xb717ec44 , 0xe7a3024e , 0x02bb8976 , 0x87e2f94f , 0xfa156372 , 0xe1325b17 , 0xe005642a , 0xc8d02eb3 , 0xe90c0a87 , 0x4cb9e6e2 ] random64s :: Vector Word64 random64s = V.fromList [ 0x62ef447e007e8732 , 0x149d6acb499feef8 , 0xca7725f9b404fbf8 , 0x4b5dfad194e626a9 , 0x6d76f2868359491b , 0x6b2284e3645dcc87 , 0x5b89b485013eaa16 , 0x6e2d4308250c435b , 0xc31e641a659e0013 , 0xe237b85e9dc7276d , 0x0b3bb7fa40d94f3f , 0x4da446874d4ca023 , 0x69240623fedbd26b , 0x76fb6810dcf894d3 , 0xa0da4e0ce57c8ea7 , 0xeb76b84453dc3873 ] numRandoms :: Int numRandoms = 16 randoms :: Vector Word randoms | wordSize == 32 = V.map fromIntegral random32s | otherwise = V.map fromIntegral random64s data BitStream s = BitStream { _curRandom :: !(STRef s Word) , _bitsLeft :: !(STRef s Int ) , _randomPos :: !(STRef s Int ) } newBitStream :: ST s (BitStream s) newBitStream = unwrapMonad $ BitStream <$> (WrapMonad $ newSTRef $ V.unsafeIndex randoms 0) <*> (WrapMonad $ newSTRef wordSize) <*> (WrapMonad $ newSTRef 1) getNextBit :: BitStream s -> ST s Word getNextBit = getNBits 1 getNBits :: Int -> BitStream s -> ST s Word getNBits nbits (BitStream crRef blRef rpRef) = do !bl <- readSTRef blRef if bl < nbits then newWord else nextBits bl where newWord = do !rp <- readSTRef rpRef let r = V.unsafeIndex randoms rp writeSTRef blRef $! wordSize - nbits writeSTRef rpRef $! if rp == (numRandoms-1) then 0 else rp + 1 extractBits r extractBits r = do let !b = r .&. ((1 `shiftL` nbits) - 1) writeSTRef crRef $! (r `shiftRL` nbits) return b nextBits bl = do !r <- readSTRef crRef writeSTRef blRef $! bl - nbits extractBits r
829207f54887b64910f7cb788ee325a4523987f6b90615a132b5bbc041d77338
eccentric-j/cljs-tui-template
test_runner.cljs
(ns {{main-ns}}.test-runner (:require ;; require all the namespaces that you want to test [{{namespace}}-test] [figwheel.main.testing :refer [run-tests-async]])) (defn -main [& args] "Tests entrypoint. Runs imported tests." (run-tests-async 5000)) (set! *main-cli-fn* nil)
null
https://raw.githubusercontent.com/eccentric-j/cljs-tui-template/6ad22eb0d069666a072c58709fc82e6f1a2ca8c3/resources/leiningen/new/cljs_tui/figwheel-main/test/test_runner.cljs
clojure
require all the namespaces that you want to test
(ns {{main-ns}}.test-runner (:require [{{namespace}}-test] [figwheel.main.testing :refer [run-tests-async]])) (defn -main [& args] "Tests entrypoint. Runs imported tests." (run-tests-async 5000)) (set! *main-cli-fn* nil)
e1dd95b49931af17d17a5f84d996f5aaddc05920f291d9d86945c4fb3b0f96e0
proglang/ldgv
FunctionSignaturesSpec.hs
# LANGUAGE BlockArguments # # OPTIONS_GHC -Wall # module FunctionSignaturesSpec (spec) where import Test.Hspec import Kinds import Syntax import Typechecker tcOptionsCast :: Options tcOptionsCast = Options{ gradual = False } spec :: Spec spec = do let tcShouldFail :: [Decl] -> Expectation tcShouldFail decls = typecheck tcOptionsCast decls `shouldNotBe` Right () let tcShouldSucceed :: [Decl] -> Expectation tcShouldSucceed decls = typecheck tcOptionsCast decls `shouldBe` Right () describe "duplicate signatures" do it "raises an error if the types agree" do tcShouldFail [ DSig "main" Many TInt , DSig "main" Many TInt ] it "raises an error if the types disagree" do tcShouldFail [ DSig "main" Many TInt , DSig "main" Many TUnit ] describe "duplicate definitions" do it "raises an error if the types agree" do let decls a r = replicate 2 $ DFun "main" a (Lit LUnit) r tcShouldFail $ decls [] Nothing tcShouldFail $ decls [] (Just TUnit) tcShouldFail $ decls [(MMany, "a", TInt)] Nothing tcShouldFail $ decls [(MMany, "a", TInt)] (Just TUnit) it "raises an error if the types disagree" do tcShouldFail [ DFun "main" [] (Lit LUnit) Nothing , DFun "main" [(MMany, "a", TInt)] (Lit LUnit) Nothing ] describe "signature and definition" do describe "agreeing types" do it "typechecks to give a signature but no return type" do tcShouldSucceed [ DSig "main" Many $ TFun MMany "a" TInt TUnit , DFun "main" [(MMany, "a", TInt)] (Lit LUnit) Nothing ] it "typechecks to give a signature and return type" do tcShouldSucceed [ DSig "main" Many $ TFun MMany "a" TInt TUnit , DFun "main" [(MMany, "a", TInt)] (Lit LUnit) (Just TUnit) ] it "typechecks if the parameter names differ" do tcShouldSucceed [ DSig "main" Many $ TFun MMany "a" TInt TUnit , DFun "main" [(MMany, "b", TInt)] (Lit LUnit) Nothing ] describe "disagreeing types" do it "raises an error if the types don't match" do tcShouldFail [ DSig "main" Many TInt , DFun "main" [] (Lit LUnit) Nothing ] it "raises an error if the returns type doesn't match" do -- The function definition would be alright by itself but the return -- type has to be equivalent with the given signature. tcShouldFail [ DSig "main" Many $ TLab ["'A", "'B"] , DFun "main" [] (Lit $ LLab "'A") (Just $ TLab ["'A"]) ]
null
https://raw.githubusercontent.com/proglang/ldgv/395af7190de7f62e2bc0ca9609a28f728ea2445e/test/FunctionSignaturesSpec.hs
haskell
The function definition would be alright by itself but the return type has to be equivalent with the given signature.
# LANGUAGE BlockArguments # # OPTIONS_GHC -Wall # module FunctionSignaturesSpec (spec) where import Test.Hspec import Kinds import Syntax import Typechecker tcOptionsCast :: Options tcOptionsCast = Options{ gradual = False } spec :: Spec spec = do let tcShouldFail :: [Decl] -> Expectation tcShouldFail decls = typecheck tcOptionsCast decls `shouldNotBe` Right () let tcShouldSucceed :: [Decl] -> Expectation tcShouldSucceed decls = typecheck tcOptionsCast decls `shouldBe` Right () describe "duplicate signatures" do it "raises an error if the types agree" do tcShouldFail [ DSig "main" Many TInt , DSig "main" Many TInt ] it "raises an error if the types disagree" do tcShouldFail [ DSig "main" Many TInt , DSig "main" Many TUnit ] describe "duplicate definitions" do it "raises an error if the types agree" do let decls a r = replicate 2 $ DFun "main" a (Lit LUnit) r tcShouldFail $ decls [] Nothing tcShouldFail $ decls [] (Just TUnit) tcShouldFail $ decls [(MMany, "a", TInt)] Nothing tcShouldFail $ decls [(MMany, "a", TInt)] (Just TUnit) it "raises an error if the types disagree" do tcShouldFail [ DFun "main" [] (Lit LUnit) Nothing , DFun "main" [(MMany, "a", TInt)] (Lit LUnit) Nothing ] describe "signature and definition" do describe "agreeing types" do it "typechecks to give a signature but no return type" do tcShouldSucceed [ DSig "main" Many $ TFun MMany "a" TInt TUnit , DFun "main" [(MMany, "a", TInt)] (Lit LUnit) Nothing ] it "typechecks to give a signature and return type" do tcShouldSucceed [ DSig "main" Many $ TFun MMany "a" TInt TUnit , DFun "main" [(MMany, "a", TInt)] (Lit LUnit) (Just TUnit) ] it "typechecks if the parameter names differ" do tcShouldSucceed [ DSig "main" Many $ TFun MMany "a" TInt TUnit , DFun "main" [(MMany, "b", TInt)] (Lit LUnit) Nothing ] describe "disagreeing types" do it "raises an error if the types don't match" do tcShouldFail [ DSig "main" Many TInt , DFun "main" [] (Lit LUnit) Nothing ] it "raises an error if the returns type doesn't match" do tcShouldFail [ DSig "main" Many $ TLab ["'A", "'B"] , DFun "main" [] (Lit $ LLab "'A") (Just $ TLab ["'A"]) ]
61c5839a2610970e825129573f0774f22a4316ed65e71ec2230af509a5d3814e
UBTECH-Walker/WalkerSimulationFor2020WAIC
CruiserJointSate.lisp
; Auto-generated. Do not edit! (cl:in-package cruiser_msgs-msg) // ! \htmlinclude (cl:defclass <CruiserJointSate> (roslisp-msg-protocol:ros-message) ((joint_num :reader joint_num :initarg :joint_num :type cl:fixnum :initform 0) (name :reader name :initarg :name :type (cl:vector cl:string) :initform (cl:make-array 0 :element-type 'cl:string :initial-element "")) (jointIndex :reader jointIndex :initarg :jointIndex :type (cl:vector cl:integer) :initform (cl:make-array 0 :element-type 'cl:integer :initial-element 0)) (position :reader position :initarg :position :type (cl:vector cl:float) :initform (cl:make-array 0 :element-type 'cl:float :initial-element 0.0)) (speed :reader speed :initarg :speed :type (cl:vector cl:float) :initform (cl:make-array 0 :element-type 'cl:float :initial-element 0.0)) (duration :reader duration :initarg :duration :type (cl:vector cl:integer) :initform (cl:make-array 0 :element-type 'cl:integer :initial-element 0))) ) (cl:defclass CruiserJointSate (<CruiserJointSate>) ()) (cl:defmethod cl:initialize-instance :after ((m <CruiserJointSate>) cl:&rest args) (cl:declare (cl:ignorable args)) (cl:unless (cl:typep m 'CruiserJointSate) (roslisp-msg-protocol:msg-deprecation-warning "using old message class name cruiser_msgs-msg:<CruiserJointSate> is deprecated: use cruiser_msgs-msg:CruiserJointSate instead."))) (cl:ensure-generic-function 'joint_num-val :lambda-list '(m)) (cl:defmethod joint_num-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:joint_num-val is deprecated. Use cruiser_msgs-msg:joint_num instead.") (joint_num m)) (cl:ensure-generic-function 'name-val :lambda-list '(m)) (cl:defmethod name-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:name-val is deprecated. Use cruiser_msgs-msg:name instead.") (name m)) (cl:ensure-generic-function 'jointIndex-val :lambda-list '(m)) (cl:defmethod jointIndex-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:jointIndex-val is deprecated. Use cruiser_msgs-msg:jointIndex instead.") (jointIndex m)) (cl:ensure-generic-function 'position-val :lambda-list '(m)) (cl:defmethod position-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:position-val is deprecated. Use cruiser_msgs-msg:position instead.") (position m)) (cl:ensure-generic-function 'speed-val :lambda-list '(m)) (cl:defmethod speed-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:speed-val is deprecated. Use cruiser_msgs-msg:speed instead.") (speed m)) (cl:ensure-generic-function 'duration-val :lambda-list '(m)) (cl:defmethod duration-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:duration-val is deprecated. Use cruiser_msgs-msg:duration instead.") (duration m)) (cl:defmethod roslisp-msg-protocol:serialize ((msg <CruiserJointSate>) ostream) "Serializes a message object of type '<CruiserJointSate>" (cl:let* ((signed (cl:slot-value msg 'joint_num)) (unsigned (cl:if (cl:< signed 0) (cl:+ signed 65536) signed))) (cl:write-byte (cl:ldb (cl:byte 8 0) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) unsigned) ostream) ) (cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'name)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream)) (cl:map cl:nil #'(cl:lambda (ele) (cl:let ((__ros_str_len (cl:length ele))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_str_len) ostream)) (cl:map cl:nil #'(cl:lambda (c) (cl:write-byte (cl:char-code c) ostream)) ele)) (cl:slot-value msg 'name)) (cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'jointIndex)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream)) (cl:map cl:nil #'(cl:lambda (ele) (cl:write-byte (cl:ldb (cl:byte 8 0) ele) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) ele) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) ele) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) ele) ostream)) (cl:slot-value msg 'jointIndex)) (cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'position)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream)) (cl:map cl:nil #'(cl:lambda (ele) (cl:let ((bits (roslisp-utils:encode-double-float-bits ele))) (cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 32) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 40) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 48) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 56) bits) ostream))) (cl:slot-value msg 'position)) (cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'speed)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream)) (cl:map cl:nil #'(cl:lambda (ele) (cl:let ((bits (roslisp-utils:encode-double-float-bits ele))) (cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 32) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 40) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 48) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 56) bits) ostream))) (cl:slot-value msg 'speed)) (cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'duration)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream)) (cl:map cl:nil #'(cl:lambda (ele) (cl:let* ((signed ele) (unsigned (cl:if (cl:< signed 0) (cl:+ signed 18446744073709551616) signed))) (cl:write-byte (cl:ldb (cl:byte 8 0) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 32) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 40) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 48) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 56) unsigned) ostream) )) (cl:slot-value msg 'duration)) ) (cl:defmethod roslisp-msg-protocol:deserialize ((msg <CruiserJointSate>) istream) "Deserializes a message object of type '<CruiserJointSate>" (cl:let ((unsigned 0)) (cl:setf (cl:ldb (cl:byte 8 0) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) unsigned) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'joint_num) (cl:if (cl:< unsigned 32768) unsigned (cl:- unsigned 65536)))) (cl:let ((__ros_arr_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'name) (cl:make-array __ros_arr_len)) (cl:let ((vals (cl:slot-value msg 'name))) (cl:dotimes (i __ros_arr_len) (cl:let ((__ros_str_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:aref vals i) (cl:make-string __ros_str_len)) (cl:dotimes (__ros_str_idx __ros_str_len msg) (cl:setf (cl:char (cl:aref vals i) __ros_str_idx) (cl:code-char (cl:read-byte istream)))))))) (cl:let ((__ros_arr_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'jointIndex) (cl:make-array __ros_arr_len)) (cl:let ((vals (cl:slot-value msg 'jointIndex))) (cl:dotimes (i __ros_arr_len) (cl:setf (cl:ldb (cl:byte 8 0) (cl:aref vals i)) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) (cl:aref vals i)) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) (cl:aref vals i)) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) (cl:aref vals i)) (cl:read-byte istream))))) (cl:let ((__ros_arr_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'position) (cl:make-array __ros_arr_len)) (cl:let ((vals (cl:slot-value msg 'position))) (cl:dotimes (i __ros_arr_len) (cl:let ((bits 0)) (cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 32) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 40) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 48) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 56) bits) (cl:read-byte istream)) (cl:setf (cl:aref vals i) (roslisp-utils:decode-double-float-bits bits)))))) (cl:let ((__ros_arr_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'speed) (cl:make-array __ros_arr_len)) (cl:let ((vals (cl:slot-value msg 'speed))) (cl:dotimes (i __ros_arr_len) (cl:let ((bits 0)) (cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 32) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 40) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 48) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 56) bits) (cl:read-byte istream)) (cl:setf (cl:aref vals i) (roslisp-utils:decode-double-float-bits bits)))))) (cl:let ((__ros_arr_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'duration) (cl:make-array __ros_arr_len)) (cl:let ((vals (cl:slot-value msg 'duration))) (cl:dotimes (i __ros_arr_len) (cl:let ((unsigned 0)) (cl:setf (cl:ldb (cl:byte 8 0) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 32) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 40) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 48) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 56) unsigned) (cl:read-byte istream)) (cl:setf (cl:aref vals i) (cl:if (cl:< unsigned 9223372036854775808) unsigned (cl:- unsigned 18446744073709551616))))))) msg ) (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<CruiserJointSate>))) "Returns string type for a message object of type '<CruiserJointSate>" "cruiser_msgs/CruiserJointSate") (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'CruiserJointSate))) "Returns string type for a message object of type 'CruiserJointSate" "cruiser_msgs/CruiserJointSate") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<CruiserJointSate>))) "Returns md5sum for a message object of type '<CruiserJointSate>" "892654ee59978ac7b005cc792fc55ba6") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'CruiserJointSate))) "Returns md5sum for a message object of type 'CruiserJointSate" "892654ee59978ac7b005cc792fc55ba6") (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<CruiserJointSate>))) "Returns full string definition for message of type '<CruiserJointSate>" (cl:format cl:nil "int16 joint_num ~% ~%# Joints name to control in array ~%# example - [\"LShoudlerRoll\", \"NeckYaw\", \"NeckPitch\"] ~%string[] name ~% ~%# Joints index to control in array ~%uint32[] jointIndex ~% ~%# Corresponding joints postion ~%# unit - radian; ~%# example - [0.54, 1.22, 1.39] ~%float64[] position ~% ~%# Corresponding joints max speed ~%float64[] speed ~% ~%# Corresponding joints motion time ~%# unit - millisecond ~%int64[] duration ~% ~%~%~%")) (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'CruiserJointSate))) "Returns full string definition for message of type 'CruiserJointSate" (cl:format cl:nil "int16 joint_num ~% ~%# Joints name to control in array ~%# example - [\"LShoudlerRoll\", \"NeckYaw\", \"NeckPitch\"] ~%string[] name ~% ~%# Joints index to control in array ~%uint32[] jointIndex ~% ~%# Corresponding joints postion ~%# unit - radian; ~%# example - [0.54, 1.22, 1.39] ~%float64[] position ~% ~%# Corresponding joints max speed ~%float64[] speed ~% ~%# Corresponding joints motion time ~%# unit - millisecond ~%int64[] duration ~% ~%~%~%")) (cl:defmethod roslisp-msg-protocol:serialization-length ((msg <CruiserJointSate>)) (cl:+ 0 2 4 (cl:reduce #'cl:+ (cl:slot-value msg 'name) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 4 (cl:length ele)))) 4 (cl:reduce #'cl:+ (cl:slot-value msg 'jointIndex) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 4))) 4 (cl:reduce #'cl:+ (cl:slot-value msg 'position) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 8))) 4 (cl:reduce #'cl:+ (cl:slot-value msg 'speed) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 8))) 4 (cl:reduce #'cl:+ (cl:slot-value msg 'duration) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 8))) )) (cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <CruiserJointSate>)) "Converts a ROS message object to a list" (cl:list 'CruiserJointSate (cl:cons ':joint_num (joint_num msg)) (cl:cons ':name (name msg)) (cl:cons ':jointIndex (jointIndex msg)) (cl:cons ':position (position msg)) (cl:cons ':speed (speed msg)) (cl:cons ':duration (duration msg)) ))
null
https://raw.githubusercontent.com/UBTECH-Walker/WalkerSimulationFor2020WAIC/7cdb21dabb8423994ba3f6021bc7934290d5faa9/walker_WAIC_18.04_v1.2_20200616/walker_install/share/common-lisp/ros/cruiser_msgs/msg/CruiserJointSate.lisp
lisp
Auto-generated. Do not edit!
(cl:in-package cruiser_msgs-msg) // ! \htmlinclude (cl:defclass <CruiserJointSate> (roslisp-msg-protocol:ros-message) ((joint_num :reader joint_num :initarg :joint_num :type cl:fixnum :initform 0) (name :reader name :initarg :name :type (cl:vector cl:string) :initform (cl:make-array 0 :element-type 'cl:string :initial-element "")) (jointIndex :reader jointIndex :initarg :jointIndex :type (cl:vector cl:integer) :initform (cl:make-array 0 :element-type 'cl:integer :initial-element 0)) (position :reader position :initarg :position :type (cl:vector cl:float) :initform (cl:make-array 0 :element-type 'cl:float :initial-element 0.0)) (speed :reader speed :initarg :speed :type (cl:vector cl:float) :initform (cl:make-array 0 :element-type 'cl:float :initial-element 0.0)) (duration :reader duration :initarg :duration :type (cl:vector cl:integer) :initform (cl:make-array 0 :element-type 'cl:integer :initial-element 0))) ) (cl:defclass CruiserJointSate (<CruiserJointSate>) ()) (cl:defmethod cl:initialize-instance :after ((m <CruiserJointSate>) cl:&rest args) (cl:declare (cl:ignorable args)) (cl:unless (cl:typep m 'CruiserJointSate) (roslisp-msg-protocol:msg-deprecation-warning "using old message class name cruiser_msgs-msg:<CruiserJointSate> is deprecated: use cruiser_msgs-msg:CruiserJointSate instead."))) (cl:ensure-generic-function 'joint_num-val :lambda-list '(m)) (cl:defmethod joint_num-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:joint_num-val is deprecated. Use cruiser_msgs-msg:joint_num instead.") (joint_num m)) (cl:ensure-generic-function 'name-val :lambda-list '(m)) (cl:defmethod name-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:name-val is deprecated. Use cruiser_msgs-msg:name instead.") (name m)) (cl:ensure-generic-function 'jointIndex-val :lambda-list '(m)) (cl:defmethod jointIndex-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:jointIndex-val is deprecated. Use cruiser_msgs-msg:jointIndex instead.") (jointIndex m)) (cl:ensure-generic-function 'position-val :lambda-list '(m)) (cl:defmethod position-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:position-val is deprecated. Use cruiser_msgs-msg:position instead.") (position m)) (cl:ensure-generic-function 'speed-val :lambda-list '(m)) (cl:defmethod speed-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:speed-val is deprecated. Use cruiser_msgs-msg:speed instead.") (speed m)) (cl:ensure-generic-function 'duration-val :lambda-list '(m)) (cl:defmethod duration-val ((m <CruiserJointSate>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:duration-val is deprecated. Use cruiser_msgs-msg:duration instead.") (duration m)) (cl:defmethod roslisp-msg-protocol:serialize ((msg <CruiserJointSate>) ostream) "Serializes a message object of type '<CruiserJointSate>" (cl:let* ((signed (cl:slot-value msg 'joint_num)) (unsigned (cl:if (cl:< signed 0) (cl:+ signed 65536) signed))) (cl:write-byte (cl:ldb (cl:byte 8 0) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) unsigned) ostream) ) (cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'name)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream)) (cl:map cl:nil #'(cl:lambda (ele) (cl:let ((__ros_str_len (cl:length ele))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_str_len) ostream)) (cl:map cl:nil #'(cl:lambda (c) (cl:write-byte (cl:char-code c) ostream)) ele)) (cl:slot-value msg 'name)) (cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'jointIndex)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream)) (cl:map cl:nil #'(cl:lambda (ele) (cl:write-byte (cl:ldb (cl:byte 8 0) ele) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) ele) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) ele) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) ele) ostream)) (cl:slot-value msg 'jointIndex)) (cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'position)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream)) (cl:map cl:nil #'(cl:lambda (ele) (cl:let ((bits (roslisp-utils:encode-double-float-bits ele))) (cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 32) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 40) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 48) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 56) bits) ostream))) (cl:slot-value msg 'position)) (cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'speed)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream)) (cl:map cl:nil #'(cl:lambda (ele) (cl:let ((bits (roslisp-utils:encode-double-float-bits ele))) (cl:write-byte (cl:ldb (cl:byte 8 0) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 32) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 40) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 48) bits) ostream) (cl:write-byte (cl:ldb (cl:byte 8 56) bits) ostream))) (cl:slot-value msg 'speed)) (cl:let ((__ros_arr_len (cl:length (cl:slot-value msg 'duration)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_arr_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_arr_len) ostream)) (cl:map cl:nil #'(cl:lambda (ele) (cl:let* ((signed ele) (unsigned (cl:if (cl:< signed 0) (cl:+ signed 18446744073709551616) signed))) (cl:write-byte (cl:ldb (cl:byte 8 0) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 32) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 40) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 48) unsigned) ostream) (cl:write-byte (cl:ldb (cl:byte 8 56) unsigned) ostream) )) (cl:slot-value msg 'duration)) ) (cl:defmethod roslisp-msg-protocol:deserialize ((msg <CruiserJointSate>) istream) "Deserializes a message object of type '<CruiserJointSate>" (cl:let ((unsigned 0)) (cl:setf (cl:ldb (cl:byte 8 0) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) unsigned) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'joint_num) (cl:if (cl:< unsigned 32768) unsigned (cl:- unsigned 65536)))) (cl:let ((__ros_arr_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'name) (cl:make-array __ros_arr_len)) (cl:let ((vals (cl:slot-value msg 'name))) (cl:dotimes (i __ros_arr_len) (cl:let ((__ros_str_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:aref vals i) (cl:make-string __ros_str_len)) (cl:dotimes (__ros_str_idx __ros_str_len msg) (cl:setf (cl:char (cl:aref vals i) __ros_str_idx) (cl:code-char (cl:read-byte istream)))))))) (cl:let ((__ros_arr_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'jointIndex) (cl:make-array __ros_arr_len)) (cl:let ((vals (cl:slot-value msg 'jointIndex))) (cl:dotimes (i __ros_arr_len) (cl:setf (cl:ldb (cl:byte 8 0) (cl:aref vals i)) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) (cl:aref vals i)) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) (cl:aref vals i)) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) (cl:aref vals i)) (cl:read-byte istream))))) (cl:let ((__ros_arr_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'position) (cl:make-array __ros_arr_len)) (cl:let ((vals (cl:slot-value msg 'position))) (cl:dotimes (i __ros_arr_len) (cl:let ((bits 0)) (cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 32) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 40) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 48) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 56) bits) (cl:read-byte istream)) (cl:setf (cl:aref vals i) (roslisp-utils:decode-double-float-bits bits)))))) (cl:let ((__ros_arr_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'speed) (cl:make-array __ros_arr_len)) (cl:let ((vals (cl:slot-value msg 'speed))) (cl:dotimes (i __ros_arr_len) (cl:let ((bits 0)) (cl:setf (cl:ldb (cl:byte 8 0) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 32) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 40) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 48) bits) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 56) bits) (cl:read-byte istream)) (cl:setf (cl:aref vals i) (roslisp-utils:decode-double-float-bits bits)))))) (cl:let ((__ros_arr_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_arr_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'duration) (cl:make-array __ros_arr_len)) (cl:let ((vals (cl:slot-value msg 'duration))) (cl:dotimes (i __ros_arr_len) (cl:let ((unsigned 0)) (cl:setf (cl:ldb (cl:byte 8 0) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 32) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 40) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 48) unsigned) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 56) unsigned) (cl:read-byte istream)) (cl:setf (cl:aref vals i) (cl:if (cl:< unsigned 9223372036854775808) unsigned (cl:- unsigned 18446744073709551616))))))) msg ) (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<CruiserJointSate>))) "Returns string type for a message object of type '<CruiserJointSate>" "cruiser_msgs/CruiserJointSate") (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'CruiserJointSate))) "Returns string type for a message object of type 'CruiserJointSate" "cruiser_msgs/CruiserJointSate") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<CruiserJointSate>))) "Returns md5sum for a message object of type '<CruiserJointSate>" "892654ee59978ac7b005cc792fc55ba6") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'CruiserJointSate))) "Returns md5sum for a message object of type 'CruiserJointSate" "892654ee59978ac7b005cc792fc55ba6") (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<CruiserJointSate>))) "Returns full string definition for message of type '<CruiserJointSate>" (cl:format cl:nil "int16 joint_num ~% ~%# Joints name to control in array ~%# example - [\"LShoudlerRoll\", \"NeckYaw\", \"NeckPitch\"] ~%string[] name ~% ~%# Joints index to control in array ~%uint32[] jointIndex ~% ~%# Corresponding joints postion ~%# unit - radian; ~%# example - [0.54, 1.22, 1.39] ~%float64[] position ~% ~%# Corresponding joints max speed ~%float64[] speed ~% ~%# Corresponding joints motion time ~%# unit - millisecond ~%int64[] duration ~% ~%~%~%")) (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'CruiserJointSate))) "Returns full string definition for message of type 'CruiserJointSate" (cl:format cl:nil "int16 joint_num ~% ~%# Joints name to control in array ~%# example - [\"LShoudlerRoll\", \"NeckYaw\", \"NeckPitch\"] ~%string[] name ~% ~%# Joints index to control in array ~%uint32[] jointIndex ~% ~%# Corresponding joints postion ~%# unit - radian; ~%# example - [0.54, 1.22, 1.39] ~%float64[] position ~% ~%# Corresponding joints max speed ~%float64[] speed ~% ~%# Corresponding joints motion time ~%# unit - millisecond ~%int64[] duration ~% ~%~%~%")) (cl:defmethod roslisp-msg-protocol:serialization-length ((msg <CruiserJointSate>)) (cl:+ 0 2 4 (cl:reduce #'cl:+ (cl:slot-value msg 'name) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 4 (cl:length ele)))) 4 (cl:reduce #'cl:+ (cl:slot-value msg 'jointIndex) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 4))) 4 (cl:reduce #'cl:+ (cl:slot-value msg 'position) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 8))) 4 (cl:reduce #'cl:+ (cl:slot-value msg 'speed) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 8))) 4 (cl:reduce #'cl:+ (cl:slot-value msg 'duration) :key #'(cl:lambda (ele) (cl:declare (cl:ignorable ele)) (cl:+ 8))) )) (cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <CruiserJointSate>)) "Converts a ROS message object to a list" (cl:list 'CruiserJointSate (cl:cons ':joint_num (joint_num msg)) (cl:cons ':name (name msg)) (cl:cons ':jointIndex (jointIndex msg)) (cl:cons ':position (position msg)) (cl:cons ':speed (speed msg)) (cl:cons ':duration (duration msg)) ))
6789eb696afd819aace5704e9987b81a655b4f3e7f1edb294bbefa4495f44024
hipsleek/hipsleek
nativefront.ml
#include "xdebug.cppo" open VarGen open Globals open Sleekcommons module I = Iast module IF = Iformula module IP = Ipure let get_command ( input : string ) : ( string * string ) = let start_idx = ref 0 in let len = String.length input in let ( ) = while ( ! start_idx < len ) & & ( ( String.get input ! start_idx ) = ' ' ) do start_idx : = ! start_idx + 1 done in let end_idx = ref ! start_idx in let ( ) = while ( ! end_idx < len ) & & ( ( String.get input ! end_idx ) ! = ' ' ) do end_idx : = ! end_idx + 1 done in let cmd = String.sub input ! start_idx ( ! end_idx - ! start_idx ) in let dat = String.sub input ! end_idx ( len - ! end_idx ) in ( cmd , dat ) let parse ( input : string ) : command = let cmd , dat = get_command input in let inlex = in match cmd with | " data " - > let ddef = Sparser.data_decl ( Slexer.tokenizer " interactive " ) inlex in ddef | " pred " - > let pdef = Sparser.view_decl ( Slexer.tokenizer " interactive " ) inlex in PredDef pdef | " lemma " - > let ldef = Sparser.coercion_decl ( Slexer.tokenizer " interactive " ) inlex in ldef | " checkentail " - > let [ a_str ; c_str ] = Gen.split_by " |- " dat in let a_lex = in let c_lex = in let a_f = Sparser.constr ( Slexer.tokenizer " interactive " ) a_lex in let c_f = Sparser.constr ( Slexer.tokenizer " interactive " ) c_lex in ( a_f , c_f ) | " print " - > Print ( Gen.trim_str dat ) | _ - > failwith ( " Unsupported command : " ^ cmd ) let get_command (input : string) : (string * string) = let start_idx = ref 0 in let len = String.length input in let () = while (!start_idx < len) && ((String.get input !start_idx) = ' ') do start_idx := !start_idx + 1 done in let end_idx = ref !start_idx in let () = while (!end_idx < len) && ((String.get input !end_idx) != ' ') do end_idx := !end_idx + 1 done in let cmd = String.sub input !start_idx (!end_idx - !start_idx) in let dat = String.sub input !end_idx (len - !end_idx) in (cmd, dat) let parse (input : string) : command = let cmd, dat = get_command input in let inlex = Lexing.from_string dat in match cmd with | "data" -> let ddef = Sparser.data_decl (Slexer.tokenizer "interactive") inlex in DataDef ddef | "pred" -> let pdef = Sparser.view_decl (Slexer.tokenizer "interactive") inlex in PredDef pdef | "lemma" -> let ldef = Sparser.coercion_decl (Slexer.tokenizer "interactive") inlex in LemmaDef ldef | "checkentail" -> let [a_str; c_str] = Gen.split_by "|-" dat in let a_lex = Lexing.from_string a_str in let c_lex = Lexing.from_string c_str in let a_f = Sparser.constr (Slexer.tokenizer "interactive") a_lex in let c_f = Sparser.constr (Slexer.tokenizer "interactive") c_lex in EntailCheck (a_f, c_f) | "print" -> Print (Gen.trim_str dat) | _ -> failwith ("Unsupported command: " ^ cmd) *) let parse_slk (input : string) : command = Parser.parse_sleek_int "sleek string" input (* let parse (input : string) : command = *) (* Debug.loop_1_no "parse" (fun x -> x) (fun _ -> "?") parse input *) let list_parse (input_file) : command list = let org_in_chnl = open_in input_file in Globals.input_file_name:= input_file; let cmd = Parser.parse_sleek input_file (Stream.of_channel org_in_chnl) in close_in org_in_chnl; cmd (* let list_parse (input_file) : command list = *) (* Debug.loop_1_no "list_parse" (fun _ -> "?") (fun _ -> "?") list_parse input_file *)
null
https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/bef_indent/nativefront.ml
ocaml
let parse (input : string) : command = Debug.loop_1_no "parse" (fun x -> x) (fun _ -> "?") parse input let list_parse (input_file) : command list = Debug.loop_1_no "list_parse" (fun _ -> "?") (fun _ -> "?") list_parse input_file
#include "xdebug.cppo" open VarGen open Globals open Sleekcommons module I = Iast module IF = Iformula module IP = Ipure let get_command ( input : string ) : ( string * string ) = let start_idx = ref 0 in let len = String.length input in let ( ) = while ( ! start_idx < len ) & & ( ( String.get input ! start_idx ) = ' ' ) do start_idx : = ! start_idx + 1 done in let end_idx = ref ! start_idx in let ( ) = while ( ! end_idx < len ) & & ( ( String.get input ! end_idx ) ! = ' ' ) do end_idx : = ! end_idx + 1 done in let cmd = String.sub input ! start_idx ( ! end_idx - ! start_idx ) in let dat = String.sub input ! end_idx ( len - ! end_idx ) in ( cmd , dat ) let parse ( input : string ) : command = let cmd , dat = get_command input in let inlex = in match cmd with | " data " - > let ddef = Sparser.data_decl ( Slexer.tokenizer " interactive " ) inlex in ddef | " pred " - > let pdef = Sparser.view_decl ( Slexer.tokenizer " interactive " ) inlex in PredDef pdef | " lemma " - > let ldef = Sparser.coercion_decl ( Slexer.tokenizer " interactive " ) inlex in ldef | " checkentail " - > let [ a_str ; c_str ] = Gen.split_by " |- " dat in let a_lex = in let c_lex = in let a_f = Sparser.constr ( Slexer.tokenizer " interactive " ) a_lex in let c_f = Sparser.constr ( Slexer.tokenizer " interactive " ) c_lex in ( a_f , c_f ) | " print " - > Print ( Gen.trim_str dat ) | _ - > failwith ( " Unsupported command : " ^ cmd ) let get_command (input : string) : (string * string) = let start_idx = ref 0 in let len = String.length input in let () = while (!start_idx < len) && ((String.get input !start_idx) = ' ') do start_idx := !start_idx + 1 done in let end_idx = ref !start_idx in let () = while (!end_idx < len) && ((String.get input !end_idx) != ' ') do end_idx := !end_idx + 1 done in let cmd = String.sub input !start_idx (!end_idx - !start_idx) in let dat = String.sub input !end_idx (len - !end_idx) in (cmd, dat) let parse (input : string) : command = let cmd, dat = get_command input in let inlex = Lexing.from_string dat in match cmd with | "data" -> let ddef = Sparser.data_decl (Slexer.tokenizer "interactive") inlex in DataDef ddef | "pred" -> let pdef = Sparser.view_decl (Slexer.tokenizer "interactive") inlex in PredDef pdef | "lemma" -> let ldef = Sparser.coercion_decl (Slexer.tokenizer "interactive") inlex in LemmaDef ldef | "checkentail" -> let [a_str; c_str] = Gen.split_by "|-" dat in let a_lex = Lexing.from_string a_str in let c_lex = Lexing.from_string c_str in let a_f = Sparser.constr (Slexer.tokenizer "interactive") a_lex in let c_f = Sparser.constr (Slexer.tokenizer "interactive") c_lex in EntailCheck (a_f, c_f) | "print" -> Print (Gen.trim_str dat) | _ -> failwith ("Unsupported command: " ^ cmd) *) let parse_slk (input : string) : command = Parser.parse_sleek_int "sleek string" input let list_parse (input_file) : command list = let org_in_chnl = open_in input_file in Globals.input_file_name:= input_file; let cmd = Parser.parse_sleek input_file (Stream.of_channel org_in_chnl) in close_in org_in_chnl; cmd
ded5e666105bc1a83845f8c697a5a29072f110feccf7b8638ad5a7d0ed5954f3
dwango/fialyzer
variable.mli
val create : unit -> string val reset_count : unit -> unit
null
https://raw.githubusercontent.com/dwango/fialyzer/3c4b4fc2dacf84008910135bfef16e4ce79f9c89/lib/variable.mli
ocaml
val create : unit -> string val reset_count : unit -> unit
e4110dadc0f94e517aece83d7d0ea9643feb425e377e59239b5844fd4cbdc539
tweag/ormolu
longer.hs
module Main (main) where a b c main :: IO () main = return () d e f g foo :: Int foo = 5
null
https://raw.githubusercontent.com/tweag/ormolu/25b04d45b4f3e8db81bc4a863f2fededda7bc384/data/diff-tests/inputs/longer.hs
haskell
module Main (main) where a b c main :: IO () main = return () d e f g foo :: Int foo = 5
ae6ea9dfeec7ff36b66233f9f3fa6d976a1ebabe77377060df2c570265197208
haskell/hackage-server
Unpack.hs
Unpack a tarball containing a Cabal package # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE FlexibleContexts # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # module Distribution.Server.Packages.Unpack ( CombinedTarErrs(..), checkEntries, checkUselessPermissions, unpackPackage, unpackPackageRaw, ) where import Distribution.Server.Prelude import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Codec.Archive.Tar.Check as Tar import Distribution.CabalSpecVersion ( CabalSpecVersion(..) ) import Distribution.Version ( nullVersion ) import Distribution.Types.PackageName ( mkPackageName, unPackageName ) import Distribution.Package ( PackageIdentifier, packageVersion, packageName ) import Distribution.PackageDescription ( GenericPackageDescription(..), PackageDescription(..) , licenseRaw, specVersion ) import Distribution.PackageDescription.Configuration ( flattenPackageDescription ) import Distribution.PackageDescription.Check ( PackageCheck(..), checkPackage, CheckPackageContentOps(..) , checkPackageContent ) import Distribution.Parsec ( showPError, showPWarning ) import Distribution.Text ( display, simpleParse ) import Distribution . Parsec ( Parsec ( .. ) ) import qualified Distribution . Parsec as P -- import qualified Distribution.Compat.CharParsing as P import Distribution.Server.Util.ParseSpecVer import qualified Distribution.SPDX as SPDX import qualified Distribution.SPDX.LicenseId as SPDX.LId import qualified Distribution.License as License import Control.Monad.Except ( ExceptT, runExceptT, MonadError, throwError ) import Control.Monad.Identity ( Identity(..) ) import Control.Monad.Writer ( WriterT(..), MonadWriter, tell ) import Data.Bits ( (.&.) ) import Data.ByteString.Lazy ( ByteString ) import qualified Data.ByteString.Lazy as LBS import Data.List ( nub, partition, isPrefixOf ) import qualified Data.Map.Strict as Map ( fromList, lookup ) import Data.Time ( UTCTime(..), fromGregorian, addUTCTime ) import Data.Time.Clock.POSIX ( posixSecondsToUTCTime ) import qualified Distribution.Server.Util.GZip as GZip import System.FilePath ( (</>), (<.>), splitDirectories, splitExtension, normalise ) import qualified System.FilePath.Windows ( takeFileName ) import qualified System.FilePath.Posix ( takeFileName, takeDirectory, addTrailingPathSeparator , dropTrailingPathSeparator ) import Text.Printf ( printf ) -- Whether to allow upload of "all rights reserved" packages allowAllRightsReserved :: Bool allowAllRightsReserved = True | Upload or check a tarball containing a Cabal package . -- Returns either an fatal error or a package description and a list -- of warnings. unpackPackage :: UTCTime -> FilePath -> ByteString -> Either String ((GenericPackageDescription, ByteString), [String]) unpackPackage now tarGzFile contents = runUploadMonad $ do (pkgId, tarIndex) <- tarPackageChecks False now tarGzFile contents (pkgDesc, warnings, cabalEntry) <- basicChecks pkgId tarIndex mapM_ throwError warnings extraChecks pkgDesc pkgId tarIndex return (pkgDesc, cabalEntry) unpackPackageRaw :: FilePath -> ByteString -> Either String ((GenericPackageDescription, ByteString), [String]) unpackPackageRaw tarGzFile contents = runUploadMonad $ do (pkgId, tarIndex) <- tarPackageChecks True noTime tarGzFile contents (pkgDesc, _warnings, cabalEntry) <- basicChecks pkgId tarIndex return (pkgDesc, cabalEntry) where noTime = UTCTime (fromGregorian 1970 1 1) 0 tarPackageChecks :: Bool -> UTCTime -> FilePath -> ByteString -> UploadMonad (PackageIdentifier, TarIndex) tarPackageChecks lax now tarGzFile contents = do let (pkgidStr, ext) = (base, tar ++ gz) where (tarFile, gz) = splitExtension (portableTakeFileName tarGzFile) (base, tar) = splitExtension tarFile unless (ext == ".tar.gz") $ throwError $ tarGzFile ++ " is not a gzipped tar file, it must have the .tar.gz extension" pkgid <- case simpleParse pkgidStr of Just pkgid | (== nullVersion) . packageVersion $ pkgid -> throwError $ "Invalid package id " ++ quote pkgidStr ++ ". It must include the package version number, and not just " ++ "the package name, e.g. 'foo-1.0'." | display pkgid == pkgidStr -> return (pkgid :: PackageIdentifier) _ -> throwError $ "Invalid package id " ++ quote pkgidStr ++ ". The tarball must use the name of the package." -- Extract entries and check the tar format / portability let entries = tarballChecks lax now expectedDir $ Tar.read (GZip.decompressNamed tarGzFile contents) expectedDir = display pkgid selectEntry entry = case Tar.entryContent entry of Tar.NormalFile bs _ -> Just (normalise (Tar.entryPath entry), NormalFile bs) Tar.Directory -> Just (normalise (Tar.entryPath entry), Directory) Tar.SymbolicLink linkTarget -> Just (normalise (Tar.entryPath entry), Link (Tar.fromLinkTarget linkTarget)) Tar.HardLink linkTarget -> Just (normalise (Tar.entryPath entry), Link (Tar.fromLinkTarget linkTarget)) _ -> Nothing files <- selectEntries explainTarError selectEntry entries return (pkgid, files) type TarIndex = [(FilePath, File)] data File = Directory | NormalFile ByteString | Link FilePath deriving Show basicChecks :: PackageIdentifier -> TarIndex -> UploadMonad (GenericPackageDescription, [String], ByteString) basicChecks pkgid tarIndex = do -- Extract the .cabal file from the tarball let cabalEntries = [ content | (fp, NormalFile content) <- tarIndex , fp == cabalFileName ] name = unPackageName (packageName pkgid) cabalFileName = display pkgid </> name <.> "cabal" cabalEntry <- case cabalEntries of NB : tar files * can * contain more than one entry for the same filename . ( This was observed in practice with the package ) . -- In this case, after extracting the tar the *last* file in the archive wins . Since selectEntries returns results in reverse order we use the head : cabalEntry:_ -> -- We tend to keep hold of the .cabal file, but -- cabalEntry itself is part of a much larger -- ByteString (the whole tar file), so we make a -- copy of it return $ LBS.copy cabalEntry [] -> throwError $ "The " ++ quote cabalFileName ++ " file is missing from the package tarball." when (startsWithBOM cabalEntry) $ throwError $ "The cabal file starts with a Unicode byte order mark (BOM), " ++ "which causes problems for older versions of cabal. Please " ++ "save the package's cabal file as UTF8 without the BOM." Parse the file (specVerOk,pkgDesc, warnings) <- case parseGenericPackageDescriptionChecked cabalEntry of (_, _, Left (_, err:_)) -> -- TODO: show all errors throwError $ showPError cabalFileName err (_, _, Left (_, [])) -> throwError $ cabalFileName ++ ": parsing failed" (specVerOk', warnings, Right pkgDesc) -> return (specVerOk',pkgDesc, map (showPWarning cabalFileName) warnings) -- make sure the parseSpecVer heuristic agrees with the full parser let specVer = specVersion $ packageDescription pkgDesc specVersionChecks specVerOk specVer Check that the name and version in Cabal file match when (packageName pkgDesc /= packageName pkgid) $ throwError "Package name in the cabal file does not match the file name." when (packageVersion pkgDesc /= packageVersion pkgid) $ throwError "Package version in the cabal file does not match the file name." -- check for reserved/magic package names when (packageName pkgid `elem` reservedPkgNames) $ throwError "Package name is reserved." return (pkgDesc, warnings, cabalEntry) where -- these names are reserved for the time being, as they have -- special meaning in cabal's UI reservedPkgNames = map mkPackageName ["all","any","none","setup","lib","exe","test"] specVersionChecks :: MonadError String m => Bool -> CabalSpecVersion -> m () specVersionChecks specVerOk specVer = do when (not specVerOk) $ throwError "The 'cabal-version' field could not be properly parsed." -- Don't allowing uploading new pre-1.2 .cabal files as the parser is likely too lax TODO : slowly phase out ancient cabal spec versions below 1.10 when (specVer < CabalSpecV1_2) $ throwError "'cabal-version' must be at least 1.2" -- Safeguard; should already be caught by parser unless (specVer <= CabalSpecV3_0) $ throwError "'cabal-version' must be at most 3.0" -- | The issue is that browsers can upload the file name using either unix -- or windows convention, so we need to take the basename using either -- convention. Since windows allows the unix '/' as a separator then we can -- use the Windows.takeFileName as a portable solution. -- portableTakeFileName :: FilePath -> String portableTakeFileName = System.FilePath.Windows.takeFileName tarOps :: PackageIdentifier -> TarIndex -> CheckPackageContentOps UploadMonad tarOps pkgId tarIndex = CheckPackageContentOps { doesFileExist = fileExist . relative, doesDirectoryExist = dirExist . relative . System.FilePath.Posix.addTrailingPathSeparator, getDirectoryContents = dirContents . System.FilePath.Posix.dropTrailingPathSeparator . relative, getFileContents = fileContents . relative } where -- The tar index has names like <pkgid>/foo.cabal, but the CheckPackageContentOps requests files without specifying the pkgid -- root. We convert the requested file paths into the tar index format. relative = normalise . (display pkgId </>) -- Build the map. In case of multiple intries for a file, we want the -- last entry in the tar file to win (per tar append-to-update semantics). Since the tarIndex list is the reversed tar file , we need to reverse it back since with Map.fromList later entries win . fileMap = Map.fromList (reverse tarIndex) resolvePath :: Int -> FilePath -> Either String (Maybe File) resolvePath 0 path = Left ("Too many links redirects when looking for file " ++ quote path) resolvePath n path = case Map.lookup path fileMap of Just (Link fp) -> resolvePath (n-1) fp Just entry -> Right (Just entry) Nothing -> Right Nothing fileExist path = case resolvePath 10 path of Left err -> throwError err Right (Just NormalFile{}) -> return True Right _ -> return False dirExist path = case resolvePath 10 path of Left err -> throwError err Right (Just Directory) -> return True -- Some .tar files miss some directory entries, though it has files in -- those directories. That's enough for the directory to be created, -- thus we should consider it to exist. _ -> return (any ((path `isPrefixOf`) . fst) tarIndex) -- O(n). Only used once to find all .cabal files in the package root. Some -- .tar files have duplicate entries for the same .cabal file, so we use -- nub. dirContents dir = return (nub [ fileName | (fp, _) <- tarIndex , System.FilePath.Posix.takeDirectory fp == dir , let fileName = System.FilePath.Posix.takeFileName fp , fileName /= "" ]) fileContents :: FilePath -> UploadMonad ByteString fileContents path = case Map.lookup path fileMap of Just (NormalFile contents) -> return contents Just (Link fp) -> fileContents fp _ -> throwError ("getFileContents: file does not exist: " ++ path) -- Miscellaneous checks on package description extraChecks :: GenericPackageDescription -> PackageIdentifier -> TarIndex -> UploadMonad () extraChecks genPkgDesc pkgId tarIndex = do let pkgDesc = flattenPackageDescription genPkgDesc fileChecks <- checkPackageContent (tarOps pkgId tarIndex) pkgDesc let pureChecks = checkPackage genPkgDesc (Just pkgDesc) checks = pureChecks ++ fileChecks isDistError (PackageDistSuspicious {}) = False -- just a warning isDistError (PackageDistSuspiciousWarn {}) = False -- just a warning isDistError _ = True (errors, warnings) = partition isDistError checks mapM_ (throwError . explanation) errors mapM_ (warn . explanation) warnings -- Proprietary License check (only active in central-server branch) unless (allowAllRightsReserved || isAcceptableLicense pkgDesc) $ throwError $ "This server does not accept packages with 'license' " ++ "field set to e.g. AllRightsReserved. See " ++ " for more information " ++ "about accepted licenses." -- Check for an existing x-revision when (isJust (lookup "x-revision" (customFieldsPD pkgDesc))) $ throwError $ "Newly uploaded packages must not specify the 'x-revision' " ++ "field in their .cabal file. This is only used for " ++ "post-release revisions." Monad for uploading packages : -- WriterT for warning messages -- Either for fatal errors newtype UploadMonad a = UploadMonad (WriterT [String] (ExceptT String Identity) a) deriving (Functor, Applicative, Monad, MonadWriter [String], MonadError String) warn :: String -> UploadMonad () warn msg = tell [msg] runUploadMonad :: UploadMonad a -> Either String (a, [String]) runUploadMonad (UploadMonad m) = runIdentity . runExceptT . runWriterT $ m selectEntries :: forall err a. (err -> String) -> (Tar.Entry -> Maybe a) -> Tar.Entries err -> UploadMonad [a] selectEntries formatErr select = extract [] where extract :: [a] -> Tar.Entries err -> UploadMonad [a] extract _ (Tar.Fail err) = throwError (formatErr err) extract selected Tar.Done = return selected extract selected (Tar.Next entry entries) = case select entry of Nothing -> extract selected entries Just saved -> extract (saved : selected) entries data CombinedTarErrs = FormatError Tar.FormatError | PortabilityError Tar.PortabilityError | TarBombError FilePath FilePath | FutureTimeError FilePath UTCTime UTCTime | PermissionsError FilePath Tar.Permissions tarballChecks :: Bool -> UTCTime -> FilePath -> Tar.Entries Tar.FormatError -> Tar.Entries CombinedTarErrs tarballChecks lax now expectedDir = (if not lax then checkFutureTimes now else id) . checkTarbomb expectedDir . (if not lax then checkUselessPermissions else id) . (if lax then ignoreShortTrailer else fmapTarError (either id PortabilityError) . Tar.checkPortability) . fmapTarError FormatError where ignoreShortTrailer = Tar.foldEntries Tar.Next Tar.Done (\e -> case e of FormatError Tar.ShortTrailer -> Tar.Done _ -> Tar.Fail e) fmapTarError f = Tar.foldEntries Tar.Next Tar.Done (Tar.Fail . f) checkFutureTimes :: UTCTime -> Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs checkFutureTimes now = checkEntries checkEntry where Allow 30s for client clock skew now' = addUTCTime 30 now checkEntry entry | entryUTCTime > now' = Just (FutureTimeError posixPath entryUTCTime now') where entryUTCTime = posixSecondsToUTCTime (realToFrac (Tar.entryTime entry)) posixPath = Tar.fromTarPathToPosixPath (Tar.entryTarPath entry) checkEntry _ = Nothing checkTarbomb :: FilePath -> Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs checkTarbomb expectedTopDir = checkEntries checkEntry where checkEntry entry = case splitDirectories (Tar.entryPath entry) of (topDir:_) | topDir == expectedTopDir -> Nothing _ -> Just $ TarBombError (Tar.entryPath entry) expectedTopDir checkUselessPermissions :: Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs checkUselessPermissions = checkEntries checkEntry where checkEntry entry = case Tar.entryContent entry of (Tar.NormalFile _ _) -> checkPermissions 0o644 (Tar.entryPermissions entry) (Tar.Directory) -> checkPermissions 0o755 (Tar.entryPermissions entry) _ -> Nothing where checkPermissions expected actual = if expected .&. actual /= expected then Just $ PermissionsError (Tar.entryPath entry) actual else Nothing checkEntries :: (Tar.Entry -> Maybe e) -> Tar.Entries e -> Tar.Entries e checkEntries checkEntry = Tar.foldEntries (\entry rest -> maybe (Tar.Next entry rest) Tar.Fail (checkEntry entry)) Tar.Done Tar.Fail explainTarError :: CombinedTarErrs -> String explainTarError (TarBombError filename expectedDir) = "Bad file name in package tarball: " ++ quote filename ++ "\nAll the file in the package tarball must be in the subdirectory " ++ quote expectedDir ++ "." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.GnuFormat)) = "This tarball is in the non-standard GNU tar format. " ++ "For portability and long-term data preservation, hackage requires that " ++ "package tarballs use the standard 'ustar' format. If you are using GNU " ++ "tar, use --format=ustar to get the standard portable format." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.V7Format)) = "This tarball is in the old Unix V7 tar format. " ++ "For portability and long-term data preservation, hackage requires that " ++ "package tarballs use the standard 'ustar' format. Virtually all tar " ++ "programs can now produce ustar format (POSIX 1988). For example if you " ++ "are using GNU tar, use --format=ustar to get the standard portable format." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.UstarFormat)) = error "explainTarError: impossible UstarFormat" explainTarError (PortabilityError Tar.NonPortableFileType) = "The package tarball contains a non-portable entry type. " ++ "For portability, package tarballs should use the 'ustar' format " ++ "and only contain normal files, directories and file links." explainTarError (PortabilityError (Tar.NonPortableEntryNameChar _)) = "The package tarball contains an entry with a non-ASCII file name. " ++ "For portability, package tarballs should contain only ASCII file names " ++ "(e.g. not UTF8 encoded Unicode)." explainTarError (PortabilityError ( {})) = show err ++ ". For portability, hackage requires that file names be valid on both Unix " ++ "and Windows systems, and not refer outside of the tarball." explainTarError (FormatError formateror) = "There is an error in the format of the tar file: " ++ show formateror ++ ". Check that it is a valid tar file (e.g. 'tar -xtf thefile.tar'). " ++ "You may need to re-create the package tarball and try again." explainTarError (FutureTimeError entryname time serverTime) = "The tarball entry " ++ quote entryname ++ " has a file timestamp that is " ++ "in the future (" ++ show time ++ " vs this server's time of " ++ show serverTime ++ "). This tends to cause problems for build systems and other tools, so hackage " ++ "does not allow it. This problem can be caused by having a misconfigured system " ++ "time, or by bugs in the tools (tarballs created by 'cabal sdist' on Windows " ++ "with cabal-install-1.18.0.2 or older have this problem)." explainTarError (PermissionsError entryname mode) = "The tarball entry " ++ quote entryname ++ " has file permissions that are " ++ "broken: " ++ showMode mode ++ ". Permissions must be 644 at a minimum " ++ "for files and 755 for directories." where showMode :: Tar.Permissions -> String showMode m = printf "%.3o" (fromIntegral m :: Int) quote :: String -> String quote s = "'" ++ s ++ "'" -- | Whether a UTF8 BOM is at the beginning of the input startsWithBOM :: ByteString -> Bool startsWithBOM bs = LBS.take 3 bs == LBS.pack [0xEF, 0xBB, 0xBF] -- | Licence acceptance predicate (only used on central-server) -- * NONE is rejected -- -- * "or later" syntax (+ postfix) is rejected -- -- * "WITH exc" exceptions are rejected -- -- * There should be a way to interpert license as (conjunction of) OSI - accepted licenses or CC0 -- isAcceptableLicense :: PackageDescription -> Bool isAcceptableLicense = either goSpdx goLegacy . licenseRaw where ` cabal - version : 2.2 ` and later goSpdx :: SPDX.License -> Bool goSpdx SPDX.NONE = False goSpdx (SPDX.License expr) = goExpr expr where goExpr (SPDX.EAnd a b) = goExpr a && goExpr b goExpr (SPDX.EOr a b) = goExpr a || goExpr b goExpr (SPDX.ELicense _ (Just _)) = False -- Don't allow exceptions goExpr (SPDX.ELicense s Nothing) = goSimple s goSimple (SPDX.ELicenseRef _) = False -- don't allow referenced licenses do n't allow + licenses ( use GPL-3.0 - or - later e.g. ) CC0 is n't OSI approved , but we allow it as " PublicDomain " , this is eg . PublicDomain in -qq-0.0.2/src/LICENSE allow only OSI or FSF approved licenses . pre ` cabal - version : 2.2 ` goLegacy License.AllRightsReserved = False goLegacy _ = True
null
https://raw.githubusercontent.com/haskell/hackage-server/e907996430c6720f61ad6313d75f6f3a97cfb334/src/Distribution/Server/Packages/Unpack.hs
haskell
# LANGUAGE RankNTypes # import qualified Distribution.Compat.CharParsing as P Whether to allow upload of "all rights reserved" packages Returns either an fatal error or a package description and a list of warnings. Extract entries and check the tar format / portability Extract the .cabal file from the tarball In this case, after extracting the tar the *last* file in the archive We tend to keep hold of the .cabal file, but cabalEntry itself is part of a much larger ByteString (the whole tar file), so we make a copy of it TODO: show all errors make sure the parseSpecVer heuristic agrees with the full parser check for reserved/magic package names these names are reserved for the time being, as they have special meaning in cabal's UI Don't allowing uploading new pre-1.2 .cabal files as the parser is likely too lax Safeguard; should already be caught by parser | The issue is that browsers can upload the file name using either unix or windows convention, so we need to take the basename using either convention. Since windows allows the unix '/' as a separator then we can use the Windows.takeFileName as a portable solution. The tar index has names like <pkgid>/foo.cabal, but the root. We convert the requested file paths into the tar index format. Build the map. In case of multiple intries for a file, we want the last entry in the tar file to win (per tar append-to-update semantics). Some .tar files miss some directory entries, though it has files in those directories. That's enough for the directory to be created, thus we should consider it to exist. O(n). Only used once to find all .cabal files in the package root. Some .tar files have duplicate entries for the same .cabal file, so we use nub. Miscellaneous checks on package description just a warning just a warning Proprietary License check (only active in central-server branch) Check for an existing x-revision WriterT for warning messages Either for fatal errors | Whether a UTF8 BOM is at the beginning of the input | Licence acceptance predicate (only used on central-server) * "or later" syntax (+ postfix) is rejected * "WITH exc" exceptions are rejected * There should be a way to interpert license as (conjunction of) Don't allow exceptions don't allow referenced licenses
Unpack a tarball containing a Cabal package # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # module Distribution.Server.Packages.Unpack ( CombinedTarErrs(..), checkEntries, checkUselessPermissions, unpackPackage, unpackPackageRaw, ) where import Distribution.Server.Prelude import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Codec.Archive.Tar.Check as Tar import Distribution.CabalSpecVersion ( CabalSpecVersion(..) ) import Distribution.Version ( nullVersion ) import Distribution.Types.PackageName ( mkPackageName, unPackageName ) import Distribution.Package ( PackageIdentifier, packageVersion, packageName ) import Distribution.PackageDescription ( GenericPackageDescription(..), PackageDescription(..) , licenseRaw, specVersion ) import Distribution.PackageDescription.Configuration ( flattenPackageDescription ) import Distribution.PackageDescription.Check ( PackageCheck(..), checkPackage, CheckPackageContentOps(..) , checkPackageContent ) import Distribution.Parsec ( showPError, showPWarning ) import Distribution.Text ( display, simpleParse ) import Distribution . Parsec ( Parsec ( .. ) ) import qualified Distribution . Parsec as P import Distribution.Server.Util.ParseSpecVer import qualified Distribution.SPDX as SPDX import qualified Distribution.SPDX.LicenseId as SPDX.LId import qualified Distribution.License as License import Control.Monad.Except ( ExceptT, runExceptT, MonadError, throwError ) import Control.Monad.Identity ( Identity(..) ) import Control.Monad.Writer ( WriterT(..), MonadWriter, tell ) import Data.Bits ( (.&.) ) import Data.ByteString.Lazy ( ByteString ) import qualified Data.ByteString.Lazy as LBS import Data.List ( nub, partition, isPrefixOf ) import qualified Data.Map.Strict as Map ( fromList, lookup ) import Data.Time ( UTCTime(..), fromGregorian, addUTCTime ) import Data.Time.Clock.POSIX ( posixSecondsToUTCTime ) import qualified Distribution.Server.Util.GZip as GZip import System.FilePath ( (</>), (<.>), splitDirectories, splitExtension, normalise ) import qualified System.FilePath.Windows ( takeFileName ) import qualified System.FilePath.Posix ( takeFileName, takeDirectory, addTrailingPathSeparator , dropTrailingPathSeparator ) import Text.Printf ( printf ) allowAllRightsReserved :: Bool allowAllRightsReserved = True | Upload or check a tarball containing a Cabal package . unpackPackage :: UTCTime -> FilePath -> ByteString -> Either String ((GenericPackageDescription, ByteString), [String]) unpackPackage now tarGzFile contents = runUploadMonad $ do (pkgId, tarIndex) <- tarPackageChecks False now tarGzFile contents (pkgDesc, warnings, cabalEntry) <- basicChecks pkgId tarIndex mapM_ throwError warnings extraChecks pkgDesc pkgId tarIndex return (pkgDesc, cabalEntry) unpackPackageRaw :: FilePath -> ByteString -> Either String ((GenericPackageDescription, ByteString), [String]) unpackPackageRaw tarGzFile contents = runUploadMonad $ do (pkgId, tarIndex) <- tarPackageChecks True noTime tarGzFile contents (pkgDesc, _warnings, cabalEntry) <- basicChecks pkgId tarIndex return (pkgDesc, cabalEntry) where noTime = UTCTime (fromGregorian 1970 1 1) 0 tarPackageChecks :: Bool -> UTCTime -> FilePath -> ByteString -> UploadMonad (PackageIdentifier, TarIndex) tarPackageChecks lax now tarGzFile contents = do let (pkgidStr, ext) = (base, tar ++ gz) where (tarFile, gz) = splitExtension (portableTakeFileName tarGzFile) (base, tar) = splitExtension tarFile unless (ext == ".tar.gz") $ throwError $ tarGzFile ++ " is not a gzipped tar file, it must have the .tar.gz extension" pkgid <- case simpleParse pkgidStr of Just pkgid | (== nullVersion) . packageVersion $ pkgid -> throwError $ "Invalid package id " ++ quote pkgidStr ++ ". It must include the package version number, and not just " ++ "the package name, e.g. 'foo-1.0'." | display pkgid == pkgidStr -> return (pkgid :: PackageIdentifier) _ -> throwError $ "Invalid package id " ++ quote pkgidStr ++ ". The tarball must use the name of the package." let entries = tarballChecks lax now expectedDir $ Tar.read (GZip.decompressNamed tarGzFile contents) expectedDir = display pkgid selectEntry entry = case Tar.entryContent entry of Tar.NormalFile bs _ -> Just (normalise (Tar.entryPath entry), NormalFile bs) Tar.Directory -> Just (normalise (Tar.entryPath entry), Directory) Tar.SymbolicLink linkTarget -> Just (normalise (Tar.entryPath entry), Link (Tar.fromLinkTarget linkTarget)) Tar.HardLink linkTarget -> Just (normalise (Tar.entryPath entry), Link (Tar.fromLinkTarget linkTarget)) _ -> Nothing files <- selectEntries explainTarError selectEntry entries return (pkgid, files) type TarIndex = [(FilePath, File)] data File = Directory | NormalFile ByteString | Link FilePath deriving Show basicChecks :: PackageIdentifier -> TarIndex -> UploadMonad (GenericPackageDescription, [String], ByteString) basicChecks pkgid tarIndex = do let cabalEntries = [ content | (fp, NormalFile content) <- tarIndex , fp == cabalFileName ] name = unPackageName (packageName pkgid) cabalFileName = display pkgid </> name <.> "cabal" cabalEntry <- case cabalEntries of NB : tar files * can * contain more than one entry for the same filename . ( This was observed in practice with the package ) . wins . Since selectEntries returns results in reverse order we use the head : return $ LBS.copy cabalEntry [] -> throwError $ "The " ++ quote cabalFileName ++ " file is missing from the package tarball." when (startsWithBOM cabalEntry) $ throwError $ "The cabal file starts with a Unicode byte order mark (BOM), " ++ "which causes problems for older versions of cabal. Please " ++ "save the package's cabal file as UTF8 without the BOM." Parse the file (specVerOk,pkgDesc, warnings) <- case parseGenericPackageDescriptionChecked cabalEntry of throwError $ showPError cabalFileName err (_, _, Left (_, [])) -> throwError $ cabalFileName ++ ": parsing failed" (specVerOk', warnings, Right pkgDesc) -> return (specVerOk',pkgDesc, map (showPWarning cabalFileName) warnings) let specVer = specVersion $ packageDescription pkgDesc specVersionChecks specVerOk specVer Check that the name and version in Cabal file match when (packageName pkgDesc /= packageName pkgid) $ throwError "Package name in the cabal file does not match the file name." when (packageVersion pkgDesc /= packageVersion pkgid) $ throwError "Package version in the cabal file does not match the file name." when (packageName pkgid `elem` reservedPkgNames) $ throwError "Package name is reserved." return (pkgDesc, warnings, cabalEntry) where reservedPkgNames = map mkPackageName ["all","any","none","setup","lib","exe","test"] specVersionChecks :: MonadError String m => Bool -> CabalSpecVersion -> m () specVersionChecks specVerOk specVer = do when (not specVerOk) $ throwError "The 'cabal-version' field could not be properly parsed." TODO : slowly phase out ancient cabal spec versions below 1.10 when (specVer < CabalSpecV1_2) $ throwError "'cabal-version' must be at least 1.2" unless (specVer <= CabalSpecV3_0) $ throwError "'cabal-version' must be at most 3.0" portableTakeFileName :: FilePath -> String portableTakeFileName = System.FilePath.Windows.takeFileName tarOps :: PackageIdentifier -> TarIndex -> CheckPackageContentOps UploadMonad tarOps pkgId tarIndex = CheckPackageContentOps { doesFileExist = fileExist . relative, doesDirectoryExist = dirExist . relative . System.FilePath.Posix.addTrailingPathSeparator, getDirectoryContents = dirContents . System.FilePath.Posix.dropTrailingPathSeparator . relative, getFileContents = fileContents . relative } where CheckPackageContentOps requests files without specifying the pkgid relative = normalise . (display pkgId </>) Since the tarIndex list is the reversed tar file , we need to reverse it back since with Map.fromList later entries win . fileMap = Map.fromList (reverse tarIndex) resolvePath :: Int -> FilePath -> Either String (Maybe File) resolvePath 0 path = Left ("Too many links redirects when looking for file " ++ quote path) resolvePath n path = case Map.lookup path fileMap of Just (Link fp) -> resolvePath (n-1) fp Just entry -> Right (Just entry) Nothing -> Right Nothing fileExist path = case resolvePath 10 path of Left err -> throwError err Right (Just NormalFile{}) -> return True Right _ -> return False dirExist path = case resolvePath 10 path of Left err -> throwError err Right (Just Directory) -> return True _ -> return (any ((path `isPrefixOf`) . fst) tarIndex) dirContents dir = return (nub [ fileName | (fp, _) <- tarIndex , System.FilePath.Posix.takeDirectory fp == dir , let fileName = System.FilePath.Posix.takeFileName fp , fileName /= "" ]) fileContents :: FilePath -> UploadMonad ByteString fileContents path = case Map.lookup path fileMap of Just (NormalFile contents) -> return contents Just (Link fp) -> fileContents fp _ -> throwError ("getFileContents: file does not exist: " ++ path) extraChecks :: GenericPackageDescription -> PackageIdentifier -> TarIndex -> UploadMonad () extraChecks genPkgDesc pkgId tarIndex = do let pkgDesc = flattenPackageDescription genPkgDesc fileChecks <- checkPackageContent (tarOps pkgId tarIndex) pkgDesc let pureChecks = checkPackage genPkgDesc (Just pkgDesc) checks = pureChecks ++ fileChecks isDistError _ = True (errors, warnings) = partition isDistError checks mapM_ (throwError . explanation) errors mapM_ (warn . explanation) warnings unless (allowAllRightsReserved || isAcceptableLicense pkgDesc) $ throwError $ "This server does not accept packages with 'license' " ++ "field set to e.g. AllRightsReserved. See " ++ " for more information " ++ "about accepted licenses." when (isJust (lookup "x-revision" (customFieldsPD pkgDesc))) $ throwError $ "Newly uploaded packages must not specify the 'x-revision' " ++ "field in their .cabal file. This is only used for " ++ "post-release revisions." Monad for uploading packages : newtype UploadMonad a = UploadMonad (WriterT [String] (ExceptT String Identity) a) deriving (Functor, Applicative, Monad, MonadWriter [String], MonadError String) warn :: String -> UploadMonad () warn msg = tell [msg] runUploadMonad :: UploadMonad a -> Either String (a, [String]) runUploadMonad (UploadMonad m) = runIdentity . runExceptT . runWriterT $ m selectEntries :: forall err a. (err -> String) -> (Tar.Entry -> Maybe a) -> Tar.Entries err -> UploadMonad [a] selectEntries formatErr select = extract [] where extract :: [a] -> Tar.Entries err -> UploadMonad [a] extract _ (Tar.Fail err) = throwError (formatErr err) extract selected Tar.Done = return selected extract selected (Tar.Next entry entries) = case select entry of Nothing -> extract selected entries Just saved -> extract (saved : selected) entries data CombinedTarErrs = FormatError Tar.FormatError | PortabilityError Tar.PortabilityError | TarBombError FilePath FilePath | FutureTimeError FilePath UTCTime UTCTime | PermissionsError FilePath Tar.Permissions tarballChecks :: Bool -> UTCTime -> FilePath -> Tar.Entries Tar.FormatError -> Tar.Entries CombinedTarErrs tarballChecks lax now expectedDir = (if not lax then checkFutureTimes now else id) . checkTarbomb expectedDir . (if not lax then checkUselessPermissions else id) . (if lax then ignoreShortTrailer else fmapTarError (either id PortabilityError) . Tar.checkPortability) . fmapTarError FormatError where ignoreShortTrailer = Tar.foldEntries Tar.Next Tar.Done (\e -> case e of FormatError Tar.ShortTrailer -> Tar.Done _ -> Tar.Fail e) fmapTarError f = Tar.foldEntries Tar.Next Tar.Done (Tar.Fail . f) checkFutureTimes :: UTCTime -> Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs checkFutureTimes now = checkEntries checkEntry where Allow 30s for client clock skew now' = addUTCTime 30 now checkEntry entry | entryUTCTime > now' = Just (FutureTimeError posixPath entryUTCTime now') where entryUTCTime = posixSecondsToUTCTime (realToFrac (Tar.entryTime entry)) posixPath = Tar.fromTarPathToPosixPath (Tar.entryTarPath entry) checkEntry _ = Nothing checkTarbomb :: FilePath -> Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs checkTarbomb expectedTopDir = checkEntries checkEntry where checkEntry entry = case splitDirectories (Tar.entryPath entry) of (topDir:_) | topDir == expectedTopDir -> Nothing _ -> Just $ TarBombError (Tar.entryPath entry) expectedTopDir checkUselessPermissions :: Tar.Entries CombinedTarErrs -> Tar.Entries CombinedTarErrs checkUselessPermissions = checkEntries checkEntry where checkEntry entry = case Tar.entryContent entry of (Tar.NormalFile _ _) -> checkPermissions 0o644 (Tar.entryPermissions entry) (Tar.Directory) -> checkPermissions 0o755 (Tar.entryPermissions entry) _ -> Nothing where checkPermissions expected actual = if expected .&. actual /= expected then Just $ PermissionsError (Tar.entryPath entry) actual else Nothing checkEntries :: (Tar.Entry -> Maybe e) -> Tar.Entries e -> Tar.Entries e checkEntries checkEntry = Tar.foldEntries (\entry rest -> maybe (Tar.Next entry rest) Tar.Fail (checkEntry entry)) Tar.Done Tar.Fail explainTarError :: CombinedTarErrs -> String explainTarError (TarBombError filename expectedDir) = "Bad file name in package tarball: " ++ quote filename ++ "\nAll the file in the package tarball must be in the subdirectory " ++ quote expectedDir ++ "." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.GnuFormat)) = "This tarball is in the non-standard GNU tar format. " ++ "For portability and long-term data preservation, hackage requires that " ++ "package tarballs use the standard 'ustar' format. If you are using GNU " ++ "tar, use --format=ustar to get the standard portable format." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.V7Format)) = "This tarball is in the old Unix V7 tar format. " ++ "For portability and long-term data preservation, hackage requires that " ++ "package tarballs use the standard 'ustar' format. Virtually all tar " ++ "programs can now produce ustar format (POSIX 1988). For example if you " ++ "are using GNU tar, use --format=ustar to get the standard portable format." explainTarError (PortabilityError (Tar.NonPortableFormat Tar.UstarFormat)) = error "explainTarError: impossible UstarFormat" explainTarError (PortabilityError Tar.NonPortableFileType) = "The package tarball contains a non-portable entry type. " ++ "For portability, package tarballs should use the 'ustar' format " ++ "and only contain normal files, directories and file links." explainTarError (PortabilityError (Tar.NonPortableEntryNameChar _)) = "The package tarball contains an entry with a non-ASCII file name. " ++ "For portability, package tarballs should contain only ASCII file names " ++ "(e.g. not UTF8 encoded Unicode)." explainTarError (PortabilityError ( {})) = show err ++ ". For portability, hackage requires that file names be valid on both Unix " ++ "and Windows systems, and not refer outside of the tarball." explainTarError (FormatError formateror) = "There is an error in the format of the tar file: " ++ show formateror ++ ". Check that it is a valid tar file (e.g. 'tar -xtf thefile.tar'). " ++ "You may need to re-create the package tarball and try again." explainTarError (FutureTimeError entryname time serverTime) = "The tarball entry " ++ quote entryname ++ " has a file timestamp that is " ++ "in the future (" ++ show time ++ " vs this server's time of " ++ show serverTime ++ "). This tends to cause problems for build systems and other tools, so hackage " ++ "does not allow it. This problem can be caused by having a misconfigured system " ++ "time, or by bugs in the tools (tarballs created by 'cabal sdist' on Windows " ++ "with cabal-install-1.18.0.2 or older have this problem)." explainTarError (PermissionsError entryname mode) = "The tarball entry " ++ quote entryname ++ " has file permissions that are " ++ "broken: " ++ showMode mode ++ ". Permissions must be 644 at a minimum " ++ "for files and 755 for directories." where showMode :: Tar.Permissions -> String showMode m = printf "%.3o" (fromIntegral m :: Int) quote :: String -> String quote s = "'" ++ s ++ "'" startsWithBOM :: ByteString -> Bool startsWithBOM bs = LBS.take 3 bs == LBS.pack [0xEF, 0xBB, 0xBF] * NONE is rejected OSI - accepted licenses or CC0 isAcceptableLicense :: PackageDescription -> Bool isAcceptableLicense = either goSpdx goLegacy . licenseRaw where ` cabal - version : 2.2 ` and later goSpdx :: SPDX.License -> Bool goSpdx SPDX.NONE = False goSpdx (SPDX.License expr) = goExpr expr where goExpr (SPDX.EAnd a b) = goExpr a && goExpr b goExpr (SPDX.EOr a b) = goExpr a || goExpr b goExpr (SPDX.ELicense s Nothing) = goSimple s do n't allow + licenses ( use GPL-3.0 - or - later e.g. ) CC0 is n't OSI approved , but we allow it as " PublicDomain " , this is eg . PublicDomain in -qq-0.0.2/src/LICENSE allow only OSI or FSF approved licenses . pre ` cabal - version : 2.2 ` goLegacy License.AllRightsReserved = False goLegacy _ = True
674a9aacd1ee0b641c10e90643e0dbbfbf521addfc12603e5f34f3c24178ed4a
lloda/guile-newra
read.scm
-*- mode : scheme ; coding : utf-8 -*- ( c ) 2017 - 2019 ; This library 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. ;;; Commentary: Reader for ra objects . They start with # % instead of # , otherwise the syntax is the same as for regular arrays . ;;; Code: (define-module (newra read) #:export (list->ra list->typed-ra)) (import (newra base) (newra map) (newra tools) (only (newra print) *ra-parenthesized-rank-zero*) (ice-9 match) (ice-9 rdelim) (rnrs io ports) (only (rnrs base) vector-map) (srfi 71) (srfi 26) (only (srfi 1) fold unzip2 car+cdr)) (re-export *ra-parenthesized-rank-zero*) (define vector-fold (@ (newra vector) vector-fold)) take a looked ahead ' c ' . FIXME should n't look ahead the last one and then again in the caller . (define (read-number port) (let* ((c (lookahead-char port)) (m c (if (eqv? c #\-) (begin (get-char port) (values -1 (lookahead-char port))) (values 1 c)))) (unless (char-numeric? c) (throw 'failed-to-read-number)) (* m (let loop ((n 0) (c c)) (if (char-numeric? c) (loop (+ (* 10 n) (string->number (string (get-char port)))) (lookahead-char port)) n))))) (define (skip-whitespace port) (let loop ((c (lookahead-char port))) (cond ((char-whitespace? c) (get-char port) (loop (lookahead-char port))) (else c)))) (define pick-functions (@ (newra base) pick-functions)) (define pick-make (@ (newra base) pick-make)) (define (make-root type size) ((pick-make type) size)) (define (root-type root) (let ((type vlen vref vset! (pick-functions root))) type)) (define (root-length root) (let ((type vlen vref vset! (pick-functions root))) (vlen root))) (define (root-ref root i) (let ((type vlen vref vset! (pick-functions root))) (vref root i))) (define (root-set! root o i) (let ((type vlen vref vset! (pick-functions root))) (vset! root i o))) ; Don't resize but make a list of vectors and cat once at the end. (define (root-resize old newsize) (let ((oldsize (root-length old))) (if (= newsize oldsize) old (let ((new (make-root (root-type old) newsize)) (size (min oldsize newsize))) (let loop ((j 0)) (cond ((= j size) new) (else (root-set! new (root-ref old j) j) (loop (+ j 1))))))))) (define (make-temp-root len type) (let* ((rank (vector-length len)) (temp final-size? (let loop ((size 1) (k 0)) (if (= k rank) (values (make-root type size) #t) (let ((l (vector-ref len k))) (if l (loop (* size l) (+ 1 k)) (values (make-root type 8) #f))))))) (values temp (if final-size? (lambda (temp j) temp) (lambda (temp j) (let ((n (root-length temp))) (if (> j n) (root-resize temp (ceiling (* (+ n j) 3/2))) temp))))))) (define (delim-pair c) (match c (#\[ #\]) (#\( #\)) (#\] #\[) (#\) #\())) (define (delim-open? c) (match c ((or #\[ #\() #t) (else #f))) (define (delim-close? c) (match c ((or #\] #\)) #t) (else #f))) (read-hash-extend #\% (lambda (chr port) (let* ((c (lookahead-char port)) (rank (if (char-numeric? c) (let ((rank (read-number port))) (if (negative? rank) (throw 'bad-rank rank) rank)) 1)) (type (read-delimited ":@([ " port 'peek)) (type (if (zero? (string-length type)) #t (string->symbol type))) (lo (make-vector rank 0)) (len (make-vector rank #f))) (let loop ((k 0)) (let ((c (lookahead-char port))) (cond ((eqv? c #\@) (unless (< k rank) (throw 'too-many-dimensions-for-rank k rank)) (get-char port) (vector-set! lo k (read-number port)) (let ((c (lookahead-char port))) (cond ((eqv? c #\:) (unless (< k rank) (throw 'too-many-dimensions-for-rank k rank)) (get-char port) (vector-set! len k (read-number port))) (else (vector-set! len k #f))) (loop (+ k 1)))) ((eqv? c #\:) (unless (< k rank) (throw 'too-many-dimensions-for-rank k rank)) (get-char port) (vector-set! len k (read-number port)) (vector-set! lo k 0) (loop (+ k 1))) (else (unless (or (zero? k) (= k rank)) (throw 'too-few-dimensions-for-rank k rank)) (let ((delim-stack (list c))) ; read content here (cond ((zero? rank) (if (*ra-parenthesized-rank-zero*) (let ((c (get-char port))) (unless (delim-open? c) (throw 'expected-open-paren c)) (let* ((item (read port)) (cc (get-char port))) (unless (eqv? (delim-pair c) cc) (throw 'mismatched-delimiters-in-zero-rank-array c cc)) (make-ra-new type item #()))) (make-ra-new type (read port) #()))) (else (unless (delim-open? c) (throw 'expected-open-paren c)) (let ((temp resize-temp (make-temp-root len type)) (j 0)) (let loop-rank ((k rank)) (cond ; read element ((zero? k) (set! temp (resize-temp temp (+ j 1))) (root-set! temp (read port) j) (set! j (+ j 1))) ; read slice (else (let ((c (skip-whitespace port))) (unless (delim-open? c) (throw 'expected-open-paren-at-dim (- rank k) c)) (set! delim-stack (cons c delim-stack)) (get-char port)) (let ((lenk (vector-ref len (- rank k)))) (cond ; read a whole slice when the dimension is known ((and (= k 1) lenk) (set! temp (resize-temp temp (+ j lenk))) (do ((i 0 (+ i 1))) ((= i lenk)) (root-set! temp (read port) (+ j i))) (set! j (+ j lenk)) (let ((c (skip-whitespace port))) (unless (delim-close? c) (throw 'too-many-elements-in-dim (- rank k) c lenk)) (unless (eqv? (delim-pair c) (car delim-stack)) (throw 'mismatched-delimiters-in-dim (- rank k) c lenk)) (set! delim-stack (cdr delim-stack)) (get-char port))) ; general case, feeling for the end (else (let loop-dim ((i 0)) (let ((c (skip-whitespace port))) (cond ((delim-close? c) (unless (eqv? (delim-pair c) (car delim-stack)) (throw 'mismatched-delimiters-in-dim (- rank k) c lenk)) (set! delim-stack (cdr delim-stack)) (get-char port) (cond ((not lenk) (vector-set! len (- rank k) i)) ((< i lenk) (throw 'too-few-elements-in-dim (- rank k) i lenk)))) ((or (not lenk) (< i lenk)) (loop-rank (- k 1)) (loop-dim (+ i 1))) (else (throw 'too-many-elements-on-dim (- rank k)))))))))))) (make-ra-root (root-resize temp (vector-fold (lambda (a b) (* (if a a 0) b)) 1 len)) (apply c-dims (vector->list (vector-map (lambda (lo len) (if len (list lo (+ lo len -1)) (list 0 -1))) lo len))))))))))))))) The docstring is from 's - array . (define list->ra (case-lambda " list->ra [type] shape l -> ra Convert the nested list L to a RA of type TYPE. TYPE defaults to #t. The argument SHAPE determines the number of dimensions of the array and their shape. It is either an exact integer, giving the number of dimensions directly, or a list whose length specifies the number of dimensions and each element specified the lower and optionally the upper bound of the corresponding dimension. When the element is list of two elements, these elements give the lower and upper bounds. When it is an exact integer, it gives only the lower bound. See also: list->typed-ra ra->list ra-copy ra-copy! as-ra " ((shape l) (list->typed-ra #t shape l)) ((type shape l) (list->typed-ra type shape l)))) FIXME looks up all lengths first . Is that necessary ? (define (list->typed-ra type shape l) " list->typed-ra type shape l -> ra Equivalent to (list->ra TYPE SHAPE L). See also: list->ra ra->list ra-copy ra-copy! as-ra " (define (list-len l rank) (let loop ((k rank) (l l)) (if (zero? k) '() (cons (length l) (loop (- k 1) (car l)))))) (let* ((rank lo len (cond ((number? shape) (values shape (make-list shape 0) (list-len l shape))) ((list shape) (let* ((rank (length shape)) (len (list-len l rank)) (lo (map (lambda (x) (if (number? x) x (car x))) shape))) (for-each (lambda (s lo len) (unless (number? s) (unless (= len (- (cadr s) lo -1)) (throw 'mismatched-shape shape)))) shape lo len) (values rank lo len))) (else (throw 'bad-shape-spec shape)))) (temp (make-root type (fold * 1 len))) (j 0)) (let loop-rank ((len len) (l l)) (cond ; read element ((null? len) (root-set! temp l j) (set! j (+ j 1))) (else (let ((lenk len (car+cdr len))) (cond read 1 - slice ((null? len) (do ((i 0 (+ i 1)) (l l (cdr l))) ((= i lenk) (unless (null? l) (throw 'mismatched-list-length-dim l lenk (- rank 1)))) (root-set! temp (car l) (+ j i))) (set! j (+ j lenk))) ; general case (else (do ((i 0 (+ i 1)) (l l (cdr l))) ((= i lenk) (unless (null? l) (throw 'mismatched-list-length-dim (- rank 1 (length len))))) (loop-rank len (car l))))))))) FIXME c - dims takes len | ( lo hi ) as in , but I 'd prefer len | ( len lo ) as in ra - iota (make-ra-root FIXME
null
https://raw.githubusercontent.com/lloda/guile-newra/bee5951bbc5351779fddba27f9bb59d435d610c8/mod/newra/read.scm
scheme
coding : utf-8 -*- This library is free software; you can redistribute it and/or modify it under either version 3 of the License , or ( at your option ) any later version. Commentary: Code: Don't resize but make a list of vectors and cat once at the end. read content here read element read slice read a whole slice when the dimension is known general case, feeling for the end read element general case
( c ) 2017 - 2019 the terms of the GNU General Public License as published by the Free Reader for ra objects . They start with # % instead of # , otherwise the syntax is the same as for regular arrays . (define-module (newra read) #:export (list->ra list->typed-ra)) (import (newra base) (newra map) (newra tools) (only (newra print) *ra-parenthesized-rank-zero*) (ice-9 match) (ice-9 rdelim) (rnrs io ports) (only (rnrs base) vector-map) (srfi 71) (srfi 26) (only (srfi 1) fold unzip2 car+cdr)) (re-export *ra-parenthesized-rank-zero*) (define vector-fold (@ (newra vector) vector-fold)) take a looked ahead ' c ' . FIXME should n't look ahead the last one and then again in the caller . (define (read-number port) (let* ((c (lookahead-char port)) (m c (if (eqv? c #\-) (begin (get-char port) (values -1 (lookahead-char port))) (values 1 c)))) (unless (char-numeric? c) (throw 'failed-to-read-number)) (* m (let loop ((n 0) (c c)) (if (char-numeric? c) (loop (+ (* 10 n) (string->number (string (get-char port)))) (lookahead-char port)) n))))) (define (skip-whitespace port) (let loop ((c (lookahead-char port))) (cond ((char-whitespace? c) (get-char port) (loop (lookahead-char port))) (else c)))) (define pick-functions (@ (newra base) pick-functions)) (define pick-make (@ (newra base) pick-make)) (define (make-root type size) ((pick-make type) size)) (define (root-type root) (let ((type vlen vref vset! (pick-functions root))) type)) (define (root-length root) (let ((type vlen vref vset! (pick-functions root))) (vlen root))) (define (root-ref root i) (let ((type vlen vref vset! (pick-functions root))) (vref root i))) (define (root-set! root o i) (let ((type vlen vref vset! (pick-functions root))) (vset! root i o))) (define (root-resize old newsize) (let ((oldsize (root-length old))) (if (= newsize oldsize) old (let ((new (make-root (root-type old) newsize)) (size (min oldsize newsize))) (let loop ((j 0)) (cond ((= j size) new) (else (root-set! new (root-ref old j) j) (loop (+ j 1))))))))) (define (make-temp-root len type) (let* ((rank (vector-length len)) (temp final-size? (let loop ((size 1) (k 0)) (if (= k rank) (values (make-root type size) #t) (let ((l (vector-ref len k))) (if l (loop (* size l) (+ 1 k)) (values (make-root type 8) #f))))))) (values temp (if final-size? (lambda (temp j) temp) (lambda (temp j) (let ((n (root-length temp))) (if (> j n) (root-resize temp (ceiling (* (+ n j) 3/2))) temp))))))) (define (delim-pair c) (match c (#\[ #\]) (#\( #\)) (#\] #\[) (#\) #\())) (define (delim-open? c) (match c ((or #\[ #\() #t) (else #f))) (define (delim-close? c) (match c ((or #\] #\)) #t) (else #f))) (read-hash-extend #\% (lambda (chr port) (let* ((c (lookahead-char port)) (rank (if (char-numeric? c) (let ((rank (read-number port))) (if (negative? rank) (throw 'bad-rank rank) rank)) 1)) (type (read-delimited ":@([ " port 'peek)) (type (if (zero? (string-length type)) #t (string->symbol type))) (lo (make-vector rank 0)) (len (make-vector rank #f))) (let loop ((k 0)) (let ((c (lookahead-char port))) (cond ((eqv? c #\@) (unless (< k rank) (throw 'too-many-dimensions-for-rank k rank)) (get-char port) (vector-set! lo k (read-number port)) (let ((c (lookahead-char port))) (cond ((eqv? c #\:) (unless (< k rank) (throw 'too-many-dimensions-for-rank k rank)) (get-char port) (vector-set! len k (read-number port))) (else (vector-set! len k #f))) (loop (+ k 1)))) ((eqv? c #\:) (unless (< k rank) (throw 'too-many-dimensions-for-rank k rank)) (get-char port) (vector-set! len k (read-number port)) (vector-set! lo k 0) (loop (+ k 1))) (else (unless (or (zero? k) (= k rank)) (throw 'too-few-dimensions-for-rank k rank)) (let ((delim-stack (list c))) (cond ((zero? rank) (if (*ra-parenthesized-rank-zero*) (let ((c (get-char port))) (unless (delim-open? c) (throw 'expected-open-paren c)) (let* ((item (read port)) (cc (get-char port))) (unless (eqv? (delim-pair c) cc) (throw 'mismatched-delimiters-in-zero-rank-array c cc)) (make-ra-new type item #()))) (make-ra-new type (read port) #()))) (else (unless (delim-open? c) (throw 'expected-open-paren c)) (let ((temp resize-temp (make-temp-root len type)) (j 0)) (let loop-rank ((k rank)) (cond ((zero? k) (set! temp (resize-temp temp (+ j 1))) (root-set! temp (read port) j) (set! j (+ j 1))) (else (let ((c (skip-whitespace port))) (unless (delim-open? c) (throw 'expected-open-paren-at-dim (- rank k) c)) (set! delim-stack (cons c delim-stack)) (get-char port)) (let ((lenk (vector-ref len (- rank k)))) (cond ((and (= k 1) lenk) (set! temp (resize-temp temp (+ j lenk))) (do ((i 0 (+ i 1))) ((= i lenk)) (root-set! temp (read port) (+ j i))) (set! j (+ j lenk)) (let ((c (skip-whitespace port))) (unless (delim-close? c) (throw 'too-many-elements-in-dim (- rank k) c lenk)) (unless (eqv? (delim-pair c) (car delim-stack)) (throw 'mismatched-delimiters-in-dim (- rank k) c lenk)) (set! delim-stack (cdr delim-stack)) (get-char port))) (else (let loop-dim ((i 0)) (let ((c (skip-whitespace port))) (cond ((delim-close? c) (unless (eqv? (delim-pair c) (car delim-stack)) (throw 'mismatched-delimiters-in-dim (- rank k) c lenk)) (set! delim-stack (cdr delim-stack)) (get-char port) (cond ((not lenk) (vector-set! len (- rank k) i)) ((< i lenk) (throw 'too-few-elements-in-dim (- rank k) i lenk)))) ((or (not lenk) (< i lenk)) (loop-rank (- k 1)) (loop-dim (+ i 1))) (else (throw 'too-many-elements-on-dim (- rank k)))))))))))) (make-ra-root (root-resize temp (vector-fold (lambda (a b) (* (if a a 0) b)) 1 len)) (apply c-dims (vector->list (vector-map (lambda (lo len) (if len (list lo (+ lo len -1)) (list 0 -1))) lo len))))))))))))))) The docstring is from 's - array . (define list->ra (case-lambda " list->ra [type] shape l -> ra Convert the nested list L to a RA of type TYPE. TYPE defaults to #t. The argument SHAPE determines the number of dimensions of the array and their shape. It is either an exact integer, giving the number of dimensions directly, or a list whose length specifies the number of dimensions and each element specified the lower and optionally the upper bound of the corresponding dimension. When the element is list of two elements, these elements give the lower and upper bounds. When it is an exact integer, it gives only the lower bound. See also: list->typed-ra ra->list ra-copy ra-copy! as-ra " ((shape l) (list->typed-ra #t shape l)) ((type shape l) (list->typed-ra type shape l)))) FIXME looks up all lengths first . Is that necessary ? (define (list->typed-ra type shape l) " list->typed-ra type shape l -> ra Equivalent to (list->ra TYPE SHAPE L). See also: list->ra ra->list ra-copy ra-copy! as-ra " (define (list-len l rank) (let loop ((k rank) (l l)) (if (zero? k) '() (cons (length l) (loop (- k 1) (car l)))))) (let* ((rank lo len (cond ((number? shape) (values shape (make-list shape 0) (list-len l shape))) ((list shape) (let* ((rank (length shape)) (len (list-len l rank)) (lo (map (lambda (x) (if (number? x) x (car x))) shape))) (for-each (lambda (s lo len) (unless (number? s) (unless (= len (- (cadr s) lo -1)) (throw 'mismatched-shape shape)))) shape lo len) (values rank lo len))) (else (throw 'bad-shape-spec shape)))) (temp (make-root type (fold * 1 len))) (j 0)) (let loop-rank ((len len) (l l)) (cond ((null? len) (root-set! temp l j) (set! j (+ j 1))) (else (let ((lenk len (car+cdr len))) (cond read 1 - slice ((null? len) (do ((i 0 (+ i 1)) (l l (cdr l))) ((= i lenk) (unless (null? l) (throw 'mismatched-list-length-dim l lenk (- rank 1)))) (root-set! temp (car l) (+ j i))) (set! j (+ j lenk))) (else (do ((i 0 (+ i 1)) (l l (cdr l))) ((= i lenk) (unless (null? l) (throw 'mismatched-list-length-dim (- rank 1 (length len))))) (loop-rank len (car l))))))))) FIXME c - dims takes len | ( lo hi ) as in , but I 'd prefer len | ( len lo ) as in ra - iota (make-ra-root FIXME
f01d177b7c082e0d3b664f5d552dac624c22ce53cadca94701256ec9fe4f70e3
k-stz/arcsynthesis
frag-position.lisp
(in-package #:arc-2) (defvar *data-directory* (merge-pathnames #p "2-chapter/data/" (asdf/system:system-source-directory :arcsynthesis))) ;;; this time we load shaders from files, check out the (init-shader-program) function (defvar *vertex-positions* (gl:alloc-gl-array :float 12)) (defparameter *verts* #(0.75 0.75 0.0 1.0 0.75 -0.75 0.0 1.0 -0.75 -0.75 0.0 1.0 0.6 0.75 0.0 1.0 -0.75 1.0 0.0 1.0 -0.75 0.0 0.0 1.0)) (setf *vertex-positions* (arc::create-gl-array-from-vector *verts*)) (defvar *program*) (defun init-shader-program () (let ((shader-list (list))) (push (arc:create-shader :vertex-shader (arc:file-to-string (merge-pathnames "frag-position.vert" *data-directory*))) shader-list) (push (arc:create-shader :fragment-shader (arc:file-to-string (merge-pathnames "frag-position.frag" *data-directory*))) shader-list) (setf *program* (arc:create-program shader-list)) (loop for shader-object in shader-list do (%gl:delete-shader shader-object)))) (defparameter *position-buffer-object* nil) ;; buffer object handle (defun set-up-opengl-state () (setf *position-buffer-object* (first (gl:gen-buffers 1))) (%gl:bind-buffer :array-buffer *position-buffer-object*) (gl:buffer-data :array-buffer :static-draw *vertex-positions*) (gl:bind-buffer :array-buffer 0) (gl:bind-buffer :array-buffer *position-buffer-object*) (%gl:enable-vertex-attrib-array 0) (%gl:vertex-attrib-pointer 0 4 :float :false 0 0)) (defun rendering-code () (gl:use-program *program*) (%gl:draw-arrays :triangles 0 6)) macro abstracting all the basic stuff from 1 - chapter one away : (defun main () (sdl2:with-init (:everything) (sdl2:with-window (win :w 400 :h 400 :flags '(:shown :opengl)) (sdl2:with-gl-context (gl-context win) ;;glClearColor(..) (gl:clear-color 0 0 0.2 1) (gl:clear :color-buffer-bit) (set-up-opengl-state) (init-shader-program) (sdl2:with-event-loop (:method :poll) (:keyup (:keysym keysym) (when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-e) ) (when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-escape) (sdl2:push-event :quit))) (:quit () t) (:idle () ;;main-loop: (rendering-code) (sdl2:gl-swap-window win) ; wow, this can be forgotten easily -.- )))))) ;; just for fun, this ONLY WORKS FOR LINEAR INTERPOLATION ... NOT LINEAR _EXTRAPOLATION_ (defun linear-interpolation (x0 y0 x1 y1 x) (let* ((rec-1 (* y0 (abs (- x x1)))) (rec-2 (* y1 (abs (- x x0)))) (rec-sum (+ rec-1 rec-2))) (float (/ rec-sum (abs (- x1 x0)))))) (defun lerp (x0 y0 x1 y1 x) "linear inter/extrapolation calculation of 'y'" (+ y0 (/ (* (- y1 y0) (- x x0)) (- x1 x0)))) ;; groovy: ;; (format t "~A~%" #\black_hexagon) ;; (format t"~a" #\GREEK_SMALL_LETTER_LAMDA) ;;note the lamda lacking its b:
null
https://raw.githubusercontent.com/k-stz/arcsynthesis/586943e74a88b60bfb9d0e16de42635a0904bf5f/2-chapter/frag-position.lisp
lisp
this time we load shaders from files, check out the (init-shader-program) function buffer object handle glClearColor(..) main-loop: wow, this can be forgotten easily -.- just for fun, this ONLY WORKS FOR LINEAR INTERPOLATION ... NOT LINEAR _EXTRAPOLATION_ groovy: (format t "~A~%" #\black_hexagon) (format t"~a" #\GREEK_SMALL_LETTER_LAMDA) ;;note the lamda lacking its b:
(in-package #:arc-2) (defvar *data-directory* (merge-pathnames #p "2-chapter/data/" (asdf/system:system-source-directory :arcsynthesis))) (defvar *vertex-positions* (gl:alloc-gl-array :float 12)) (defparameter *verts* #(0.75 0.75 0.0 1.0 0.75 -0.75 0.0 1.0 -0.75 -0.75 0.0 1.0 0.6 0.75 0.0 1.0 -0.75 1.0 0.0 1.0 -0.75 0.0 0.0 1.0)) (setf *vertex-positions* (arc::create-gl-array-from-vector *verts*)) (defvar *program*) (defun init-shader-program () (let ((shader-list (list))) (push (arc:create-shader :vertex-shader (arc:file-to-string (merge-pathnames "frag-position.vert" *data-directory*))) shader-list) (push (arc:create-shader :fragment-shader (arc:file-to-string (merge-pathnames "frag-position.frag" *data-directory*))) shader-list) (setf *program* (arc:create-program shader-list)) (loop for shader-object in shader-list do (%gl:delete-shader shader-object)))) (defun set-up-opengl-state () (setf *position-buffer-object* (first (gl:gen-buffers 1))) (%gl:bind-buffer :array-buffer *position-buffer-object*) (gl:buffer-data :array-buffer :static-draw *vertex-positions*) (gl:bind-buffer :array-buffer 0) (gl:bind-buffer :array-buffer *position-buffer-object*) (%gl:enable-vertex-attrib-array 0) (%gl:vertex-attrib-pointer 0 4 :float :false 0 0)) (defun rendering-code () (gl:use-program *program*) (%gl:draw-arrays :triangles 0 6)) macro abstracting all the basic stuff from 1 - chapter one away : (defun main () (sdl2:with-init (:everything) (sdl2:with-window (win :w 400 :h 400 :flags '(:shown :opengl)) (sdl2:with-gl-context (gl-context win) (gl:clear-color 0 0 0.2 1) (gl:clear :color-buffer-bit) (set-up-opengl-state) (init-shader-program) (sdl2:with-event-loop (:method :poll) (:keyup (:keysym keysym) (when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-e) ) (when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-escape) (sdl2:push-event :quit))) (:quit () t) (:idle () (rendering-code) )))))) (defun linear-interpolation (x0 y0 x1 y1 x) (let* ((rec-1 (* y0 (abs (- x x1)))) (rec-2 (* y1 (abs (- x x0)))) (rec-sum (+ rec-1 rec-2))) (float (/ rec-sum (abs (- x1 x0)))))) (defun lerp (x0 y0 x1 y1 x) "linear inter/extrapolation calculation of 'y'" (+ y0 (/ (* (- y1 y0) (- x x0)) (- x1 x0))))
0cc6cd8353e0ec9de76012d7b7d381c3a9b7d36f7cb33b54c6dbb4c6a68a0bc7
fused-effects/fused-effects
Cut.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # {-# OPTIONS_GHC -Wno-unrecognised-pragmas #-} # HLINT ignore " Eta reduce " # module Cut ( tests , gen0 , genN , test ) where import qualified Control.Carrier.Cut.Church as CutC import Control.Carrier.Reader import Control.Effect.Choose import Control.Effect.Cut (Cut, call, cutfail) import Control.Effect.NonDet (NonDet) import Data.Semigroup as S ((<>)) import Gen import qualified Monad import qualified MonadFix import qualified NonDet import qualified Reader tests :: TestTree tests = testGroup "Cut" [ testGroup "CutC" $ [ testMonad , testMonadFix , testCut ] >>= ($ runL CutC.runCutA) , testGroup "ReaderC · CutC" $ Cut.test (local (id @R)) (m (gen0 S.<> Reader.gen0 r) (\ m -> genN m S.<> Reader.genN r m)) a b (pair <*> r <*> unit) (Run (CutC.runCutA . uncurry runReader)) , testGroup "CutC · ReaderC" $ Cut.test (local (id @R)) (m (gen0 S.<> Reader.gen0 r) (\ m -> genN m S.<> Reader.genN r m)) a b (pair <*> r <*> unit) (Run (uncurry ((. CutC.runCutA) . runReader))) ] where testMonad run = Monad.test (m gen0 genN) a b c initial run testMonadFix run = MonadFix.test (m gen0 genN) a b initial run testCut run = Cut.test id (m gen0 genN) a b initial run initial = identity <*> unit gen0 :: (Has Cut sig m, Has NonDet sig m) => GenTerm a -> [GenTerm (m a)] gen0 a = label "cutfail" cutfail : NonDet.gen0 a genN :: (Has Cut sig m, Has NonDet sig m) => GenM m -> GenTerm a -> [GenTerm (m a)] genN m a = subtermM (m a) (label "call" call <*>) : NonDet.genN m a test :: forall a b m f sig . (Has Cut sig m, Has NonDet sig m, Arg a, Eq a, Eq b, Show a, Show b, Vary a, Functor f) => (forall a . m a -> m a) -> GenM m -> GenTerm a -> GenTerm b -> GenTerm (f ()) -> Run f [] m -> [TestTree] test hom m = (\ a _ i (Run runCut) -> [ testProperty "cutfail annihilates >>=" (forall_ (i :. fn @a (m a) :. Nil) (\ i k -> runCut ((hom cutfail >>= k) <$ i) === runCut (hom cutfail <$ i))) , testProperty "cutfail annihilates <|>" (forall_ (i :. m a :. Nil) (\ i m -> runCut ((hom cutfail <|> m) <$ i) === runCut (hom cutfail <$ i))) , testProperty "call delimits cutfail" (forall_ (i :. m a :. Nil) (\ i m -> runCut ((hom (call (hom cutfail)) <|> m) <$ i) === runCut (m <$ i))) ]) S.<> NonDet.test m
null
https://raw.githubusercontent.com/fused-effects/fused-effects/85f4b7499789a1750eb9a8d35ea09933b0d7a97b/test/Cut.hs
haskell
# LANGUAGE RankNTypes # # OPTIONS_GHC -Wno-unrecognised-pragmas #
# LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # HLINT ignore " Eta reduce " # module Cut ( tests , gen0 , genN , test ) where import qualified Control.Carrier.Cut.Church as CutC import Control.Carrier.Reader import Control.Effect.Choose import Control.Effect.Cut (Cut, call, cutfail) import Control.Effect.NonDet (NonDet) import Data.Semigroup as S ((<>)) import Gen import qualified Monad import qualified MonadFix import qualified NonDet import qualified Reader tests :: TestTree tests = testGroup "Cut" [ testGroup "CutC" $ [ testMonad , testMonadFix , testCut ] >>= ($ runL CutC.runCutA) , testGroup "ReaderC · CutC" $ Cut.test (local (id @R)) (m (gen0 S.<> Reader.gen0 r) (\ m -> genN m S.<> Reader.genN r m)) a b (pair <*> r <*> unit) (Run (CutC.runCutA . uncurry runReader)) , testGroup "CutC · ReaderC" $ Cut.test (local (id @R)) (m (gen0 S.<> Reader.gen0 r) (\ m -> genN m S.<> Reader.genN r m)) a b (pair <*> r <*> unit) (Run (uncurry ((. CutC.runCutA) . runReader))) ] where testMonad run = Monad.test (m gen0 genN) a b c initial run testMonadFix run = MonadFix.test (m gen0 genN) a b initial run testCut run = Cut.test id (m gen0 genN) a b initial run initial = identity <*> unit gen0 :: (Has Cut sig m, Has NonDet sig m) => GenTerm a -> [GenTerm (m a)] gen0 a = label "cutfail" cutfail : NonDet.gen0 a genN :: (Has Cut sig m, Has NonDet sig m) => GenM m -> GenTerm a -> [GenTerm (m a)] genN m a = subtermM (m a) (label "call" call <*>) : NonDet.genN m a test :: forall a b m f sig . (Has Cut sig m, Has NonDet sig m, Arg a, Eq a, Eq b, Show a, Show b, Vary a, Functor f) => (forall a . m a -> m a) -> GenM m -> GenTerm a -> GenTerm b -> GenTerm (f ()) -> Run f [] m -> [TestTree] test hom m = (\ a _ i (Run runCut) -> [ testProperty "cutfail annihilates >>=" (forall_ (i :. fn @a (m a) :. Nil) (\ i k -> runCut ((hom cutfail >>= k) <$ i) === runCut (hom cutfail <$ i))) , testProperty "cutfail annihilates <|>" (forall_ (i :. m a :. Nil) (\ i m -> runCut ((hom cutfail <|> m) <$ i) === runCut (hom cutfail <$ i))) , testProperty "call delimits cutfail" (forall_ (i :. m a :. Nil) (\ i m -> runCut ((hom (call (hom cutfail)) <|> m) <$ i) === runCut (m <$ i))) ]) S.<> NonDet.test m
88997950bb0ff22a3b6f0c014f749919e44e6a487e44ba7958613ba355030d5b
DeaR/xl-git
package.lisp
;; -*- mode: lisp; package: user; encoding: shift_jis -*- @name xl - git / package.lisp @description A front - end for git in xyzzy . ;; @namespace / ;; @author DeaR @timestamp < 2012 - 05 - 01 15:42:16 DeaR > Copyright ( c ) 2012 DeaR < > ;; ;; 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. (eval-when (:compile-toplevel :load-toplevel :execute) (unless (find-package :xl-git) (defpackage :xl-git (:nicknames :git) (:use :lisp :editor)) (use-package :xl-git :user))) (provide "xl-git/package")
null
https://raw.githubusercontent.com/DeaR/xl-git/ae9da0ee87f45f51569bd31c475f622ebc32e42b/site-lisp/xl-git/package.lisp
lisp
-*- mode: lisp; package: user; encoding: shift_jis -*- @namespace / @author DeaR 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 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies 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, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@name xl - git / package.lisp @description A front - end for git in xyzzy . @timestamp < 2012 - 05 - 01 15:42:16 DeaR > Copyright ( c ) 2012 DeaR < > the Software without restriction , including without limitation the rights to the Software , and to permit persons to whom the Software is furnished to do so , or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR IMPLIED , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , (eval-when (:compile-toplevel :load-toplevel :execute) (unless (find-package :xl-git) (defpackage :xl-git (:nicknames :git) (:use :lisp :editor)) (use-package :xl-git :user))) (provide "xl-git/package")
25f7b88a7a0494b56fa3850cc4d087d61c88206363542c07601417d72da7f3a5
yutopp/rill
module_info.ml
* Copyright yutopp 2015 - . * * Distributed under the Boost Software License , Version 1.0 . * ( See accompanying file LICENSE_1_0.txt or copy at * ) * Copyright yutopp 2015 - . * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * ) *) open Base module type INFO_TYPE = sig val full_filepath : string val package_names : string list val module_name : string end type 'env dep_t = Pkg of (string, 'env dep_t) Hashtbl.t | Mod of 'env module Bag = struct type 'env t = { mutable fresh_id : int; mutable modules : 'env dep_t; } let empty () = { fresh_id = 0; modules = Pkg (Hashtbl.create 4); } let search_package (bag:'env t) pkg_names = let dig opt_mods pkg_name = let f mods = match mods with | Pkg (inner_tbl) -> Hashtbl.find_option inner_tbl pkg_name | _ -> None in Option.bind opt_mods f in List.fold_left dig (Some bag.modules) pkg_names let search_module (bag:'env t) pkg_names mod_name = let opt_pkg = search_package bag pkg_names in let find_mod pkg = match pkg with | Pkg tbl -> begin let regard_as_mod m : 'env option = match m with | Mod env -> Some env | _ -> None in Option.bind (Hashtbl.find_option tbl mod_name) regard_as_mod end | Mod _ -> None in Option.bind opt_pkg find_mod let register bag pkg_names mod_name env = let dig mods pkg_name = match mods with | Pkg (inner_tbl) -> begin match Hashtbl.find_option inner_tbl pkg_name with | Some r -> r | None -> begin let npkg = Pkg (Hashtbl.create 4) in Hashtbl.add inner_tbl pkg_name npkg; npkg end end | _ -> failwith "[ERR] package name is already registerd as module" in let holder = List.fold_left dig bag.modules pkg_names in match holder with | Pkg tbl -> begin if Hashtbl.mem tbl mod_name then failwith "[ERR] already defined"; let mod_ = Mod env in Hashtbl.add tbl mod_name mod_; 0 end | Mod _ -> failwith "[ERR] package name is already registered as package" end
null
https://raw.githubusercontent.com/yutopp/rill/375b67c03ab2087d0a2a833bd9e80f3e51e2694f/rillc/_migrating/module_info.ml
ocaml
* Copyright yutopp 2015 - . * * Distributed under the Boost Software License , Version 1.0 . * ( See accompanying file LICENSE_1_0.txt or copy at * ) * Copyright yutopp 2015 - . * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * ) *) open Base module type INFO_TYPE = sig val full_filepath : string val package_names : string list val module_name : string end type 'env dep_t = Pkg of (string, 'env dep_t) Hashtbl.t | Mod of 'env module Bag = struct type 'env t = { mutable fresh_id : int; mutable modules : 'env dep_t; } let empty () = { fresh_id = 0; modules = Pkg (Hashtbl.create 4); } let search_package (bag:'env t) pkg_names = let dig opt_mods pkg_name = let f mods = match mods with | Pkg (inner_tbl) -> Hashtbl.find_option inner_tbl pkg_name | _ -> None in Option.bind opt_mods f in List.fold_left dig (Some bag.modules) pkg_names let search_module (bag:'env t) pkg_names mod_name = let opt_pkg = search_package bag pkg_names in let find_mod pkg = match pkg with | Pkg tbl -> begin let regard_as_mod m : 'env option = match m with | Mod env -> Some env | _ -> None in Option.bind (Hashtbl.find_option tbl mod_name) regard_as_mod end | Mod _ -> None in Option.bind opt_pkg find_mod let register bag pkg_names mod_name env = let dig mods pkg_name = match mods with | Pkg (inner_tbl) -> begin match Hashtbl.find_option inner_tbl pkg_name with | Some r -> r | None -> begin let npkg = Pkg (Hashtbl.create 4) in Hashtbl.add inner_tbl pkg_name npkg; npkg end end | _ -> failwith "[ERR] package name is already registerd as module" in let holder = List.fold_left dig bag.modules pkg_names in match holder with | Pkg tbl -> begin if Hashtbl.mem tbl mod_name then failwith "[ERR] already defined"; let mod_ = Mod env in Hashtbl.add tbl mod_name mod_; 0 end | Mod _ -> failwith "[ERR] package name is already registered as package" end
aa4a19fec7bac12ab6a97b173c19361897a3aa40d7961f7b29f6292e47b6aa1b
mejgun/haskell-tdlib
NetworkStatistics.hs
{-# LANGUAGE OverloadedStrings #-} -- | module TD.Data.NetworkStatistics where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified TD.Data.NetworkStatisticsEntry as NetworkStatisticsEntry import qualified Utils as U -- | | A full list of available network statistic entries @since_date Point in time ( Unix timestamp ) from which the statistics are collected @entries Network statistics entries NetworkStatistics { -- | entries :: Maybe [NetworkStatisticsEntry.NetworkStatisticsEntry], -- | since_date :: Maybe Int } deriving (Eq) instance Show NetworkStatistics where show NetworkStatistics { entries = entries_, since_date = since_date_ } = "NetworkStatistics" ++ U.cc [ U.p "entries" entries_, U.p "since_date" since_date_ ] instance T.FromJSON NetworkStatistics where parseJSON v@(T.Object obj) = do t <- obj A..: "@type" :: T.Parser String case t of "networkStatistics" -> parseNetworkStatistics v _ -> mempty where parseNetworkStatistics :: A.Value -> T.Parser NetworkStatistics parseNetworkStatistics = A.withObject "NetworkStatistics" $ \o -> do entries_ <- o A..:? "entries" since_date_ <- o A..:? "since_date" return $ NetworkStatistics {entries = entries_, since_date = since_date_} parseJSON _ = mempty instance T.ToJSON NetworkStatistics where toJSON NetworkStatistics { entries = entries_, since_date = since_date_ } = A.object [ "@type" A..= T.String "networkStatistics", "entries" A..= entries_, "since_date" A..= since_date_ ]
null
https://raw.githubusercontent.com/mejgun/haskell-tdlib/ddcb47043c7a339b4e5995355e5d5a228e21ccb0/src/TD/Data/NetworkStatistics.hs
haskell
# LANGUAGE OverloadedStrings # | | | |
module TD.Data.NetworkStatistics where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified TD.Data.NetworkStatisticsEntry as NetworkStatisticsEntry import qualified Utils as U | A full list of available network statistic entries @since_date Point in time ( Unix timestamp ) from which the statistics are collected @entries Network statistics entries NetworkStatistics entries :: Maybe [NetworkStatisticsEntry.NetworkStatisticsEntry], since_date :: Maybe Int } deriving (Eq) instance Show NetworkStatistics where show NetworkStatistics { entries = entries_, since_date = since_date_ } = "NetworkStatistics" ++ U.cc [ U.p "entries" entries_, U.p "since_date" since_date_ ] instance T.FromJSON NetworkStatistics where parseJSON v@(T.Object obj) = do t <- obj A..: "@type" :: T.Parser String case t of "networkStatistics" -> parseNetworkStatistics v _ -> mempty where parseNetworkStatistics :: A.Value -> T.Parser NetworkStatistics parseNetworkStatistics = A.withObject "NetworkStatistics" $ \o -> do entries_ <- o A..:? "entries" since_date_ <- o A..:? "since_date" return $ NetworkStatistics {entries = entries_, since_date = since_date_} parseJSON _ = mempty instance T.ToJSON NetworkStatistics where toJSON NetworkStatistics { entries = entries_, since_date = since_date_ } = A.object [ "@type" A..= T.String "networkStatistics", "entries" A..= entries_, "since_date" A..= since_date_ ]
7d0fc50c783d1bdd1315dbfed1547a34bbb8aea1fa25e002da0539b06e1765b2
shayan-najd/QFeldspar
NameResolution.hs
module QFeldspar.Expression.Conversions.NameResolution () where import QFeldspar.MyPrelude import qualified QFeldspar.Expression.ADTUntypedNamed as AUN import qualified QFeldspar.Expression.ADTUntypedDebruijn as AUD import qualified QFeldspar.Environment.Map as EM import qualified QFeldspar.Environment.Plain as EP import QFeldspar.Variable.Plain import QFeldspar.Conversion import QFeldspar.Variable.Conversion () instance (Show x , Eq x) => Cnv (AUN.Exp x , (EP.Env x , EP.Env x)) AUD.Exp where cnv (e , (s , g)) = cnv (e , (zip s [Zro ..] , zip g [Zro ..])) instance (Show x , Eq x) => Cnv (AUN.Exp x , (EM.Env x Var , EM.Env x Var)) AUD.Exp where cnv (ee , (s , g)) = case ee of AUN.Var x -> AUD.Var <$> EM.get x g AUN.Prm x ns -> AUD.Prm <$> EM.get x s <*> mapM (\m -> cnv (m , (s , g))) ns _ -> $(biGenOverloadedM 'ee ''AUN.Exp "AUD" ['AUN.Var,'AUN.Prm] (\ _tt -> [| \ m -> cnv (m , (s , g)) |])) instance (Show x , Eq x) => Cnv ((x , AUN.Exp x) ,(EM.Env x Var , EM.Env x Var)) AUD.Fun where cnv ((x , m) , (s , g)) = fmap AUD.Fun (cnv (m , (s , (x , Zro) : fmap (fmap Suc) g))) instance Cnv ( Var , ( EP.Env x ' , EM.Env ) ) x ' where cnv ( v , r ) = EM.get v ( snd r ) instance ( x ~ x ' ) = > Cnv ( AUD.Exp , ( EP.Env x , EM.Env ) ) ( AUN.Exp x ' ) where cnv ( ee , r ) = let ? r = r in case ee of AUD.Var v - > _ - > $ ( biRecAppMQW ' ee '' AUD.Exp " AUN " [ ' AUD.Var ] ( const i d ) ) instance ( x ~ x ' ) = > Cnv ( AUD.Fun , ( EP.Env x , EM.Env ) ) ( x ' , AUN.Exp x ' ) where cnv ( AUD.Fun e , r ) = case r of ( x : xs , r ' ) - > do e ' < - cnv ( e , ( xs , ( Zro , x ) : fmap ( \(v , n ) - > ( Suc v , n ) ) r ' ) ) pure ( x , e ' ) _ - > fail " Bad Name Pool ! " instance Cnv (Var, (EP.Env x', EM.Env Var x')) x' where cnv (v , r) = EM.get v (snd r) instance (x ~ x') => Cnv (AUD.Exp , (EP.Env x , EM.Env Var x)) (AUN.Exp x') where cnv (ee , r) = let ?r = r in case ee of AUD.Var v -> _ -> $(biRecAppMQW 'ee ''AUD.Exp "AUN" ['AUD.Var] (const id)) instance (x ~ x') => Cnv (AUD.Fun , (EP.Env x , EM.Env Var x)) (x' , AUN.Exp x') where cnv (AUD.Fun e , r) = case r of (x : xs , r') -> do e' <- cnv (e , (xs , (Zro , x) : fmap (\(v , n) -> (Suc v , n)) r')) pure (x , e') _ -> fail "Bad Name Pool!" -}
null
https://raw.githubusercontent.com/shayan-najd/QFeldspar/ed60ce02794a548833317388f6e82e2ab1eabc1c/QFeldspar/Expression/Conversions/NameResolution.hs
haskell
module QFeldspar.Expression.Conversions.NameResolution () where import QFeldspar.MyPrelude import qualified QFeldspar.Expression.ADTUntypedNamed as AUN import qualified QFeldspar.Expression.ADTUntypedDebruijn as AUD import qualified QFeldspar.Environment.Map as EM import qualified QFeldspar.Environment.Plain as EP import QFeldspar.Variable.Plain import QFeldspar.Conversion import QFeldspar.Variable.Conversion () instance (Show x , Eq x) => Cnv (AUN.Exp x , (EP.Env x , EP.Env x)) AUD.Exp where cnv (e , (s , g)) = cnv (e , (zip s [Zro ..] , zip g [Zro ..])) instance (Show x , Eq x) => Cnv (AUN.Exp x , (EM.Env x Var , EM.Env x Var)) AUD.Exp where cnv (ee , (s , g)) = case ee of AUN.Var x -> AUD.Var <$> EM.get x g AUN.Prm x ns -> AUD.Prm <$> EM.get x s <*> mapM (\m -> cnv (m , (s , g))) ns _ -> $(biGenOverloadedM 'ee ''AUN.Exp "AUD" ['AUN.Var,'AUN.Prm] (\ _tt -> [| \ m -> cnv (m , (s , g)) |])) instance (Show x , Eq x) => Cnv ((x , AUN.Exp x) ,(EM.Env x Var , EM.Env x Var)) AUD.Fun where cnv ((x , m) , (s , g)) = fmap AUD.Fun (cnv (m , (s , (x , Zro) : fmap (fmap Suc) g))) instance Cnv ( Var , ( EP.Env x ' , EM.Env ) ) x ' where cnv ( v , r ) = EM.get v ( snd r ) instance ( x ~ x ' ) = > Cnv ( AUD.Exp , ( EP.Env x , EM.Env ) ) ( AUN.Exp x ' ) where cnv ( ee , r ) = let ? r = r in case ee of AUD.Var v - > _ - > $ ( biRecAppMQW ' ee '' AUD.Exp " AUN " [ ' AUD.Var ] ( const i d ) ) instance ( x ~ x ' ) = > Cnv ( AUD.Fun , ( EP.Env x , EM.Env ) ) ( x ' , AUN.Exp x ' ) where cnv ( AUD.Fun e , r ) = case r of ( x : xs , r ' ) - > do e ' < - cnv ( e , ( xs , ( Zro , x ) : fmap ( \(v , n ) - > ( Suc v , n ) ) r ' ) ) pure ( x , e ' ) _ - > fail " Bad Name Pool ! " instance Cnv (Var, (EP.Env x', EM.Env Var x')) x' where cnv (v , r) = EM.get v (snd r) instance (x ~ x') => Cnv (AUD.Exp , (EP.Env x , EM.Env Var x)) (AUN.Exp x') where cnv (ee , r) = let ?r = r in case ee of AUD.Var v -> _ -> $(biRecAppMQW 'ee ''AUD.Exp "AUN" ['AUD.Var] (const id)) instance (x ~ x') => Cnv (AUD.Fun , (EP.Env x , EM.Env Var x)) (x' , AUN.Exp x') where cnv (AUD.Fun e , r) = case r of (x : xs , r') -> do e' <- cnv (e , (xs , (Zro , x) : fmap (\(v , n) -> (Suc v , n)) r')) pure (x , e') _ -> fail "Bad Name Pool!" -}
9275cc540640e48f6386d35cd9f26480d4d2bd953d4e5af8aa5d59cc151048df
hackinghat/cl-mysql
mysql.lisp
;;;; -*- Mode: Lisp -*- $ Id$ ;;;; Copyright ( c ) 2009 < > ;;;; ;;;; 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. ;;; Decoders ;;; (in-package "CL-MYSQL-SYSTEM") (defun string-to-integer (string &optional len) (declare (optimize (speed 3) (safety 3)) (type (or null simple-string) string) (type (or null (integer 0 128)) len)) (when (and string (> (or len (length string)) 0)) (parse-integer string :junk-allowed t))) (defun string-to-float (string len) "Convert a MySQL float representation into a double. Note that we could do better on DECIMAL/NUMERICs that have 0 places after the decimal." (declare (optimize (speed 3) (safety 3)) (type fixnum len) (type (or null simple-string) string)) (when (and string (> len 0)) (let ((sign 1) (integer-part 0) (decimal-part 0) (mantissa-part 0) (decimal-length 1) (mantissa-sign 1) (passed-decimal nil) (passed-mantissa nil)) (declare (type integer integer-part decimal-part) (type (integer 0 310) mantissa-part) (type (integer -1 1) mantissa-sign sign) (type (or null t) passed-decimal passed-mantissa)) (loop for c across string do (cond ((char= c #\+) (if passed-mantissa (setf mantissa-sign 1) (setf sign 1))) ((char= c #\-) (if passed-mantissa (setf mantissa-sign -1) (setf sign -1))) ((char= c #\.) (setf passed-decimal t)) ((char= c #\e) (setf passed-mantissa t)) (passed-mantissa (setf mantissa-part (+ (* mantissa-part 10) (digit-char-p c)))) (passed-decimal (setf decimal-part (+ (* decimal-part 10) (digit-char-p c)) decimal-length (* 10 decimal-length))) (t (setf integer-part (+ (* integer-part 10) (digit-char-p c)))))) (coerce (* sign (+ integer-part (/ decimal-part decimal-length)) (expt 10 (* mantissa-sign mantissa-part))) 'double-float)))) (defun string-to-ratio (string len) (when (and string (> (or len (length string)) 0)) (let ((numerator 0) (denominator 1) (passed-decimal nil) (sign 1)) (declare (type integer numerator denominator)) (loop for c across string do (progn (cond ((eq c #\.) (setf passed-decimal t)t) ((eq c #\-) (setf sign (* -1 sign))) (t (when passed-decimal (setf denominator (* denominator 10))) (setf numerator (+ (digit-char-p c) (* numerator 10))))))) (* sign (/ numerator denominator))))) (defun string-to-date (string &optional len) (declare (optimize (speed 3) (safety 3)) (type (or null simple-string) string) (type (or null fixnum) len)) (when (and string (> (or len (length string)) 9)) (let ((y (parse-integer string :start 0 :end 4)) (m (parse-integer string :start 5 :end 7)) (d (parse-integer string :start 8 :end 10))) (unless (or (zerop y) (zerop m) (zerop d)) (encode-universal-time 0 0 0 d m y))))) (defun string-to-seconds (string &optional len) "Fairly ugly function to turn MySQL TIME duration into an integer representation. It's complicated because of ... well, read this: " (declare (optimize (speed 3) (safety 3)) (type (or null simple-string) string) (type (or null fixnum) len)) (when string (let* ((strlen (or len (length string))) (offset (- strlen 8))) (when (and (>= offset 0) (< offset 3)) (let* ((start (if (eql #\- (elt string 0)) 1 0)) (h (parse-integer string :start start :end (+ 2 offset))) (m (parse-integer string :start (+ 3 offset) :end (+ 5 offset))) (s (parse-integer string :start (+ 6 offset) :end (+ 8 offset))) (time (+ (* h 3600) (* m 60) s))) (declare (type (integer 0 839) h) (type (integer 0 59) m s)) (if (eql start 1) (* -1 time) time)))))) (defun string-to-universal-time (string &optional len) (declare (optimize (speed 3) (safety 3)) (type (or null simple-string) string) (type (or null fixnum) len)) (cond ((equal "0000-00-00 00:00:00" string) nil) ((and string (> (or len (length string)) 0)) (+ (string-to-date (subseq string 0 10)) (string-to-seconds (subseq string 11)))))) (eval-when (:load-toplevel) (mapcar (lambda (map) (setf (gethash (first map) *type-map*) (second map))) '((:DECIMAL string-to-ratio) (:TINY string-to-integer) (:SHORT string-to-integer) (:LONG string-to-integer) (:FLOAT string-to-float) (:DOUBLE string-to-float) (:NULL (lambda (string) (declare (ignore string)) nil)) (:TIMESTAMP string-to-universal-time) (:LONGLONG string-to-integer) (:INT24 string-to-integer) (:DATE string-to-date) (:TIME string-to-seconds) (:DATETIME string-to-universal-time) (:YEAR string-to-integer) (:NEWDATE string-to-universal-time) (:NEWDECIMAL string-to-ratio)))) ;;; Error handling ;;; (define-condition mysql-error (error) ((message :initarg :message :reader mysql-error-message) (errno :initarg :errno :reader mysql-error-errno)) (:report (lambda (condition stream) (format stream "MySQL error: \"~A\" (errno = ~D)." (mysql-error-message condition) (mysql-error-errno condition))))) (define-condition cl-mysql-error (error) ((message :initarg :message :reader cl-mysql-error-message)) (:report (lambda (condition stream) (format stream "cl-mysql error: \"~A\"" (cl-mysql-error-message condition))))) (defun error-if-non-zero (database return-value) (let ((error-function (etypecase database (statement #'mysql-stmt-error) (connection #'mysql-error))) (errorno-function (etypecase database (statement #'mysql-stmt-errno) (connection #'mysql-errno)))) (if (not (eql 0 return-value)) (error 'mysql-error :message (funcall error-function (pointer database)) :errno (funcall errorno-function (pointer database)))) return-value)) (defun error-if-null (database return-value) (if (null-pointer-p return-value) (let ((db-handle (typecase database (integer database) ; Not quite sure if this is right ; but it seems to work - RG (connection (pointer database)) (t database)))) (error 'mysql-error :message (mysql-error db-handle) :errno (mysql-errno db-handle)))) return-value) (defun error-if-null-with-fields (database return-value) (if (> (mysql-field-count (pointer database)) 0) (error-if-null database return-value))) (defun error-if-set (database) (let ((errno (mysql-errno (pointer database)))) (when (not (eql 0 errno)) (error 'mysql-error :message (mysql-error (pointer database)) :errno errno)))) ;;; High level API ;;; (defmacro with-connection ((var &optional database (release t)) &body body) (let ((retval (gensym))) `(let* ((,var (aquire (or ,database *last-database*) t)) (,retval ())) (unwind-protect (setq ,retval (progn ,@body)) (when ,release (release ,var))) ,retval))) (defun use (name &key database) "Equivalent to running: CL-USER> (query \"USE <name>\")" (with-connection (conn database) (error-if-non-zero conn (mysql-select-db (pointer conn) name)) (values))) (defun decode-version (int-version) "Return a list of version details <major> <release> <version>" (let* ((version (mod int-version 100)) (major-version (floor int-version 10000)) (release-level (mod (floor int-version 100) 10))) (list major-version release-level version))) (defun client-version () "Returns a three part list containing the decoded client version information" (decode-version (mysql-get-client-version))) (defun server-version (&key database) "Returns a three part list containing the decoded server version information" (with-connection (conn database) (decode-version (mysql-get-server-version (pointer conn))))) (defun single-result-set (conn fn &rest args) "MySQL provides a class of functions that just process a single result set. Note that we won't explicity free the result set because return-or-close will do the cleanup for us." (let ((result (apply fn args))) (error-if-null conn result) (setf (result-set conn) result) (list (cons (process-result-set conn *type-map*) (result-set-fields conn))))) (defun list-dbs (&key database) (with-connection (conn database) (single-result-set conn (lambda () (mysql-list-dbs (pointer conn) (null-pointer)))))) (defun list-tables (&key database) (with-connection (conn database) (single-result-set conn (lambda () (mysql-list-tables (pointer conn) (null-pointer)))))) (defun list-fields (table &key database) (with-connection (conn database) (single-result-set conn (lambda () (mysql-list-fields (pointer conn) table (null-pointer)))))) (defun list-processes (&key database) (with-connection (conn database) (single-result-set conn (lambda () (mysql-list-processes (pointer conn)))))) ;;; String/Character set/Collation stuff ;;; (defun escape-string (string &key database) "Given a string, encode it appropriately. This function relies on the fact that the character set encoding was set to UTF-8 when the connection is made." (when string (with-connection (conn database) (with-foreign-string (from-string string) (let* ((from-length (cffi-utf8-length from-string)) (to-length (1+ (* from-length 2))) (to-string (foreign-alloc :unsigned-char :count to-length)) (return-string nil)) (unwind-protect (progn (mysql-real-escape-string (pointer conn) to-string from-string from-length) (setf return-string (foreign-string-to-lisp to-string))) (foreign-free to-string)) (values return-string)))))) (defun cffi-utf8-length (cffi-string) "We need this function because mysql_real_escape_string requires the length of the from string in bytes (not characters)" (do ((i 0 (incf i))) ((eql 0 (mem-ref cffi-string :unsigned-char i)) i))) (defun get-character-set-info (&key database) "Returns the character set information for the connection as a sequence: (collation name number state)" (with-connection (conn database) (with-foreign-object (charset 'character-set) (mysql-get-character-set-info (pointer conn) charset) (list (foreign-slot-value charset 'character-set 'csname) (foreign-slot-value charset 'character-set 'name) (foreign-slot-value charset 'character-set 'number) (foreign-slot-value charset 'character-set 'state))))) (defun set-character-set (csname &key database) (with-connection (conn database) (error-if-non-zero conn (mysql-set-character-set (pointer conn) csname)))) ;;; Result set functions ;;; (defparameter *binary-types* #(:BIT :BINARY :VARBINARY :GEOMETRY)) (declaim (inline extract-field process-row)) (defun extract-field (row field-index field-length type-map field-detail) "Returns either a string or an unsigned byte array for known binary types. The designation of binary types per the C API seems a bit weird. Basically, BIT, BINARY and VARBINARY are binary and so are BLOBs with the binary flag set. It seems that other fields also have the binary flag set that are not binary and the BIT type, whilst binary doesn't have the flag set. Bizarre-o." (destructuring-bind (field-name field-type field-flag) field-detail (declare (ignore field-name) (optimize (speed 3) (safety 3)) (type (integer 0 65536) field-index field-flag) (type (integer 0 4294967296) field-length ) (type (simple-array symbol) *binary-types*)) (if (eql field-length 0) (return-from extract-field nil)) (if (or (and (eq field-type :BLOB) (logtest +field-binary+ field-flag)) (find field-type *binary-types*)) (let ((arr (make-array field-length :element-type '(unsigned-byte 8))) (ptr (mem-ref row :pointer field-index))) (loop for i from 0 to (1- field-length) do (setf (elt arr i) (mem-ref ptr :unsigned-char i))) (values arr)) (let ((fn (gethash field-type type-map))) (declare (type (or null symbol function) fn)) (values (if fn (funcall fn (mem-ref row :string field-index) field-length) (mem-ref row :string field-index))))))) (defun process-row (mysql-res row num-fields field-names-and-types type-map) (declare (optimize (speed 3) (safety 3)) (type (integer 0 65536) num-fields)) (let* ((mysql-lens (mysql-fetch-lengths mysql-res)) (int-size (foreign-type-size :pointer))) (declare (type (integer 0 16) int-size)) (loop for i of-type fixnum from 0 to (* num-fields int-size) by int-size for f of-type list in field-names-and-types collect (extract-field row i (mem-aref mysql-lens :unsigned-long (/ i int-size)) type-map f)))) (defun query (query &key (type-map *type-map*) database (store t)) "For a SELECT query or stored procedure that returns data, query will return a list of result sets. Each result set will have 1 or more sublists where the first sublist contains the column names and the remaining lists represent the rows of the result set. If the query does not return a result set (for example if the query is an INSERT, UPDATE) the return value is the number of rows affected. Because cl-mysql supports multiple-statements you can execute code like the following: <pre><code>CL-MYSQL-SYSTEM> (query \"CREATE TABLE a(a INT); INSERT INTO a (a) VALUES (1); DELETE FROM a; DROP TABLE a\") ((0) (1) (1) (0))</code></pre> The type-map, if set will alter the decoding into CL types. If you set this to nil it will have the effect of disabling all CL type conversions and return either character or binary data only. This might be useful for performance reasons, (cl-mysql is much faster when it doesn't need to translate types) but it also might be all you need. Consider for instance if you're displaying a lot of numerics on a web-page. If you do not need to convert the data into floats/integers before displaying them on a page then raw could be useful here too. cl-mysql attempts to convert all numeric types to their closest CL representation. For very large numerics, or numerics that have very high precision this might not be what you want. In this case you could attempt to write your own conversion routine and inject it into cl-mysql through the type-map. The currented supported conversions are as follows (MySQL type -> CL type): <ul><li><strong>DECIMAL/NUMERIC</strong> -> RATIO</li> <li><strong>INT/TINYINT/SMALLINT/MEDIUMINT/BIGINT/YEAR</strong> -> INTEGER</li> <li><strong>FLOAT/REAL/DOUBLE PRECISION</strong> -> DOUBLE-FLOAT</li> <li><strong>DATE/DATETIME/TIMESTAMP</strong> -> INTEGER (Universal time)</li> <li><strong>TIME</strong> -> INTEGER (Seconds)</li> <li><strong>CHAR/VARCHAR/TEXT/TINYTEXT/MEDIUMTEXT/LONGTEXT</strong> -> STRING</li> <li><strong>BIT/BLOB/MEDIUMBLOB/LONGBLOB/TINYBLOB/GEOMETRY</strong> -> SIMPLE-ARRAY '(UNSIGNED-BYTE 8 )</li> </ul> If :store is T query returns a list of result sets. Each result set is a list with the first element set to the data and the second elements set to the column data. Since this structure can be a little awkward to handle you can use nth-row to manipulate the structure more sanely. If :store is NIL query returns the allocated connection object. You should use next-result-set and next-row to step through the results." (with-connection (conn database store) (error-if-non-zero conn (mysql-query (pointer conn) query)) (cond (store (loop while (next-result-set conn :store t :dont-release t) nconc (list (list (process-result-set conn (or type-map (make-hash-table))) (car (result-set-fields conn)))))) (t (setf (use-query-active conn) t) (values conn))))) (defun ping (&key database) "Check whether a connection is established or not. If :opt-reconnect is set and there is no connection then MySQL's C API attempts a reconnection." (with-connection (conn database) (error-if-non-zero conn (mysql-ping (pointer conn))) (values t))) (defun %set-string-option (option value &key database) (let ((retval 0)) (with-connection (conn database) (with-foreign-pointer-as-string (str 255) (setf retval (mysql-options (pointer conn) (foreign-enum-value 'enum-options option) (lisp-string-to-foreign value str 255))))) (values retval))) (defun %set-int-option (option value &key database) (let ((retval 0)) (with-connection (conn database) (with-foreign-object (int-value :int) (setf (mem-ref int-value :int) value) (setf retval (mysql-options (pointer conn) (foreign-enum-value 'enum-options option) int-value)))) (values retval))) (defun option (option value &key database) "Use this to set a client specific connection option. CL-USER> (option :opt-reconnect 1)" (typecase value (string (%set-string-option option value :database database)) (null (%set-int-option option 0 :database database)) (t (%set-int-option option value :database database)))) (defun get-field (column-name field-names-and-types row) "Returns the correct element in the sequence from the row that matches the column-name" (elt row (position column-name field-names-and-types :test 'string= :key 'car))) (defun force-kill () "Internal convenience function to clean up connections" (connect) (query (with-output-to-string (s) (loop for f in (car (list-processes)) do (format s "KILL ~D;" (car f)))))) ;;; Convenience functions for accessing results (defun nth-row (result-set-list n &optional nth-result-set) "Return the nth-row of the nth-result set." (let ((row (nth n (first (nth (or nth-result-set 0) result-set-list))))) (typecase row (number row) (t row)))) (defmacro with-rows ((var-row query-string &key (var-result (gensym)) (database '*last-database*) (type-map '*type-map*)) &body body) "Takes a query-string and iterates over the result sets assigning var-row to each individual row. If you supply var-result it will hold the result set sequence number. This macro generates code that does not store the complete result so should be suitable for working with very large data sets." `(let ((connection (query ,query-string :type-map ,type-map :database ,database :store nil)) (,var-result 0)) (loop while (next-result-set connection) do (progn (loop for ,var-row = (next-row connection :type-map ,type-map) until (null,var-row) do (progn ,@body)) (incf ,var-result)))))
null
https://raw.githubusercontent.com/hackinghat/cl-mysql/3fbf6e1421484f64c5bcf2ff3c4b96c6f0414f09/mysql.lisp
lisp
-*- Mode: 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 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 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Decoders Error handling Not quite sure if this is right but it seems to work - RG High level API String/Character set/Collation stuff Result set functions DELETE FROM a; DROP TABLE a\") Convenience functions for accessing results
$ Id$ Copyright ( c ) 2009 < > " 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 included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION (in-package "CL-MYSQL-SYSTEM") (defun string-to-integer (string &optional len) (declare (optimize (speed 3) (safety 3)) (type (or null simple-string) string) (type (or null (integer 0 128)) len)) (when (and string (> (or len (length string)) 0)) (parse-integer string :junk-allowed t))) (defun string-to-float (string len) "Convert a MySQL float representation into a double. Note that we could do better on DECIMAL/NUMERICs that have 0 places after the decimal." (declare (optimize (speed 3) (safety 3)) (type fixnum len) (type (or null simple-string) string)) (when (and string (> len 0)) (let ((sign 1) (integer-part 0) (decimal-part 0) (mantissa-part 0) (decimal-length 1) (mantissa-sign 1) (passed-decimal nil) (passed-mantissa nil)) (declare (type integer integer-part decimal-part) (type (integer 0 310) mantissa-part) (type (integer -1 1) mantissa-sign sign) (type (or null t) passed-decimal passed-mantissa)) (loop for c across string do (cond ((char= c #\+) (if passed-mantissa (setf mantissa-sign 1) (setf sign 1))) ((char= c #\-) (if passed-mantissa (setf mantissa-sign -1) (setf sign -1))) ((char= c #\.) (setf passed-decimal t)) ((char= c #\e) (setf passed-mantissa t)) (passed-mantissa (setf mantissa-part (+ (* mantissa-part 10) (digit-char-p c)))) (passed-decimal (setf decimal-part (+ (* decimal-part 10) (digit-char-p c)) decimal-length (* 10 decimal-length))) (t (setf integer-part (+ (* integer-part 10) (digit-char-p c)))))) (coerce (* sign (+ integer-part (/ decimal-part decimal-length)) (expt 10 (* mantissa-sign mantissa-part))) 'double-float)))) (defun string-to-ratio (string len) (when (and string (> (or len (length string)) 0)) (let ((numerator 0) (denominator 1) (passed-decimal nil) (sign 1)) (declare (type integer numerator denominator)) (loop for c across string do (progn (cond ((eq c #\.) (setf passed-decimal t)t) ((eq c #\-) (setf sign (* -1 sign))) (t (when passed-decimal (setf denominator (* denominator 10))) (setf numerator (+ (digit-char-p c) (* numerator 10))))))) (* sign (/ numerator denominator))))) (defun string-to-date (string &optional len) (declare (optimize (speed 3) (safety 3)) (type (or null simple-string) string) (type (or null fixnum) len)) (when (and string (> (or len (length string)) 9)) (let ((y (parse-integer string :start 0 :end 4)) (m (parse-integer string :start 5 :end 7)) (d (parse-integer string :start 8 :end 10))) (unless (or (zerop y) (zerop m) (zerop d)) (encode-universal-time 0 0 0 d m y))))) (defun string-to-seconds (string &optional len) "Fairly ugly function to turn MySQL TIME duration into an integer representation. It's complicated because of ... well, read this: " (declare (optimize (speed 3) (safety 3)) (type (or null simple-string) string) (type (or null fixnum) len)) (when string (let* ((strlen (or len (length string))) (offset (- strlen 8))) (when (and (>= offset 0) (< offset 3)) (let* ((start (if (eql #\- (elt string 0)) 1 0)) (h (parse-integer string :start start :end (+ 2 offset))) (m (parse-integer string :start (+ 3 offset) :end (+ 5 offset))) (s (parse-integer string :start (+ 6 offset) :end (+ 8 offset))) (time (+ (* h 3600) (* m 60) s))) (declare (type (integer 0 839) h) (type (integer 0 59) m s)) (if (eql start 1) (* -1 time) time)))))) (defun string-to-universal-time (string &optional len) (declare (optimize (speed 3) (safety 3)) (type (or null simple-string) string) (type (or null fixnum) len)) (cond ((equal "0000-00-00 00:00:00" string) nil) ((and string (> (or len (length string)) 0)) (+ (string-to-date (subseq string 0 10)) (string-to-seconds (subseq string 11)))))) (eval-when (:load-toplevel) (mapcar (lambda (map) (setf (gethash (first map) *type-map*) (second map))) '((:DECIMAL string-to-ratio) (:TINY string-to-integer) (:SHORT string-to-integer) (:LONG string-to-integer) (:FLOAT string-to-float) (:DOUBLE string-to-float) (:NULL (lambda (string) (declare (ignore string)) nil)) (:TIMESTAMP string-to-universal-time) (:LONGLONG string-to-integer) (:INT24 string-to-integer) (:DATE string-to-date) (:TIME string-to-seconds) (:DATETIME string-to-universal-time) (:YEAR string-to-integer) (:NEWDATE string-to-universal-time) (:NEWDECIMAL string-to-ratio)))) (define-condition mysql-error (error) ((message :initarg :message :reader mysql-error-message) (errno :initarg :errno :reader mysql-error-errno)) (:report (lambda (condition stream) (format stream "MySQL error: \"~A\" (errno = ~D)." (mysql-error-message condition) (mysql-error-errno condition))))) (define-condition cl-mysql-error (error) ((message :initarg :message :reader cl-mysql-error-message)) (:report (lambda (condition stream) (format stream "cl-mysql error: \"~A\"" (cl-mysql-error-message condition))))) (defun error-if-non-zero (database return-value) (let ((error-function (etypecase database (statement #'mysql-stmt-error) (connection #'mysql-error))) (errorno-function (etypecase database (statement #'mysql-stmt-errno) (connection #'mysql-errno)))) (if (not (eql 0 return-value)) (error 'mysql-error :message (funcall error-function (pointer database)) :errno (funcall errorno-function (pointer database)))) return-value)) (defun error-if-null (database return-value) (if (null-pointer-p return-value) (let ((db-handle (typecase database (integer database) (connection (pointer database)) (t database)))) (error 'mysql-error :message (mysql-error db-handle) :errno (mysql-errno db-handle)))) return-value) (defun error-if-null-with-fields (database return-value) (if (> (mysql-field-count (pointer database)) 0) (error-if-null database return-value))) (defun error-if-set (database) (let ((errno (mysql-errno (pointer database)))) (when (not (eql 0 errno)) (error 'mysql-error :message (mysql-error (pointer database)) :errno errno)))) (defmacro with-connection ((var &optional database (release t)) &body body) (let ((retval (gensym))) `(let* ((,var (aquire (or ,database *last-database*) t)) (,retval ())) (unwind-protect (setq ,retval (progn ,@body)) (when ,release (release ,var))) ,retval))) (defun use (name &key database) "Equivalent to running: CL-USER> (query \"USE <name>\")" (with-connection (conn database) (error-if-non-zero conn (mysql-select-db (pointer conn) name)) (values))) (defun decode-version (int-version) "Return a list of version details <major> <release> <version>" (let* ((version (mod int-version 100)) (major-version (floor int-version 10000)) (release-level (mod (floor int-version 100) 10))) (list major-version release-level version))) (defun client-version () "Returns a three part list containing the decoded client version information" (decode-version (mysql-get-client-version))) (defun server-version (&key database) "Returns a three part list containing the decoded server version information" (with-connection (conn database) (decode-version (mysql-get-server-version (pointer conn))))) (defun single-result-set (conn fn &rest args) "MySQL provides a class of functions that just process a single result set. Note that we won't explicity free the result set because return-or-close will do the cleanup for us." (let ((result (apply fn args))) (error-if-null conn result) (setf (result-set conn) result) (list (cons (process-result-set conn *type-map*) (result-set-fields conn))))) (defun list-dbs (&key database) (with-connection (conn database) (single-result-set conn (lambda () (mysql-list-dbs (pointer conn) (null-pointer)))))) (defun list-tables (&key database) (with-connection (conn database) (single-result-set conn (lambda () (mysql-list-tables (pointer conn) (null-pointer)))))) (defun list-fields (table &key database) (with-connection (conn database) (single-result-set conn (lambda () (mysql-list-fields (pointer conn) table (null-pointer)))))) (defun list-processes (&key database) (with-connection (conn database) (single-result-set conn (lambda () (mysql-list-processes (pointer conn)))))) (defun escape-string (string &key database) "Given a string, encode it appropriately. This function relies on the fact that the character set encoding was set to UTF-8 when the connection is made." (when string (with-connection (conn database) (with-foreign-string (from-string string) (let* ((from-length (cffi-utf8-length from-string)) (to-length (1+ (* from-length 2))) (to-string (foreign-alloc :unsigned-char :count to-length)) (return-string nil)) (unwind-protect (progn (mysql-real-escape-string (pointer conn) to-string from-string from-length) (setf return-string (foreign-string-to-lisp to-string))) (foreign-free to-string)) (values return-string)))))) (defun cffi-utf8-length (cffi-string) "We need this function because mysql_real_escape_string requires the length of the from string in bytes (not characters)" (do ((i 0 (incf i))) ((eql 0 (mem-ref cffi-string :unsigned-char i)) i))) (defun get-character-set-info (&key database) "Returns the character set information for the connection as a sequence: (collation name number state)" (with-connection (conn database) (with-foreign-object (charset 'character-set) (mysql-get-character-set-info (pointer conn) charset) (list (foreign-slot-value charset 'character-set 'csname) (foreign-slot-value charset 'character-set 'name) (foreign-slot-value charset 'character-set 'number) (foreign-slot-value charset 'character-set 'state))))) (defun set-character-set (csname &key database) (with-connection (conn database) (error-if-non-zero conn (mysql-set-character-set (pointer conn) csname)))) (defparameter *binary-types* #(:BIT :BINARY :VARBINARY :GEOMETRY)) (declaim (inline extract-field process-row)) (defun extract-field (row field-index field-length type-map field-detail) "Returns either a string or an unsigned byte array for known binary types. The designation of binary types per the C API seems a bit weird. Basically, BIT, BINARY and VARBINARY are binary and so are BLOBs with the binary flag set. It seems that other fields also have the binary flag set that are not binary and the BIT type, whilst binary doesn't have the flag set. Bizarre-o." (destructuring-bind (field-name field-type field-flag) field-detail (declare (ignore field-name) (optimize (speed 3) (safety 3)) (type (integer 0 65536) field-index field-flag) (type (integer 0 4294967296) field-length ) (type (simple-array symbol) *binary-types*)) (if (eql field-length 0) (return-from extract-field nil)) (if (or (and (eq field-type :BLOB) (logtest +field-binary+ field-flag)) (find field-type *binary-types*)) (let ((arr (make-array field-length :element-type '(unsigned-byte 8))) (ptr (mem-ref row :pointer field-index))) (loop for i from 0 to (1- field-length) do (setf (elt arr i) (mem-ref ptr :unsigned-char i))) (values arr)) (let ((fn (gethash field-type type-map))) (declare (type (or null symbol function) fn)) (values (if fn (funcall fn (mem-ref row :string field-index) field-length) (mem-ref row :string field-index))))))) (defun process-row (mysql-res row num-fields field-names-and-types type-map) (declare (optimize (speed 3) (safety 3)) (type (integer 0 65536) num-fields)) (let* ((mysql-lens (mysql-fetch-lengths mysql-res)) (int-size (foreign-type-size :pointer))) (declare (type (integer 0 16) int-size)) (loop for i of-type fixnum from 0 to (* num-fields int-size) by int-size for f of-type list in field-names-and-types collect (extract-field row i (mem-aref mysql-lens :unsigned-long (/ i int-size)) type-map f)))) (defun query (query &key (type-map *type-map*) database (store t)) "For a SELECT query or stored procedure that returns data, query will return a list of result sets. Each result set will have 1 or more sublists where the first sublist contains the column names and the remaining lists represent the rows of the result set. If the query does not return a result set (for example if the query is an INSERT, UPDATE) the return value is the number of rows affected. Because cl-mysql supports multiple-statements you can execute code like the following: ((0) (1) (1) (0))</code></pre> The type-map, if set will alter the decoding into CL types. If you set this to nil it will have the effect of disabling all CL type conversions and return either character or binary data only. This might be useful for performance reasons, (cl-mysql is much faster when it doesn't need to translate types) but it also might be all you need. Consider for instance if you're displaying a lot of numerics on a web-page. If you do not need to convert the data into floats/integers before displaying them on a page then raw could be useful here too. cl-mysql attempts to convert all numeric types to their closest CL representation. For very large numerics, or numerics that have very high precision this might not be what you want. In this case you could attempt to write your own conversion routine and inject it into cl-mysql through the type-map. The currented supported conversions are as follows (MySQL type -> CL type): <ul><li><strong>DECIMAL/NUMERIC</strong> -> RATIO</li> <li><strong>INT/TINYINT/SMALLINT/MEDIUMINT/BIGINT/YEAR</strong> -> INTEGER</li> <li><strong>FLOAT/REAL/DOUBLE PRECISION</strong> -> DOUBLE-FLOAT</li> <li><strong>DATE/DATETIME/TIMESTAMP</strong> -> INTEGER (Universal time)</li> <li><strong>TIME</strong> -> INTEGER (Seconds)</li> <li><strong>CHAR/VARCHAR/TEXT/TINYTEXT/MEDIUMTEXT/LONGTEXT</strong> -> STRING</li> <li><strong>BIT/BLOB/MEDIUMBLOB/LONGBLOB/TINYBLOB/GEOMETRY</strong> -> SIMPLE-ARRAY '(UNSIGNED-BYTE 8 )</li> </ul> If :store is T query returns a list of result sets. Each result set is a list with the first element set to the data and the second elements set to the column data. Since this structure can be a little awkward to handle you can use nth-row to manipulate the structure more sanely. If :store is NIL query returns the allocated connection object. You should use next-result-set and next-row to step through the results." (with-connection (conn database store) (error-if-non-zero conn (mysql-query (pointer conn) query)) (cond (store (loop while (next-result-set conn :store t :dont-release t) nconc (list (list (process-result-set conn (or type-map (make-hash-table))) (car (result-set-fields conn)))))) (t (setf (use-query-active conn) t) (values conn))))) (defun ping (&key database) "Check whether a connection is established or not. If :opt-reconnect is set and there is no connection then MySQL's C API attempts a reconnection." (with-connection (conn database) (error-if-non-zero conn (mysql-ping (pointer conn))) (values t))) (defun %set-string-option (option value &key database) (let ((retval 0)) (with-connection (conn database) (with-foreign-pointer-as-string (str 255) (setf retval (mysql-options (pointer conn) (foreign-enum-value 'enum-options option) (lisp-string-to-foreign value str 255))))) (values retval))) (defun %set-int-option (option value &key database) (let ((retval 0)) (with-connection (conn database) (with-foreign-object (int-value :int) (setf (mem-ref int-value :int) value) (setf retval (mysql-options (pointer conn) (foreign-enum-value 'enum-options option) int-value)))) (values retval))) (defun option (option value &key database) "Use this to set a client specific connection option. CL-USER> (option :opt-reconnect 1)" (typecase value (string (%set-string-option option value :database database)) (null (%set-int-option option 0 :database database)) (t (%set-int-option option value :database database)))) (defun get-field (column-name field-names-and-types row) "Returns the correct element in the sequence from the row that matches the column-name" (elt row (position column-name field-names-and-types :test 'string= :key 'car))) (defun force-kill () "Internal convenience function to clean up connections" (connect) (query (with-output-to-string (s) (loop for f in (car (list-processes)) do (format s "KILL ~D;" (car f)))))) (defun nth-row (result-set-list n &optional nth-result-set) "Return the nth-row of the nth-result set." (let ((row (nth n (first (nth (or nth-result-set 0) result-set-list))))) (typecase row (number row) (t row)))) (defmacro with-rows ((var-row query-string &key (var-result (gensym)) (database '*last-database*) (type-map '*type-map*)) &body body) "Takes a query-string and iterates over the result sets assigning var-row to each individual row. If you supply var-result it will hold the result set sequence number. This macro generates code that does not store the complete result so should be suitable for working with very large data sets." `(let ((connection (query ,query-string :type-map ,type-map :database ,database :store nil)) (,var-result 0)) (loop while (next-result-set connection) do (progn (loop for ,var-row = (next-row connection :type-map ,type-map) until (null,var-row) do (progn ,@body)) (incf ,var-result)))))
7e33348cbf5d66006a9ac5a971caeda09656ec1bec29ba05c62a992d092de601
Helium4Haskell/helium
Lambda2.hs
main :: Bool -> Bool -> () main = \True False -> ()
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/staticwarnings/Lambda2.hs
haskell
main :: Bool -> Bool -> () main = \True False -> ()
6eeceebc7c02753f14f30016ff2f061dc2b06e48adee0a220ef747630a9e6b8a
aharisu/Gauche-CV
objdetect_type.scm
;;; imgproc_type.scm ;;; MIT License Copyright 2011 - 2012 aharisu ;;; All rights reserved. ;;; ;;; 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. ;;; ;;; ;;; aharisu ;;; ;;; (add-load-path ".") (load "cv_struct_generator") (use file.util) (define (main args) (gen-type (simplify-path (path-sans-extension (car args))) structs foreign-pointer (lambda () ;;prologue (cgen-extern "#include \"../core_type.gen.h\"") (cgen-extern "#include \"../gauche_cv_core.h\"") (cgen-extern "//opencv2 header") (cgen-extern "#include <opencv2/objdetect/objdetect.hpp>") (cgen-extern "") ) (lambda () ;;epilogue )) 0) sym - name sym - scm - type pointer ? finalize - name finalize - ref (define structs '( (CvHaarClassifierCascade <cv-haar-classifier-cascade> #t "cvReleaseHaarClassifierCascade" "&") (CvAvgComp <cv-avg-comp> #f #f "") (CvLSVMFilterPosition <cv-lsvm-filter-position> #f #f "") (CvLatentSvmDetector <cv-latent-svm-detector> #t "cvReleaseLatentSvmDetector" "&") (CvObjectDetection <cv-object-detection> #f #f "") )) sym - name sym - scm - type ponter ? finalize finalize - ref (define foreign-pointer '( ))
null
https://raw.githubusercontent.com/aharisu/Gauche-CV/5e4c51501431c72270765121ea4d92693f11d60b/src/objdetect/objdetect_type.scm
scheme
All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal to use, copy, modify, merge, publish, distribute, sublicense, and/or sell furnished to do so, subject to the following conditions: ; ; 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. aharisu prologue epilogue
imgproc_type.scm MIT License Copyright 2011 - 2012 aharisu in the Software without restriction , including without limitation the rights copies of the Software , and to permit persons to whom the Software is THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , (add-load-path ".") (load "cv_struct_generator") (use file.util) (define (main args) (gen-type (simplify-path (path-sans-extension (car args))) structs foreign-pointer (cgen-extern "#include \"../core_type.gen.h\"") (cgen-extern "#include \"../gauche_cv_core.h\"") (cgen-extern "//opencv2 header") (cgen-extern "#include <opencv2/objdetect/objdetect.hpp>") (cgen-extern "") ) )) 0) sym - name sym - scm - type pointer ? finalize - name finalize - ref (define structs '( (CvHaarClassifierCascade <cv-haar-classifier-cascade> #t "cvReleaseHaarClassifierCascade" "&") (CvAvgComp <cv-avg-comp> #f #f "") (CvLSVMFilterPosition <cv-lsvm-filter-position> #f #f "") (CvLatentSvmDetector <cv-latent-svm-detector> #t "cvReleaseLatentSvmDetector" "&") (CvObjectDetection <cv-object-detection> #f #f "") )) sym - name sym - scm - type ponter ? finalize finalize - ref (define foreign-pointer '( ))
d744a6b80a6f0e9fcb432219f3b28b6b92f3fbb0b6456fee1ceb8979e3a2f5f1
well-typed-lightbulbs/ocaml-esp32
ocaml_flags.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Gallium , INRIA Paris (* *) Copyright 2018 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. *) (* *) (**************************************************************************) (* Flags used in OCaml commands *) val stdlib : string -> string val include_toplevel_directory : string -> string val c_includes : string -> string val runtime_flags : string -> Environments.t -> Ocaml_backends.t -> bool -> string val toplevel_default_flags : string val ocamldebug_default_flags : string -> string val ocamlobjinfo_default_flags : string
null
https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/ocamltest/ocaml_flags.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Flags used in OCaml commands
, projet Gallium , INRIA Paris Copyright 2018 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the val stdlib : string -> string val include_toplevel_directory : string -> string val c_includes : string -> string val runtime_flags : string -> Environments.t -> Ocaml_backends.t -> bool -> string val toplevel_default_flags : string val ocamldebug_default_flags : string -> string val ocamlobjinfo_default_flags : string
a430fc327d42d1754993f2dfb0c5ce922dac1fef3e47fb80969d754dc2868575
silviucpp/erltls
erltls.erl
-module(erltls). -include("erltls.hrl"). %% todo: 1 . implement the missing methods 2 . In handshake process add a timeout param ( affects connect and ssl_accept methods ) -export([ start/0, start/1, stop/0, cipher_suites/0, clear_pem_cache/0, connect/2, connect/3, connect/4, controlling_process/2, getopts/2, setopts/2, getstat/1, getstat/2, peercert/1, connection_information/1, peername/1, sockname/1, session_reused/1, listen/2, transport_accept/1, transport_accept/2, ssl_accept/1, ssl_accept/2, ssl_accept/3, send/2, recv/2, recv/3, close/1, close/2, shutdown/2, versions/0 ]). -spec start() -> ok | {error, reason()}. start() -> start(temporary). -spec start(permanent | transient | temporary) -> ok | {error, reason()}. start(Type) -> case application:ensure_all_started(erltls, Type) of {ok, _} -> ok; Other -> Other end. -spec stop() -> ok. stop() -> application:stop(erltls). cipher_suites() -> case erltls_manager:get_context([], false) of {ok, Ctx} -> erltls_nif:ciphers(Ctx); _ -> {error, <<"invalid ssl context">>} end. clear_pem_cache() -> case erltls_manager:clear_cache() of true -> ok; Error -> {error, Error} end. -spec connect(port(), [connect_option()]) -> {ok, tlssocket()} | {error, reason()}. connect(Socket, TlsOpt) -> connect(Socket, TlsOpt, ?DEFAULT_TIMEOUT). -spec connect(port() | host(), [connect_option()] | inet:port_number(), timeout() | list()) -> {ok, tlssocket()} | {error, reason()}. connect(Socket, TlsOpt0, Timeout) when is_port(Socket) -> %todo: implement timeout in this case case inet:setopts(Socket, erltls_options:default_inet_options()) of ok -> case erltls_options:get_options(TlsOpt0) of {ok, [], TlsOpt, []} -> do_connect(Socket, TlsOpt, erltls_options:emulated_for_socket(Socket), Timeout); {ok, TcpOpt, _TlsOpt, EmulatedOpt} -> {error, {options, TcpOpt ++ EmulatedOpt}}; Error -> Error end; Error -> Error end; connect(Host, Port, Options) -> connect(Host, Port, Options, ?DEFAULT_TIMEOUT). -spec connect(host(), inet:port_number(), [connect_option()], timeout()) -> {ok, tlssocket()} | {error, reason()}. connect(Host, Port, Options, Timeout) -> case erltls_options:get_options(Options) of {ok, TcpOpt, TlsOpt, EmulatedOpts} -> case gen_tcp:connect(Host, Port, TcpOpt ++ erltls_options:default_inet_options(), Timeout) of {ok, TcpSocket} -> do_connect(TcpSocket, TlsOpt, EmulatedOpts, Timeout); Error -> Error end; Error -> Error end. -spec controlling_process(tlssocket(), pid()) -> ok | {error, reason()}. controlling_process(#tlssocket{ssl_pid = Pid} = Socket, NewOwner) -> erltls_ssl_process:controlling_process(Pid, Socket, NewOwner). -spec getopts(tlssocket(), [gen_tcp:option_name()]) -> {ok, [gen_tcp:option()]} | {error, reason()}. getopts(#tlssocket{tcp_sock = TcpSock, ssl_pid = Pid}, OptionNames) -> case erltls_options:get_inet_names(OptionNames) of {ok, InetOptsNames, []} -> inet:getopts(TcpSock, InetOptsNames); {ok, [], EmulatedOptsNames} -> erltls_ssl_process:get_emulated_options(Pid, EmulatedOptsNames); {ok, InetOptsNames, EmulatedOptsNames} -> case inet:getopts(TcpSock, InetOptsNames) of {ok, Opts1} -> case erltls_ssl_process:get_emulated_options(Pid, EmulatedOptsNames) of {ok, Opts2} -> {ok, Opts1 ++ Opts2}; Error -> Error end; Error -> Error end; Error -> Error end. -spec setopts(tlssocket(), [gen_tcp:option()]) -> ok | {error, reason()}. setopts(#tlssocket{ssl_pid = Pid}, Options) -> case erltls_options:get_inet_options(Options) of {ok, InetOpts, EmulatedOpts} -> erltls_ssl_process:setopts(Pid, InetOpts, EmulatedOpts); Error -> Error end. -spec getstat(tlssocket()) -> {ok, [{inet:stat_option(), integer()}]} | {error, inet:posix()}. getstat(#tlssocket{tcp_sock = TcpSock}) -> inet:getstat(TcpSock). -spec getstat(tlssocket(), [inet:stat_option()]) -> {ok, [{inet:stat_option(), integer()}]} | {error, inet:posix()}. getstat(#tlssocket{tcp_sock = TcpSock}, Opt) -> inet:getstat(TcpSock, Opt). -spec peercert(tlssocket()) -> {ok, binary()} | {error, reason()}. peercert(#tlssocket{ssl_pid = Pid}) -> erltls_ssl_process:peercert(Pid). -spec peername(tlssocket()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, reason()}. peername(#tlssocket{tcp_sock = TcpSock}) -> inet:peername(TcpSock). -spec sockname(tlssocket()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, reason()}. sockname(#tlssocket{tcp_sock = TcpSock}) -> inet:sockname(TcpSock). -spec connection_information(tlssocket()) -> {ok, list()} | {error, reason()}. connection_information(#tlssocket{ssl_pid = Pid}) -> erltls_ssl_process:session_info(Pid). -spec session_reused(tlssocket()) -> boolean() | {error, reason()}. session_reused(#tlssocket{ssl_pid = Pid}) -> erltls_ssl_process:session_reused(Pid). -spec listen(inet:port_number(), [listen_option()]) -> {ok, tlssocket()} | {error, reason()}. listen(Port, Options) -> case erltls_options:get_options(Options) of {ok, TcpOpt, TlsOpt, EmulatedOpt} -> case gen_tcp:listen(Port, TcpOpt ++ erltls_options:default_inet_options()) of {ok, TcpSocket} -> erltls_ssl_process:new(TcpSocket, TlsOpt, EmulatedOpt, ?SSL_ROLE_SERVER); Error -> Error end; Error -> Error end. -spec transport_accept(tlssocket()) -> {ok, tlssocket()} |{error, reason()}. transport_accept(ListenSocket) -> transport_accept(ListenSocket, ?DEFAULT_TIMEOUT). -spec transport_accept(tlssocket(), timeout()) -> {ok, tlssocket()} | {error, reason()}. transport_accept(#tlssocket{tcp_sock = TcpSock, ssl_pid = Pid}, Timeout) -> case gen_tcp:accept(TcpSock, Timeout) of {ok, ASocket} -> case erltls_ssl_process:get_options(Pid) of {ok, TlsOpts, EmulatedOpts} -> erltls_ssl_process:new(ASocket, TlsOpts, EmulatedOpts, ?SSL_ROLE_SERVER); Error -> Error end; Error -> Error end. -spec ssl_accept(tlssocket()) -> ok | {error, reason()}. ssl_accept(Socket) -> ssl_accept(Socket, ?DEFAULT_TIMEOUT). -spec ssl_accept(tlssocket() | port(), timeout()| [tls_option()]) -> ok | {ok, tlssocket()} | {error, reason()}. ssl_accept(#tlssocket{} = Socket, Timeout) -> ssl_accept(Socket, [], Timeout); ssl_accept(Socket, SslOptions) when is_port(Socket) -> ssl_accept(Socket, SslOptions, ?DEFAULT_TIMEOUT). -spec ssl_accept(tlssocket() | port(), [tls_option()], timeout()) -> {ok, tlssocket()} | {error, reason()}. ssl_accept(#tlssocket{tcp_sock = TcpSock, ssl_pid = Pid}, [], Timeout) -> erltls_ssl_process:handshake(Pid, TcpSock, Timeout); ssl_accept(Socket, SslOptions, Timeout) when is_port(Socket) -> case erltls_options:get_options(SslOptions) of {ok, [], TlsOpt, []} -> case erltls_ssl_process:new(Socket, TlsOpt, erltls_options:emulated_for_socket(Socket), ?SSL_ROLE_SERVER) of {ok, SslSocket} -> case erltls_ssl_process:handshake(SslSocket#tlssocket.ssl_pid, Socket, Timeout) of ok -> {ok, SslSocket}; Error -> Error end; Error -> Error end; {ok, TcpOpt, _TlsOpt, EmulatedOpt} -> {error, {options, TcpOpt ++ EmulatedOpt}}; Error -> Error end. -spec send(tlssocket(), iodata()) -> ok | {error, reason()}. send(#tlssocket{ssl_pid = Pid, tcp_sock = TcpSocket}, Data) -> case erltls_ssl_process:encode_data(Pid, Data) of {ok, TlsData} -> gen_tcp:send(TcpSocket, TlsData); Error -> Error end. -spec recv(tlssocket(), integer()) -> {ok, binary()| list()} | {error, reason()}. recv(Socket, Length) -> recv(Socket, Length, infinity). -spec recv(tlssocket(), integer(), timeout()) -> {ok, binary()| list()} | {error, reason()}. recv(#tlssocket{tcp_sock = TcpSock, ssl_pid = Pid}, Length, Timeout) -> case erltls_ssl_process:get_pending_buffer(Pid, Length) of need_more -> passive_read_more(TcpSock, Pid, Length, Timeout); Response-> Response end. passive_read_more(TcpSock, TlsPid, TotalLength, Timeout) -> case gen_tcp:recv(TcpSock, 0, Timeout) of {ok, Packet} -> case erltls_ssl_process:decode_data(TlsPid, Packet, TotalLength) of need_more -> passive_read_more(TcpSock, TlsPid, TotalLength, Timeout); Response -> Response end; Error -> Error end. -spec close(tlssocket(), timeout() | {pid(), integer()}) -> ok | {ok, port()} | {error, reason()}. close(#tlssocket{tcp_sock = TcpSock, ssl_pid = SslPid} = Socket, {NewOwnerPid, Timeout}) when is_pid(NewOwnerPid) -> case erltls_ssl_process:downgrade(SslPid, NewOwnerPid, Timeout) of ok -> {ok, TcpSock}; Error -> close(Socket), Error end; close(TlsSocket, _Timeout) -> %todo: implement timeout parameter here. close(TlsSocket). -spec close(tlssocket()) -> term(). close(#tlssocket{ssl_pid = Pid, tcp_sock = TcpSocket}) -> erltls_ssl_process:shutdown(Pid), erltls_ssl_process:close(Pid), gen_tcp:close(TcpSocket). -spec shutdown(tlssocket(), read | write | read_write) -> ok | {error, reason()}. shutdown(#tlssocket{tcp_sock = TcpSocket, ssl_pid = Pid}, How)-> case How =:= write orelse How =:= read_write of true -> erltls_ssl_process:shutdown(Pid); _ -> ok end, gen_tcp:shutdown(TcpSocket, How). -spec versions() -> {ok, list()}. versions() -> erltls_nif:version(). %internals do_connect(TcpSocket, TlsOpt, EmulatedOpts, Timeout) when is_list(EmulatedOpts) -> UseSessionTicket = erltls_options:use_session_ticket(erltls_utils:lookup(use_session_ticket, TlsOpt)), case get_session_ticket(UseSessionTicket, TcpSocket) of {ok, SessionAsn1, Host, Port} -> case erltls_ssl_process:new(TcpSocket, TlsOpt, EmulatedOpts, ?SSL_ROLE_CLIENT, SessionAsn1, Timeout) of {ok, #tlssocket{ssl_pid = Pid} = TlsSocketRef} -> update_session_ticket(UseSessionTicket, Host, Port, Pid), {ok, TlsSocketRef}; Error -> Error end; Error -> Error end; do_connect(_TcpSocket, _TlsOpt, EmulatedOpts, _Timeout) -> {error, EmulatedOpts}. get_session_ticket(true, Socket) -> case inet:peername(Socket) of {ok, {Host, Port}} -> case erltls_ticket_cache:get(Host, Port) of null -> {ok, <<>>, Host, Port}; {ok, SessionAsn1} -> {ok, SessionAsn1, Host, Port}; Resp -> Resp end; Error -> Error end; get_session_ticket(_, _Socket) -> {ok, <<>>, undefined, undefined}. update_session_ticket(true, Host, Port, TlsRef) -> case erltls_ssl_process:get_session_asn1(TlsRef) of {ok, HasTicket, SessionAsn1} -> case HasTicket of true -> erltls_ticket_cache:set(Host, Port, SessionAsn1); _ -> true end; Error -> Error end; update_session_ticket(_, _Host, _Port, _TlsRef) -> true.
null
https://raw.githubusercontent.com/silviucpp/erltls/da527e75a5792ecfa9379d499628e0c2fe611f52/src/erltls.erl
erlang
todo: todo: implement timeout in this case todo: implement timeout parameter here. internals
-module(erltls). -include("erltls.hrl"). 1 . implement the missing methods 2 . In handshake process add a timeout param ( affects connect and ssl_accept methods ) -export([ start/0, start/1, stop/0, cipher_suites/0, clear_pem_cache/0, connect/2, connect/3, connect/4, controlling_process/2, getopts/2, setopts/2, getstat/1, getstat/2, peercert/1, connection_information/1, peername/1, sockname/1, session_reused/1, listen/2, transport_accept/1, transport_accept/2, ssl_accept/1, ssl_accept/2, ssl_accept/3, send/2, recv/2, recv/3, close/1, close/2, shutdown/2, versions/0 ]). -spec start() -> ok | {error, reason()}. start() -> start(temporary). -spec start(permanent | transient | temporary) -> ok | {error, reason()}. start(Type) -> case application:ensure_all_started(erltls, Type) of {ok, _} -> ok; Other -> Other end. -spec stop() -> ok. stop() -> application:stop(erltls). cipher_suites() -> case erltls_manager:get_context([], false) of {ok, Ctx} -> erltls_nif:ciphers(Ctx); _ -> {error, <<"invalid ssl context">>} end. clear_pem_cache() -> case erltls_manager:clear_cache() of true -> ok; Error -> {error, Error} end. -spec connect(port(), [connect_option()]) -> {ok, tlssocket()} | {error, reason()}. connect(Socket, TlsOpt) -> connect(Socket, TlsOpt, ?DEFAULT_TIMEOUT). -spec connect(port() | host(), [connect_option()] | inet:port_number(), timeout() | list()) -> {ok, tlssocket()} | {error, reason()}. connect(Socket, TlsOpt0, Timeout) when is_port(Socket) -> case inet:setopts(Socket, erltls_options:default_inet_options()) of ok -> case erltls_options:get_options(TlsOpt0) of {ok, [], TlsOpt, []} -> do_connect(Socket, TlsOpt, erltls_options:emulated_for_socket(Socket), Timeout); {ok, TcpOpt, _TlsOpt, EmulatedOpt} -> {error, {options, TcpOpt ++ EmulatedOpt}}; Error -> Error end; Error -> Error end; connect(Host, Port, Options) -> connect(Host, Port, Options, ?DEFAULT_TIMEOUT). -spec connect(host(), inet:port_number(), [connect_option()], timeout()) -> {ok, tlssocket()} | {error, reason()}. connect(Host, Port, Options, Timeout) -> case erltls_options:get_options(Options) of {ok, TcpOpt, TlsOpt, EmulatedOpts} -> case gen_tcp:connect(Host, Port, TcpOpt ++ erltls_options:default_inet_options(), Timeout) of {ok, TcpSocket} -> do_connect(TcpSocket, TlsOpt, EmulatedOpts, Timeout); Error -> Error end; Error -> Error end. -spec controlling_process(tlssocket(), pid()) -> ok | {error, reason()}. controlling_process(#tlssocket{ssl_pid = Pid} = Socket, NewOwner) -> erltls_ssl_process:controlling_process(Pid, Socket, NewOwner). -spec getopts(tlssocket(), [gen_tcp:option_name()]) -> {ok, [gen_tcp:option()]} | {error, reason()}. getopts(#tlssocket{tcp_sock = TcpSock, ssl_pid = Pid}, OptionNames) -> case erltls_options:get_inet_names(OptionNames) of {ok, InetOptsNames, []} -> inet:getopts(TcpSock, InetOptsNames); {ok, [], EmulatedOptsNames} -> erltls_ssl_process:get_emulated_options(Pid, EmulatedOptsNames); {ok, InetOptsNames, EmulatedOptsNames} -> case inet:getopts(TcpSock, InetOptsNames) of {ok, Opts1} -> case erltls_ssl_process:get_emulated_options(Pid, EmulatedOptsNames) of {ok, Opts2} -> {ok, Opts1 ++ Opts2}; Error -> Error end; Error -> Error end; Error -> Error end. -spec setopts(tlssocket(), [gen_tcp:option()]) -> ok | {error, reason()}. setopts(#tlssocket{ssl_pid = Pid}, Options) -> case erltls_options:get_inet_options(Options) of {ok, InetOpts, EmulatedOpts} -> erltls_ssl_process:setopts(Pid, InetOpts, EmulatedOpts); Error -> Error end. -spec getstat(tlssocket()) -> {ok, [{inet:stat_option(), integer()}]} | {error, inet:posix()}. getstat(#tlssocket{tcp_sock = TcpSock}) -> inet:getstat(TcpSock). -spec getstat(tlssocket(), [inet:stat_option()]) -> {ok, [{inet:stat_option(), integer()}]} | {error, inet:posix()}. getstat(#tlssocket{tcp_sock = TcpSock}, Opt) -> inet:getstat(TcpSock, Opt). -spec peercert(tlssocket()) -> {ok, binary()} | {error, reason()}. peercert(#tlssocket{ssl_pid = Pid}) -> erltls_ssl_process:peercert(Pid). -spec peername(tlssocket()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, reason()}. peername(#tlssocket{tcp_sock = TcpSock}) -> inet:peername(TcpSock). -spec sockname(tlssocket()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, reason()}. sockname(#tlssocket{tcp_sock = TcpSock}) -> inet:sockname(TcpSock). -spec connection_information(tlssocket()) -> {ok, list()} | {error, reason()}. connection_information(#tlssocket{ssl_pid = Pid}) -> erltls_ssl_process:session_info(Pid). -spec session_reused(tlssocket()) -> boolean() | {error, reason()}. session_reused(#tlssocket{ssl_pid = Pid}) -> erltls_ssl_process:session_reused(Pid). -spec listen(inet:port_number(), [listen_option()]) -> {ok, tlssocket()} | {error, reason()}. listen(Port, Options) -> case erltls_options:get_options(Options) of {ok, TcpOpt, TlsOpt, EmulatedOpt} -> case gen_tcp:listen(Port, TcpOpt ++ erltls_options:default_inet_options()) of {ok, TcpSocket} -> erltls_ssl_process:new(TcpSocket, TlsOpt, EmulatedOpt, ?SSL_ROLE_SERVER); Error -> Error end; Error -> Error end. -spec transport_accept(tlssocket()) -> {ok, tlssocket()} |{error, reason()}. transport_accept(ListenSocket) -> transport_accept(ListenSocket, ?DEFAULT_TIMEOUT). -spec transport_accept(tlssocket(), timeout()) -> {ok, tlssocket()} | {error, reason()}. transport_accept(#tlssocket{tcp_sock = TcpSock, ssl_pid = Pid}, Timeout) -> case gen_tcp:accept(TcpSock, Timeout) of {ok, ASocket} -> case erltls_ssl_process:get_options(Pid) of {ok, TlsOpts, EmulatedOpts} -> erltls_ssl_process:new(ASocket, TlsOpts, EmulatedOpts, ?SSL_ROLE_SERVER); Error -> Error end; Error -> Error end. -spec ssl_accept(tlssocket()) -> ok | {error, reason()}. ssl_accept(Socket) -> ssl_accept(Socket, ?DEFAULT_TIMEOUT). -spec ssl_accept(tlssocket() | port(), timeout()| [tls_option()]) -> ok | {ok, tlssocket()} | {error, reason()}. ssl_accept(#tlssocket{} = Socket, Timeout) -> ssl_accept(Socket, [], Timeout); ssl_accept(Socket, SslOptions) when is_port(Socket) -> ssl_accept(Socket, SslOptions, ?DEFAULT_TIMEOUT). -spec ssl_accept(tlssocket() | port(), [tls_option()], timeout()) -> {ok, tlssocket()} | {error, reason()}. ssl_accept(#tlssocket{tcp_sock = TcpSock, ssl_pid = Pid}, [], Timeout) -> erltls_ssl_process:handshake(Pid, TcpSock, Timeout); ssl_accept(Socket, SslOptions, Timeout) when is_port(Socket) -> case erltls_options:get_options(SslOptions) of {ok, [], TlsOpt, []} -> case erltls_ssl_process:new(Socket, TlsOpt, erltls_options:emulated_for_socket(Socket), ?SSL_ROLE_SERVER) of {ok, SslSocket} -> case erltls_ssl_process:handshake(SslSocket#tlssocket.ssl_pid, Socket, Timeout) of ok -> {ok, SslSocket}; Error -> Error end; Error -> Error end; {ok, TcpOpt, _TlsOpt, EmulatedOpt} -> {error, {options, TcpOpt ++ EmulatedOpt}}; Error -> Error end. -spec send(tlssocket(), iodata()) -> ok | {error, reason()}. send(#tlssocket{ssl_pid = Pid, tcp_sock = TcpSocket}, Data) -> case erltls_ssl_process:encode_data(Pid, Data) of {ok, TlsData} -> gen_tcp:send(TcpSocket, TlsData); Error -> Error end. -spec recv(tlssocket(), integer()) -> {ok, binary()| list()} | {error, reason()}. recv(Socket, Length) -> recv(Socket, Length, infinity). -spec recv(tlssocket(), integer(), timeout()) -> {ok, binary()| list()} | {error, reason()}. recv(#tlssocket{tcp_sock = TcpSock, ssl_pid = Pid}, Length, Timeout) -> case erltls_ssl_process:get_pending_buffer(Pid, Length) of need_more -> passive_read_more(TcpSock, Pid, Length, Timeout); Response-> Response end. passive_read_more(TcpSock, TlsPid, TotalLength, Timeout) -> case gen_tcp:recv(TcpSock, 0, Timeout) of {ok, Packet} -> case erltls_ssl_process:decode_data(TlsPid, Packet, TotalLength) of need_more -> passive_read_more(TcpSock, TlsPid, TotalLength, Timeout); Response -> Response end; Error -> Error end. -spec close(tlssocket(), timeout() | {pid(), integer()}) -> ok | {ok, port()} | {error, reason()}. close(#tlssocket{tcp_sock = TcpSock, ssl_pid = SslPid} = Socket, {NewOwnerPid, Timeout}) when is_pid(NewOwnerPid) -> case erltls_ssl_process:downgrade(SslPid, NewOwnerPid, Timeout) of ok -> {ok, TcpSock}; Error -> close(Socket), Error end; close(TlsSocket, _Timeout) -> close(TlsSocket). -spec close(tlssocket()) -> term(). close(#tlssocket{ssl_pid = Pid, tcp_sock = TcpSocket}) -> erltls_ssl_process:shutdown(Pid), erltls_ssl_process:close(Pid), gen_tcp:close(TcpSocket). -spec shutdown(tlssocket(), read | write | read_write) -> ok | {error, reason()}. shutdown(#tlssocket{tcp_sock = TcpSocket, ssl_pid = Pid}, How)-> case How =:= write orelse How =:= read_write of true -> erltls_ssl_process:shutdown(Pid); _ -> ok end, gen_tcp:shutdown(TcpSocket, How). -spec versions() -> {ok, list()}. versions() -> erltls_nif:version(). do_connect(TcpSocket, TlsOpt, EmulatedOpts, Timeout) when is_list(EmulatedOpts) -> UseSessionTicket = erltls_options:use_session_ticket(erltls_utils:lookup(use_session_ticket, TlsOpt)), case get_session_ticket(UseSessionTicket, TcpSocket) of {ok, SessionAsn1, Host, Port} -> case erltls_ssl_process:new(TcpSocket, TlsOpt, EmulatedOpts, ?SSL_ROLE_CLIENT, SessionAsn1, Timeout) of {ok, #tlssocket{ssl_pid = Pid} = TlsSocketRef} -> update_session_ticket(UseSessionTicket, Host, Port, Pid), {ok, TlsSocketRef}; Error -> Error end; Error -> Error end; do_connect(_TcpSocket, _TlsOpt, EmulatedOpts, _Timeout) -> {error, EmulatedOpts}. get_session_ticket(true, Socket) -> case inet:peername(Socket) of {ok, {Host, Port}} -> case erltls_ticket_cache:get(Host, Port) of null -> {ok, <<>>, Host, Port}; {ok, SessionAsn1} -> {ok, SessionAsn1, Host, Port}; Resp -> Resp end; Error -> Error end; get_session_ticket(_, _Socket) -> {ok, <<>>, undefined, undefined}. update_session_ticket(true, Host, Port, TlsRef) -> case erltls_ssl_process:get_session_asn1(TlsRef) of {ok, HasTicket, SessionAsn1} -> case HasTicket of true -> erltls_ticket_cache:set(Host, Port, SessionAsn1); _ -> true end; Error -> Error end; update_session_ticket(_, _Host, _Port, _TlsRef) -> true.
feebd59da27d9161666ce6c4abf79181b3ab0244c93001d532a4d8a431938458
hopv/MoCHi
linTermIntRel.ml
open Util open Combinator open Term (** linear relations with integer term coefficients *) include LinRel.Make(LinTermIntExp.Coeff) * { 6 Auxiliary constructors } (* val of_formula : Formula.t -> t *) let of_formula phi = match phi |> Formula.term_of |> fun_args with | Const(c), [t1; t2] when Const.is_brel c(*@todo[Const.is_ibrel c] rejects the equality with a polymorphic type*) -> c, IntTerm.sub t1 t2 |> LinTermIntExp.of_term | _ -> Logger.printf "LinTermIntRel.of_formula: %a@," Formula.pr phi; invalid_arg "LinTermIntRel.of_formula" let of_formula = Logger.log_block1 "LinTermIntRel.of_formula" of_formula let of_literal = Literal.formula_of >> of_formula (** @require c is not <> @ensure the result only uses geq and eq *) (* val normalize : t -> t *) let normalize (c, (nxs, n)) = match c with @todo [ when ] rejects the equality with a polymorphic type c, (nxs, n) @todo [ when ] rejects the equality with a polymorphic type assert false @todo [ when ] rejects the equality with a polymorphic type Logger.printf0 "elim_lt!!@,"; Const.Geq(Type.mk_int), LinTermIntExp.neg (nxs, IntTerm.add n (IntTerm.one)) @todo [ when ] rejects the equality with a polymorphic type Logger.printf0 "elim_gt!!@,"; Const.Geq(Type.mk_int), (nxs, CunTerm.poly_simplify (IntTerm.sub n (IntTerm.one))) @todo [ when ] rejects the equality with a polymorphic type Const.Geq(Type.mk_int), LinTermIntExp.neg (nxs, n) @todo [ when ] rejects the equality with a polymorphic type c, (nxs, n) | _ -> Format.printf "Uncaught const: %s@," (Const.string_of c); assert false let normalize = Logger.log_block1 "LinTermIntRel.normalize" normalize * { 6 Inspectors } let is_linear phi = try ignore (of_formula phi); true with Invalid_argument _ -> false @todo move to LinRel * @ensure the result does not contain Const . Neg , Const . Sub , and negative integer constants and negative integer constants *) (* val formula_of : t -> Formula.t *) let formula_of (c, (nxs, n)) = if nxs = [] && IntTerm.is_const n then if Const.lift_brel c (IntTerm.int_of n) 0 then Formula.mk_true else Formula.mk_false else let nxs = List.filter_map (fun (n, x) -> if IntTerm.equiv n (IntTerm.zero) then None else Some(n, x)) nxs in let nxs1, nxs2 = List.partition (fun (n, _) -> not (IntTerm.is_const n) || IntTerm.(>) n IntTerm.zero) nxs in let n1, n2 = if not (IntTerm.is_const n) || IntTerm.(>) n IntTerm.zero then n, IntTerm.zero else if IntTerm.(<) n IntTerm.zero then IntTerm.zero, n else IntTerm.zero, IntTerm.zero in let tp = LinTermIntExp.term_of (nxs1, n1) in let tm = LinTermIntExp.term_of (LinTermIntExp.neg (nxs2, n2)) in Formula.of_term (mk_app (mk_const c) [tp; tm]) let simplify_formula = of_formula >> formula_of (** @ensure pred res *) (* val elem_of : (elem -> bool) -> LinTermIntRel.t -> elem *) let elem_of pred (c, (nxs, n)) = if c = Const.Eq(Type.mk_int) then List.find_maplr (fun nxs1 (n', x) nxs2 -> if IntTerm.equiv n' IntTerm.one || IntTerm.equiv n' (IntTerm.make (-1)) then let t = if IntTerm.equiv n' IntTerm.one then LinTermIntExp.term_of (LinTermIntExp.neg (nxs1 @ nxs2, n)) else if IntTerm.equiv n' (IntTerm.make (-1)) then LinTermIntExp.term_of (nxs1 @ nxs2, n) else assert false in let ty = Type.mk_int in if pred (x, (t, ty)) then Some(x, (t, ty)) else None else None) nxs else raise Not_found let tttrue = Formula.term_of Formula.mk_true, Type.mk_bool let ttfalse = Formula.term_of Formula.mk_false, Type.mk_bool (** @ensure if [r] is returned, [pred r] holds *) (* val elem_of_formula : (TypTermSubst.elem -> bool) -> Formula.t -> TypTermSubst.elem *) let elem_of_formula pred phi = try phi |> of_formula |> elem_of pred with | Invalid_argument _ -> match phi |> Formula.term_of |> Term.fun_args with | Const(Const.Eq(ty)), [Var(x); t] when pred (x, (t, ty)) -> x, (t, ty) | Const(Const.Eq(ty)), [t; Var(x)] when pred (x, (t, ty)) -> x, (t, ty) | Var(x), [] when pred (x, tttrue) -> x, (Formula.term_of Formula.mk_true, Type.mk_bool) | Const(Const.Not), [Var(x)] when pred (x, ttfalse) -> x, (Formula.term_of Formula.mk_false, Type.mk_bool) | _ -> raise Not_found * possibly return a substitution of the form { x - > y , y - > z } @param pred do not require that mem x ( fvs t ) implies not ( pred ( x , ( t , ty ) ) ) @todo is this also sound for non - linear expressions ? @ensure if [ ( ttsub , phis ) ] is retuned not ( cyclic ttsub ) & & List.for_all pred ttsub {x -> y, y -> z} @param pred do not require that mem x (fvs t) implies not (pred (x, (t, ty))) @todo is this also sound for non-linear expressions? @ensure if [(ttsub, phis)] is retuned not (cyclic ttsub) && List.for_all pred ttsub *) (* val of_formulas : (TypTermSubst.elem -> bool) -> Formula.t list -> t * Formula.t *) let of_formulas pred = List.fold_left (fun (ttsub0, phis0) phi -> try let xtty = let pred = let dom = TypTermSubst.dom ttsub0 in fun (x, (t, ty)) -> pred (x, (t, ty)) && @todo check whether substitution is acyclic instead Set_.inter (x :: dom) (Term.fvs t) = [] in phi |> elem_of_formula pred |> Logger.pprintf "xtty: %a@," TypTermSubst.pr_elem in xtty :: ttsub0, phis0 with Not_found -> ttsub0, phi :: phis0) ([], []) >> Pair.map_fst Formula.resolve_duplicates_in_ttsub >> fun ((ttsub, phis0), phis1) -> ttsub, phis0 @ phis1 |> Formula.band let of_formulas = Logger.log_block2 "LinTermIntRel.of_formulas" of_formulas
null
https://raw.githubusercontent.com/hopv/MoCHi/b0ac0d626d64b1e3c779d8e98cb232121cc3196a/fpat/linTermIntRel.ml
ocaml
* linear relations with integer term coefficients val of_formula : Formula.t -> t @todo[Const.is_ibrel c] rejects the equality with a polymorphic type * @require c is not <> @ensure the result only uses geq and eq val normalize : t -> t val formula_of : t -> Formula.t * @ensure pred res val elem_of : (elem -> bool) -> LinTermIntRel.t -> elem * @ensure if [r] is returned, [pred r] holds val elem_of_formula : (TypTermSubst.elem -> bool) -> Formula.t -> TypTermSubst.elem val of_formulas : (TypTermSubst.elem -> bool) -> Formula.t list -> t * Formula.t
open Util open Combinator open Term include LinRel.Make(LinTermIntExp.Coeff) * { 6 Auxiliary constructors } let of_formula phi = match phi |> Formula.term_of |> fun_args with c, IntTerm.sub t1 t2 |> LinTermIntExp.of_term | _ -> Logger.printf "LinTermIntRel.of_formula: %a@," Formula.pr phi; invalid_arg "LinTermIntRel.of_formula" let of_formula = Logger.log_block1 "LinTermIntRel.of_formula" of_formula let of_literal = Literal.formula_of >> of_formula let normalize (c, (nxs, n)) = match c with @todo [ when ] rejects the equality with a polymorphic type c, (nxs, n) @todo [ when ] rejects the equality with a polymorphic type assert false @todo [ when ] rejects the equality with a polymorphic type Logger.printf0 "elim_lt!!@,"; Const.Geq(Type.mk_int), LinTermIntExp.neg (nxs, IntTerm.add n (IntTerm.one)) @todo [ when ] rejects the equality with a polymorphic type Logger.printf0 "elim_gt!!@,"; Const.Geq(Type.mk_int), (nxs, CunTerm.poly_simplify (IntTerm.sub n (IntTerm.one))) @todo [ when ] rejects the equality with a polymorphic type Const.Geq(Type.mk_int), LinTermIntExp.neg (nxs, n) @todo [ when ] rejects the equality with a polymorphic type c, (nxs, n) | _ -> Format.printf "Uncaught const: %s@," (Const.string_of c); assert false let normalize = Logger.log_block1 "LinTermIntRel.normalize" normalize * { 6 Inspectors } let is_linear phi = try ignore (of_formula phi); true with Invalid_argument _ -> false @todo move to LinRel * @ensure the result does not contain Const . Neg , Const . Sub , and negative integer constants and negative integer constants *) let formula_of (c, (nxs, n)) = if nxs = [] && IntTerm.is_const n then if Const.lift_brel c (IntTerm.int_of n) 0 then Formula.mk_true else Formula.mk_false else let nxs = List.filter_map (fun (n, x) -> if IntTerm.equiv n (IntTerm.zero) then None else Some(n, x)) nxs in let nxs1, nxs2 = List.partition (fun (n, _) -> not (IntTerm.is_const n) || IntTerm.(>) n IntTerm.zero) nxs in let n1, n2 = if not (IntTerm.is_const n) || IntTerm.(>) n IntTerm.zero then n, IntTerm.zero else if IntTerm.(<) n IntTerm.zero then IntTerm.zero, n else IntTerm.zero, IntTerm.zero in let tp = LinTermIntExp.term_of (nxs1, n1) in let tm = LinTermIntExp.term_of (LinTermIntExp.neg (nxs2, n2)) in Formula.of_term (mk_app (mk_const c) [tp; tm]) let simplify_formula = of_formula >> formula_of let elem_of pred (c, (nxs, n)) = if c = Const.Eq(Type.mk_int) then List.find_maplr (fun nxs1 (n', x) nxs2 -> if IntTerm.equiv n' IntTerm.one || IntTerm.equiv n' (IntTerm.make (-1)) then let t = if IntTerm.equiv n' IntTerm.one then LinTermIntExp.term_of (LinTermIntExp.neg (nxs1 @ nxs2, n)) else if IntTerm.equiv n' (IntTerm.make (-1)) then LinTermIntExp.term_of (nxs1 @ nxs2, n) else assert false in let ty = Type.mk_int in if pred (x, (t, ty)) then Some(x, (t, ty)) else None else None) nxs else raise Not_found let tttrue = Formula.term_of Formula.mk_true, Type.mk_bool let ttfalse = Formula.term_of Formula.mk_false, Type.mk_bool let elem_of_formula pred phi = try phi |> of_formula |> elem_of pred with | Invalid_argument _ -> match phi |> Formula.term_of |> Term.fun_args with | Const(Const.Eq(ty)), [Var(x); t] when pred (x, (t, ty)) -> x, (t, ty) | Const(Const.Eq(ty)), [t; Var(x)] when pred (x, (t, ty)) -> x, (t, ty) | Var(x), [] when pred (x, tttrue) -> x, (Formula.term_of Formula.mk_true, Type.mk_bool) | Const(Const.Not), [Var(x)] when pred (x, ttfalse) -> x, (Formula.term_of Formula.mk_false, Type.mk_bool) | _ -> raise Not_found * possibly return a substitution of the form { x - > y , y - > z } @param pred do not require that mem x ( fvs t ) implies not ( pred ( x , ( t , ty ) ) ) @todo is this also sound for non - linear expressions ? @ensure if [ ( ttsub , phis ) ] is retuned not ( cyclic ttsub ) & & List.for_all pred ttsub {x -> y, y -> z} @param pred do not require that mem x (fvs t) implies not (pred (x, (t, ty))) @todo is this also sound for non-linear expressions? @ensure if [(ttsub, phis)] is retuned not (cyclic ttsub) && List.for_all pred ttsub *) let of_formulas pred = List.fold_left (fun (ttsub0, phis0) phi -> try let xtty = let pred = let dom = TypTermSubst.dom ttsub0 in fun (x, (t, ty)) -> pred (x, (t, ty)) && @todo check whether substitution is acyclic instead Set_.inter (x :: dom) (Term.fvs t) = [] in phi |> elem_of_formula pred |> Logger.pprintf "xtty: %a@," TypTermSubst.pr_elem in xtty :: ttsub0, phis0 with Not_found -> ttsub0, phi :: phis0) ([], []) >> Pair.map_fst Formula.resolve_duplicates_in_ttsub >> fun ((ttsub, phis0), phis1) -> ttsub, phis0 @ phis1 |> Formula.band let of_formulas = Logger.log_block2 "LinTermIntRel.of_formulas" of_formulas
9a65a156c852677408fae3e37a1c57b9d3243d0004e207d92f9a842213a8370d
Simspace/postgresql-tx
DB.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE RankNTypes #-} module Example.PgSimple.Internal.DB where data Handle f = Handle { insertMessage :: String -> f Int , fetchMessage :: Int -> f (Maybe String) , close :: IO () }
null
https://raw.githubusercontent.com/Simspace/postgresql-tx/6769f10a4b928aa37c47ffa5f89f0fa3a9c6fc01/example/test/Example/PgSimple/Internal/DB.hs
haskell
# LANGUAGE RankNTypes #
# LANGUAGE FlexibleContexts # module Example.PgSimple.Internal.DB where data Handle f = Handle { insertMessage :: String -> f Int , fetchMessage :: Int -> f (Maybe String) , close :: IO () }
befd3e90d28170c2b4c0d52d40f12a6276b8300fcab9f258d8107bcb8811fc6a
Clozure/ccl-tests
load-test-file-2.lsp
(in-package :cl-test) (declaim (special *load-test-var.1* *load-test-var.2*)) (eval-when (:load-toplevel) (setq *load-test-var.1* *load-pathname*) (setq *load-test-var.2* *load-truename*))
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/load-test-file-2.lsp
lisp
(in-package :cl-test) (declaim (special *load-test-var.1* *load-test-var.2*)) (eval-when (:load-toplevel) (setq *load-test-var.1* *load-pathname*) (setq *load-test-var.2* *load-truename*))
b950c9c7697d67cccf3ba910fe6881b2f67e898be827756e4c1ce26edcb563c3
fengctor/octune
Annotate.hs
module Octune.Annotate where import qualified Data.Map.Strict as Map import Control.Lens import Octune.Types annotateBeatLengths :: Env (AST Ann) -> Env (AST Ann) annotateBeatLengths env = cache where cache :: Env (AST Ann) cache = fmap go env memoAnnotate :: AST Ann -> AST Ann memoAnnotate v@(Var _ vName) = v & annotation . beatLength .~ (cache Map.! vName) ^. annotation . beatLength memoAnnotate expr = go expr go :: AST Ann -> AST Ann go e@(Song _ _ expr) = e & _Song . _3 .~ annotatedExpr & annotation . beatLength .~ annotatedExpr ^. annotation . beatLength where annotatedExpr = memoAnnotate expr go e@(Var _ vName) = e & annotation . beatLength .~ memoAnnotate (env Map.! vName) ^. annotation . beatLength go e@(LineNote _ (Note _ beats _)) = e & annotation . beatLength ?~ beats go e@(LineApp _ lFun args) = e & _LineApp . _3 .~ annotatedArgs & annotation . beatLength ?~ adjustFun (foldlOf' (traversed . annotation . beatLength . _Just) combineFun 0 annotatedArgs) where annotatedArgs = fmap memoAnnotate args (combineFun, adjustFun) = case lFun of Seq -> ((+), id) Merge -> (max, id) Repeat n -> ((+), (* toRational n)) UsingWaveform _ -> ((+), id) Volume _ -> ((+), id) Subsection l r -> ((+), \total -> max 0 (min r total - l)) -- Beats assertions do not take up time go b@BeatsAssertion{} = b go _ = error "Should not have File or Decl from parsing"
null
https://raw.githubusercontent.com/fengctor/octune/a50f2b8d3750a6660de9d94cb46cb83ac7d31421/src/Octune/Annotate.hs
haskell
Beats assertions do not take up time
module Octune.Annotate where import qualified Data.Map.Strict as Map import Control.Lens import Octune.Types annotateBeatLengths :: Env (AST Ann) -> Env (AST Ann) annotateBeatLengths env = cache where cache :: Env (AST Ann) cache = fmap go env memoAnnotate :: AST Ann -> AST Ann memoAnnotate v@(Var _ vName) = v & annotation . beatLength .~ (cache Map.! vName) ^. annotation . beatLength memoAnnotate expr = go expr go :: AST Ann -> AST Ann go e@(Song _ _ expr) = e & _Song . _3 .~ annotatedExpr & annotation . beatLength .~ annotatedExpr ^. annotation . beatLength where annotatedExpr = memoAnnotate expr go e@(Var _ vName) = e & annotation . beatLength .~ memoAnnotate (env Map.! vName) ^. annotation . beatLength go e@(LineNote _ (Note _ beats _)) = e & annotation . beatLength ?~ beats go e@(LineApp _ lFun args) = e & _LineApp . _3 .~ annotatedArgs & annotation . beatLength ?~ adjustFun (foldlOf' (traversed . annotation . beatLength . _Just) combineFun 0 annotatedArgs) where annotatedArgs = fmap memoAnnotate args (combineFun, adjustFun) = case lFun of Seq -> ((+), id) Merge -> (max, id) Repeat n -> ((+), (* toRational n)) UsingWaveform _ -> ((+), id) Volume _ -> ((+), id) Subsection l r -> ((+), \total -> max 0 (min r total - l)) go b@BeatsAssertion{} = b go _ = error "Should not have File or Decl from parsing"
0b7856abd78a23533dc8958455d22bd5f6fd82ec545db1bce8ea8c23e9a9c202
replikativ/datahike-frontend
pathom.clj
(ns app.server-components.pathom (:require [mount.core :refer [defstate]] [taoensso.timbre :as log] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.core :as p] [com.wsscode.common.async-clj :refer [let-chan]] [clojure.core.async :as async] [app.model.account :as acct] [app.model.session :as session] [app.server-components.config :refer [config]] [app.model.mock-database :as db])) (pc/defresolver index-explorer [env _] {::pc/input #{:com.wsscode.pathom.viz.index-explorer/id} ::pc/output [:com.wsscode.pathom.viz.index-explorer/index]} {:com.wsscode.pathom.viz.index-explorer/index (-> (get env ::pc/indexes) (update ::pc/index-resolvers #(into {} (map (fn [[k v]] [k (dissoc v ::pc/resolve)])) %)) (update ::pc/index-mutations #(into {} (map (fn [[k v]] [k (dissoc v ::pc/mutate)])) %)))}) (def all-resolvers [acct/resolvers session/resolvers index-explorer]) (defn preprocess-parser-plugin "Helper to create a plugin that can view/modify the env/tx of a top-level request. f - (fn [{:keys [env tx]}] {:env new-env :tx new-tx}) If the function returns no env or tx, then the parser will not be called (aborts the parse)" [f] {::p/wrap-parser (fn transform-parser-out-plugin-external [parser] (fn transform-parser-out-plugin-internal [env tx] (let [{:keys [env tx] :as req} (f {:env env :tx tx})] (if (and (map? env) (seq tx)) (parser env tx) {}))))}) (defn log-requests [{:keys [env tx] :as req}] (log/debug "Pathom transaction:" (pr-str tx)) req) (defn build-parser [db-connection] (let [real-parser (p/parallel-parser {::p/mutate pc/mutate-async ::p/env {::p/reader [p/map-reader pc/parallel-reader pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/plugins [(pc/connect-plugin {::pc/register all-resolvers}) (p/env-wrap-plugin (fn [env] ;; Here is where you can dynamically add things to the resolver/mutation ;; environment, like the server config, database connections, etc. (assoc env real datomic would use ( d / db db - connection ) :connection db-connection :config config))) (preprocess-parser-plugin log-requests) p/error-handler-plugin p/request-cache-plugin (p/post-process-parser-plugin p/elide-not-found) p/trace-plugin]}) NOTE : Add -Dtrace to the server JVM to enable Fulcro Inspect query performance traces to the network tab . ;; Understand that this makes the network responses much larger and should not be used in production. trace? (not (nil? (System/getProperty "trace")))] (fn wrapped-parser [env tx] (async/<!! (real-parser env (if trace? (conj tx :com.wsscode.pathom/trace) tx)))))) (defstate parser :start (build-parser db/conn))
null
https://raw.githubusercontent.com/replikativ/datahike-frontend/6e3ab3bb761b41c4ffea792297286f8942a27909/src/main/app/server_components/pathom.clj
clojure
Here is where you can dynamically add things to the resolver/mutation environment, like the server config, database connections, etc. Understand that this makes the network responses much larger and should not be used in production.
(ns app.server-components.pathom (:require [mount.core :refer [defstate]] [taoensso.timbre :as log] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.core :as p] [com.wsscode.common.async-clj :refer [let-chan]] [clojure.core.async :as async] [app.model.account :as acct] [app.model.session :as session] [app.server-components.config :refer [config]] [app.model.mock-database :as db])) (pc/defresolver index-explorer [env _] {::pc/input #{:com.wsscode.pathom.viz.index-explorer/id} ::pc/output [:com.wsscode.pathom.viz.index-explorer/index]} {:com.wsscode.pathom.viz.index-explorer/index (-> (get env ::pc/indexes) (update ::pc/index-resolvers #(into {} (map (fn [[k v]] [k (dissoc v ::pc/resolve)])) %)) (update ::pc/index-mutations #(into {} (map (fn [[k v]] [k (dissoc v ::pc/mutate)])) %)))}) (def all-resolvers [acct/resolvers session/resolvers index-explorer]) (defn preprocess-parser-plugin "Helper to create a plugin that can view/modify the env/tx of a top-level request. f - (fn [{:keys [env tx]}] {:env new-env :tx new-tx}) If the function returns no env or tx, then the parser will not be called (aborts the parse)" [f] {::p/wrap-parser (fn transform-parser-out-plugin-external [parser] (fn transform-parser-out-plugin-internal [env tx] (let [{:keys [env tx] :as req} (f {:env env :tx tx})] (if (and (map? env) (seq tx)) (parser env tx) {}))))}) (defn log-requests [{:keys [env tx] :as req}] (log/debug "Pathom transaction:" (pr-str tx)) req) (defn build-parser [db-connection] (let [real-parser (p/parallel-parser {::p/mutate pc/mutate-async ::p/env {::p/reader [p/map-reader pc/parallel-reader pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/plugins [(pc/connect-plugin {::pc/register all-resolvers}) (p/env-wrap-plugin (fn [env] (assoc env real datomic would use ( d / db db - connection ) :connection db-connection :config config))) (preprocess-parser-plugin log-requests) p/error-handler-plugin p/request-cache-plugin (p/post-process-parser-plugin p/elide-not-found) p/trace-plugin]}) NOTE : Add -Dtrace to the server JVM to enable Fulcro Inspect query performance traces to the network tab . trace? (not (nil? (System/getProperty "trace")))] (fn wrapped-parser [env tx] (async/<!! (real-parser env (if trace? (conj tx :com.wsscode.pathom/trace) tx)))))) (defstate parser :start (build-parser db/conn))
0338f205ecfd33ee78425b948e7a5cfce7d052fa1daaa68e4708f752530fb337
racket/honu
define.rkt
#lang racket/base (require (for-syntax racket/base syntax/parse syntax/define "compile.rkt")) (provide (all-defined-out)) (define-syntax-rule (define-literal name ...) (begin (define-syntax name (lambda (stx) (raise-syntax-error 'name "this is a literal and cannot be used outside a macro" (syntax->datum stx)))) ...)) (define-syntax-rule (define-literal+set set literal ...) (begin (define-literal literal ...) (begin-for-syntax (define-literal-set set (literal ...)))))
null
https://raw.githubusercontent.com/racket/honu/b36b9aeda8be22bf7fda177e831f42ac1a1de79b/honu-parse/define.rkt
racket
#lang racket/base (require (for-syntax racket/base syntax/parse syntax/define "compile.rkt")) (provide (all-defined-out)) (define-syntax-rule (define-literal name ...) (begin (define-syntax name (lambda (stx) (raise-syntax-error 'name "this is a literal and cannot be used outside a macro" (syntax->datum stx)))) ...)) (define-syntax-rule (define-literal+set set literal ...) (begin (define-literal literal ...) (begin-for-syntax (define-literal-set set (literal ...)))))
31faec098c58e8f1628e86957252e03472fa9071ce767a2f4560ccab43077c9f
nikodemus/SBCL
vm-fndb.lisp
;;;; signatures of machine-specific functions This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!C") ;;;; internal type predicates Simple TYPEP uses that do n't have any standard predicate are ;;; translated into non-standard unary predicates. (defknown (fixnump bignump ratiop short-float-p single-float-p double-float-p long-float-p complex-rational-p complex-float-p complex-single-float-p complex-double-float-p #!+long-float complex-long-float-p complex-vector-p base-char-p %standard-char-p %instancep %other-pointer-p base-string-p simple-base-string-p #!+sb-unicode character-string-p #!+sb-unicode simple-character-string-p array-header-p sequencep extended-sequence-p simple-array-p simple-array-nil-p vector-nil-p simple-array-unsigned-byte-2-p simple-array-unsigned-byte-4-p simple-array-unsigned-byte-7-p simple-array-unsigned-byte-8-p simple-array-unsigned-byte-15-p simple-array-unsigned-byte-16-p simple-array-unsigned-fixnum-p simple-array-unsigned-byte-31-p simple-array-unsigned-byte-32-p #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or)) simple-array-unsigned-byte-63-p #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or)) simple-array-unsigned-byte-64-p simple-array-signed-byte-8-p simple-array-signed-byte-16-p simple-array-fixnum-p simple-array-signed-byte-32-p #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or)) simple-array-signed-byte-64-p simple-array-single-float-p simple-array-double-float-p #!+long-float simple-array-long-float-p simple-array-complex-single-float-p simple-array-complex-double-float-p #!+long-float simple-array-complex-long-float-p system-area-pointer-p realp # ! + # .(cl : if ( cl:= 32 sb!vm : n - word - bits ) ' ( and ) ' ( or ) ) unsigned-byte-32-p # ! + # .(cl : if ( cl:= 32 sb!vm : n - word - bits ) ' ( and ) ' ( or ) ) signed-byte-32-p #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or)) unsigned-byte-64-p #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or)) signed-byte-64-p weak-pointer-p code-component-p lra-p funcallable-instance-p) (t) boolean (movable foldable flushable)) (defknown #.(loop for (name) in *vector-without-complex-typecode-infos* collect name) (t) boolean (movable foldable flushable)) ;;;; miscellaneous "sub-primitives" (defknown pointer-hash (t) hash (flushable)) (defknown %sp-string-compare (simple-string index index simple-string index index) (or index null) (foldable flushable)) (defknown %sxhash-simple-string (simple-string) hash (foldable flushable)) (defknown %sxhash-simple-substring (simple-string index) hash (foldable flushable)) (defknown symbol-hash (symbol) hash (flushable movable)) (defknown %set-symbol-hash (symbol hash) t ()) (defknown initialize-vector ((simple-array * (*)) &rest t) (simple-array * (*)) (always-translatable flushable) :result-arg 0) (defknown vector-fill* (t t t t) vector () :result-arg 0) (defknown vector-length (vector) index (flushable dx-safe)) (defknown vector-sap ((simple-unboxed-array (*))) system-area-pointer (flushable)) (defknown lowtag-of (t) (unsigned-byte #.sb!vm:n-lowtag-bits) (flushable movable)) (defknown widetag-of (t) (unsigned-byte #.sb!vm:n-widetag-bits) (flushable movable)) (defknown (get-header-data get-closure-length) (t) (unsigned-byte 24) (flushable)) (defknown set-header-data (t (unsigned-byte 24)) t ()) (defknown %array-dimension (t index) index (flushable)) (defknown %set-array-dimension (t index index) index ()) (defknown %array-rank (t) index (flushable)) (defknown %make-instance (index) instance (flushable)) (defknown %make-structure-instance (defstruct-description list &rest t) instance (flushable always-translatable)) (defknown %instance-layout (instance) layout (foldable flushable)) (defknown %set-instance-layout (instance layout) layout ()) (defknown %instance-length (instance) index (foldable flushable)) (defknown %instance-ref (instance index) t (flushable always-translatable)) (defknown %instance-set (instance index t) t (always-translatable)) (defknown %layout-invalid-error (t layout) nil) (defknown %raw-instance-ref/word (instance index) sb!vm:word (flushable always-translatable)) (defknown %raw-instance-set/word (instance index sb!vm:word) sb!vm:word (always-translatable)) (defknown %raw-instance-ref/single (instance index) single-float (flushable always-translatable)) (defknown %raw-instance-set/single (instance index single-float) single-float (always-translatable)) (defknown %raw-instance-ref/double (instance index) double-float (flushable always-translatable)) (defknown %raw-instance-set/double (instance index double-float) double-float (always-translatable)) (defknown %raw-instance-ref/complex-single (instance index) (complex single-float) (flushable always-translatable)) (defknown %raw-instance-set/complex-single (instance index (complex single-float)) (complex single-float) (always-translatable)) (defknown %raw-instance-ref/complex-double (instance index) (complex double-float) (flushable always-translatable)) (defknown %raw-instance-set/complex-double (instance index (complex double-float)) (complex double-float) (always-translatable)) #!+(or x86 x86-64 ppc) (defknown %raw-instance-atomic-incf/word (instance index sb!vm:word) sb!vm:word (always-translatable)) #!+(or x86 x86-64 ppc) (defknown %array-atomic-incf/word (t index sb!vm:word) sb!vm:word (always-translatable)) These two are mostly used for bit - bashing operations . (defknown %vector-raw-bits (t fixnum) sb!vm:word (flushable)) (defknown (%set-vector-raw-bits) (t fixnum sb!vm:word) sb!vm:word ()) (defknown allocate-vector ((unsigned-byte 8) index index) (simple-array * (*)) (flushable movable)) (defknown make-array-header ((unsigned-byte 8) (unsigned-byte 24)) array (flushable movable)) (defknown make-weak-pointer (t) weak-pointer (flushable)) (defknown %make-complex (real real) complex (flushable movable)) (defknown %make-ratio (rational rational) ratio (flushable movable)) (defknown make-value-cell (t) t (flushable movable)) ;;;; threading (defknown (dynamic-space-free-pointer binding-stack-pointer-sap control-stack-pointer-sap) () system-area-pointer (flushable)) ;;;; debugger support (defknown current-sp () system-area-pointer (movable flushable)) (defknown current-fp () system-area-pointer (movable flushable)) (defknown stack-ref (system-area-pointer index) t (flushable)) (defknown %set-stack-ref (system-area-pointer index t) t ()) (defknown lra-code-header (t) t (movable flushable)) (defknown fun-code-header (t) t (movable flushable)) (defknown %make-lisp-obj (sb!vm:word) t (movable flushable)) (defknown get-lisp-obj-address (t) sb!vm:word (movable flushable)) (defknown fun-word-offset (function) index (movable flushable)) 32 - bit logical operations (defknown word-logical-not (sb!vm:word) sb!vm:word (foldable flushable movable)) (defknown (word-logical-and word-logical-nand word-logical-or word-logical-nor word-logical-xor word-logical-eqv word-logical-andc1 word-logical-andc2 word-logical-orc1 word-logical-orc2) (sb!vm:word sb!vm:word) sb!vm:word (foldable flushable movable)) (defknown (shift-towards-start shift-towards-end) (sb!vm:word fixnum) sb!vm:word (foldable flushable movable)) ;;;; bignum operations (defknown %allocate-bignum (bignum-index) bignum-type (flushable)) (defknown %bignum-length (bignum-type) bignum-index (foldable flushable movable)) (defknown %bignum-set-length (bignum-type bignum-index) bignum-type ()) (defknown %bignum-ref (bignum-type bignum-index) bignum-element-type (flushable)) #!+(or x86 x86-64) (defknown %bignum-ref-with-offset (bignum-type bignum-index (signed-byte 24)) bignum-element-type (flushable always-translatable)) (defknown %bignum-set (bignum-type bignum-index bignum-element-type) bignum-element-type ()) #!+(or x86 x86-64) (defknown %bignum-set-with-offset (bignum-type bignum-index (signed-byte 24) bignum-element-type) bignum-element-type (always-translatable)) (defknown %digit-0-or-plusp (bignum-element-type) boolean (foldable flushable movable)) (defknown (%add-with-carry %subtract-with-borrow) (bignum-element-type bignum-element-type (mod 2)) (values bignum-element-type (mod 2)) (foldable flushable movable)) (defknown %multiply-and-add (bignum-element-type bignum-element-type bignum-element-type &optional bignum-element-type) (values bignum-element-type bignum-element-type) (foldable flushable movable)) (defknown %multiply (bignum-element-type bignum-element-type) (values bignum-element-type bignum-element-type) (foldable flushable movable)) (defknown %lognot (bignum-element-type) bignum-element-type (foldable flushable movable)) (defknown (%logand %logior %logxor) (bignum-element-type bignum-element-type) bignum-element-type (foldable flushable movable)) (defknown %fixnum-to-digit (fixnum) bignum-element-type (foldable flushable movable)) (defknown %bigfloor (bignum-element-type bignum-element-type bignum-element-type) (values bignum-element-type bignum-element-type) (foldable flushable movable)) (defknown %fixnum-digit-with-correct-sign (bignum-element-type) (signed-byte #.sb!vm:n-word-bits) (foldable flushable movable)) (defknown (%ashl %ashr %digit-logical-shift-right) (bignum-element-type (mod #.sb!vm:n-word-bits)) bignum-element-type (foldable flushable movable)) ;;;; bit-bashing routines ;;; FIXME: there's some ugly duplication between the (INTERN (FORMAT ...)) ;;; magic here and the same magic in src/code/bit-bash.lisp. I don't know ;;; of any good way to clean it up, but it's definitely violating OAOO. (macrolet ((define-known-copiers () `(progn ,@(loop for i = 1 then (* i 2) collect `(defknown ,(intern (format nil "UB~D-BASH-COPY" i) (find-package "SB!KERNEL")) ((simple-unboxed-array (*)) index (simple-unboxed-array (*)) index index) (values) ()) collect `(defknown ,(intern (format nil "SYSTEM-AREA-UB~D-COPY" i) (find-package "SB!KERNEL")) (system-area-pointer index system-area-pointer index index) (values) ()) collect `(defknown ,(intern (format nil "COPY-UB~D-TO-SYSTEM-AREA" i) (find-package "SB!KERNEL")) ((simple-unboxed-array (*)) index system-area-pointer index index) (values) ()) collect `(defknown ,(intern (format nil "COPY-UB~D-FROM-SYSTEM-AREA" i) (find-package "SB!KERNEL")) (system-area-pointer index (simple-unboxed-array (*)) index index) (values) ()) until (= i sb!vm:n-word-bits))))) (define-known-copiers)) ;;; (not really a bit-bashing routine, but starting to take over from ;;; bit-bashing routines in byte-sized copies as of sbcl-0.6.12.29:) (defknown %byte-blt ((or (simple-unboxed-array (*)) system-area-pointer) index (or (simple-unboxed-array (*)) system-area-pointer) index index) (values) ()) ;;;; code/function/fdefn object manipulation routines (defknown code-instructions (t) system-area-pointer (flushable movable)) (defknown code-header-ref (t index) t (flushable)) (defknown code-header-set (t index t) t ()) (defknown fun-subtype (function) (unsigned-byte #.sb!vm:n-widetag-bits) (flushable)) (defknown ((setf fun-subtype)) ((unsigned-byte #.sb!vm:n-widetag-bits) function) (unsigned-byte #.sb!vm:n-widetag-bits) ()) (defknown make-fdefn (t) fdefn (flushable movable)) (defknown fdefn-p (t) boolean (movable foldable flushable)) (defknown fdefn-name (fdefn) t (foldable flushable)) (defknown fdefn-fun (fdefn) (or function null) (flushable)) (defknown (setf fdefn-fun) (function fdefn) t ()) (defknown fdefn-makunbound (fdefn) t ()) (defknown %simple-fun-self (function) function (flushable)) (defknown (setf %simple-fun-self) (function function) function ()) (defknown %closure-fun (function) function (flushable)) (defknown %closure-index-ref (function index) t (flushable)) (defknown %make-funcallable-instance (index) function ()) (defknown %funcallable-instance-info (function index) t (flushable)) (defknown %set-funcallable-instance-info (function index t) t ()) ;;;; mutator accessors (defknown mutator-self () system-area-pointer (flushable movable)) (defknown %data-vector-and-index (array index) (values (simple-array * (*)) index) (foldable flushable))
null
https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/src/compiler/generic/vm-fndb.lisp
lisp
signatures of machine-specific functions more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. internal type predicates translated into non-standard unary predicates. miscellaneous "sub-primitives" threading debugger support bignum operations bit-bashing routines FIXME: there's some ugly duplication between the (INTERN (FORMAT ...)) magic here and the same magic in src/code/bit-bash.lisp. I don't know of any good way to clean it up, but it's definitely violating OAOO. (not really a bit-bashing routine, but starting to take over from bit-bashing routines in byte-sized copies as of sbcl-0.6.12.29:) code/function/fdefn object manipulation routines mutator accessors
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!C") Simple TYPEP uses that do n't have any standard predicate are (defknown (fixnump bignump ratiop short-float-p single-float-p double-float-p long-float-p complex-rational-p complex-float-p complex-single-float-p complex-double-float-p #!+long-float complex-long-float-p complex-vector-p base-char-p %standard-char-p %instancep %other-pointer-p base-string-p simple-base-string-p #!+sb-unicode character-string-p #!+sb-unicode simple-character-string-p array-header-p sequencep extended-sequence-p simple-array-p simple-array-nil-p vector-nil-p simple-array-unsigned-byte-2-p simple-array-unsigned-byte-4-p simple-array-unsigned-byte-7-p simple-array-unsigned-byte-8-p simple-array-unsigned-byte-15-p simple-array-unsigned-byte-16-p simple-array-unsigned-fixnum-p simple-array-unsigned-byte-31-p simple-array-unsigned-byte-32-p #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or)) simple-array-unsigned-byte-63-p #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or)) simple-array-unsigned-byte-64-p simple-array-signed-byte-8-p simple-array-signed-byte-16-p simple-array-fixnum-p simple-array-signed-byte-32-p #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or)) simple-array-signed-byte-64-p simple-array-single-float-p simple-array-double-float-p #!+long-float simple-array-long-float-p simple-array-complex-single-float-p simple-array-complex-double-float-p #!+long-float simple-array-complex-long-float-p system-area-pointer-p realp # ! + # .(cl : if ( cl:= 32 sb!vm : n - word - bits ) ' ( and ) ' ( or ) ) unsigned-byte-32-p # ! + # .(cl : if ( cl:= 32 sb!vm : n - word - bits ) ' ( and ) ' ( or ) ) signed-byte-32-p #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or)) unsigned-byte-64-p #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or)) signed-byte-64-p weak-pointer-p code-component-p lra-p funcallable-instance-p) (t) boolean (movable foldable flushable)) (defknown #.(loop for (name) in *vector-without-complex-typecode-infos* collect name) (t) boolean (movable foldable flushable)) (defknown pointer-hash (t) hash (flushable)) (defknown %sp-string-compare (simple-string index index simple-string index index) (or index null) (foldable flushable)) (defknown %sxhash-simple-string (simple-string) hash (foldable flushable)) (defknown %sxhash-simple-substring (simple-string index) hash (foldable flushable)) (defknown symbol-hash (symbol) hash (flushable movable)) (defknown %set-symbol-hash (symbol hash) t ()) (defknown initialize-vector ((simple-array * (*)) &rest t) (simple-array * (*)) (always-translatable flushable) :result-arg 0) (defknown vector-fill* (t t t t) vector () :result-arg 0) (defknown vector-length (vector) index (flushable dx-safe)) (defknown vector-sap ((simple-unboxed-array (*))) system-area-pointer (flushable)) (defknown lowtag-of (t) (unsigned-byte #.sb!vm:n-lowtag-bits) (flushable movable)) (defknown widetag-of (t) (unsigned-byte #.sb!vm:n-widetag-bits) (flushable movable)) (defknown (get-header-data get-closure-length) (t) (unsigned-byte 24) (flushable)) (defknown set-header-data (t (unsigned-byte 24)) t ()) (defknown %array-dimension (t index) index (flushable)) (defknown %set-array-dimension (t index index) index ()) (defknown %array-rank (t) index (flushable)) (defknown %make-instance (index) instance (flushable)) (defknown %make-structure-instance (defstruct-description list &rest t) instance (flushable always-translatable)) (defknown %instance-layout (instance) layout (foldable flushable)) (defknown %set-instance-layout (instance layout) layout ()) (defknown %instance-length (instance) index (foldable flushable)) (defknown %instance-ref (instance index) t (flushable always-translatable)) (defknown %instance-set (instance index t) t (always-translatable)) (defknown %layout-invalid-error (t layout) nil) (defknown %raw-instance-ref/word (instance index) sb!vm:word (flushable always-translatable)) (defknown %raw-instance-set/word (instance index sb!vm:word) sb!vm:word (always-translatable)) (defknown %raw-instance-ref/single (instance index) single-float (flushable always-translatable)) (defknown %raw-instance-set/single (instance index single-float) single-float (always-translatable)) (defknown %raw-instance-ref/double (instance index) double-float (flushable always-translatable)) (defknown %raw-instance-set/double (instance index double-float) double-float (always-translatable)) (defknown %raw-instance-ref/complex-single (instance index) (complex single-float) (flushable always-translatable)) (defknown %raw-instance-set/complex-single (instance index (complex single-float)) (complex single-float) (always-translatable)) (defknown %raw-instance-ref/complex-double (instance index) (complex double-float) (flushable always-translatable)) (defknown %raw-instance-set/complex-double (instance index (complex double-float)) (complex double-float) (always-translatable)) #!+(or x86 x86-64 ppc) (defknown %raw-instance-atomic-incf/word (instance index sb!vm:word) sb!vm:word (always-translatable)) #!+(or x86 x86-64 ppc) (defknown %array-atomic-incf/word (t index sb!vm:word) sb!vm:word (always-translatable)) These two are mostly used for bit - bashing operations . (defknown %vector-raw-bits (t fixnum) sb!vm:word (flushable)) (defknown (%set-vector-raw-bits) (t fixnum sb!vm:word) sb!vm:word ()) (defknown allocate-vector ((unsigned-byte 8) index index) (simple-array * (*)) (flushable movable)) (defknown make-array-header ((unsigned-byte 8) (unsigned-byte 24)) array (flushable movable)) (defknown make-weak-pointer (t) weak-pointer (flushable)) (defknown %make-complex (real real) complex (flushable movable)) (defknown %make-ratio (rational rational) ratio (flushable movable)) (defknown make-value-cell (t) t (flushable movable)) (defknown (dynamic-space-free-pointer binding-stack-pointer-sap control-stack-pointer-sap) () system-area-pointer (flushable)) (defknown current-sp () system-area-pointer (movable flushable)) (defknown current-fp () system-area-pointer (movable flushable)) (defknown stack-ref (system-area-pointer index) t (flushable)) (defknown %set-stack-ref (system-area-pointer index t) t ()) (defknown lra-code-header (t) t (movable flushable)) (defknown fun-code-header (t) t (movable flushable)) (defknown %make-lisp-obj (sb!vm:word) t (movable flushable)) (defknown get-lisp-obj-address (t) sb!vm:word (movable flushable)) (defknown fun-word-offset (function) index (movable flushable)) 32 - bit logical operations (defknown word-logical-not (sb!vm:word) sb!vm:word (foldable flushable movable)) (defknown (word-logical-and word-logical-nand word-logical-or word-logical-nor word-logical-xor word-logical-eqv word-logical-andc1 word-logical-andc2 word-logical-orc1 word-logical-orc2) (sb!vm:word sb!vm:word) sb!vm:word (foldable flushable movable)) (defknown (shift-towards-start shift-towards-end) (sb!vm:word fixnum) sb!vm:word (foldable flushable movable)) (defknown %allocate-bignum (bignum-index) bignum-type (flushable)) (defknown %bignum-length (bignum-type) bignum-index (foldable flushable movable)) (defknown %bignum-set-length (bignum-type bignum-index) bignum-type ()) (defknown %bignum-ref (bignum-type bignum-index) bignum-element-type (flushable)) #!+(or x86 x86-64) (defknown %bignum-ref-with-offset (bignum-type bignum-index (signed-byte 24)) bignum-element-type (flushable always-translatable)) (defknown %bignum-set (bignum-type bignum-index bignum-element-type) bignum-element-type ()) #!+(or x86 x86-64) (defknown %bignum-set-with-offset (bignum-type bignum-index (signed-byte 24) bignum-element-type) bignum-element-type (always-translatable)) (defknown %digit-0-or-plusp (bignum-element-type) boolean (foldable flushable movable)) (defknown (%add-with-carry %subtract-with-borrow) (bignum-element-type bignum-element-type (mod 2)) (values bignum-element-type (mod 2)) (foldable flushable movable)) (defknown %multiply-and-add (bignum-element-type bignum-element-type bignum-element-type &optional bignum-element-type) (values bignum-element-type bignum-element-type) (foldable flushable movable)) (defknown %multiply (bignum-element-type bignum-element-type) (values bignum-element-type bignum-element-type) (foldable flushable movable)) (defknown %lognot (bignum-element-type) bignum-element-type (foldable flushable movable)) (defknown (%logand %logior %logxor) (bignum-element-type bignum-element-type) bignum-element-type (foldable flushable movable)) (defknown %fixnum-to-digit (fixnum) bignum-element-type (foldable flushable movable)) (defknown %bigfloor (bignum-element-type bignum-element-type bignum-element-type) (values bignum-element-type bignum-element-type) (foldable flushable movable)) (defknown %fixnum-digit-with-correct-sign (bignum-element-type) (signed-byte #.sb!vm:n-word-bits) (foldable flushable movable)) (defknown (%ashl %ashr %digit-logical-shift-right) (bignum-element-type (mod #.sb!vm:n-word-bits)) bignum-element-type (foldable flushable movable)) (macrolet ((define-known-copiers () `(progn ,@(loop for i = 1 then (* i 2) collect `(defknown ,(intern (format nil "UB~D-BASH-COPY" i) (find-package "SB!KERNEL")) ((simple-unboxed-array (*)) index (simple-unboxed-array (*)) index index) (values) ()) collect `(defknown ,(intern (format nil "SYSTEM-AREA-UB~D-COPY" i) (find-package "SB!KERNEL")) (system-area-pointer index system-area-pointer index index) (values) ()) collect `(defknown ,(intern (format nil "COPY-UB~D-TO-SYSTEM-AREA" i) (find-package "SB!KERNEL")) ((simple-unboxed-array (*)) index system-area-pointer index index) (values) ()) collect `(defknown ,(intern (format nil "COPY-UB~D-FROM-SYSTEM-AREA" i) (find-package "SB!KERNEL")) (system-area-pointer index (simple-unboxed-array (*)) index index) (values) ()) until (= i sb!vm:n-word-bits))))) (define-known-copiers)) (defknown %byte-blt ((or (simple-unboxed-array (*)) system-area-pointer) index (or (simple-unboxed-array (*)) system-area-pointer) index index) (values) ()) (defknown code-instructions (t) system-area-pointer (flushable movable)) (defknown code-header-ref (t index) t (flushable)) (defknown code-header-set (t index t) t ()) (defknown fun-subtype (function) (unsigned-byte #.sb!vm:n-widetag-bits) (flushable)) (defknown ((setf fun-subtype)) ((unsigned-byte #.sb!vm:n-widetag-bits) function) (unsigned-byte #.sb!vm:n-widetag-bits) ()) (defknown make-fdefn (t) fdefn (flushable movable)) (defknown fdefn-p (t) boolean (movable foldable flushable)) (defknown fdefn-name (fdefn) t (foldable flushable)) (defknown fdefn-fun (fdefn) (or function null) (flushable)) (defknown (setf fdefn-fun) (function fdefn) t ()) (defknown fdefn-makunbound (fdefn) t ()) (defknown %simple-fun-self (function) function (flushable)) (defknown (setf %simple-fun-self) (function function) function ()) (defknown %closure-fun (function) function (flushable)) (defknown %closure-index-ref (function index) t (flushable)) (defknown %make-funcallable-instance (index) function ()) (defknown %funcallable-instance-info (function index) t (flushable)) (defknown %set-funcallable-instance-info (function index t) t ()) (defknown mutator-self () system-area-pointer (flushable movable)) (defknown %data-vector-and-index (array index) (values (simple-array * (*)) index) (foldable flushable))
925ac3802871dead91ef207b74f18b0ebf2c00e29afbd5be771f68a7665e83b9
rbkmoney/fistful-server
ff_deposit_SUITE.erl
-module(ff_deposit_SUITE). -include_lib("stdlib/include/assert.hrl"). -include_lib("damsel/include/dmsl_payment_processing_thrift.hrl"). %% Common test API -export([all/0]). -export([groups/0]). -export([init_per_suite/1]). -export([end_per_suite/1]). -export([init_per_group/2]). -export([end_per_group/2]). -export([init_per_testcase/2]). -export([end_per_testcase/2]). %% Tests -export([limit_check_fail_test/1]). -export([create_bad_amount_test/1]). -export([create_currency_validation_error_test/1]). -export([create_source_notfound_test/1]). -export([create_wallet_notfound_test/1]). -export([preserve_revisions_test/1]). -export([create_ok_test/1]). -export([unknown_test/1]). %% Internal types -type config() :: ct_helper:config(). -type test_case_name() :: ct_helper:test_case_name(). -type group_name() :: ct_helper:group_name(). -type test_return() :: _ | no_return(). Macro helpers -define(final_balance(Amount, Currency), {Amount, {{inclusive, Amount}, {inclusive, Amount}}, Currency}). %% API -spec all() -> [test_case_name() | {group, group_name()}]. all() -> [{group, default}]. -spec groups() -> [{group_name(), list(), [test_case_name()]}]. groups() -> [ {default, [parallel], [ limit_check_fail_test, create_bad_amount_test, create_currency_validation_error_test, create_source_notfound_test, create_wallet_notfound_test, preserve_revisions_test, create_ok_test, unknown_test ]} ]. -spec init_per_suite(config()) -> config(). init_per_suite(C) -> ct_helper:makeup_cfg( [ ct_helper:test_case_name(init), ct_payment_system:setup() ], C ). -spec end_per_suite(config()) -> _. end_per_suite(C) -> ok = ct_payment_system:shutdown(C). %% -spec init_per_group(group_name(), config()) -> config(). init_per_group(_, C) -> C. -spec end_per_group(group_name(), config()) -> _. end_per_group(_, _) -> ok. %% -spec init_per_testcase(test_case_name(), config()) -> config(). init_per_testcase(Name, C) -> C1 = ct_helper:makeup_cfg([ct_helper:test_case_name(Name), ct_helper:woody_ctx()], C), ok = ct_helper:set_context(C1), C1. -spec end_per_testcase(test_case_name(), config()) -> _. end_per_testcase(_Name, _C) -> ok = ct_helper:unset_context(). %% Tests -spec limit_check_fail_test(config()) -> test_return(). limit_check_fail_test(C) -> #{ wallet_id := WalletID, source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositParams = #{ id => DepositID, body => {20000000, <<"RUB">>}, source_id => SourceID, wallet_id => WalletID, external_id => generate_id() }, ok = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), Result = await_final_deposit_status(DepositID), ?assertMatch( {failed, #{ code := <<"account_limit_exceeded">>, sub := #{ code := <<"amount">> } }}, Result ), ok = await_wallet_balance({0, <<"RUB">>}, WalletID). -spec create_bad_amount_test(config()) -> test_return(). create_bad_amount_test(C) -> #{ wallet_id := WalletID, source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositParams = #{ id => DepositID, body => {0, <<"RUB">>}, source_id => SourceID, wallet_id => WalletID, external_id => generate_id() }, Result = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), ?assertMatch({error, {bad_deposit_amount, {0, <<"RUB">>}}}, Result). -spec create_currency_validation_error_test(config()) -> test_return(). create_currency_validation_error_test(C) -> #{ wallet_id := WalletID, source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositParams = #{ id => DepositID, body => {5000, <<"EUR">>}, source_id => SourceID, wallet_id => WalletID, external_id => generate_id() }, Result = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), Details = { #domain_CurrencyRef{symbolic_code = <<"EUR">>}, [ #domain_CurrencyRef{symbolic_code = <<"RUB">>}, #domain_CurrencyRef{symbolic_code = <<"USD">>} ] }, ?assertMatch({error, {terms_violation, {not_allowed_currency, Details}}}, Result). -spec create_source_notfound_test(config()) -> test_return(). create_source_notfound_test(C) -> #{ wallet_id := WalletID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositParams = #{ id => DepositID, body => {5000, <<"RUB">>}, source_id => <<"unknown_source">>, wallet_id => WalletID, external_id => generate_id() }, Result = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), ?assertMatch({error, {source, notfound}}, Result). -spec create_wallet_notfound_test(config()) -> test_return(). create_wallet_notfound_test(C) -> #{ source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositParams = #{ id => DepositID, body => {5000, <<"RUB">>}, source_id => SourceID, wallet_id => <<"unknown_wallet">>, external_id => generate_id() }, Result = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), ?assertMatch({error, {wallet, notfound}}, Result). -spec preserve_revisions_test(config()) -> test_return(). preserve_revisions_test(C) -> #{ wallet_id := WalletID, source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositCash = {5000, <<"RUB">>}, DepositParams = #{ id => DepositID, body => DepositCash, source_id => SourceID, wallet_id => WalletID, external_id => DepositID }, ok = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), Deposit = get_deposit(DepositID), ?assertNotEqual(undefined, ff_deposit:domain_revision(Deposit)), ?assertNotEqual(undefined, ff_deposit:party_revision(Deposit)), ?assertNotEqual(undefined, ff_deposit:created_at(Deposit)). -spec create_ok_test(config()) -> test_return(). create_ok_test(C) -> #{ wallet_id := WalletID, source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositCash = {5000, <<"RUB">>}, DepositParams = #{ id => DepositID, body => DepositCash, source_id => SourceID, wallet_id => WalletID, external_id => DepositID }, ok = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), succeeded = await_final_deposit_status(DepositID), ok = await_wallet_balance(DepositCash, WalletID), Deposit = get_deposit(DepositID), DepositCash = ff_deposit:body(Deposit), WalletID = ff_deposit:wallet_id(Deposit), SourceID = ff_deposit:source_id(Deposit), DepositID = ff_deposit:external_id(Deposit). -spec unknown_test(config()) -> test_return(). unknown_test(_C) -> DepositID = <<"unknown_deposit">>, Result = ff_deposit_machine:get(DepositID), ?assertMatch({error, {unknown_deposit, DepositID}}, Result). Utils prepare_standard_environment(Currency, C) -> Party = create_party(C), IdentityID = create_identity(Party, C), WalletID = create_wallet(IdentityID, <<"My wallet">>, <<"RUB">>, C), ok = await_wallet_balance({0, Currency}, WalletID), SourceID = create_source(IdentityID, C), #{ identity_id => IdentityID, party_id => Party, wallet_id => WalletID, source_id => SourceID }. get_deposit(DepositID) -> {ok, Machine} = ff_deposit_machine:get(DepositID), ff_deposit_machine:deposit(Machine). get_deposit_status(DepositID) -> ff_deposit:status(get_deposit(DepositID)). await_final_deposit_status(DepositID) -> finished = ct_helper:await( finished, fun() -> {ok, Machine} = ff_deposit_machine:get(DepositID), Deposit = ff_deposit_machine:deposit(Machine), case ff_deposit:is_finished(Deposit) of false -> {not_finished, Deposit}; true -> finished end end, genlib_retry:linear(90, 1000) ), get_deposit_status(DepositID). create_party(_C) -> ID = genlib:bsuuid(), _ = ff_party:create(ID), ID. create_identity(Party, C) -> create_identity(Party, <<"good-one">>, C). create_identity(Party, ProviderID, C) -> create_identity(Party, <<"Identity Name">>, ProviderID, C). create_identity(Party, Name, ProviderID, _C) -> ID = genlib:unique(), ok = ff_identity_machine:create( #{id => ID, name => Name, party => Party, provider => ProviderID}, #{<<"com.rbkmoney.wapi">> => #{<<"name">> => Name}} ), ID. create_wallet(IdentityID, Name, Currency, _C) -> ID = genlib:unique(), ok = ff_wallet_machine:create( #{id => ID, identity => IdentityID, name => Name, currency => Currency}, ff_entity_context:new() ), ID. await_wallet_balance({Amount, Currency}, ID) -> Balance = {Amount, {{inclusive, Amount}, {inclusive, Amount}}, Currency}, Balance = ct_helper:await( Balance, fun() -> get_wallet_balance(ID) end, genlib_retry:linear(3, 500) ), ok. get_wallet_balance(ID) -> {ok, Machine} = ff_wallet_machine:get(ID), get_account_balance(ff_wallet:account(ff_wallet_machine:wallet(Machine))). %% NOTE: This function can flap tests after switch to shumpune %% because of potentially wrong Clock. In common case it should be passed %% from caller after applying changes to account balance. This will work fine with shumway because it return LatestClock on any %% balance changes, therefore it will broke tests with shumpune %% because of proper clocks. get_account_balance(Account) -> {ok, {Amounts, Currency}} = ff_transaction:balance( Account, ff_clock:latest_clock() ), {ff_indef:current(Amounts), ff_indef:to_range(Amounts), Currency}. generate_id() -> ff_id:generate_snowflake_id(). create_source(IID, _C) -> ID = generate_id(), SrcResource = #{type => internal, details => <<"Infinite source of cash">>}, Params = #{id => ID, identity => IID, name => <<"XSource">>, currency => <<"RUB">>, resource => SrcResource}, ok = ff_source_machine:create(Params, ff_entity_context:new()), authorized = ct_helper:await( authorized, fun() -> {ok, SrcM} = ff_source_machine:get(ID), Source = ff_source_machine:source(SrcM), ff_source:status(Source) end ), ID.
null
https://raw.githubusercontent.com/rbkmoney/fistful-server/f6155acb0475987e47a4fbc911758c595e129c80/apps/ff_transfer/test/ff_deposit_SUITE.erl
erlang
Common test API Tests Internal types API Tests NOTE: This function can flap tests after switch to shumpune because of potentially wrong Clock. In common case it should be passed from caller after applying changes to account balance. balance changes, therefore it will broke tests with shumpune because of proper clocks.
-module(ff_deposit_SUITE). -include_lib("stdlib/include/assert.hrl"). -include_lib("damsel/include/dmsl_payment_processing_thrift.hrl"). -export([all/0]). -export([groups/0]). -export([init_per_suite/1]). -export([end_per_suite/1]). -export([init_per_group/2]). -export([end_per_group/2]). -export([init_per_testcase/2]). -export([end_per_testcase/2]). -export([limit_check_fail_test/1]). -export([create_bad_amount_test/1]). -export([create_currency_validation_error_test/1]). -export([create_source_notfound_test/1]). -export([create_wallet_notfound_test/1]). -export([preserve_revisions_test/1]). -export([create_ok_test/1]). -export([unknown_test/1]). -type config() :: ct_helper:config(). -type test_case_name() :: ct_helper:test_case_name(). -type group_name() :: ct_helper:group_name(). -type test_return() :: _ | no_return(). Macro helpers -define(final_balance(Amount, Currency), {Amount, {{inclusive, Amount}, {inclusive, Amount}}, Currency}). -spec all() -> [test_case_name() | {group, group_name()}]. all() -> [{group, default}]. -spec groups() -> [{group_name(), list(), [test_case_name()]}]. groups() -> [ {default, [parallel], [ limit_check_fail_test, create_bad_amount_test, create_currency_validation_error_test, create_source_notfound_test, create_wallet_notfound_test, preserve_revisions_test, create_ok_test, unknown_test ]} ]. -spec init_per_suite(config()) -> config(). init_per_suite(C) -> ct_helper:makeup_cfg( [ ct_helper:test_case_name(init), ct_payment_system:setup() ], C ). -spec end_per_suite(config()) -> _. end_per_suite(C) -> ok = ct_payment_system:shutdown(C). -spec init_per_group(group_name(), config()) -> config(). init_per_group(_, C) -> C. -spec end_per_group(group_name(), config()) -> _. end_per_group(_, _) -> ok. -spec init_per_testcase(test_case_name(), config()) -> config(). init_per_testcase(Name, C) -> C1 = ct_helper:makeup_cfg([ct_helper:test_case_name(Name), ct_helper:woody_ctx()], C), ok = ct_helper:set_context(C1), C1. -spec end_per_testcase(test_case_name(), config()) -> _. end_per_testcase(_Name, _C) -> ok = ct_helper:unset_context(). -spec limit_check_fail_test(config()) -> test_return(). limit_check_fail_test(C) -> #{ wallet_id := WalletID, source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositParams = #{ id => DepositID, body => {20000000, <<"RUB">>}, source_id => SourceID, wallet_id => WalletID, external_id => generate_id() }, ok = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), Result = await_final_deposit_status(DepositID), ?assertMatch( {failed, #{ code := <<"account_limit_exceeded">>, sub := #{ code := <<"amount">> } }}, Result ), ok = await_wallet_balance({0, <<"RUB">>}, WalletID). -spec create_bad_amount_test(config()) -> test_return(). create_bad_amount_test(C) -> #{ wallet_id := WalletID, source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositParams = #{ id => DepositID, body => {0, <<"RUB">>}, source_id => SourceID, wallet_id => WalletID, external_id => generate_id() }, Result = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), ?assertMatch({error, {bad_deposit_amount, {0, <<"RUB">>}}}, Result). -spec create_currency_validation_error_test(config()) -> test_return(). create_currency_validation_error_test(C) -> #{ wallet_id := WalletID, source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositParams = #{ id => DepositID, body => {5000, <<"EUR">>}, source_id => SourceID, wallet_id => WalletID, external_id => generate_id() }, Result = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), Details = { #domain_CurrencyRef{symbolic_code = <<"EUR">>}, [ #domain_CurrencyRef{symbolic_code = <<"RUB">>}, #domain_CurrencyRef{symbolic_code = <<"USD">>} ] }, ?assertMatch({error, {terms_violation, {not_allowed_currency, Details}}}, Result). -spec create_source_notfound_test(config()) -> test_return(). create_source_notfound_test(C) -> #{ wallet_id := WalletID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositParams = #{ id => DepositID, body => {5000, <<"RUB">>}, source_id => <<"unknown_source">>, wallet_id => WalletID, external_id => generate_id() }, Result = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), ?assertMatch({error, {source, notfound}}, Result). -spec create_wallet_notfound_test(config()) -> test_return(). create_wallet_notfound_test(C) -> #{ source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositParams = #{ id => DepositID, body => {5000, <<"RUB">>}, source_id => SourceID, wallet_id => <<"unknown_wallet">>, external_id => generate_id() }, Result = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), ?assertMatch({error, {wallet, notfound}}, Result). -spec preserve_revisions_test(config()) -> test_return(). preserve_revisions_test(C) -> #{ wallet_id := WalletID, source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositCash = {5000, <<"RUB">>}, DepositParams = #{ id => DepositID, body => DepositCash, source_id => SourceID, wallet_id => WalletID, external_id => DepositID }, ok = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), Deposit = get_deposit(DepositID), ?assertNotEqual(undefined, ff_deposit:domain_revision(Deposit)), ?assertNotEqual(undefined, ff_deposit:party_revision(Deposit)), ?assertNotEqual(undefined, ff_deposit:created_at(Deposit)). -spec create_ok_test(config()) -> test_return(). create_ok_test(C) -> #{ wallet_id := WalletID, source_id := SourceID } = prepare_standard_environment(<<"RUB">>, C), DepositID = generate_id(), DepositCash = {5000, <<"RUB">>}, DepositParams = #{ id => DepositID, body => DepositCash, source_id => SourceID, wallet_id => WalletID, external_id => DepositID }, ok = ff_deposit_machine:create(DepositParams, ff_entity_context:new()), succeeded = await_final_deposit_status(DepositID), ok = await_wallet_balance(DepositCash, WalletID), Deposit = get_deposit(DepositID), DepositCash = ff_deposit:body(Deposit), WalletID = ff_deposit:wallet_id(Deposit), SourceID = ff_deposit:source_id(Deposit), DepositID = ff_deposit:external_id(Deposit). -spec unknown_test(config()) -> test_return(). unknown_test(_C) -> DepositID = <<"unknown_deposit">>, Result = ff_deposit_machine:get(DepositID), ?assertMatch({error, {unknown_deposit, DepositID}}, Result). Utils prepare_standard_environment(Currency, C) -> Party = create_party(C), IdentityID = create_identity(Party, C), WalletID = create_wallet(IdentityID, <<"My wallet">>, <<"RUB">>, C), ok = await_wallet_balance({0, Currency}, WalletID), SourceID = create_source(IdentityID, C), #{ identity_id => IdentityID, party_id => Party, wallet_id => WalletID, source_id => SourceID }. get_deposit(DepositID) -> {ok, Machine} = ff_deposit_machine:get(DepositID), ff_deposit_machine:deposit(Machine). get_deposit_status(DepositID) -> ff_deposit:status(get_deposit(DepositID)). await_final_deposit_status(DepositID) -> finished = ct_helper:await( finished, fun() -> {ok, Machine} = ff_deposit_machine:get(DepositID), Deposit = ff_deposit_machine:deposit(Machine), case ff_deposit:is_finished(Deposit) of false -> {not_finished, Deposit}; true -> finished end end, genlib_retry:linear(90, 1000) ), get_deposit_status(DepositID). create_party(_C) -> ID = genlib:bsuuid(), _ = ff_party:create(ID), ID. create_identity(Party, C) -> create_identity(Party, <<"good-one">>, C). create_identity(Party, ProviderID, C) -> create_identity(Party, <<"Identity Name">>, ProviderID, C). create_identity(Party, Name, ProviderID, _C) -> ID = genlib:unique(), ok = ff_identity_machine:create( #{id => ID, name => Name, party => Party, provider => ProviderID}, #{<<"com.rbkmoney.wapi">> => #{<<"name">> => Name}} ), ID. create_wallet(IdentityID, Name, Currency, _C) -> ID = genlib:unique(), ok = ff_wallet_machine:create( #{id => ID, identity => IdentityID, name => Name, currency => Currency}, ff_entity_context:new() ), ID. await_wallet_balance({Amount, Currency}, ID) -> Balance = {Amount, {{inclusive, Amount}, {inclusive, Amount}}, Currency}, Balance = ct_helper:await( Balance, fun() -> get_wallet_balance(ID) end, genlib_retry:linear(3, 500) ), ok. get_wallet_balance(ID) -> {ok, Machine} = ff_wallet_machine:get(ID), get_account_balance(ff_wallet:account(ff_wallet_machine:wallet(Machine))). This will work fine with shumway because it return LatestClock on any get_account_balance(Account) -> {ok, {Amounts, Currency}} = ff_transaction:balance( Account, ff_clock:latest_clock() ), {ff_indef:current(Amounts), ff_indef:to_range(Amounts), Currency}. generate_id() -> ff_id:generate_snowflake_id(). create_source(IID, _C) -> ID = generate_id(), SrcResource = #{type => internal, details => <<"Infinite source of cash">>}, Params = #{id => ID, identity => IID, name => <<"XSource">>, currency => <<"RUB">>, resource => SrcResource}, ok = ff_source_machine:create(Params, ff_entity_context:new()), authorized = ct_helper:await( authorized, fun() -> {ok, SrcM} = ff_source_machine:get(ID), Source = ff_source_machine:source(SrcM), ff_source:status(Source) end ), ID.
682f56a3ffe50e2010fe79fc5daf207e15c48f880bc87c621349129adb4b93ae
ahrefs/devkit
reader.mli
(** Simple string reader *) type t exception EOS exception Not_equal of string val init : string -> t val eos : t -> bool (** post-condition: [eos] is true *) val rest : t -> string val till : t -> string -> string val try_till : t -> string -> string val tillc : t -> char -> string val try_tillc : t -> char -> string val take : t -> int -> string val try_take : t -> int -> string val is_const : t -> string -> bool val const : t -> string -> unit val try_const : t -> string -> unit val while_ : t -> (char -> bool) -> string val skipc : t -> char -> unit
null
https://raw.githubusercontent.com/ahrefs/devkit/559c2df8f6eacb091e0eac38f508c45b6567bdd8/reader.mli
ocaml
* Simple string reader * post-condition: [eos] is true
type t exception EOS exception Not_equal of string val init : string -> t val eos : t -> bool val rest : t -> string val till : t -> string -> string val try_till : t -> string -> string val tillc : t -> char -> string val try_tillc : t -> char -> string val take : t -> int -> string val try_take : t -> int -> string val is_const : t -> string -> bool val const : t -> string -> unit val try_const : t -> string -> unit val while_ : t -> (char -> bool) -> string val skipc : t -> char -> unit
bf6e959596f196a356c2caaa40628bfc0387772590c9975837dc2dba58a935cc
tmfg/mmtis-national-access-point
gtfs.clj
(ns ote.integration.export.gtfs "GTFS export of routes" (:require [specql.core :refer [fetch]] [com.stuartsierra.component :as component] [ote.components.http :as http] [compojure.core :refer [GET]] [ote.db.transit :as transit] [specql.op :as op] [ring.util.io :as ring-io] [taoensso.timbre :as log] [ote.components.http :as http] [ote.db.transit :as transit] [ote.db.transport-operator :as t-operator] [ote.db.transport-service :as t-service] [ote.time :as time] [ote.gtfs.transform :as gtfs-transform] [ote.util.zip :refer [write-zip]] [ote.util.fn :refer [flip]] [ote.util.transport-operator-util :as op-util] [ote.localization :refer [*language*]] [ote.services.routes :refer [fetch-sea-trips]])) (declare export-sea-gtfs) (defrecord GTFSExport [] component/Lifecycle (start [{http :http db :db :as this}] (assoc this ::stop (http/publish! http {:authenticated? false} (GET "/export/gtfs/:transport-operator-id{[0-9]+}" [transport-operator-id] (export-sea-gtfs db (Long/parseLong transport-operator-id)))))) (stop [{stop ::stop :as this}] (stop) (dissoc this ::stop))) (defn fetch-sea-routes-published "Return the currently available published sea routes of the given transport operator." [db transport-operator-id] (let [routes (fetch db ::transit/route #{::transit/route-id ::transit/name ::transit/departure-point-name ::transit/destination-point-name ::transit/stops ::transit/route-type ::transit/service-calendars} {::transit/transport-operator-id transport-operator-id ::transit/published? true})] (mapv #(assoc % ::transit/trips (fetch-sea-trips db (::transit/route-id %))) routes))) (defn sea-routes-gtfs-zip [transport-operator routes output-stream] (try (write-zip (gtfs-transform/sea-routes-gtfs transport-operator routes) output-stream) (catch Exception e (log/warn "Exception while generating GTFS zip" e)))) (defn get-transport-operator [db transport-operator-id] (first (fetch db ::t-operator/transport-operator #{::t-operator/id ::t-operator/name ::t-operator/homepage ::t-operator/phone ::t-operator/email} {::t-operator/id transport-operator-id}))) (defn get-sea-routes [db transport-operator-id] (fetch-sea-routes-published db transport-operator-id) #_(map #(update % ::transit/name (flip t-service/localized-text-with-fallback) *language*) (fetch-sea-routes-published db transport-operator-id))) (defn export-sea-gtfs [db transport-operator-id] (let [transport-operator (get-transport-operator db transport-operator-id) routes (get-sea-routes db transport-operator-id)] {:status 200 :headers {"Content-Type" "application/zip" "Content-Disposition" (str "attachment; filename=" (op-util/gtfs-file-name transport-operator))} :body (ring-io/piped-input-stream (partial sea-routes-gtfs-zip transport-operator routes))}))
null
https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/1aba1c36aac7d6d55ee11accbf5a444e5f514f6c/ote/src/clj/ote/integration/export/gtfs.clj
clojure
(ns ote.integration.export.gtfs "GTFS export of routes" (:require [specql.core :refer [fetch]] [com.stuartsierra.component :as component] [ote.components.http :as http] [compojure.core :refer [GET]] [ote.db.transit :as transit] [specql.op :as op] [ring.util.io :as ring-io] [taoensso.timbre :as log] [ote.components.http :as http] [ote.db.transit :as transit] [ote.db.transport-operator :as t-operator] [ote.db.transport-service :as t-service] [ote.time :as time] [ote.gtfs.transform :as gtfs-transform] [ote.util.zip :refer [write-zip]] [ote.util.fn :refer [flip]] [ote.util.transport-operator-util :as op-util] [ote.localization :refer [*language*]] [ote.services.routes :refer [fetch-sea-trips]])) (declare export-sea-gtfs) (defrecord GTFSExport [] component/Lifecycle (start [{http :http db :db :as this}] (assoc this ::stop (http/publish! http {:authenticated? false} (GET "/export/gtfs/:transport-operator-id{[0-9]+}" [transport-operator-id] (export-sea-gtfs db (Long/parseLong transport-operator-id)))))) (stop [{stop ::stop :as this}] (stop) (dissoc this ::stop))) (defn fetch-sea-routes-published "Return the currently available published sea routes of the given transport operator." [db transport-operator-id] (let [routes (fetch db ::transit/route #{::transit/route-id ::transit/name ::transit/departure-point-name ::transit/destination-point-name ::transit/stops ::transit/route-type ::transit/service-calendars} {::transit/transport-operator-id transport-operator-id ::transit/published? true})] (mapv #(assoc % ::transit/trips (fetch-sea-trips db (::transit/route-id %))) routes))) (defn sea-routes-gtfs-zip [transport-operator routes output-stream] (try (write-zip (gtfs-transform/sea-routes-gtfs transport-operator routes) output-stream) (catch Exception e (log/warn "Exception while generating GTFS zip" e)))) (defn get-transport-operator [db transport-operator-id] (first (fetch db ::t-operator/transport-operator #{::t-operator/id ::t-operator/name ::t-operator/homepage ::t-operator/phone ::t-operator/email} {::t-operator/id transport-operator-id}))) (defn get-sea-routes [db transport-operator-id] (fetch-sea-routes-published db transport-operator-id) #_(map #(update % ::transit/name (flip t-service/localized-text-with-fallback) *language*) (fetch-sea-routes-published db transport-operator-id))) (defn export-sea-gtfs [db transport-operator-id] (let [transport-operator (get-transport-operator db transport-operator-id) routes (get-sea-routes db transport-operator-id)] {:status 200 :headers {"Content-Type" "application/zip" "Content-Disposition" (str "attachment; filename=" (op-util/gtfs-file-name transport-operator))} :body (ring-io/piped-input-stream (partial sea-routes-gtfs-zip transport-operator routes))}))
ef798b718ff9061aa4f0e0f1c811ff8e22e4c3e5b7caba9341c742f9200ab595
janestreet/universe
tyxml.ml
open Js_of_ocaml open Tyxml_f module type XML = Xml_sigs.T with type uri = string and type event_handler = Dom_html.event Js.t -> Event.t and type mouse_event_handler = Dom_html.mouseEvent Js.t -> Event.t and type touch_event_handler = Dom_html.touchEvent Js.t -> Event.t and type keyboard_event_handler = Dom_html.keyboardEvent Js.t -> Event.t and type elt = Vdom.Node.t module Xml = struct module W = Xml_wrap.NoWrap type 'a wrap = 'a type 'a list_wrap = 'a list type uri = string let uri_of_string s = s let string_of_uri s = s type aname = string type event_handler = Dom_html.event Js.t -> Event.t type mouse_event_handler = Dom_html.mouseEvent Js.t -> Event.t type touch_event_handler = Dom_html.touchEvent Js.t -> Event.t type keyboard_event_handler = Dom_html.keyboardEvent Js.t -> Event.t type attrib = Attr.t let attr name value = match name with | "value" | "checked" | "selected" -> Attr.property name (Js.Unsafe.inject (Js.string value)) | name -> Attr.create name value ;; let attr_ev name cvt_to_vdom_event = let f e = Event.Expert.handle e (cvt_to_vdom_event e); Js._true in Attr.property name (Js.Unsafe.inject (Dom.handler f)) ;; let float_attrib name value : attrib = attr name (string_of_float value) let int_attrib name value = attr name (string_of_int value) let string_attrib name value = attr name value let space_sep_attrib name values = attr name (String.concat " " values) let comma_sep_attrib name values = attr name (String.concat "," values) let event_handler_attrib name (value : event_handler) = attr_ev name value let mouse_event_handler_attrib name (value : mouse_event_handler) = attr_ev name value let touch_event_handler_attrib name (value : touch_event_handler) = attr_ev name value let keyboard_event_handler_attrib name (value : keyboard_event_handler) = attr_ev name value ;; let uri_attrib name value = attr name value let uris_attrib name values = attr name (String.concat " " values) (** Element *) type elt = Vdom.Node.t type ename = string let make_a x = x let empty () = assert false let comment _c = assert false let pcdata s = Vdom.Node.text s let encodedpcdata s = Vdom.Node.text s let entity e = let entity = Dom_html.decode_html_entities (Js.string ("&" ^ e ^ ";")) in Vdom.Node.text (Js.to_string entity) ;; let leaf ?(a = []) name = Vdom.Node.create name (make_a a) [] let node ?(a = []) name children = Vdom.Node.create name (make_a a) children let cdata s = pcdata s let cdata_script s = cdata s let cdata_style s = cdata s end module Xml_Svg = struct include Xml let leaf ?(a = []) name = Vdom.Node.create_svg name (make_a a) [] let node ?(a = []) name children = Vdom.Node.create_svg name (make_a a) children end module Svg = Svg_f.Make (Xml_Svg) module Html = Html_f.Make (Xml) (Svg)
null
https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/virtual_dom/src/tyxml.ml
ocaml
* Element
open Js_of_ocaml open Tyxml_f module type XML = Xml_sigs.T with type uri = string and type event_handler = Dom_html.event Js.t -> Event.t and type mouse_event_handler = Dom_html.mouseEvent Js.t -> Event.t and type touch_event_handler = Dom_html.touchEvent Js.t -> Event.t and type keyboard_event_handler = Dom_html.keyboardEvent Js.t -> Event.t and type elt = Vdom.Node.t module Xml = struct module W = Xml_wrap.NoWrap type 'a wrap = 'a type 'a list_wrap = 'a list type uri = string let uri_of_string s = s let string_of_uri s = s type aname = string type event_handler = Dom_html.event Js.t -> Event.t type mouse_event_handler = Dom_html.mouseEvent Js.t -> Event.t type touch_event_handler = Dom_html.touchEvent Js.t -> Event.t type keyboard_event_handler = Dom_html.keyboardEvent Js.t -> Event.t type attrib = Attr.t let attr name value = match name with | "value" | "checked" | "selected" -> Attr.property name (Js.Unsafe.inject (Js.string value)) | name -> Attr.create name value ;; let attr_ev name cvt_to_vdom_event = let f e = Event.Expert.handle e (cvt_to_vdom_event e); Js._true in Attr.property name (Js.Unsafe.inject (Dom.handler f)) ;; let float_attrib name value : attrib = attr name (string_of_float value) let int_attrib name value = attr name (string_of_int value) let string_attrib name value = attr name value let space_sep_attrib name values = attr name (String.concat " " values) let comma_sep_attrib name values = attr name (String.concat "," values) let event_handler_attrib name (value : event_handler) = attr_ev name value let mouse_event_handler_attrib name (value : mouse_event_handler) = attr_ev name value let touch_event_handler_attrib name (value : touch_event_handler) = attr_ev name value let keyboard_event_handler_attrib name (value : keyboard_event_handler) = attr_ev name value ;; let uri_attrib name value = attr name value let uris_attrib name values = attr name (String.concat " " values) type elt = Vdom.Node.t type ename = string let make_a x = x let empty () = assert false let comment _c = assert false let pcdata s = Vdom.Node.text s let encodedpcdata s = Vdom.Node.text s let entity e = let entity = Dom_html.decode_html_entities (Js.string ("&" ^ e ^ ";")) in Vdom.Node.text (Js.to_string entity) ;; let leaf ?(a = []) name = Vdom.Node.create name (make_a a) [] let node ?(a = []) name children = Vdom.Node.create name (make_a a) children let cdata s = pcdata s let cdata_script s = cdata s let cdata_style s = cdata s end module Xml_Svg = struct include Xml let leaf ?(a = []) name = Vdom.Node.create_svg name (make_a a) [] let node ?(a = []) name children = Vdom.Node.create_svg name (make_a a) children end module Svg = Svg_f.Make (Xml_Svg) module Html = Html_f.Make (Xml) (Svg)
f46a0dbc37ee8cd51b960bf03efdd2cd9a3191704a2e4ba9c4b960470ed15ecf
borodust/claw
record.lisp
(cl:in-package :claw.cffi.c) (declaim (special *anonymous-field-number*)) (defun next-anonymous-field-number () (prog1 *anonymous-field-number* (incf *anonymous-field-number*))) ;;; ;;; RECORD ;;; (defun field-c-name->lisp (field) (let ((name (claw.spec:foreign-entity-name field))) (if (emptyp name) (let ((lispified (c-name->lisp (format nil "@~A" (next-anonymous-field-number)) :field))) (register-anonymous-name lispified) lispified) (c-name->lisp name :field)))) (defun generate-c-field (record-kind field) (let* ((name (field-c-name->lisp field)) (entity (claw.spec:foreign-enveloped-entity field))) (export-symbol name) (append (if (and (typep entity 'claw.spec:foreign-array) (claw.spec:foreign-array-dimensions entity)) (let ((enveloped (claw.spec:foreign-enveloped-entity entity)) (count (apply #'* (claw.spec:foreign-array-dimensions entity)))) `(,name ,(entity->cffi-type enveloped) :count ,count)) `(,name ,(entity->cffi-type entity))) (when (eq record-kind :struct) `(:offset ,(/ (claw.spec:foreign-record-field-bit-offset field) 8)))))) (defun generate-c-fields (kind entity) (flet ((%generate-c-field (field) (generate-c-field kind field))) (let ((*anonymous-field-number* 0)) (mapcar #'%generate-c-field (claw.spec:foreign-record-fields entity))))) (defun generate-record-binding (kind entity name fields) (let* ((id (entity->cffi-type entity)) (name (or name (second id))) (byte-size (/ (claw.spec:foreign-entity-bit-size entity) 8))) (export-symbol name) `((,kind (,name :size ,byte-size) ,@fields)))) (defmethod foreign-entity-dependencies ((entity claw.spec:foreign-record)) (mapcar #'claw.spec:foreign-enveloped-entity (claw.spec:foreign-record-fields entity))) (defmethod dependablep ((entity claw.spec:foreign-record)) (declare (ignore entity)) t) ;;; ;;; STRUCT ;;; (defmethod generate-binding ((generator cffi-generator) (entity claw.spec:foreign-struct) &key name) (generate-record-binding 'cffi:defcstruct entity name (generate-c-fields :struct entity))) (defmethod generate-forward-declaration ((generator cffi-generator) (entity claw.spec:foreign-struct) &key name) (generate-record-binding 'cffi:defcstruct entity name nil)) ;;; ;;; UNION ;;; (defmethod generate-binding ((generator cffi-generator) (entity claw.spec:foreign-union) &key name) (generate-record-binding 'cffi:defcunion entity name (generate-c-fields :union entity))) (defmethod generate-forward-declaration ((generator cffi-generator) (entity claw.spec:foreign-union) &key name) (generate-record-binding 'cffi:defcunion entity name nil))
null
https://raw.githubusercontent.com/borodust/claw/ef59eeaed16841da659e3b6f449486950240791a/src/gen/cffi/c/generator/record.lisp
lisp
RECORD STRUCT UNION
(cl:in-package :claw.cffi.c) (declaim (special *anonymous-field-number*)) (defun next-anonymous-field-number () (prog1 *anonymous-field-number* (incf *anonymous-field-number*))) (defun field-c-name->lisp (field) (let ((name (claw.spec:foreign-entity-name field))) (if (emptyp name) (let ((lispified (c-name->lisp (format nil "@~A" (next-anonymous-field-number)) :field))) (register-anonymous-name lispified) lispified) (c-name->lisp name :field)))) (defun generate-c-field (record-kind field) (let* ((name (field-c-name->lisp field)) (entity (claw.spec:foreign-enveloped-entity field))) (export-symbol name) (append (if (and (typep entity 'claw.spec:foreign-array) (claw.spec:foreign-array-dimensions entity)) (let ((enveloped (claw.spec:foreign-enveloped-entity entity)) (count (apply #'* (claw.spec:foreign-array-dimensions entity)))) `(,name ,(entity->cffi-type enveloped) :count ,count)) `(,name ,(entity->cffi-type entity))) (when (eq record-kind :struct) `(:offset ,(/ (claw.spec:foreign-record-field-bit-offset field) 8)))))) (defun generate-c-fields (kind entity) (flet ((%generate-c-field (field) (generate-c-field kind field))) (let ((*anonymous-field-number* 0)) (mapcar #'%generate-c-field (claw.spec:foreign-record-fields entity))))) (defun generate-record-binding (kind entity name fields) (let* ((id (entity->cffi-type entity)) (name (or name (second id))) (byte-size (/ (claw.spec:foreign-entity-bit-size entity) 8))) (export-symbol name) `((,kind (,name :size ,byte-size) ,@fields)))) (defmethod foreign-entity-dependencies ((entity claw.spec:foreign-record)) (mapcar #'claw.spec:foreign-enveloped-entity (claw.spec:foreign-record-fields entity))) (defmethod dependablep ((entity claw.spec:foreign-record)) (declare (ignore entity)) t) (defmethod generate-binding ((generator cffi-generator) (entity claw.spec:foreign-struct) &key name) (generate-record-binding 'cffi:defcstruct entity name (generate-c-fields :struct entity))) (defmethod generate-forward-declaration ((generator cffi-generator) (entity claw.spec:foreign-struct) &key name) (generate-record-binding 'cffi:defcstruct entity name nil)) (defmethod generate-binding ((generator cffi-generator) (entity claw.spec:foreign-union) &key name) (generate-record-binding 'cffi:defcunion entity name (generate-c-fields :union entity))) (defmethod generate-forward-declaration ((generator cffi-generator) (entity claw.spec:foreign-union) &key name) (generate-record-binding 'cffi:defcunion entity name nil))
2c42ae72e1d9a9780ebde23b4d15b5666587bab8b69fb283c0b197d62d13cb0f
pixlsus/registry.gimp.org_static
Orton-Effect.scm
; ; 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 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 program; if not, write to the Free Software Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . ; (define (script-fu-Orton-Effect inImage inLayer inBlur inOpacity inKeepOriginal) (gimp-image-undo-group-start inImage) (define (copy-and-add-layer orig-layer) (let ((layer (car (gimp-layer-copy orig-layer TRUE)))) (gimp-image-add-layer inImage layer -1) layer ) ) (define (create-light-layer orig-layer) (let ((layer (copy-and-add-layer orig-layer))) (gimp-layer-set-mode layer SCREEN-MODE) (car (gimp-image-merge-down inImage layer CLIP-TO-BOTTOM-LAYER)) ) ) (let* ( (layer (create-light-layer (if (= inKeepOriginal TRUE) (copy-and-add-layer inLayer) inLayer))) (layer2 (copy-and-add-layer layer)) ) (if (> inBlur 0) (plug-in-gauss 1 inImage layer2 inBlur inBlur 0) ) (gimp-layer-set-mode layer2 MULTIPLY-MODE) (gimp-layer-set-opacity layer2 inOpacity) ) (gimp-image-undo-group-end inImage) (gimp-displays-flush) ) ; (script-fu-register "script-fu-Orton-Effect" "<Image>/Script-F_u/Orton Effect" "Imitates Orton effect by creating two \ lighter layers from the original - \ one blurred and one sharp, and mixing them.\ Description of this method: -orton-effect-digital-photography-tip-of-the-week" "Julia Jomantaite <>" "Julia Jomantaite" "20.04.2008" "RGB* GRAY*" SF-IMAGE "Image" 0 SF-DRAWABLE "Layer" 0 SF-ADJUSTMENT "Blur radius" '(10.0 0.0 99.0 1.0 5 1 1) SF-ADJUSTMENT "Opacity" '(100.0 0.0 100.0 1.0 5 1 0) SF-TOGGLE "Keep the original layer" FALSE )
null
https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/Orton-Effect.scm
scheme
This program is free software; you can redistribute it and/or modify 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. along with this program; if not, write to the Free Software
it under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . (define (script-fu-Orton-Effect inImage inLayer inBlur inOpacity inKeepOriginal) (gimp-image-undo-group-start inImage) (define (copy-and-add-layer orig-layer) (let ((layer (car (gimp-layer-copy orig-layer TRUE)))) (gimp-image-add-layer inImage layer -1) layer ) ) (define (create-light-layer orig-layer) (let ((layer (copy-and-add-layer orig-layer))) (gimp-layer-set-mode layer SCREEN-MODE) (car (gimp-image-merge-down inImage layer CLIP-TO-BOTTOM-LAYER)) ) ) (let* ( (layer (create-light-layer (if (= inKeepOriginal TRUE) (copy-and-add-layer inLayer) inLayer))) (layer2 (copy-and-add-layer layer)) ) (if (> inBlur 0) (plug-in-gauss 1 inImage layer2 inBlur inBlur 0) ) (gimp-layer-set-mode layer2 MULTIPLY-MODE) (gimp-layer-set-opacity layer2 inOpacity) ) (gimp-image-undo-group-end inImage) (gimp-displays-flush) ) (script-fu-register "script-fu-Orton-Effect" "<Image>/Script-F_u/Orton Effect" "Imitates Orton effect by creating two \ lighter layers from the original - \ one blurred and one sharp, and mixing them.\ Description of this method: -orton-effect-digital-photography-tip-of-the-week" "Julia Jomantaite <>" "Julia Jomantaite" "20.04.2008" "RGB* GRAY*" SF-IMAGE "Image" 0 SF-DRAWABLE "Layer" 0 SF-ADJUSTMENT "Blur radius" '(10.0 0.0 99.0 1.0 5 1 1) SF-ADJUSTMENT "Opacity" '(100.0 0.0 100.0 1.0 5 1 0) SF-TOGGLE "Keep the original layer" FALSE )
1abc6d612b719e4eb7b6e76fde5a53fd829da1ccc061603b01be413df0c9af02
rbkmoney/fistful-server
ff_string.erl
%%% %%% String manipultion facilities. -module(ff_string). -export([join/1]). -export([join/2]). %% -type fragment() :: iodata() | char() | atom() | number(). -spec join([fragment()]) -> binary(). join(Fragments) -> join(<<>>, Fragments). -spec join(Delim, [fragment()]) -> binary() when Delim :: char() | iodata(). join(Delim, Fragments) -> genlib_string:join(Delim, lists:map(fun genlib:to_binary/1, Fragments)).
null
https://raw.githubusercontent.com/rbkmoney/fistful-server/60b964d0e07f911c841903bc61d8d9fb20a32658/apps/ff_core/src/ff_string.erl
erlang
String manipultion facilities.
-module(ff_string). -export([join/1]). -export([join/2]). -type fragment() :: iodata() | char() | atom() | number(). -spec join([fragment()]) -> binary(). join(Fragments) -> join(<<>>, Fragments). -spec join(Delim, [fragment()]) -> binary() when Delim :: char() | iodata(). join(Delim, Fragments) -> genlib_string:join(Delim, lists:map(fun genlib:to_binary/1, Fragments)).
11aecef9a62741ad196e53f54a76f4a0d5aa5eec4d91d68e9eb68809475ddde8
mwand/eopl3
translator.scm
(module translator (lib "eopl.ss" "eopl") (require "lang.scm") (provide translation-of-program) ;;;;;;;;;;;;;;;; lexical address calculator ;;;;;;;;;;;;;;;; ;; translation-of-program : Program -> Nameless-program Page : 96 (define translation-of-program (lambda (pgm) (cases program pgm (a-program (exp1) (a-program (translation-of exp1 (init-senv))))))) ;; translation-of : Exp * Senv -> Nameless-exp Page 97 (define translation-of (lambda (exp senv) (cases expression exp (const-exp (num) (const-exp num)) (diff-exp (exp1 exp2) (diff-exp (translation-of exp1 senv) (translation-of exp2 senv))) (zero?-exp (exp1) (zero?-exp (translation-of exp1 senv))) (if-exp (exp1 exp2 exp3) (if-exp (translation-of exp1 senv) (translation-of exp2 senv) (translation-of exp3 senv))) (var-exp (var) (nameless-var-exp (apply-senv senv var))) (let-exp (var exp1 body) (nameless-let-exp (translation-of exp1 senv) (translation-of body (extend-senv var senv)))) (proc-exp (var body) (nameless-proc-exp (translation-of body (extend-senv var senv)))) (call-exp (rator rand) (call-exp (translation-of rator senv) (translation-of rand senv))) (else (report-invalid-source-expression exp)) ))) (define report-invalid-source-expression (lambda (exp) (eopl:error 'value-of "Illegal expression in source code: ~s" exp))) ;;;;;;;;;;;;;;;; static environments ;;;;;;;;;;;;;;;; ;;; Senv = Listof(Sym) ;;; Lexaddr = N ;; empty-senv : () -> Senv Page : 95 (define empty-senv (lambda () '())) ;; extend-senv : Var * Senv -> Senv Page : 95 (define extend-senv (lambda (var senv) (cons var senv))) ;; apply-senv : Senv * Var -> Lexaddr Page : 95 (define apply-senv (lambda (senv var) (cond ((null? senv) (report-unbound-var var)) ((eqv? var (car senv)) 0) (else (+ 1 (apply-senv (cdr senv) var)))))) (define report-unbound-var (lambda (var) (eopl:error 'translation-of "unbound variable in code: ~s" var))) ;; init-senv : () -> Senv Page : 96 (define init-senv (lambda () (extend-senv 'i (extend-senv 'v (extend-senv 'x (empty-senv)))))) )
null
https://raw.githubusercontent.com/mwand/eopl3/b50e015be7f021d94c1af5f0e3a05d40dd2b0cbf/chapter3/lexaddr-lang/translator.scm
scheme
lexical address calculator ;;;;;;;;;;;;;;;; translation-of-program : Program -> Nameless-program translation-of : Exp * Senv -> Nameless-exp static environments ;;;;;;;;;;;;;;;; Senv = Listof(Sym) Lexaddr = N empty-senv : () -> Senv extend-senv : Var * Senv -> Senv apply-senv : Senv * Var -> Lexaddr init-senv : () -> Senv
(module translator (lib "eopl.ss" "eopl") (require "lang.scm") (provide translation-of-program) Page : 96 (define translation-of-program (lambda (pgm) (cases program pgm (a-program (exp1) (a-program (translation-of exp1 (init-senv))))))) Page 97 (define translation-of (lambda (exp senv) (cases expression exp (const-exp (num) (const-exp num)) (diff-exp (exp1 exp2) (diff-exp (translation-of exp1 senv) (translation-of exp2 senv))) (zero?-exp (exp1) (zero?-exp (translation-of exp1 senv))) (if-exp (exp1 exp2 exp3) (if-exp (translation-of exp1 senv) (translation-of exp2 senv) (translation-of exp3 senv))) (var-exp (var) (nameless-var-exp (apply-senv senv var))) (let-exp (var exp1 body) (nameless-let-exp (translation-of exp1 senv) (translation-of body (extend-senv var senv)))) (proc-exp (var body) (nameless-proc-exp (translation-of body (extend-senv var senv)))) (call-exp (rator rand) (call-exp (translation-of rator senv) (translation-of rand senv))) (else (report-invalid-source-expression exp)) ))) (define report-invalid-source-expression (lambda (exp) (eopl:error 'value-of "Illegal expression in source code: ~s" exp))) Page : 95 (define empty-senv (lambda () '())) Page : 95 (define extend-senv (lambda (var senv) (cons var senv))) Page : 95 (define apply-senv (lambda (senv var) (cond ((null? senv) (report-unbound-var var)) ((eqv? var (car senv)) 0) (else (+ 1 (apply-senv (cdr senv) var)))))) (define report-unbound-var (lambda (var) (eopl:error 'translation-of "unbound variable in code: ~s" var))) Page : 96 (define init-senv (lambda () (extend-senv 'i (extend-senv 'v (extend-senv 'x (empty-senv)))))) )
c34bd8409ee9056ac31bcd651235ca08c85a68c9bfd1b7204e939ec83f4dbf07
functionally/mantis
Info.hs
# LANGUAGE RecordWildCards # module Mantra.Command.Info ( command , mainUtxo , mainAddress , mainTxBody , mainTx ) where import Cardano.Api (AsType(AsAllegraEra, AsAlonzoEra, AsByronEra, AsMaryEra, AsShelleyEra, AsTx, AsTxBody), ConsensusModeParams(CardanoModeParams), EpochSlots(..), FromSomeType(..), IsCardanoEra, NetworkId(..), NetworkMagic(..), ShelleyBasedEra, getTxBody, getTxId, readFileTextEnvelopeAnyOf) import Control.Monad (forM_) import Control.Monad.IO.Class (MonadIO, liftIO) import Mantra.Command.Types (Configuration(..), Mantra(InfoAddress, InfoTx, InfoTxBody, InfoUtxo)) import Mantra.Query (queryUTxO) import Mantra.Transaction (printUTxO) import Mantra.Types (MantraM, foistMantraEitherIO, printMantra) import Mantra.Wallet (readAddress) import qualified Options.Applicative as O command :: O.Mod O.CommandFields Mantra command = mconcat [ O.command "info-address" $ O.info ( InfoAddress <$> O.many (O.strArgument $ O.metavar "ADDRESS" <> O.help "Shelley address.") ) (O.progDesc "Print information about addresses.") , O.command "info-tx" $ O.info ( InfoTx <$> O.many (O.strArgument $ O.metavar "TX_FILE" <> O.help "Signed transaction file.") ) (O.progDesc "Print contents of transaction files.") , O.command "info-txbody" $ O.info ( InfoTxBody <$> O.many (O.strArgument $ O.metavar "TXBODY_FILE" <> O.help "Transaction body file.") ) (O.progDesc "Print contents of transaction body files.") , O.command "info-utxo" $ O.info ( InfoUtxo <$> O.strArgument ( O.metavar "CONFIG_FILE" <> O.help "Path to configuration file.") <*> O.many (O.strArgument $ O.metavar "ADDRESS" <> O.help "Shelley address." ) ) (O.progDesc "Print UTxO information for addresses.") ] mainUtxo :: IsCardanoEra era => MonadFail m => MonadIO m => ShelleyBasedEra era -> (String -> MantraM m ()) -> FilePath -> [String] -> MantraM m () mainUtxo sbe debugMantra configFile addresses = do Configuration{..} <- liftIO $ read <$> readFile configFile printMantra "" let protocol = CardanoModeParams $ EpochSlots epochSlots network = maybe Mainnet (Testnet . NetworkMagic) magic debugMantra $ "Network: " ++ show network forM_ addresses $ \address -> do debugMantra "" address' <- readAddress address debugMantra "Output Address: " debugMantra $ " " ++ show address debugMantra $ " " ++ show address' printMantra "Unspent UTxO:" utxo <- queryUTxO sbe socketPath protocol address' network printUTxO " " utxo mainAddress :: MonadIO m => (String -> MantraM m ()) -> [String] -> MantraM m () mainAddress _ addresses = forM_ addresses $ \address -> do printMantra "" address' <- readAddress address printMantra "Output Address: " printMantra $ " " ++ show address printMantra $ " " ++ show address' mainTxBody :: MonadIO m => (String -> MantraM m ()) -> [FilePath] -> MantraM m () mainTxBody _ txBodyFiles = forM_ txBodyFiles $ \file -> do printMantra "" printMantra $ "Transaction body file: " ++ file (txId, txBody) <- foistMantraEitherIO $ readFileTextEnvelopeAnyOf [ FromSomeType (AsTxBody AsAlonzoEra ) $ \txBody -> (show $ getTxId txBody, show txBody) , FromSomeType (AsTxBody AsMaryEra ) $ \txBody -> (show $ getTxId txBody, show txBody) , FromSomeType (AsTxBody AsAllegraEra) $ \txBody -> (show $ getTxId txBody, show txBody) , FromSomeType (AsTxBody AsShelleyEra) $ \txBody -> (show $ getTxId txBody, show txBody) , FromSomeType (AsTxBody AsByronEra ) $ \txBody -> (show $ getTxId txBody, show txBody) ] file printMantra txId printMantra txBody mainTx :: MonadIO m => (String -> MantraM m ()) -> [FilePath] -> MantraM m () mainTx _ txFiles = forM_ txFiles $ \file -> do printMantra "" printMantra $ "Transaction file: " ++ file (txId, tx) <- foistMantraEitherIO $ readFileTextEnvelopeAnyOf [ FromSomeType (AsTx AsAlonzoEra ) $ \tx -> (show . getTxId $ getTxBody tx, show tx) , FromSomeType (AsTx AsMaryEra ) $ \tx -> (show . getTxId $ getTxBody tx, show tx) , FromSomeType (AsTx AsAllegraEra) $ \tx -> (show . getTxId $ getTxBody tx, show tx) , FromSomeType (AsTx AsShelleyEra) $ \tx -> (show . getTxId $ getTxBody tx, show tx) , FromSomeType (AsTx AsByronEra ) $ \tx -> (show . getTxId $ getTxBody tx, show tx) ] file printMantra txId printMantra tx
null
https://raw.githubusercontent.com/functionally/mantis/1cd121202452dcc1bce56ed4b4f41f0e880c9d04/app/Mantra/Command/Info.hs
haskell
# LANGUAGE RecordWildCards # module Mantra.Command.Info ( command , mainUtxo , mainAddress , mainTxBody , mainTx ) where import Cardano.Api (AsType(AsAllegraEra, AsAlonzoEra, AsByronEra, AsMaryEra, AsShelleyEra, AsTx, AsTxBody), ConsensusModeParams(CardanoModeParams), EpochSlots(..), FromSomeType(..), IsCardanoEra, NetworkId(..), NetworkMagic(..), ShelleyBasedEra, getTxBody, getTxId, readFileTextEnvelopeAnyOf) import Control.Monad (forM_) import Control.Monad.IO.Class (MonadIO, liftIO) import Mantra.Command.Types (Configuration(..), Mantra(InfoAddress, InfoTx, InfoTxBody, InfoUtxo)) import Mantra.Query (queryUTxO) import Mantra.Transaction (printUTxO) import Mantra.Types (MantraM, foistMantraEitherIO, printMantra) import Mantra.Wallet (readAddress) import qualified Options.Applicative as O command :: O.Mod O.CommandFields Mantra command = mconcat [ O.command "info-address" $ O.info ( InfoAddress <$> O.many (O.strArgument $ O.metavar "ADDRESS" <> O.help "Shelley address.") ) (O.progDesc "Print information about addresses.") , O.command "info-tx" $ O.info ( InfoTx <$> O.many (O.strArgument $ O.metavar "TX_FILE" <> O.help "Signed transaction file.") ) (O.progDesc "Print contents of transaction files.") , O.command "info-txbody" $ O.info ( InfoTxBody <$> O.many (O.strArgument $ O.metavar "TXBODY_FILE" <> O.help "Transaction body file.") ) (O.progDesc "Print contents of transaction body files.") , O.command "info-utxo" $ O.info ( InfoUtxo <$> O.strArgument ( O.metavar "CONFIG_FILE" <> O.help "Path to configuration file.") <*> O.many (O.strArgument $ O.metavar "ADDRESS" <> O.help "Shelley address." ) ) (O.progDesc "Print UTxO information for addresses.") ] mainUtxo :: IsCardanoEra era => MonadFail m => MonadIO m => ShelleyBasedEra era -> (String -> MantraM m ()) -> FilePath -> [String] -> MantraM m () mainUtxo sbe debugMantra configFile addresses = do Configuration{..} <- liftIO $ read <$> readFile configFile printMantra "" let protocol = CardanoModeParams $ EpochSlots epochSlots network = maybe Mainnet (Testnet . NetworkMagic) magic debugMantra $ "Network: " ++ show network forM_ addresses $ \address -> do debugMantra "" address' <- readAddress address debugMantra "Output Address: " debugMantra $ " " ++ show address debugMantra $ " " ++ show address' printMantra "Unspent UTxO:" utxo <- queryUTxO sbe socketPath protocol address' network printUTxO " " utxo mainAddress :: MonadIO m => (String -> MantraM m ()) -> [String] -> MantraM m () mainAddress _ addresses = forM_ addresses $ \address -> do printMantra "" address' <- readAddress address printMantra "Output Address: " printMantra $ " " ++ show address printMantra $ " " ++ show address' mainTxBody :: MonadIO m => (String -> MantraM m ()) -> [FilePath] -> MantraM m () mainTxBody _ txBodyFiles = forM_ txBodyFiles $ \file -> do printMantra "" printMantra $ "Transaction body file: " ++ file (txId, txBody) <- foistMantraEitherIO $ readFileTextEnvelopeAnyOf [ FromSomeType (AsTxBody AsAlonzoEra ) $ \txBody -> (show $ getTxId txBody, show txBody) , FromSomeType (AsTxBody AsMaryEra ) $ \txBody -> (show $ getTxId txBody, show txBody) , FromSomeType (AsTxBody AsAllegraEra) $ \txBody -> (show $ getTxId txBody, show txBody) , FromSomeType (AsTxBody AsShelleyEra) $ \txBody -> (show $ getTxId txBody, show txBody) , FromSomeType (AsTxBody AsByronEra ) $ \txBody -> (show $ getTxId txBody, show txBody) ] file printMantra txId printMantra txBody mainTx :: MonadIO m => (String -> MantraM m ()) -> [FilePath] -> MantraM m () mainTx _ txFiles = forM_ txFiles $ \file -> do printMantra "" printMantra $ "Transaction file: " ++ file (txId, tx) <- foistMantraEitherIO $ readFileTextEnvelopeAnyOf [ FromSomeType (AsTx AsAlonzoEra ) $ \tx -> (show . getTxId $ getTxBody tx, show tx) , FromSomeType (AsTx AsMaryEra ) $ \tx -> (show . getTxId $ getTxBody tx, show tx) , FromSomeType (AsTx AsAllegraEra) $ \tx -> (show . getTxId $ getTxBody tx, show tx) , FromSomeType (AsTx AsShelleyEra) $ \tx -> (show . getTxId $ getTxBody tx, show tx) , FromSomeType (AsTx AsByronEra ) $ \tx -> (show . getTxId $ getTxBody tx, show tx) ] file printMantra txId printMantra tx
af167bfed6b8332546e2972d079bbff4c5afdd064c6d406482877b4f7a4ab063
terezka/cherry-core
Reporting.hs
# OPTIONS_GHC -Wall # module Parser.Reporting ( Located(..) , Position(..) , Region(..) , traverse , toValue , merge , at , toRegion , mergeRegions , zero , one ) where import Prelude hiding (traverse) import Control.Monad (liftM2) import Data.Binary (Binary, get, put) import Data.Word (Word16) -- LOCATED data Located a = At Region a -- TODO see if unpacking region is helpful instance Functor Located where fmap f (At region a) = At region (f a) traverse :: (Functor f) => (a -> f b) -> Located a -> f (Located b) traverse func (At region value) = At region <$> func value toValue :: Located a -> a toValue (At _ value) = value merge :: Located a -> Located b -> value -> Located value merge (At r1 _) (At r2 _) value = At (mergeRegions r1 r2) value -- POSITION data Position = Position {-# UNPACK #-} !Word16 {-# UNPACK #-} !Word16 deriving (Eq) at :: Position -> Position -> a -> Located a at start end a = At (Region start end) a -- REGION data Region = Region Position Position deriving (Eq) toRegion :: Located a -> Region toRegion (At region _) = region mergeRegions :: Region -> Region -> Region mergeRegions (Region start _) (Region _ end) = Region start end zero :: Region zero = Region (Position 0 0) (Position 0 0) one :: Region one = Region (Position 1 1) (Position 1 1) instance Binary Region where put (Region a b) = put a >> put b get = liftM2 Region get get instance Binary Position where put (Position a b) = put a >> put b get = liftM2 Position get get
null
https://raw.githubusercontent.com/terezka/cherry-core/d9bd446e226fc9b04783532969fa670211a150c6/src/Parser/Reporting.hs
haskell
LOCATED TODO see if unpacking region is helpful POSITION # UNPACK # # UNPACK # REGION
# OPTIONS_GHC -Wall # module Parser.Reporting ( Located(..) , Position(..) , Region(..) , traverse , toValue , merge , at , toRegion , mergeRegions , zero , one ) where import Prelude hiding (traverse) import Control.Monad (liftM2) import Data.Binary (Binary, get, put) import Data.Word (Word16) data Located a = instance Functor Located where fmap f (At region a) = At region (f a) traverse :: (Functor f) => (a -> f b) -> Located a -> f (Located b) traverse func (At region value) = At region <$> func value toValue :: Located a -> a toValue (At _ value) = value merge :: Located a -> Located b -> value -> Located value merge (At r1 _) (At r2 _) value = At (mergeRegions r1 r2) value data Position = Position deriving (Eq) at :: Position -> Position -> a -> Located a at start end a = At (Region start end) a data Region = Region Position Position deriving (Eq) toRegion :: Located a -> Region toRegion (At region _) = region mergeRegions :: Region -> Region -> Region mergeRegions (Region start _) (Region _ end) = Region start end zero :: Region zero = Region (Position 0 0) (Position 0 0) one :: Region one = Region (Position 1 1) (Position 1 1) instance Binary Region where put (Region a b) = put a >> put b get = liftM2 Region get get instance Binary Position where put (Position a b) = put a >> put b get = liftM2 Position get get
235e7e5e975a951671dce171ca56a25b5684e874786812281f91cfda8b1eedf5
NetComposer/nkmedia
nkmedia_api_syntax.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2016 . All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- %% @doc NkMEDIA external API -module(nkmedia_api_syntax). -author('Carlos Gonzalez <>'). -export([syntax/4, offer/0, answer/0, get_info/1]). %% =================================================================== %% Syntax %% =================================================================== @private syntax(<<"create">>, Syntax, Defaults, Mandatory) -> { Syntax#{ type => atom, %% p2p, proxy... wait_reply => boolean, session_id => binary, offer => offer(), no_offer_trickle_ice => atom, no_answer_trickle_ice => atom, trickle_ice_timeout => {integer, 100, 30000}, For generated SDP only backend => atom, %% nkmedia_janus, etc. master_id => binary, set_master_answer => boolean, stop_after_peer => boolean, subscribe => boolean, events_body => any, wait_timeout => {integer, 1, none}, ready_timeout => {integer, 1, none}, % Type-specific peer_id => binary, room_id => binary, create_room => boolean, publisher_id => binary, layout => binary, loops => {integer, 0, none}, uri => binary, mute_audio => boolean, mute_video => boolean, mute_data => boolean, bitrate => integer }, Defaults, [type|Mandatory] }; syntax(<<"destroy">>, Syntax, Defaults, Mandatory) -> { Syntax#{session_id => binary}, Defaults, [session_id|Mandatory] }; syntax(<<"set_answer">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, answer => answer() }, Defaults, [session_id, answer|Mandatory] }; syntax(<<"get_offer">>, Syntax, Defaults, Mandatory) -> { Syntax#{session_id => binary}, Defaults, [session_id|Mandatory] }; syntax(<<"get_answer">>, Syntax, Defaults, Mandatory) -> { Syntax#{session_id => binary}, Defaults, [session_id|Mandatory] }; syntax(<<"update_media">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, mute_audio => boolean, mute_video => boolean, mute_data => boolean, bitrate => integer }, Defaults, [session_id|Mandatory] }; syntax(<<"set_type">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, type => atom, % Type specific room_id => binary, create_room => boolean, publisher_id => binary, uri => binary, layout => binary }, Defaults, [session_id, type|Mandatory] }; syntax(<<"recorder_action">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, action => atom, uri => binary }, Defaults, [session_id|Mandatory] }; syntax(<<"player_action">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, action => atom, uri => binary, loops => {integer, 0, none}, position => integer }, Defaults, [session_id|Mandatory] }; syntax(<<"room_action">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, action => atom, layout => binary }, Defaults, [session_id|Mandatory] }; syntax(<<"set_candidate">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, sdpMid => binary, sdpMLineIndex => integer, candidate => binary }, Defaults#{sdpMid=><<>>}, [session_id, sdpMLineIndex, candidate|Mandatory] }; syntax(<<"set_candidate_end">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary }, Defaults, [session_id|Mandatory] }; syntax(<<"get_info">>, Syntax, Defaults, Mandatory) -> { Syntax#{session_id => binary}, Defaults, [session_id|Mandatory] }; syntax(<<"get_list">>, Syntax, Defaults, Mandatory) -> { Syntax, Defaults, Mandatory }; syntax(_Cmd, Syntax, Defaults, Mandatory) -> {Syntax, Defaults, Mandatory}. @private offer() -> #{ sdp => binary, sdp_type => {enum, [rtp, webrtc]}, trickle_ice => boolean }. @private answer() -> #{ sdp => binary, sdp_type => {enum, [rtp, webrtc]}, trickle_ice => boolean }. %% =================================================================== %% Get info %% =================================================================== @private get_info(Session) -> Keys = [ session_id, offer, answer, no_offer_trickle_ice, no_answer_trickle_ice, trickle_ice_timeout, sdp_type, backend, master_id, slave_id, set_master_answer, stop_after_peer, wait_timeout, ready_timeout, user_id, user_session, backend_role, type, type_ext, status, peer_id, room_id, create_room, publisher_id, layout, loops, uri, mute_audio, mute_video, mute_data, bitrate ], maps:with(Keys, Session).
null
https://raw.githubusercontent.com/NetComposer/nkmedia/24480866a523bfd6490abfe90ea46c6130ffe51f/src/nkmedia_api_syntax.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- @doc NkMEDIA external API =================================================================== Syntax =================================================================== p2p, proxy... nkmedia_janus, etc. Type-specific Type specific =================================================================== Get info ===================================================================
Copyright ( c ) 2016 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(nkmedia_api_syntax). -author('Carlos Gonzalez <>'). -export([syntax/4, offer/0, answer/0, get_info/1]). @private syntax(<<"create">>, Syntax, Defaults, Mandatory) -> { Syntax#{ wait_reply => boolean, session_id => binary, offer => offer(), no_offer_trickle_ice => atom, no_answer_trickle_ice => atom, trickle_ice_timeout => {integer, 100, 30000}, For generated SDP only master_id => binary, set_master_answer => boolean, stop_after_peer => boolean, subscribe => boolean, events_body => any, wait_timeout => {integer, 1, none}, ready_timeout => {integer, 1, none}, peer_id => binary, room_id => binary, create_room => boolean, publisher_id => binary, layout => binary, loops => {integer, 0, none}, uri => binary, mute_audio => boolean, mute_video => boolean, mute_data => boolean, bitrate => integer }, Defaults, [type|Mandatory] }; syntax(<<"destroy">>, Syntax, Defaults, Mandatory) -> { Syntax#{session_id => binary}, Defaults, [session_id|Mandatory] }; syntax(<<"set_answer">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, answer => answer() }, Defaults, [session_id, answer|Mandatory] }; syntax(<<"get_offer">>, Syntax, Defaults, Mandatory) -> { Syntax#{session_id => binary}, Defaults, [session_id|Mandatory] }; syntax(<<"get_answer">>, Syntax, Defaults, Mandatory) -> { Syntax#{session_id => binary}, Defaults, [session_id|Mandatory] }; syntax(<<"update_media">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, mute_audio => boolean, mute_video => boolean, mute_data => boolean, bitrate => integer }, Defaults, [session_id|Mandatory] }; syntax(<<"set_type">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, type => atom, room_id => binary, create_room => boolean, publisher_id => binary, uri => binary, layout => binary }, Defaults, [session_id, type|Mandatory] }; syntax(<<"recorder_action">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, action => atom, uri => binary }, Defaults, [session_id|Mandatory] }; syntax(<<"player_action">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, action => atom, uri => binary, loops => {integer, 0, none}, position => integer }, Defaults, [session_id|Mandatory] }; syntax(<<"room_action">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, action => atom, layout => binary }, Defaults, [session_id|Mandatory] }; syntax(<<"set_candidate">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary, sdpMid => binary, sdpMLineIndex => integer, candidate => binary }, Defaults#{sdpMid=><<>>}, [session_id, sdpMLineIndex, candidate|Mandatory] }; syntax(<<"set_candidate_end">>, Syntax, Defaults, Mandatory) -> { Syntax#{ session_id => binary }, Defaults, [session_id|Mandatory] }; syntax(<<"get_info">>, Syntax, Defaults, Mandatory) -> { Syntax#{session_id => binary}, Defaults, [session_id|Mandatory] }; syntax(<<"get_list">>, Syntax, Defaults, Mandatory) -> { Syntax, Defaults, Mandatory }; syntax(_Cmd, Syntax, Defaults, Mandatory) -> {Syntax, Defaults, Mandatory}. @private offer() -> #{ sdp => binary, sdp_type => {enum, [rtp, webrtc]}, trickle_ice => boolean }. @private answer() -> #{ sdp => binary, sdp_type => {enum, [rtp, webrtc]}, trickle_ice => boolean }. @private get_info(Session) -> Keys = [ session_id, offer, answer, no_offer_trickle_ice, no_answer_trickle_ice, trickle_ice_timeout, sdp_type, backend, master_id, slave_id, set_master_answer, stop_after_peer, wait_timeout, ready_timeout, user_id, user_session, backend_role, type, type_ext, status, peer_id, room_id, create_room, publisher_id, layout, loops, uri, mute_audio, mute_video, mute_data, bitrate ], maps:with(Keys, Session).
92d663d64d085351efc57fc2a397fbb492712f7434cb579adb4b8821bf20bb32
iamFIREcracker/adventofcode
quickutils.lisp
;;;; This file was automatically generated by Quickutil. ;;;; See for details. ;;;; To regenerate: ( qtlc : save - utils - as " quickutils.lisp " : utilities ' (: COPY - ARRAY : COPY - HASH - TABLE : : FLATTEN : HASH - TABLE - ALIST : HASH - TABLE - KEYS : HASH - TABLE - VALUES : HASH - TABLE - KEY - EXISTS - P : IF - LET : IOTA : MAKE - KEYWORD : MKSTR : : NCYCLE : SYMB : VOID : WHEN - LET : WITH - GENSYMS ) : ensure - package T : package " AOC.QUICKUTILS " ) (eval-when (:compile-toplevel :load-toplevel :execute) (unless (find-package "AOC.QUICKUTILS") (defpackage "AOC.QUICKUTILS" (:documentation "Package that contains Quickutil utility functions.") (:use #:cl)))) (in-package "AOC.QUICKUTILS") (when (boundp '*utilities*) (setf *utilities* (union *utilities* '(:COPY-ARRAY :COPY-HASH-TABLE :DIVF :FLATTEN :HASH-TABLE-ALIST :MAPHASH-KEYS :HASH-TABLE-KEYS :MAPHASH-VALUES :HASH-TABLE-VALUES :HASH-TABLE-KEY-EXISTS-P :IF-LET :IOTA :MAKE-KEYWORD :MKSTR :MULF :NCYCLE :SYMB :VOID :WHEN-LET :STRING-DESIGNATOR :WITH-GENSYMS)))) (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))) "Returns an undisplaced copy of `array`, with same `fill-pointer` and adjustability (if any) as the original, unless overridden by the keyword arguments." (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)) (defun copy-hash-table (table &key key test size rehash-size rehash-threshold) "Returns a copy of hash table `table`, with the same keys and values as the `table`. The copy has the same properties as the original, unless overridden by the keyword arguments. Before each of the original values is set into the new hash-table, `key` is invoked on the value. As `key` defaults to `cl:identity`, a shallow copy is returned by default." (setf key (or key 'identity)) (setf test (or test (hash-table-test table))) (setf size (or size (hash-table-size table))) (setf rehash-size (or rehash-size (hash-table-rehash-size table))) (setf rehash-threshold (or rehash-threshold (hash-table-rehash-threshold table))) (let ((copy (make-hash-table :test test :size size :rehash-size rehash-size :rehash-threshold rehash-threshold))) (maphash (lambda (k v) (setf (gethash k copy) (funcall key v))) table) copy)) (define-modify-macro divf (&optional (1/ratio 2)) / "A modifying version of division, similar to `decf`.") (defun flatten (&rest xs) "Flatten (and append) all lists `xs` completely." (labels ((rec (xs acc) (cond ((null xs) acc) ((consp xs) (rec (car xs) (rec (cdr xs) acc))) (t (cons xs acc))))) (rec xs nil))) (defun hash-table-alist (table) "Returns an association list containing the keys and values of hash table `table`." (let ((alist nil)) (maphash (lambda (k v) (push (cons k v) alist)) table) alist)) (declaim (inline maphash-keys)) (defun maphash-keys (function table) "Like `maphash`, but calls `function` with each key in the hash table `table`." (maphash (lambda (k v) (declare (ignore v)) (funcall function k)) table)) (defun hash-table-keys (table) "Returns a list containing the keys of hash table `table`." (let ((keys nil)) (maphash-keys (lambda (k) (push k keys)) table) keys)) (declaim (inline maphash-values)) (defun maphash-values (function table) "Like `maphash`, but calls `function` with each value in the hash table `table`." (maphash (lambda (k v) (declare (ignore k)) (funcall function v)) table)) (defun hash-table-values (table) "Returns a list containing the values of hash table `table`." (let ((values nil)) (maphash-values (lambda (v) (push v values)) table) values)) (defun hash-table-key-exists-p (hash-table key) "Does `key` exist in `hash-table`?" (nth-value 1 (gethash key hash-table))) (defmacro if-let (bindings &body (then-form &optional else-form)) "Creates new variable bindings, and conditionally executes either `then-form` or `else-form`. `else-form` defaults to `nil`. `bindings` must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) All initial-forms are executed sequentially in the specified order. Then all the variables are bound to the corresponding values. If all variables were bound to true values, the `then-form` is executed with the bindings in effect, otherwise the `else-form` is executed with the bindings in effect." (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings)) (variables (mapcar #'car binding-list))) `(let ,binding-list (if (and ,@variables) ,then-form ,else-form)))) (declaim (inline iota)) (defun iota (n &key (start 0) (step 1)) "Return a list of `n` numbers, starting from `start` (with numeric contagion from `step` applied), each consequtive number being the sum of the previous one and `step`. `start` defaults to `0` and `step` to `1`. Examples: (iota 4) => (0 1 2 3) (iota 3 :start 1 :step 1.0) => (1.0 2.0 3.0) (iota 3 :start -1 :step -1/2) => (-1 -3/2 -2)" (declare (type (integer 0) n) (number start step)) (loop repeat n : get numeric contagion right for the first element too for i = (+ (- (+ start step) step)) then (+ i step) collect i)) (defun make-keyword (name) "Interns the string designated by `name` in the `keyword` package." (intern (string name) :keyword)) (defun mkstr (&rest args) "Receives any number of objects (string, symbol, keyword, char, number), extracts all printed representations, and concatenates them all into one string. Extracted from _On Lisp_, chapter 4." (with-output-to-string (s) (dolist (a args) (princ a s)))) (define-modify-macro mulf (&optional (ratio 2)) * "A modifying version of multiplication, similar to `incf`.") (defun ncycle (list) "Mutate `list` into a circlular list." (nconc list list)) (defun symb (&rest args) "Receives any number of objects, concatenates all into one string with `#'mkstr` and converts them to symbol. Extracted from _On Lisp_, chapter 4. See also: `symbolicate`" (values (intern (apply #'mkstr args)))) (defun void (&rest args) "Do absolutely nothing, and return absolutely nothing." (declare (ignore args)) (values)) (defmacro when-let (bindings &body forms) "Creates new variable bindings, and conditionally executes FORMS. BINDINGS must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) All initial-forms are executed sequentially in the specified order. Then all the variables are bound to the corresponding values. If all variables were bound to true values, then FORMS are executed as an implicit PROGN." (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings)) (variables (mapcar #'car binding-list))) `(let ,binding-list (when (and ,@variables) ,@forms)))) (defmacro when-let* (bindings &body forms) "Creates new variable bindings, and conditionally executes FORMS. BINDINGS must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) Each initial-form is executed in turn, and the variable bound to the corresponding value. Initial-form expressions can refer to variables previously bound by the WHEN-LET*. Execution of WHEN-LET* stops immediately if any initial-form evaluates to NIL. If all initial-forms evaluate to true, then FORMS are executed as an implicit PROGN." (let ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings))) (labels ((bind (bindings forms) (if bindings `((let (,(car bindings)) (when ,(caar bindings) ,@(bind (cdr bindings) forms)))) forms))) `(let (,(car binding-list)) (when ,(caar binding-list) ,@(bind (cdr binding-list) forms)))))) (deftype string-designator () "A string designator type. A string designator is either a string, a symbol, or a character." `(or symbol string character)) (defmacro with-gensyms (names &body forms) "Binds each variable named by a symbol in `names` to a unique symbol around `forms`. Each of `names` must either be either a symbol, or of the form: (symbol string-designator) Bare symbols appearing in `names` are equivalent to: (symbol symbol) The string-designator is used as the argument to `gensym` when constructing the unique symbol the named variable will be bound to." `(let ,(mapcar (lambda (name) (multiple-value-bind (symbol string) (etypecase name (symbol (values name (symbol-name name))) ((cons symbol (cons string-designator null)) (values (first name) (string (second name))))) `(,symbol (gensym ,string)))) names) ,@forms)) (defmacro with-unique-names (names &body forms) "Binds each variable named by a symbol in `names` to a unique symbol around `forms`. Each of `names` must either be either a symbol, or of the form: (symbol string-designator) Bare symbols appearing in `names` are equivalent to: (symbol symbol) The string-designator is used as the argument to `gensym` when constructing the unique symbol the named variable will be bound to." `(with-gensyms ,names ,@forms)) (eval-when (:compile-toplevel :load-toplevel :execute) (export '(copy-array copy-hash-table divf flatten hash-table-alist hash-table-keys hash-table-values hash-table-key-exists-p if-let iota make-keyword mkstr mulf ncycle symb void when-let when-let* with-gensyms with-unique-names))) ;;;; END OF quickutils.lisp ;;;;
null
https://raw.githubusercontent.com/iamFIREcracker/adventofcode/cb3831581d95913d1ef1baf7b09b2562fd78c66e/vendor/quickutils.lisp
lisp
This file was automatically generated by Quickutil. See for details. To regenerate: END OF quickutils.lisp ;;;;
( qtlc : save - utils - as " quickutils.lisp " : utilities ' (: COPY - ARRAY : COPY - HASH - TABLE : : FLATTEN : HASH - TABLE - ALIST : HASH - TABLE - KEYS : HASH - TABLE - VALUES : HASH - TABLE - KEY - EXISTS - P : IF - LET : IOTA : MAKE - KEYWORD : MKSTR : : NCYCLE : SYMB : VOID : WHEN - LET : WITH - GENSYMS ) : ensure - package T : package " AOC.QUICKUTILS " ) (eval-when (:compile-toplevel :load-toplevel :execute) (unless (find-package "AOC.QUICKUTILS") (defpackage "AOC.QUICKUTILS" (:documentation "Package that contains Quickutil utility functions.") (:use #:cl)))) (in-package "AOC.QUICKUTILS") (when (boundp '*utilities*) (setf *utilities* (union *utilities* '(:COPY-ARRAY :COPY-HASH-TABLE :DIVF :FLATTEN :HASH-TABLE-ALIST :MAPHASH-KEYS :HASH-TABLE-KEYS :MAPHASH-VALUES :HASH-TABLE-VALUES :HASH-TABLE-KEY-EXISTS-P :IF-LET :IOTA :MAKE-KEYWORD :MKSTR :MULF :NCYCLE :SYMB :VOID :WHEN-LET :STRING-DESIGNATOR :WITH-GENSYMS)))) (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))) "Returns an undisplaced copy of `array`, with same `fill-pointer` and adjustability (if any) as the original, unless overridden by the keyword arguments." (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)) (defun copy-hash-table (table &key key test size rehash-size rehash-threshold) "Returns a copy of hash table `table`, with the same keys and values as the `table`. The copy has the same properties as the original, unless overridden by the keyword arguments. Before each of the original values is set into the new hash-table, `key` is invoked on the value. As `key` defaults to `cl:identity`, a shallow copy is returned by default." (setf key (or key 'identity)) (setf test (or test (hash-table-test table))) (setf size (or size (hash-table-size table))) (setf rehash-size (or rehash-size (hash-table-rehash-size table))) (setf rehash-threshold (or rehash-threshold (hash-table-rehash-threshold table))) (let ((copy (make-hash-table :test test :size size :rehash-size rehash-size :rehash-threshold rehash-threshold))) (maphash (lambda (k v) (setf (gethash k copy) (funcall key v))) table) copy)) (define-modify-macro divf (&optional (1/ratio 2)) / "A modifying version of division, similar to `decf`.") (defun flatten (&rest xs) "Flatten (and append) all lists `xs` completely." (labels ((rec (xs acc) (cond ((null xs) acc) ((consp xs) (rec (car xs) (rec (cdr xs) acc))) (t (cons xs acc))))) (rec xs nil))) (defun hash-table-alist (table) "Returns an association list containing the keys and values of hash table `table`." (let ((alist nil)) (maphash (lambda (k v) (push (cons k v) alist)) table) alist)) (declaim (inline maphash-keys)) (defun maphash-keys (function table) "Like `maphash`, but calls `function` with each key in the hash table `table`." (maphash (lambda (k v) (declare (ignore v)) (funcall function k)) table)) (defun hash-table-keys (table) "Returns a list containing the keys of hash table `table`." (let ((keys nil)) (maphash-keys (lambda (k) (push k keys)) table) keys)) (declaim (inline maphash-values)) (defun maphash-values (function table) "Like `maphash`, but calls `function` with each value in the hash table `table`." (maphash (lambda (k v) (declare (ignore k)) (funcall function v)) table)) (defun hash-table-values (table) "Returns a list containing the values of hash table `table`." (let ((values nil)) (maphash-values (lambda (v) (push v values)) table) values)) (defun hash-table-key-exists-p (hash-table key) "Does `key` exist in `hash-table`?" (nth-value 1 (gethash key hash-table))) (defmacro if-let (bindings &body (then-form &optional else-form)) "Creates new variable bindings, and conditionally executes either `then-form` or `else-form`. `else-form` defaults to `nil`. `bindings` must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) All initial-forms are executed sequentially in the specified order. Then all the variables are bound to the corresponding values. If all variables were bound to true values, the `then-form` is executed with the bindings in effect, otherwise the `else-form` is executed with the bindings in effect." (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings)) (variables (mapcar #'car binding-list))) `(let ,binding-list (if (and ,@variables) ,then-form ,else-form)))) (declaim (inline iota)) (defun iota (n &key (start 0) (step 1)) "Return a list of `n` numbers, starting from `start` (with numeric contagion from `step` applied), each consequtive number being the sum of the previous one and `step`. `start` defaults to `0` and `step` to `1`. Examples: (iota 4) => (0 1 2 3) (iota 3 :start 1 :step 1.0) => (1.0 2.0 3.0) (iota 3 :start -1 :step -1/2) => (-1 -3/2 -2)" (declare (type (integer 0) n) (number start step)) (loop repeat n : get numeric contagion right for the first element too for i = (+ (- (+ start step) step)) then (+ i step) collect i)) (defun make-keyword (name) "Interns the string designated by `name` in the `keyword` package." (intern (string name) :keyword)) (defun mkstr (&rest args) "Receives any number of objects (string, symbol, keyword, char, number), extracts all printed representations, and concatenates them all into one string. Extracted from _On Lisp_, chapter 4." (with-output-to-string (s) (dolist (a args) (princ a s)))) (define-modify-macro mulf (&optional (ratio 2)) * "A modifying version of multiplication, similar to `incf`.") (defun ncycle (list) "Mutate `list` into a circlular list." (nconc list list)) (defun symb (&rest args) "Receives any number of objects, concatenates all into one string with `#'mkstr` and converts them to symbol. Extracted from _On Lisp_, chapter 4. See also: `symbolicate`" (values (intern (apply #'mkstr args)))) (defun void (&rest args) "Do absolutely nothing, and return absolutely nothing." (declare (ignore args)) (values)) (defmacro when-let (bindings &body forms) "Creates new variable bindings, and conditionally executes FORMS. BINDINGS must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) All initial-forms are executed sequentially in the specified order. Then all the variables are bound to the corresponding values. If all variables were bound to true values, then FORMS are executed as an implicit PROGN." (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings)) (variables (mapcar #'car binding-list))) `(let ,binding-list (when (and ,@variables) ,@forms)))) (defmacro when-let* (bindings &body forms) "Creates new variable bindings, and conditionally executes FORMS. BINDINGS must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) Each initial-form is executed in turn, and the variable bound to the corresponding value. Initial-form expressions can refer to variables previously bound by the WHEN-LET*. Execution of WHEN-LET* stops immediately if any initial-form evaluates to NIL. If all initial-forms evaluate to true, then FORMS are executed as an implicit PROGN." (let ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings))) (labels ((bind (bindings forms) (if bindings `((let (,(car bindings)) (when ,(caar bindings) ,@(bind (cdr bindings) forms)))) forms))) `(let (,(car binding-list)) (when ,(caar binding-list) ,@(bind (cdr binding-list) forms)))))) (deftype string-designator () "A string designator type. A string designator is either a string, a symbol, or a character." `(or symbol string character)) (defmacro with-gensyms (names &body forms) "Binds each variable named by a symbol in `names` to a unique symbol around `forms`. Each of `names` must either be either a symbol, or of the form: (symbol string-designator) Bare symbols appearing in `names` are equivalent to: (symbol symbol) The string-designator is used as the argument to `gensym` when constructing the unique symbol the named variable will be bound to." `(let ,(mapcar (lambda (name) (multiple-value-bind (symbol string) (etypecase name (symbol (values name (symbol-name name))) ((cons symbol (cons string-designator null)) (values (first name) (string (second name))))) `(,symbol (gensym ,string)))) names) ,@forms)) (defmacro with-unique-names (names &body forms) "Binds each variable named by a symbol in `names` to a unique symbol around `forms`. Each of `names` must either be either a symbol, or of the form: (symbol string-designator) Bare symbols appearing in `names` are equivalent to: (symbol symbol) The string-designator is used as the argument to `gensym` when constructing the unique symbol the named variable will be bound to." `(with-gensyms ,names ,@forms)) (eval-when (:compile-toplevel :load-toplevel :execute) (export '(copy-array copy-hash-table divf flatten hash-table-alist hash-table-keys hash-table-values hash-table-key-exists-p if-let iota make-keyword mkstr mulf ncycle symb void when-let when-let* with-gensyms with-unique-names)))
e0aa38622e199087927e7688140e0b3d141c61f7808c1ab61a6a94192247c969
8l/asif
runEquivTest.hs
import System.Environment (getArgs) import Language.FOmega.Test.Derivation (newBuiltinQCfg) import Language.FOmega.Syntax import Language.FOmega.Derivation (TyError(..), runM, tc, runQ, expandQuotations) import Language.FOmega.Parse (loadPgmFile, parseExpr) Right _fst = parseExpr "\\x:*. \\y:*. x" Right _snd = parseExpr "\\x:*. \\y:*. y" unTyError :: Either TyError a -> IO a unTyError = either (fail . show) return runEquivTest tm = do qCfg <- newBuiltinQCfg der <- unTyError =<< runM qCfg [] (tc tm) {-- Type check --} tm <- runQ (expandQuotations der) qCfg {-- Expand quotations --} - select first term - - select second term - return $ if a == b then "Succeeded." else unlines [ "Failed." , "Not alpha-equivalent: " , " " ++ take 25 (show a) ++ "..." , " " ++ take 25 (show b) ++ "..." ] main = do [nm] <- getArgs src <- loadPgmFile "fomega/lib" nm putStrLn =<< runEquivTest (pgm2Tm src)
null
https://raw.githubusercontent.com/8l/asif/3a0b0909e71a2e19e0773b3c77eadfa753751b41/tests/runEquivTest.hs
haskell
- Type check - - Expand quotations -
import System.Environment (getArgs) import Language.FOmega.Test.Derivation (newBuiltinQCfg) import Language.FOmega.Syntax import Language.FOmega.Derivation (TyError(..), runM, tc, runQ, expandQuotations) import Language.FOmega.Parse (loadPgmFile, parseExpr) Right _fst = parseExpr "\\x:*. \\y:*. x" Right _snd = parseExpr "\\x:*. \\y:*. y" unTyError :: Either TyError a -> IO a unTyError = either (fail . show) return runEquivTest tm = do qCfg <- newBuiltinQCfg - select first term - - select second term - return $ if a == b then "Succeeded." else unlines [ "Failed." , "Not alpha-equivalent: " , " " ++ take 25 (show a) ++ "..." , " " ++ take 25 (show b) ++ "..." ] main = do [nm] <- getArgs src <- loadPgmFile "fomega/lib" nm putStrLn =<< runEquivTest (pgm2Tm src)
6856db39e3de4298b820766388e898a9a6c783dd03804e0d4f44ad47474f0a51
mokus0/junkbox
Steps.hs
# LANGUAGE ParallelListComp # module Monads.Steps where import Control.Monad.Writer import Text.Printf newtype Steps m a = Steps {unSteps :: WriterT [(String, m ())] m a} instance Monad m => Functor (Steps m) where fmap f (Steps x) = Steps (fmap f x) instance Monad m => Monad (Steps m) where fail = Steps . fail return = Steps . return Steps x >>= f = Steps (x >>= unSteps.f) step desc action = Steps (tell [(desc, action)]) runSteps (Steps ss) eval = do (a,steps) <- runWriterT ss b <- eval steps return (a,b) progress disp steps = sequence_ [ do disp i n desc step | (desc, step) <- steps | i <- [1..] :: [Int] ] where n = length steps simpleProgress :: [(String, IO ())] -> IO () simpleProgress = progress (printf "Executing step %d of %d: %s\n")
null
https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/Haskell/Monads/Steps.hs
haskell
# LANGUAGE ParallelListComp # module Monads.Steps where import Control.Monad.Writer import Text.Printf newtype Steps m a = Steps {unSteps :: WriterT [(String, m ())] m a} instance Monad m => Functor (Steps m) where fmap f (Steps x) = Steps (fmap f x) instance Monad m => Monad (Steps m) where fail = Steps . fail return = Steps . return Steps x >>= f = Steps (x >>= unSteps.f) step desc action = Steps (tell [(desc, action)]) runSteps (Steps ss) eval = do (a,steps) <- runWriterT ss b <- eval steps return (a,b) progress disp steps = sequence_ [ do disp i n desc step | (desc, step) <- steps | i <- [1..] :: [Int] ] where n = length steps simpleProgress :: [(String, IO ())] -> IO () simpleProgress = progress (printf "Executing step %d of %d: %s\n")
deff151dcd966fc70b11dc2b120abb6d61c2010a5ac4e9e939b68e62350300b5
VERIMAG-Polyhedra/VPL
Cons.ml
module Cs = Cstr.Rat type 'c t = Cs.t * 'c let triv : 'c Factory.t -> 'c t = fun factory -> (Cs.eq [] Scalar.Rat.z, factory.Factory.top) let mkTriv : 'c Factory.t -> Cstr_type.cmpT -> Scalar.Rat.t -> 'c t = fun factory cmp r -> (Cs.mk cmp [] r, factory.Factory.triv cmp r) let get_c (c,_) = c let get_cert (_,cert) = cert let to_string : (Var.t -> string) -> 'c t -> string = fun varPr (c,_) -> Cs.to_string varPr c let to_string_ext : 'c Factory.t -> (Var.t -> string) -> 'c t -> string = fun factory varPr (c,cert) -> Printf.sprintf "%s: %s" (Cs.to_string varPr c) (factory.Factory.to_string cert) let equal (c1,_) (c2,_) = Cs.equal c1 c2 let implies (c1,_) (c2,_) = Cs.incl c1 c2 let elim : 'c Factory.t -> Var.t -> 'c t -> Cs.t -> Cs.t * 'c t = fun factory x (eq,eq_cert) cstr -> if Cs.Vec.Coeff.cmpz (Cs.Vec.get (Cs.get_v cstr) x) = 0 then (cstr, (Cs.eq [] Scalar.Rat.z, factory.Factory.top)) else let (c, n1, n2) = Cs.elim eq cstr x in let coeff = Scalar.Rat.div n1 n2 |> Scalar.Rat.neg in let cstr = Cs.mulc coeff eq in let cert = factory.Factory.mul coeff eq_cert in (c, (cstr,cert)) let rename : 'c Factory.t -> Var.t -> Var.t -> 'c t -> 'c t = fun factory fromX toY (c,cert) -> let c' = Cs.rename fromX toY c in let cert' = factory.Factory.rename fromX toY cert in (c',cert') let linear_combination_cons : 'c Factory. t -> 'c t list -> (int * Scalar.Rat.t) list -> 'c t = fun factory conss witness -> List.fold_left (fun (cstr_res, cert_res) (i,n) -> let (cstr,cert) = List.nth conss i in Cs.add cstr_res (Cs.mulc n cstr) , factory.Factory.add cert_res (factory.Factory.mul n cert)) (triv factory) witness let linear_combination_cert : 'c Factory. t -> 'c t list -> (int * Scalar.Rat.t) list -> 'c = fun factory conss witness -> try List.fold_left (fun res (i,n) -> let cert = List.nth conss i |> get_cert in factory.Factory.add res (factory.Factory.mul n cert)) factory.Factory.top witness with _ -> Stdlib.invalid_arg "Cons.linear_combination" let add : 'c Factory.t -> 'c t -> 'c t -> 'c t = fun factory (c1,cert1) (c2,cert2)-> (Cs.add c1 c2, factory.Factory.add cert1 cert2) let mul : 'c Factory.t -> Scalar.Rat.t -> 'c t -> 'c t = fun factory r (c,cert) -> (Cs.mulc r c, factory.Factory.mul r cert) let split : 'c Factory.t -> 'c t -> 'c t * 'c t = fun factory eq -> match get_c eq |> Cs.get_typ with | Cstr_type.Le | Cstr_type.Lt -> Stdlib.invalid_arg "Cons.split" | Cstr_type.Eq -> let triv = mkTriv factory Cstr_type.Le Scalar.Rat.z in let up = add factory eq triv in let low = add factory (mul factory Scalar.Rat.negU eq) triv in (up,low) let normalize : 'c Factory.t -> 'c t -> 'c t = fun factory (cstr, cert) -> let gcd = Cs.Vec.gcd (Cs.get_v cstr) in mul factory gcd (cstr, cert) let elimc : 'c Factory.t -> Var.t -> 'c t -> 'c t -> 'c t = fun factory x (c1,cert1) (c2,cert2) -> let (c, n1, n2) = Cs.elim c1 c2 x in (c, Factory.linear_combination factory [cert1, n1; cert2, n2]) |> normalize factory type ('c1,'c2) discr_t = 'c1 * 'c2 type ('c1,'c2) discr_cert = (('c1,'c2) discr_t) Factory.t let discr_factory : 'c1 Factory.t -> 'c2 Factory.t -> ('c1,'c2) discr_cert = fun fac1 fac2 -> Factory.({ name = "discr"; top = (fac1.top, fac2.top); triv = (fun cmp r -> fac1.triv cmp r, fac2.triv cmp r); add = (fun (c1,c2) (c1',c2') -> fac1.add c1 c1', fac2.add c2 c2'); mul = (fun r (c,c') -> fac1.mul r c, fac2.mul r c'); merge = (fun (c1,c2) (c1',c2') -> fac1.merge c1 c1', fac2.merge c2 c2'); to_le = (fun (c,c') -> fac1.to_le c, fac2.to_le c'); to_string = (fun (c,c') -> (fac1.to_string c) ^ "( ; )" ^ (fac2.to_string c')); rename = (fun fromX toY (c,c') -> fac1.rename fromX toY c, fac2.rename fromX toY c'); }) let joinSetup_1 : 'c2 Factory.t -> Var.t -> Var.t option Rtree.t -> Var.t -> 'c1 t -> Var.t * Var.t option Rtree.t * (('c1,'c2) discr_t) t = fun factory2 nxt relocTbl alpha (c,cert) -> let (nxt1, vec1, relocTbl1) = Cs.Vec.shift nxt (Cs.get_v c) relocTbl in let (vec2, alphaCoef, cst) = (vec1, Cs.Vec.Coeff.neg (Cs.get_c c), Cs.Vec.Coeff.z) in let c' = {c with Cs.v = Cs.Vec.set vec2 alpha alphaCoef; Cs.c = cst} in let cert' = (cert, factory2.Factory.top) in (nxt1, relocTbl1, (c',cert')) let joinSetup_2 : 'c1 Factory.t -> Var.t -> Var.t option Rtree.t -> Var.t -> 'c2 t -> Var.t * Var.t option Rtree.t * (('c1,'c2) discr_t) t = fun factory1 nxt relocTbl alpha (c,cert) -> let (nxt1, vec1, relocTbl1) = Cs.Vec.shift nxt (Cs.get_v c) relocTbl in let (vec2, alphaCoef, cst) = (Cs.Vec.add (Cs.get_v c) (Cs.Vec.neg vec1), Cs.get_c c, Cs.get_c c) in let c' = {c with Cs.v = Cs.Vec.set vec2 alpha alphaCoef; Cs.c = cst} in let cert' = (factory1.Factory.top, cert) in (nxt1, relocTbl1, (c',cert')) let minkowskiSetup_1 : 'c2 Factory.t -> Var.t -> Var.t option Rtree.t -> 'c1 t -> Var.t * Var.t option Rtree.t * (('c1,'c2) discr_t) t = fun factory2 nxt relocTbl (c,cert) -> let (nxt1, vec1, relocTbl1) = Cs.Vec.shift nxt (Cs.get_v c) relocTbl in let c' = {c with Cs.v = vec1} in let cert' = (cert, factory2.Factory.top) in (nxt1, relocTbl1, (c',cert')) let minkowskiSetup_2 : 'c1 Factory.t -> Var.t -> Var.t option Rtree.t -> 'c2 t -> Var.t * Var.t option Rtree.t * (('c1,'c2) discr_t) t = fun factory1 nxt relocTbl (c,cert) -> let (nxt1, vec1, relocTbl1) = Cs.Vec.shift nxt (Cs.get_v c) relocTbl in let vec2 = Cs.Vec.add (Cs.get_v c) (Cs.Vec.neg vec1) in let c' = {c with Cs.v = vec2} in let cert' = (factory1.Factory.top, cert) in (nxt1, relocTbl1, (c',cert')) let rec clean : 'c t list -> 'c t list = function | [] -> [] | (c,cert) :: l -> match Cs.tellProp c with | Cs.Contrad -> invalid_arg "clean: contradictory constraint" | Cs.Trivial -> clean l | Cs.Nothing -> if List.exists (fun (c',_) -> Cs.equal c c') l then clean l else (c,cert) :: clean l let adjust_cert_constant : 'c Factory.t -> 'c t -> Cs.t -> 'c = fun factory (c1,cert1) c2 -> let v1 = Cs.get_v c1 in let v2 = Cs.get_v c2 in match Vector.Rat.isomorph v2 v1 with | Some r -> (* v2 = r.v1 *) begin let cert = let cste = Scalar.Rat.sub (Cs.get_c c2) (Scalar.Rat.mul r (Cs.get_c c1)) in if Cs.get_typ c2 = Cstr_type.Lt && Scalar.Rat.equal r Scalar.Rat.u && Scalar.Rat.equal cste Scalar.Rat.z then cert1 else if Scalar.Rat.lt cste Scalar.Rat.z then factory.Factory.mul r cert1 else let cste_cert = factory.Factory.triv (Cs.get_typ c2) cste in factory.Factory.mul r cert1 |> factory.Factory.add cste_cert in match Cs.get_typ c1, Cs.get_typ c2 with | Cstr_type.Lt, Cstr_type.Le -> factory.Factory.to_le cert | _,_ -> cert end | None -> Stdlib.invalid_arg "Inclusion does not hold"
null
https://raw.githubusercontent.com/VERIMAG-Polyhedra/VPL/cd78d6e7d120508fd5a694bdb01300477e5646f8/ocaml/core/Cons.ml
ocaml
v2 = r.v1
module Cs = Cstr.Rat type 'c t = Cs.t * 'c let triv : 'c Factory.t -> 'c t = fun factory -> (Cs.eq [] Scalar.Rat.z, factory.Factory.top) let mkTriv : 'c Factory.t -> Cstr_type.cmpT -> Scalar.Rat.t -> 'c t = fun factory cmp r -> (Cs.mk cmp [] r, factory.Factory.triv cmp r) let get_c (c,_) = c let get_cert (_,cert) = cert let to_string : (Var.t -> string) -> 'c t -> string = fun varPr (c,_) -> Cs.to_string varPr c let to_string_ext : 'c Factory.t -> (Var.t -> string) -> 'c t -> string = fun factory varPr (c,cert) -> Printf.sprintf "%s: %s" (Cs.to_string varPr c) (factory.Factory.to_string cert) let equal (c1,_) (c2,_) = Cs.equal c1 c2 let implies (c1,_) (c2,_) = Cs.incl c1 c2 let elim : 'c Factory.t -> Var.t -> 'c t -> Cs.t -> Cs.t * 'c t = fun factory x (eq,eq_cert) cstr -> if Cs.Vec.Coeff.cmpz (Cs.Vec.get (Cs.get_v cstr) x) = 0 then (cstr, (Cs.eq [] Scalar.Rat.z, factory.Factory.top)) else let (c, n1, n2) = Cs.elim eq cstr x in let coeff = Scalar.Rat.div n1 n2 |> Scalar.Rat.neg in let cstr = Cs.mulc coeff eq in let cert = factory.Factory.mul coeff eq_cert in (c, (cstr,cert)) let rename : 'c Factory.t -> Var.t -> Var.t -> 'c t -> 'c t = fun factory fromX toY (c,cert) -> let c' = Cs.rename fromX toY c in let cert' = factory.Factory.rename fromX toY cert in (c',cert') let linear_combination_cons : 'c Factory. t -> 'c t list -> (int * Scalar.Rat.t) list -> 'c t = fun factory conss witness -> List.fold_left (fun (cstr_res, cert_res) (i,n) -> let (cstr,cert) = List.nth conss i in Cs.add cstr_res (Cs.mulc n cstr) , factory.Factory.add cert_res (factory.Factory.mul n cert)) (triv factory) witness let linear_combination_cert : 'c Factory. t -> 'c t list -> (int * Scalar.Rat.t) list -> 'c = fun factory conss witness -> try List.fold_left (fun res (i,n) -> let cert = List.nth conss i |> get_cert in factory.Factory.add res (factory.Factory.mul n cert)) factory.Factory.top witness with _ -> Stdlib.invalid_arg "Cons.linear_combination" let add : 'c Factory.t -> 'c t -> 'c t -> 'c t = fun factory (c1,cert1) (c2,cert2)-> (Cs.add c1 c2, factory.Factory.add cert1 cert2) let mul : 'c Factory.t -> Scalar.Rat.t -> 'c t -> 'c t = fun factory r (c,cert) -> (Cs.mulc r c, factory.Factory.mul r cert) let split : 'c Factory.t -> 'c t -> 'c t * 'c t = fun factory eq -> match get_c eq |> Cs.get_typ with | Cstr_type.Le | Cstr_type.Lt -> Stdlib.invalid_arg "Cons.split" | Cstr_type.Eq -> let triv = mkTriv factory Cstr_type.Le Scalar.Rat.z in let up = add factory eq triv in let low = add factory (mul factory Scalar.Rat.negU eq) triv in (up,low) let normalize : 'c Factory.t -> 'c t -> 'c t = fun factory (cstr, cert) -> let gcd = Cs.Vec.gcd (Cs.get_v cstr) in mul factory gcd (cstr, cert) let elimc : 'c Factory.t -> Var.t -> 'c t -> 'c t -> 'c t = fun factory x (c1,cert1) (c2,cert2) -> let (c, n1, n2) = Cs.elim c1 c2 x in (c, Factory.linear_combination factory [cert1, n1; cert2, n2]) |> normalize factory type ('c1,'c2) discr_t = 'c1 * 'c2 type ('c1,'c2) discr_cert = (('c1,'c2) discr_t) Factory.t let discr_factory : 'c1 Factory.t -> 'c2 Factory.t -> ('c1,'c2) discr_cert = fun fac1 fac2 -> Factory.({ name = "discr"; top = (fac1.top, fac2.top); triv = (fun cmp r -> fac1.triv cmp r, fac2.triv cmp r); add = (fun (c1,c2) (c1',c2') -> fac1.add c1 c1', fac2.add c2 c2'); mul = (fun r (c,c') -> fac1.mul r c, fac2.mul r c'); merge = (fun (c1,c2) (c1',c2') -> fac1.merge c1 c1', fac2.merge c2 c2'); to_le = (fun (c,c') -> fac1.to_le c, fac2.to_le c'); to_string = (fun (c,c') -> (fac1.to_string c) ^ "( ; )" ^ (fac2.to_string c')); rename = (fun fromX toY (c,c') -> fac1.rename fromX toY c, fac2.rename fromX toY c'); }) let joinSetup_1 : 'c2 Factory.t -> Var.t -> Var.t option Rtree.t -> Var.t -> 'c1 t -> Var.t * Var.t option Rtree.t * (('c1,'c2) discr_t) t = fun factory2 nxt relocTbl alpha (c,cert) -> let (nxt1, vec1, relocTbl1) = Cs.Vec.shift nxt (Cs.get_v c) relocTbl in let (vec2, alphaCoef, cst) = (vec1, Cs.Vec.Coeff.neg (Cs.get_c c), Cs.Vec.Coeff.z) in let c' = {c with Cs.v = Cs.Vec.set vec2 alpha alphaCoef; Cs.c = cst} in let cert' = (cert, factory2.Factory.top) in (nxt1, relocTbl1, (c',cert')) let joinSetup_2 : 'c1 Factory.t -> Var.t -> Var.t option Rtree.t -> Var.t -> 'c2 t -> Var.t * Var.t option Rtree.t * (('c1,'c2) discr_t) t = fun factory1 nxt relocTbl alpha (c,cert) -> let (nxt1, vec1, relocTbl1) = Cs.Vec.shift nxt (Cs.get_v c) relocTbl in let (vec2, alphaCoef, cst) = (Cs.Vec.add (Cs.get_v c) (Cs.Vec.neg vec1), Cs.get_c c, Cs.get_c c) in let c' = {c with Cs.v = Cs.Vec.set vec2 alpha alphaCoef; Cs.c = cst} in let cert' = (factory1.Factory.top, cert) in (nxt1, relocTbl1, (c',cert')) let minkowskiSetup_1 : 'c2 Factory.t -> Var.t -> Var.t option Rtree.t -> 'c1 t -> Var.t * Var.t option Rtree.t * (('c1,'c2) discr_t) t = fun factory2 nxt relocTbl (c,cert) -> let (nxt1, vec1, relocTbl1) = Cs.Vec.shift nxt (Cs.get_v c) relocTbl in let c' = {c with Cs.v = vec1} in let cert' = (cert, factory2.Factory.top) in (nxt1, relocTbl1, (c',cert')) let minkowskiSetup_2 : 'c1 Factory.t -> Var.t -> Var.t option Rtree.t -> 'c2 t -> Var.t * Var.t option Rtree.t * (('c1,'c2) discr_t) t = fun factory1 nxt relocTbl (c,cert) -> let (nxt1, vec1, relocTbl1) = Cs.Vec.shift nxt (Cs.get_v c) relocTbl in let vec2 = Cs.Vec.add (Cs.get_v c) (Cs.Vec.neg vec1) in let c' = {c with Cs.v = vec2} in let cert' = (factory1.Factory.top, cert) in (nxt1, relocTbl1, (c',cert')) let rec clean : 'c t list -> 'c t list = function | [] -> [] | (c,cert) :: l -> match Cs.tellProp c with | Cs.Contrad -> invalid_arg "clean: contradictory constraint" | Cs.Trivial -> clean l | Cs.Nothing -> if List.exists (fun (c',_) -> Cs.equal c c') l then clean l else (c,cert) :: clean l let adjust_cert_constant : 'c Factory.t -> 'c t -> Cs.t -> 'c = fun factory (c1,cert1) c2 -> let v1 = Cs.get_v c1 in let v2 = Cs.get_v c2 in match Vector.Rat.isomorph v2 v1 with begin let cert = let cste = Scalar.Rat.sub (Cs.get_c c2) (Scalar.Rat.mul r (Cs.get_c c1)) in if Cs.get_typ c2 = Cstr_type.Lt && Scalar.Rat.equal r Scalar.Rat.u && Scalar.Rat.equal cste Scalar.Rat.z then cert1 else if Scalar.Rat.lt cste Scalar.Rat.z then factory.Factory.mul r cert1 else let cste_cert = factory.Factory.triv (Cs.get_typ c2) cste in factory.Factory.mul r cert1 |> factory.Factory.add cste_cert in match Cs.get_typ c1, Cs.get_typ c2 with | Cstr_type.Lt, Cstr_type.Le -> factory.Factory.to_le cert | _,_ -> cert end | None -> Stdlib.invalid_arg "Inclusion does not hold"
823152a42aab9cc4e61c1b2b773eb628f24ce56b3ab2ceeef9916208519805af
codereport/SICP-2020
geoffrey_viola_solutions.rkt
#lang racket Exercise 3.38 . ;; a 3 ! = 6 total permutations 4 different values ;; , , Mary = $ 45 , , Mary = $ 45 ;; , , = $ 50 ;; , , = $ 35 ;; , , = $ 40 , , = $ 40 ;; b ;; Some actors can read the initial balance and write the final amount Peter $ 110 Paul $ 80 ;; Mary $50 ;; ;; Some actors can effectively get skipped , Mary = $ 60 , Mary = $ 40 , = $ 60 , = $ 30 Exercise 3.39 121 : P1->P2 101 : P1->P2 100 : P1 x*x - > P2- > P1 set ! with old 100 value 11 : P1 x*x - > P2 10 + 1 - > P1 set ! x 100 - > P2 set ! 11 Exercise 3.40 1,000,000 : P1->P2 , P2->P1 100 : P1 read all - > P2 - > P2 write 1000 : P2 read all - > P1 - > P2 write 10,000 : P1 read first x - > P2 - > P1 10 * 1000 , P2 reads two x 's - > P1 - > P2 10 * 10 * 100 100,000 : P2 reads first x - > P1 - > P2 10 * 100 * 100 After serialization only 1000000 is possible Exercise 3.41 ;; I disagree. Reading the balance is atomic by definition. ;; It will either read before or after a modification. ;; Therefore, it is correct at the time it is called. Exercise 3.42 . ;; There shouldn't make a difference to the concurrency, ;; since the withdraw and deposit are protected. Exercise 3.47 a ;; placeholder function (define (make-mutex) false) (define (make-semaphore n) (let ((lock (make-mutex)) (taken 0)) (define (semaphore command) (match command ['acquire (begin (lock 'acquire) (if (< taken n) (begin (set! taken (+ taken 1)) (lock 'release)) (begin (lock 'release) (semaphore 'acquire))))] ['release (begin (lock 'acquire) (set! taken (- taken 1)) (lock 'release))])) semaphore))
null
https://raw.githubusercontent.com/codereport/SICP-2020/2d1e60048db89678830d93fcc558a846b7f57b76/Chapter%203.4%20Solutions/geoffrey_viola_solutions.rkt
racket
a b Some actors can read the initial balance and write the final amount Mary $50 Some actors can effectively get skipped I disagree. Reading the balance is atomic by definition. It will either read before or after a modification. Therefore, it is correct at the time it is called. There shouldn't make a difference to the concurrency, since the withdraw and deposit are protected. placeholder function
#lang racket Exercise 3.38 . 3 ! = 6 total permutations 4 different values , , Mary = $ 45 , , Mary = $ 45 , , = $ 50 , , = $ 35 , , = $ 40 , , = $ 40 Peter $ 110 Paul $ 80 , Mary = $ 60 , Mary = $ 40 , = $ 60 , = $ 30 Exercise 3.39 121 : P1->P2 101 : P1->P2 100 : P1 x*x - > P2- > P1 set ! with old 100 value 11 : P1 x*x - > P2 10 + 1 - > P1 set ! x 100 - > P2 set ! 11 Exercise 3.40 1,000,000 : P1->P2 , P2->P1 100 : P1 read all - > P2 - > P2 write 1000 : P2 read all - > P1 - > P2 write 10,000 : P1 read first x - > P2 - > P1 10 * 1000 , P2 reads two x 's - > P1 - > P2 10 * 10 * 100 100,000 : P2 reads first x - > P1 - > P2 10 * 100 * 100 After serialization only 1000000 is possible Exercise 3.41 Exercise 3.42 . Exercise 3.47 a (define (make-mutex) false) (define (make-semaphore n) (let ((lock (make-mutex)) (taken 0)) (define (semaphore command) (match command ['acquire (begin (lock 'acquire) (if (< taken n) (begin (set! taken (+ taken 1)) (lock 'release)) (begin (lock 'release) (semaphore 'acquire))))] ['release (begin (lock 'acquire) (set! taken (- taken 1)) (lock 'release))])) semaphore))
12d392a8c8c286aa2e1d2840afd1a2176c42591d74e9032fbbcaad48a50d1058
ghc/packages-dph
DT.hs
{-# OPTIONS -Wall -fno-warn-orphans -fno-warn-missing-signatures #-} # LANGUAGE CPP # #include "fusion-phases.h" -- | Distribution of Segment Descriptors module Data.Array.Parallel.Unlifted.Distributed.Data.USegd.DT where import Data.Array.Parallel.Unlifted.Distributed.Data.Vector () import Data.Array.Parallel.Unlifted.Distributed.Primitive import Data.Array.Parallel.Unlifted.Sequential.USegd (USegd) import Data.Array.Parallel.Unlifted.Sequential.Vector (Vector) import qualified Data.Array.Parallel.Unlifted.Sequential.USegd as USegd import Prelude as P import Data.Array.Parallel.Pretty import Control.Monad instance DT USegd where data Dist USegd = DUSegd !(Dist (Vector Int)) -- segment lengths !(Dist (Vector Int)) -- segment indices !(Dist Int) -- number of elements in this chunk data MDist USegd s = MDUSegd !(MDist (Vector Int) s) -- segment lengths !(MDist (Vector Int) s) -- segment indices !(MDist Int s) -- number of elements in this chunk indexD str (DUSegd lens idxs eles) i = USegd.mkUSegd (indexD (str ++ "/indexD[USegd]") lens i) (indexD (str ++ "/indexD[USegd]") idxs i) (indexD (str ++ "/indexD[USegd]") eles i) # INLINE_DIST indexD # newMD g = liftM3 MDUSegd (newMD g) (newMD g) (newMD g) # INLINE_DIST newMD # readMD (MDUSegd lens idxs eles) i = liftM3 USegd.mkUSegd (readMD lens i) (readMD idxs i) (readMD eles i) {-# INLINE_DIST readMD #-} writeMD (MDUSegd lens idxs eles) i segd = do writeMD lens i (USegd.takeLengths segd) writeMD idxs i (USegd.takeIndices segd) writeMD eles i (USegd.takeElements segd) # INLINE_DIST writeMD # unsafeFreezeMD (MDUSegd lens idxs eles) = liftM3 DUSegd (unsafeFreezeMD lens) (unsafeFreezeMD idxs) (unsafeFreezeMD eles) # INLINE_DIST unsafeFreezeMD # deepSeqD segd z = deepSeqD (USegd.takeLengths segd) $ deepSeqD (USegd.takeIndices segd) $ deepSeqD (USegd.takeElements segd) z # INLINE_DIST deepSeqD # sizeD (DUSegd _ _ eles) = sizeD eles # INLINE_DIST sizeD # sizeMD (MDUSegd _ _ eles) = sizeMD eles # INLINE_DIST sizeMD # measureD segd = "Segd " P.++ show (USegd.length segd) P.++ " " P.++ show (USegd.takeElements segd) {-# NOINLINE measureD #-} NOINLINE because this is only used for debugging . instance PprPhysical (Dist USegd) where pprp (DUSegd lens indices elements) = text "DUSegd" $$ (nest 7 $ vcat [ text "lengths: " <+> pprp lens , text "indices: " <+> pprp indices , text "elements:" <+> pprp elements]) # NOINLINE pprp # NOINLINE because this is only used for debugging .
null
https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-prim-par/Data/Array/Parallel/Unlifted/Distributed/Data/USegd/DT.hs
haskell
# OPTIONS -Wall -fno-warn-orphans -fno-warn-missing-signatures # | Distribution of Segment Descriptors segment lengths segment indices number of elements in this chunk segment lengths segment indices number of elements in this chunk # INLINE_DIST readMD # # NOINLINE measureD #
# LANGUAGE CPP # #include "fusion-phases.h" module Data.Array.Parallel.Unlifted.Distributed.Data.USegd.DT where import Data.Array.Parallel.Unlifted.Distributed.Data.Vector () import Data.Array.Parallel.Unlifted.Distributed.Primitive import Data.Array.Parallel.Unlifted.Sequential.USegd (USegd) import Data.Array.Parallel.Unlifted.Sequential.Vector (Vector) import qualified Data.Array.Parallel.Unlifted.Sequential.USegd as USegd import Prelude as P import Data.Array.Parallel.Pretty import Control.Monad instance DT USegd where data Dist USegd data MDist USegd s indexD str (DUSegd lens idxs eles) i = USegd.mkUSegd (indexD (str ++ "/indexD[USegd]") lens i) (indexD (str ++ "/indexD[USegd]") idxs i) (indexD (str ++ "/indexD[USegd]") eles i) # INLINE_DIST indexD # newMD g = liftM3 MDUSegd (newMD g) (newMD g) (newMD g) # INLINE_DIST newMD # readMD (MDUSegd lens idxs eles) i = liftM3 USegd.mkUSegd (readMD lens i) (readMD idxs i) (readMD eles i) writeMD (MDUSegd lens idxs eles) i segd = do writeMD lens i (USegd.takeLengths segd) writeMD idxs i (USegd.takeIndices segd) writeMD eles i (USegd.takeElements segd) # INLINE_DIST writeMD # unsafeFreezeMD (MDUSegd lens idxs eles) = liftM3 DUSegd (unsafeFreezeMD lens) (unsafeFreezeMD idxs) (unsafeFreezeMD eles) # INLINE_DIST unsafeFreezeMD # deepSeqD segd z = deepSeqD (USegd.takeLengths segd) $ deepSeqD (USegd.takeIndices segd) $ deepSeqD (USegd.takeElements segd) z # INLINE_DIST deepSeqD # sizeD (DUSegd _ _ eles) = sizeD eles # INLINE_DIST sizeD # sizeMD (MDUSegd _ _ eles) = sizeMD eles # INLINE_DIST sizeMD # measureD segd = "Segd " P.++ show (USegd.length segd) P.++ " " P.++ show (USegd.takeElements segd) NOINLINE because this is only used for debugging . instance PprPhysical (Dist USegd) where pprp (DUSegd lens indices elements) = text "DUSegd" $$ (nest 7 $ vcat [ text "lengths: " <+> pprp lens , text "indices: " <+> pprp indices , text "elements:" <+> pprp elements]) # NOINLINE pprp # NOINLINE because this is only used for debugging .
957318a1392d73de98058078010359a50dc8172205411165eb7957d635a60c77
narkisr-deprecated/core
api.clj
(ns re-core.test.api "These scenarios describe how the API works and mainly validates routing" (:refer-clojure :exclude [type]) (:require [re-core.model :as m] [re-core.fixtures.data :as d] [re-core.api.users :refer (into-persisted)] [re-core.jobs :as jobs] [re-core.persistency.systems :as s] [clojure.core.strint :refer (<<)] [cemerick.friend :as friend] [re-core.roles :as roles] [re-core.persistency [types :as t] [users :as u]]) (:use midje.sweet ring.mock.request [re-core.api :only (app)])) (def non-sec-app (app false)) (fact "system get" (non-sec-app (request :get (<< "/systems/1"))) => (contains {:status 200}) (provided (s/get-system "1") => "foo")) (fact "getting host type" (non-sec-app (header (request :get (<< "/systems/1/type")) "accept" "application/json")) => (contains {:status 200}) (provided (s/get-system "1") => {:type "redis"} (t/get-type "redis") => {:classes {:redis {:append true}}})) (let [machine {:type "redis" :machine {:host "foo"}} type {:run-opts nil :classes {:redis {}}}] (fact "provisioning job" (non-sec-app (request :post "/jobs/provision/1" {})) => (contains {:status 200}) (provided (u/op-allowed? "provision" nil) => true (s/system-exists? "1") => true (s/get-system "1") => machine (s/get-system "1" :env) => :dev (t/get-type "redis") => type (jobs/enqueue "provision" {:identity "1" :args [type (assoc machine :system-id 1)] :tid nil :env :dev :user nil}) => nil))) (fact "staging job" (non-sec-app (request :post "/jobs/stage/1")) => (contains {:status 200}) (provided (u/op-allowed? "stage" nil) => true (s/system-exists? "1") => true (t/get-type "redis") => {:puppet-module "bar"} (s/get-system "1") => {:type "redis"} (s/get-system "1" :env) => :dev (jobs/enqueue "stage" {:identity "1" :args [{:puppet-module "bar"} {:system-id 1 :type "redis"}] :tid nil :env :dev :user nil}) => nil)) (fact "creation job" (non-sec-app (request :post "/jobs/create/1")) => (contains {:status 200}) (provided (u/op-allowed? "create" nil) => true (s/system-exists? "1") => true (s/get-system "1") => {} (s/get-system "1" :env) => :dev (jobs/enqueue "create" {:identity "1" :args [{:system-id 1}] :tid nil :env :dev :user nil}) => nil)) (let [user (merge d/admin {:roles ["admin"] :envs ["dev" "qa"]}) ops-vec (into [] m/operations)] (fact "user conversion" (dissoc (into-persisted user) :password) => {:envs [:dev :qa] :roles #{:re-core.roles/admin} :username "admin" :operations ops-vec} (into-persisted (dissoc user :password)) => {:envs [:dev :qa] :roles #{:re-core.roles/admin} :username "admin" :operations ops-vec}))
null
https://raw.githubusercontent.com/narkisr-deprecated/core/85b4a768ef4b3a4eae86695bce36d270dd51dbae/test/re_core/test/api.clj
clojure
(ns re-core.test.api "These scenarios describe how the API works and mainly validates routing" (:refer-clojure :exclude [type]) (:require [re-core.model :as m] [re-core.fixtures.data :as d] [re-core.api.users :refer (into-persisted)] [re-core.jobs :as jobs] [re-core.persistency.systems :as s] [clojure.core.strint :refer (<<)] [cemerick.friend :as friend] [re-core.roles :as roles] [re-core.persistency [types :as t] [users :as u]]) (:use midje.sweet ring.mock.request [re-core.api :only (app)])) (def non-sec-app (app false)) (fact "system get" (non-sec-app (request :get (<< "/systems/1"))) => (contains {:status 200}) (provided (s/get-system "1") => "foo")) (fact "getting host type" (non-sec-app (header (request :get (<< "/systems/1/type")) "accept" "application/json")) => (contains {:status 200}) (provided (s/get-system "1") => {:type "redis"} (t/get-type "redis") => {:classes {:redis {:append true}}})) (let [machine {:type "redis" :machine {:host "foo"}} type {:run-opts nil :classes {:redis {}}}] (fact "provisioning job" (non-sec-app (request :post "/jobs/provision/1" {})) => (contains {:status 200}) (provided (u/op-allowed? "provision" nil) => true (s/system-exists? "1") => true (s/get-system "1") => machine (s/get-system "1" :env) => :dev (t/get-type "redis") => type (jobs/enqueue "provision" {:identity "1" :args [type (assoc machine :system-id 1)] :tid nil :env :dev :user nil}) => nil))) (fact "staging job" (non-sec-app (request :post "/jobs/stage/1")) => (contains {:status 200}) (provided (u/op-allowed? "stage" nil) => true (s/system-exists? "1") => true (t/get-type "redis") => {:puppet-module "bar"} (s/get-system "1") => {:type "redis"} (s/get-system "1" :env) => :dev (jobs/enqueue "stage" {:identity "1" :args [{:puppet-module "bar"} {:system-id 1 :type "redis"}] :tid nil :env :dev :user nil}) => nil)) (fact "creation job" (non-sec-app (request :post "/jobs/create/1")) => (contains {:status 200}) (provided (u/op-allowed? "create" nil) => true (s/system-exists? "1") => true (s/get-system "1") => {} (s/get-system "1" :env) => :dev (jobs/enqueue "create" {:identity "1" :args [{:system-id 1}] :tid nil :env :dev :user nil}) => nil)) (let [user (merge d/admin {:roles ["admin"] :envs ["dev" "qa"]}) ops-vec (into [] m/operations)] (fact "user conversion" (dissoc (into-persisted user) :password) => {:envs [:dev :qa] :roles #{:re-core.roles/admin} :username "admin" :operations ops-vec} (into-persisted (dissoc user :password)) => {:envs [:dev :qa] :roles #{:re-core.roles/admin} :username "admin" :operations ops-vec}))