_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 |
|---|---|---|---|---|---|---|---|---|
5b0c8105a5f88f140e7aedc263a7444afeee66d1b17da16e77f91c18a4219bd0 | mariari/Misc-Lisp-Scripts | chapter2.lisp | (defun range (first &optional (second nil) (step 1))
(macrolet ((for (second word first)
`(loop :for x :from ,second ,word ,first by step
collect x)))
(cond ((and second (> second first)) (for first to second))
(second (for first downto second))
(t (for 0 to first)))))
(defun suffixes (xs)
(when xs
(cons xs (suffixes (cdr xs)))))
(defun suffixes-cps (xs &optional (cps #'identity))
(if (null xs)
(funcall cps xs)
(suffixes-cps (cdr xs) (lambda (x) (funcall cps (cons xs x))))))
(defun suffixes-tco (xs &optional (acc '()))
(if (null xs)
(reverse acc)
(suffixes-tco (cdr xs) (cons xs acc))))
;; (room)
( time ( suffixes - tco ( range 100 ) ) )
;; (print (sb-kernel::dynamic-usage))
| null | https://raw.githubusercontent.com/mariari/Misc-Lisp-Scripts/acecadc75fcbe15e6b97e084d179aacdbbde06a8/book-adaptations/Purely-Functional/chapter2.lisp | lisp | (room)
(print (sb-kernel::dynamic-usage)) | (defun range (first &optional (second nil) (step 1))
(macrolet ((for (second word first)
`(loop :for x :from ,second ,word ,first by step
collect x)))
(cond ((and second (> second first)) (for first to second))
(second (for first downto second))
(t (for 0 to first)))))
(defun suffixes (xs)
(when xs
(cons xs (suffixes (cdr xs)))))
(defun suffixes-cps (xs &optional (cps #'identity))
(if (null xs)
(funcall cps xs)
(suffixes-cps (cdr xs) (lambda (x) (funcall cps (cons xs x))))))
(defun suffixes-tco (xs &optional (acc '()))
(if (null xs)
(reverse acc)
(suffixes-tco (cdr xs) (cons xs acc))))
( time ( suffixes - tco ( range 100 ) ) )
|
4383d088dbec4a24e283590d17293bc63b321b196dd1f0e908c23457fc69cd43 | michalkonecny/aern2 | Frac.hs | module AERN2.Frac
(
module AERN2.Frac.Eval
, module AERN2.Frac.Maximum
, module AERN2.Frac.Integration
, module AERN2.Frac.Type
)
where
import AERN2.Frac.Eval
import AERN2.Frac.Maximum
import AERN2.Frac.Integration
import AERN2.Frac.Ring()
import AERN2.Frac.Field()
import AERN2.Frac.Type
| null | https://raw.githubusercontent.com/michalkonecny/aern2/1c8f12dfcb287bd8e3353802a94865d7c2c121ec/aern2-fun-univariate/src/AERN2/Frac.hs | haskell | module AERN2.Frac
(
module AERN2.Frac.Eval
, module AERN2.Frac.Maximum
, module AERN2.Frac.Integration
, module AERN2.Frac.Type
)
where
import AERN2.Frac.Eval
import AERN2.Frac.Maximum
import AERN2.Frac.Integration
import AERN2.Frac.Ring()
import AERN2.Frac.Field()
import AERN2.Frac.Type
| |
e6a835348c4d6a1cec6f46a8347bcd02d5f8b7b35f1e897963955c4b304da9ae | faylang/fay | records.hs | module Records where
data Person1 = Person1 String String Int
data Person2 = Person2 { fname :: String, sname :: String, age :: Int }
data Person3 = Person3 { slot3 :: String, slot2 :: String, slot1 :: Int }
p1 = Person1 "Chris" "Done" 13
p2 = Person2 "Chris" "Done" 13
p2a = Person2 { fname = "Chris", sname = "Done", age = 13 }
p3 = Person3 "Chris" "Done" 13
main = do
putStrLn (case p1 of Person1 "Chris" "Done" 13 -> "Hello!")
putStrLn (case p2 of Person2 "Chris" "Done" 13 -> "Hello!")
putStrLn (case p2a of Person2 "Chris" "Done" 13 -> "Hello!")
putStrLn (case p3 of Person3 "Chris" "Done" 13 -> "Hello!")
| null | https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/tests/records.hs | haskell | module Records where
data Person1 = Person1 String String Int
data Person2 = Person2 { fname :: String, sname :: String, age :: Int }
data Person3 = Person3 { slot3 :: String, slot2 :: String, slot1 :: Int }
p1 = Person1 "Chris" "Done" 13
p2 = Person2 "Chris" "Done" 13
p2a = Person2 { fname = "Chris", sname = "Done", age = 13 }
p3 = Person3 "Chris" "Done" 13
main = do
putStrLn (case p1 of Person1 "Chris" "Done" 13 -> "Hello!")
putStrLn (case p2 of Person2 "Chris" "Done" 13 -> "Hello!")
putStrLn (case p2a of Person2 "Chris" "Done" 13 -> "Hello!")
putStrLn (case p3 of Person3 "Chris" "Done" 13 -> "Hello!")
| |
ccb651e2881e4842fdfa6b16796c97fdbf74d7bd52c6a7305db725c6877bf0e4 | lexi-lambda/freer-simple | Fresh.hs | module Fresh (module Fresh) where
import Control.Monad.Freer.Fresh (evalFresh, fresh)
import Control.Monad.Freer.Trace (runTrace, trace)
| Generate two fresh values .
--
-- >>> traceFresh
-- Fresh 0
-- Fresh 1
traceFresh :: IO ()
traceFresh = runTrace $ evalFresh 0 $ do
n <- fresh
trace $ "Fresh " ++ show n
n' <- fresh
trace $ "Fresh " ++ show n'
| null | https://raw.githubusercontent.com/lexi-lambda/freer-simple/e5ef0fec4a79585f99c0df8bc9e2e67cc0c0fb4a/examples/src/Fresh.hs | haskell |
>>> traceFresh
Fresh 0
Fresh 1 | module Fresh (module Fresh) where
import Control.Monad.Freer.Fresh (evalFresh, fresh)
import Control.Monad.Freer.Trace (runTrace, trace)
| Generate two fresh values .
traceFresh :: IO ()
traceFresh = runTrace $ evalFresh 0 $ do
n <- fresh
trace $ "Fresh " ++ show n
n' <- fresh
trace $ "Fresh " ++ show n'
|
66bb9a3c5f149d28fa9e8193512bd350d5f41614c7ff460f2a7fdc31d92d94ee | nuvla/api-server | infrastructure_service_template.cljc | (ns sixsq.nuvla.server.resources.spec.infrastructure-service-template
(:require
[clojure.spec.alpha :as s]
[sixsq.nuvla.server.resources.spec.common :as common]
[sixsq.nuvla.server.resources.spec.core :as core]
[sixsq.nuvla.server.util.spec :as su]
[spec-tools.core :as st]))
;; Restrict the href used to create services.
(def service-template-regex #"^infrastructure-service-template/[a-z]+(-[a-z]+)*$")
(s/def ::href (s/and string? #(re-matches service-template-regex %)))
(s/def ::method
(-> (st/spec ::core/identifier)
(assoc :name "method"
:json-schema/description "service creation method"
:json-schema/order 20
:json-schema/hidden true)))
(s/def ::subtype
(-> (st/spec ::core/identifier)
(assoc :name "subtype"
:json-schema/display-name "service subtype"
:json-schema/description "kebab-case identifier for the service subtype"
:json-schema/order 21)))
;;
;; Keys specifications for service-template resources.
;; As this is a "base class" for service-template resources, there
;; is no sense in defining map resources for the resource itself.
;;
(def service-template-keys-spec {:req-un [::subtype
::method]})
(def resource-keys-spec
(su/merge-keys-specs [common/common-attrs
service-template-keys-spec]))
;; Used only to provide metadata resource for collection.
(s/def ::schema
(su/only-keys-maps resource-keys-spec))
(def create-keys-spec
(su/merge-keys-specs [common/create-attrs]))
(def template-keys-spec
(su/merge-keys-specs [common/template-attrs
service-template-keys-spec
{:req-un [::href]}]))
| null | https://raw.githubusercontent.com/nuvla/api-server/a64a61b227733f1a0a945003edf5abaf5150a15c/code/src/sixsq/nuvla/server/resources/spec/infrastructure_service_template.cljc | clojure | Restrict the href used to create services.
Keys specifications for service-template resources.
As this is a "base class" for service-template resources, there
is no sense in defining map resources for the resource itself.
Used only to provide metadata resource for collection. | (ns sixsq.nuvla.server.resources.spec.infrastructure-service-template
(:require
[clojure.spec.alpha :as s]
[sixsq.nuvla.server.resources.spec.common :as common]
[sixsq.nuvla.server.resources.spec.core :as core]
[sixsq.nuvla.server.util.spec :as su]
[spec-tools.core :as st]))
(def service-template-regex #"^infrastructure-service-template/[a-z]+(-[a-z]+)*$")
(s/def ::href (s/and string? #(re-matches service-template-regex %)))
(s/def ::method
(-> (st/spec ::core/identifier)
(assoc :name "method"
:json-schema/description "service creation method"
:json-schema/order 20
:json-schema/hidden true)))
(s/def ::subtype
(-> (st/spec ::core/identifier)
(assoc :name "subtype"
:json-schema/display-name "service subtype"
:json-schema/description "kebab-case identifier for the service subtype"
:json-schema/order 21)))
(def service-template-keys-spec {:req-un [::subtype
::method]})
(def resource-keys-spec
(su/merge-keys-specs [common/common-attrs
service-template-keys-spec]))
(s/def ::schema
(su/only-keys-maps resource-keys-spec))
(def create-keys-spec
(su/merge-keys-specs [common/create-attrs]))
(def template-keys-spec
(su/merge-keys-specs [common/template-attrs
service-template-keys-spec
{:req-un [::href]}]))
|
c4fa82eeeae67451b4760eab5d9261ea1ea14eef752e73c97e96092da9f1f8de | RefactoringTools/HaRe | A1.hs | module AddOneParameter.A1 where
import AddOneParameter.C1
import AddOneParameter.D1
sumSq xs = sum (map sq xs) + sumSquares xs + sumSquares1 xs
main = sumSq [1..4]
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/AddOneParameter/A1.hs | haskell | module AddOneParameter.A1 where
import AddOneParameter.C1
import AddOneParameter.D1
sumSq xs = sum (map sq xs) + sumSquares xs + sumSquares1 xs
main = sumSq [1..4]
| |
c319cd2327aeaa57724fd26385549f2bf52861916d8572af3744c56187a7349f | mysql-otp/mysql-otp | mysql_encode.erl | @private
%% @doc Functions for encoding a term as an SQL literal. This is not really
%% part of the protocol; thus the separate module.
-module(mysql_encode).
-export([encode/1, backslash_escape/1]).
@doc Encodes a term as an ANSI SQL literal so that it can be used to inside
%% a query. In strings only single quotes (') are escaped. If backslash escapes
are enabled for the connection , you should first use backslash_escape/1 to
%% escape backslashes in strings.
-spec encode(term()) -> iodata().
encode(null) -> <<"NULL">>;
encode(Int) when is_integer(Int) ->
integer_to_binary(Int);
encode(Float) when is_float(Float) ->
%% "floats are printed accurately as the shortest, correctly rounded string"
io_lib:format("~w", [Float]);
encode(Bin) when is_binary(Bin) ->
Escaped = binary:replace(Bin, <<"'">>, <<"''">>, [global]),
[$', Escaped, $'];
encode(String) when is_list(String) ->
encode(unicode:characters_to_binary(String));
encode(Bitstring) when is_bitstring(Bitstring) ->
["b'", [ case B of 0 -> $0; 1 -> $1 end || <<B:1>> <= Bitstring ], $'];
encode({decimal, Num}) when is_float(Num); is_integer(Num) ->
encode(Num);
encode({decimal, Str}) when is_binary(Str); is_list(Str) ->
%% Simple injection block
nomatch = re:run(Str, <<"[^0-9.+\\-eE]">>),
Str;
encode({Y, M, D}) ->
io_lib:format("'~4..0b-~2..0b-~2..0b'", [Y, M, D]);
encode({{Y, M, D}, {H, Mi, S}}) when is_integer(S) ->
io_lib:format("'~4..0b-~2..0b-~2..0b ~2..0b:~2..0b:~2..0b'",
[Y, M, D, H, Mi, S]);
encode({{Y, M, D}, {H, Mi, S}}) when is_float(S) ->
io_lib:format("'~4..0b-~2..0b-~2..0b ~2..0b:~2..0b:~9.6.0f'",
[Y, M, D, H, Mi, S]);
encode({D, {H, M, S}}) when D >= 0 ->
Args = [H1 = D * 24 + H, M, S],
if
H1 > 99, is_integer(S) -> io_lib:format("'~b:~2..0b:~2..0b'", Args);
H1 > 99, is_float(S) -> io_lib:format("'~b:~2..0b:~9.6.0f'", Args);
is_integer(S) -> io_lib:format("'~2..0b:~2..0b:~2..0b'", Args);
is_float(S) -> io_lib:format("'~2..0b:~2..0b:~9.6.0f'", Args)
end;
encode({D, {H, M, S}}) when D < 0, is_integer(S) ->
Sec = (D * 24 + H) * 3600 + M * 60 + S,
{D1, {H1, M1, S1}} = calendar:seconds_to_daystime(-Sec),
Args = [H2 = D1 * 24 + H1, M1, S1],
if
H2 > 99 -> io_lib:format("'-~b:~2..0b:~2..0b'", Args);
true -> io_lib:format("'-~2..0b:~2..0b:~2..0b'", Args)
end;
encode({D, {H, M, S}}) when D < 0, is_float(S) ->
trunc(57.654321 ) = 57
57.6543 - 57 = 0.654321
0.0 -> {SInt, 0.0};
{ 58 , 0.345679 }
end,
Sec = (D * 24 + H) * 3600 + M * 60 + SInt1,
{D1, {H1, M1, S1}} = calendar:seconds_to_daystime(-Sec),
Args = [H2 = D1 * 24 + H1, M1, S1 + Frac],
if
H2 > 99 -> io_lib:format("'-~b:~2..0b:~9.6.0f'", Args);
true -> io_lib:format("'-~2..0b:~2..0b:~9.6.0f'", Args)
end.
%% @doc Escapes backslashes with an extra backslash. This is necessary if
%% backslash escapes are enabled in the session.
backslash_escape(String) ->
Bin = iolist_to_binary(String),
binary:replace(Bin, <<"\\">>, <<"\\\\">>, [global]).
| null | https://raw.githubusercontent.com/mysql-otp/mysql-otp/a74aff1e45b5df26240bcf2e30fe2e516cf4e2a0/src/mysql_encode.erl | erlang | @doc Functions for encoding a term as an SQL literal. This is not really
part of the protocol; thus the separate module.
a query. In strings only single quotes (') are escaped. If backslash escapes
escape backslashes in strings.
"floats are printed accurately as the shortest, correctly rounded string"
Simple injection block
@doc Escapes backslashes with an extra backslash. This is necessary if
backslash escapes are enabled in the session. | @private
-module(mysql_encode).
-export([encode/1, backslash_escape/1]).
@doc Encodes a term as an ANSI SQL literal so that it can be used to inside
are enabled for the connection , you should first use backslash_escape/1 to
-spec encode(term()) -> iodata().
encode(null) -> <<"NULL">>;
encode(Int) when is_integer(Int) ->
integer_to_binary(Int);
encode(Float) when is_float(Float) ->
io_lib:format("~w", [Float]);
encode(Bin) when is_binary(Bin) ->
Escaped = binary:replace(Bin, <<"'">>, <<"''">>, [global]),
[$', Escaped, $'];
encode(String) when is_list(String) ->
encode(unicode:characters_to_binary(String));
encode(Bitstring) when is_bitstring(Bitstring) ->
["b'", [ case B of 0 -> $0; 1 -> $1 end || <<B:1>> <= Bitstring ], $'];
encode({decimal, Num}) when is_float(Num); is_integer(Num) ->
encode(Num);
encode({decimal, Str}) when is_binary(Str); is_list(Str) ->
nomatch = re:run(Str, <<"[^0-9.+\\-eE]">>),
Str;
encode({Y, M, D}) ->
io_lib:format("'~4..0b-~2..0b-~2..0b'", [Y, M, D]);
encode({{Y, M, D}, {H, Mi, S}}) when is_integer(S) ->
io_lib:format("'~4..0b-~2..0b-~2..0b ~2..0b:~2..0b:~2..0b'",
[Y, M, D, H, Mi, S]);
encode({{Y, M, D}, {H, Mi, S}}) when is_float(S) ->
io_lib:format("'~4..0b-~2..0b-~2..0b ~2..0b:~2..0b:~9.6.0f'",
[Y, M, D, H, Mi, S]);
encode({D, {H, M, S}}) when D >= 0 ->
Args = [H1 = D * 24 + H, M, S],
if
H1 > 99, is_integer(S) -> io_lib:format("'~b:~2..0b:~2..0b'", Args);
H1 > 99, is_float(S) -> io_lib:format("'~b:~2..0b:~9.6.0f'", Args);
is_integer(S) -> io_lib:format("'~2..0b:~2..0b:~2..0b'", Args);
is_float(S) -> io_lib:format("'~2..0b:~2..0b:~9.6.0f'", Args)
end;
encode({D, {H, M, S}}) when D < 0, is_integer(S) ->
Sec = (D * 24 + H) * 3600 + M * 60 + S,
{D1, {H1, M1, S1}} = calendar:seconds_to_daystime(-Sec),
Args = [H2 = D1 * 24 + H1, M1, S1],
if
H2 > 99 -> io_lib:format("'-~b:~2..0b:~2..0b'", Args);
true -> io_lib:format("'-~2..0b:~2..0b:~2..0b'", Args)
end;
encode({D, {H, M, S}}) when D < 0, is_float(S) ->
trunc(57.654321 ) = 57
57.6543 - 57 = 0.654321
0.0 -> {SInt, 0.0};
{ 58 , 0.345679 }
end,
Sec = (D * 24 + H) * 3600 + M * 60 + SInt1,
{D1, {H1, M1, S1}} = calendar:seconds_to_daystime(-Sec),
Args = [H2 = D1 * 24 + H1, M1, S1 + Frac],
if
H2 > 99 -> io_lib:format("'-~b:~2..0b:~9.6.0f'", Args);
true -> io_lib:format("'-~2..0b:~2..0b:~9.6.0f'", Args)
end.
backslash_escape(String) ->
Bin = iolist_to_binary(String),
binary:replace(Bin, <<"\\">>, <<"\\\\">>, [global]).
|
7a142173091eafb0aebcb8542100e809a62309fe9aea5b2a668d27604e0d16da | ocaml/ocaml | scheduling.ml | # 2 "asmcomp/power/scheduling.ml"
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Instruction scheduling for the Power PC *)
open Arch
open Mach
class scheduler = object
inherit Schedgen.scheduler_generic
Latencies ( in cycles ) . Based roughly on the " common model " .
method oper_latency = function
Ireload -> 2
| Iload _ -> 2
| Iconst_float _ -> 2 (* turned into a load *)
| Iconst_symbol _ -> 1
| Iintop(Imul | Imulh) -> 9
| Iintop_imm(Imul, _) -> 5
| Iintop(Idiv | Imod) -> 36
| Iaddf | Isubf -> 4
| Imulf -> 5
| Idivf -> 33
| Ispecific(Imultaddf | Imultsubf) -> 5
| _ -> 1
method! reload_retaddr_latency = 12
If we can have that many cycles between the reloadretaddr and the
return , we can expect that the blr branch will be completely folded .
return, we can expect that the blr branch will be completely folded. *)
Issue cycles . Rough approximations .
method oper_issue_cycles = function
Iconst_float _ | Iconst_symbol _ -> 2
| Iload { addressing_mode = Ibased(_, _); _ } -> 2
| Istore(_, Ibased(_, _), _) -> 2
| Ialloc _ -> 4
| Iintop(Imod) -> 40 (* assuming full stall *)
| Iintop(Icomp _) -> 4
| Iintop_imm(Icomp _, _) -> 4
| Ifloatofint -> 9
| Iintoffloat -> 4
| _ -> 1
method! reload_retaddr_issue_cycles = 3
load then stalling
end
let fundecl f = (new scheduler)#schedule_fundecl f
| null | https://raw.githubusercontent.com/ocaml/ocaml/4bf5393bf3e1c55dffe00b779ca288d168ca967b/asmcomp/power/scheduling.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Instruction scheduling for the Power PC
turned into a load
assuming full stall | # 2 "asmcomp/power/scheduling.ml"
, projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Arch
open Mach
class scheduler = object
inherit Schedgen.scheduler_generic
Latencies ( in cycles ) . Based roughly on the " common model " .
method oper_latency = function
Ireload -> 2
| Iload _ -> 2
| Iconst_symbol _ -> 1
| Iintop(Imul | Imulh) -> 9
| Iintop_imm(Imul, _) -> 5
| Iintop(Idiv | Imod) -> 36
| Iaddf | Isubf -> 4
| Imulf -> 5
| Idivf -> 33
| Ispecific(Imultaddf | Imultsubf) -> 5
| _ -> 1
method! reload_retaddr_latency = 12
If we can have that many cycles between the reloadretaddr and the
return , we can expect that the blr branch will be completely folded .
return, we can expect that the blr branch will be completely folded. *)
Issue cycles . Rough approximations .
method oper_issue_cycles = function
Iconst_float _ | Iconst_symbol _ -> 2
| Iload { addressing_mode = Ibased(_, _); _ } -> 2
| Istore(_, Ibased(_, _), _) -> 2
| Ialloc _ -> 4
| Iintop(Icomp _) -> 4
| Iintop_imm(Icomp _, _) -> 4
| Ifloatofint -> 9
| Iintoffloat -> 4
| _ -> 1
method! reload_retaddr_issue_cycles = 3
load then stalling
end
let fundecl f = (new scheduler)#schedule_fundecl f
|
f4bd4348594ceb34e93de7928d175b477d316c245b0daefb5909f8d124c47c6c | cubicle-model-checker/cubicle | bitv.mli | (**************************************************************************)
(* *)
Cubicle
(* *)
Copyright ( C ) 2011 - 2014
(* *)
and
Universite Paris - Sud 11
(* *)
(* *)
This file is distributed under the terms of the Apache Software
(* License version 2.0 *)
(* *)
(**************************************************************************)
i $ I d : bitv.mli , v 1.19 2012/08/14 07:26:00 filliatr Exp $ i
s .
This module implements bit vectors , as an abstract datatype [ t ] .
Since bit vectors are particular cases of arrays , this module provides
the same operations as module [ Array ] ( Sections~\ref{barray }
up to \ref{earray } ) . It also provides bitwise operations
( Section~\ref{bitwise } ) and conversions to / from integer types .
In the following , [ false ] stands for bit 0 and [ true ] for bit 1 .
This module implements bit vectors, as an abstract datatype [t].
Since bit vectors are particular cases of arrays, this module provides
the same operations as module [Array] (Sections~\ref{barray}
up to \ref{earray}). It also provides bitwise operations
(Section~\ref{bitwise}) and conversions to/from integer types.
In the following, [false] stands for bit 0 and [true] for bit 1. *)
type t
s { \bf Creation , access and assignment . } \label{barray }
[ ( Bitv.create n b ) ] creates a new bit vector of length [ n ] ,
initialized with [ b ] .
[ ( Bitv.init n f ) ] returns a fresh vector of length [ n ] ,
with bit number [ i ] initialized to the result of [ ( f i ) ] .
[ ( v n b ) ] sets the [ n]th bit of [ v ] to the value [ b ] .
[ ( Bitv.get v n ) ] returns the [ n]th bit of [ v ] .
[ Bitv.length ] returns the length ( number of elements ) of the given
vector .
[(Bitv.create n b)] creates a new bit vector of length [n],
initialized with [b].
[(Bitv.init n f)] returns a fresh vector of length [n],
with bit number [i] initialized to the result of [(f i)].
[(Bitv.set v n b)] sets the [n]th bit of [v] to the value [b].
[(Bitv.get v n)] returns the [n]th bit of [v].
[Bitv.length] returns the length (number of elements) of the given
vector. *)
val create : int -> bool -> t
val init : int -> (int -> bool) -> t
val set : t -> int -> bool -> unit
val get : t -> int -> bool
val length : t -> int
(*s [max_length] is the maximum length of a bit vector (System dependent). *)
val max_length : int
(*s {\bf Copies and concatenations.}
[(Bitv.copy v)] returns a copy of [v],
that is, a fresh vector containing the same elements as
[v]. [(Bitv.append v1 v2)] returns a fresh vector containing the
concatenation of the vectors [v1] and [v2]. [Bitv.concat] is
similar to [Bitv.append], but catenates a list of vectors. *)
val copy : t -> t
val append : t -> t -> t
val concat : t list -> t
s { \bf Sub - vectors and filling . }
[ ( Bitv.sub v start len ) ] returns a fresh
vector of length [ len ] , containing the bits number [ start ] to
[ start + len - 1 ] of vector [ v ] . Raise [ Invalid_argument
" Bitv.sub " ] if [ start ] and [ len ] do not designate a valid
subvector of [ v ] ; that is , if [ start < 0 ] , or [ len < 0 ] , or [ start
+ len > Bitv.length a ] .
[ ( Bitv.fill v ofs len b ) ] modifies the vector [ v ] in place ,
storing [ b ] in elements number [ ofs ] to ] . Raise
[ Invalid_argument " Bitv.fill " ] if [ ofs ] and [ len ] do not designate
a valid subvector of [ v ] .
[ ( Bitv.blit v1 o1 v2 o2 len ) ] copies [ len ] elements from vector
[ v1 ] , starting at element number [ o1 ] , to vector [ v2 ] , starting at
element number [ o2 ] . It { \em does not work } correctly if [ v1 ] and [ v2 ] are
the same vector with the source and destination chunks overlapping .
Raise [ Invalid_argument " Bitv.blit " ] if [ o1 ] and [ len ] do not
designate a valid subvector of [ v1 ] , or if [ o2 ] and [ len ] do not
designate a valid subvector of [ v2 ] .
[(Bitv.sub v start len)] returns a fresh
vector of length [len], containing the bits number [start] to
[start + len - 1] of vector [v]. Raise [Invalid_argument
"Bitv.sub"] if [start] and [len] do not designate a valid
subvector of [v]; that is, if [start < 0], or [len < 0], or [start
+ len > Bitv.length a].
[(Bitv.fill v ofs len b)] modifies the vector [v] in place,
storing [b] in elements number [ofs] to [ofs + len - 1]. Raise
[Invalid_argument "Bitv.fill"] if [ofs] and [len] do not designate
a valid subvector of [v].
[(Bitv.blit v1 o1 v2 o2 len)] copies [len] elements from vector
[v1], starting at element number [o1], to vector [v2], starting at
element number [o2]. It {\em does not work} correctly if [v1] and [v2] are
the same vector with the source and destination chunks overlapping.
Raise [Invalid_argument "Bitv.blit"] if [o1] and [len] do not
designate a valid subvector of [v1], or if [o2] and [len] do not
designate a valid subvector of [v2]. *)
val sub : t -> int -> int -> t
val fill : t -> int -> int -> bool -> unit
val blit : t -> int -> t -> int -> int -> unit
s { \bf Iterators . } \label{earray }
[ ( Bitv.iter f v ) ] applies function [ f ] in turn to all
the elements of [ v ] . Given a function [ f ] , [ ( Bitv.map f v ) ] applies
[ f ] to all
the elements of [ v ] , and builds a vector with the results returned
by [ f ] . [ Bitv.iteri ] and [ Bitv.mapi ] are similar to [ Bitv.iter ]
and [ Bitv.map ] respectively , but the function is applied to the
index of the element as first argument , and the element itself as
second argument .
[ ( Bitv.fold_left f x v ) ] computes [ f ( ... ( f ( f x ( get v 0 ) ) ( get
v 1 ) ) ... ) ( get v ( n-1 ) ) ] , where [ n ] is the length of the vector
[ v ] .
[ ( Bitv.fold_right f a x ) ] computes [ f ( get v 0 ) ( f ( get v 1 )
( ... ( f ( get v ( n-1 ) ) x ) ... ) ) ] , where [ n ] is the length of the
vector [ v ] .
[(Bitv.iter f v)] applies function [f] in turn to all
the elements of [v]. Given a function [f], [(Bitv.map f v)] applies
[f] to all
the elements of [v], and builds a vector with the results returned
by [f]. [Bitv.iteri] and [Bitv.mapi] are similar to [Bitv.iter]
and [Bitv.map] respectively, but the function is applied to the
index of the element as first argument, and the element itself as
second argument.
[(Bitv.fold_left f x v)] computes [f (... (f (f x (get v 0)) (get
v 1)) ...) (get v (n-1))], where [n] is the length of the vector
[v].
[(Bitv.fold_right f a x)] computes [f (get v 0) (f (get v 1)
( ... (f (get v (n-1)) x) ...))], where [n] is the length of the
vector [v]. *)
val iter : (bool -> unit) -> t -> unit
val map : (bool -> bool) -> t -> t
val iteri : (int -> bool -> unit) -> t -> unit
val mapi : (int -> bool -> bool) -> t -> t
val fold_left : ('a -> bool -> 'a) -> 'a -> t -> 'a
val fold_right : (bool -> 'a -> 'a) -> t -> 'a -> 'a
val foldi_left : ('a -> int -> bool -> 'a) -> 'a -> t -> 'a
val foldi_right : (int -> bool -> 'a -> 'a) -> t -> 'a -> 'a
(*s [iteri_true f v] applies function [f] in turn to all indexes of
the elements of [v] which are set (i.e. [true]); indexes are
visited from least significant to most significant. *)
val iteri_true : (int -> unit) -> t -> unit
s [ gray_iter f n ] iterates function [ f ] on all bit vectors
of length [ n ] , once each , using a Gray code . The order in which
bit vectors are processed is unspecified .
of length [n], once each, using a Gray code. The order in which
bit vectors are processed is unspecified. *)
val gray_iter : (t -> unit) -> int -> unit
s { \bf Bitwise operations . } } [ bwand ] , [ bwor ] and
[ ] implement logical and , or and exclusive or . They return
fresh vectors and raise [ Invalid_argument " Bitv.xxx " ] if the two
vectors do not have the same length ( where \texttt{xxx } is the
name of the function ) . [ bwnot ] implements the logical negation .
It returns a fresh vector .
[ shiftl ] and [ shiftr ] implement shifts . They return fresh vectors .
[ shiftl ] moves bits from least to most significant , and [ shiftr ]
from most to least significant ( think [ lsl ] and [ lsr ] ) .
[ all_zeros ] and [ all_ones ] respectively test for a vector only
containing zeros and only containing ones .
[bwxor] implement logical and, or and exclusive or. They return
fresh vectors and raise [Invalid_argument "Bitv.xxx"] if the two
vectors do not have the same length (where \texttt{xxx} is the
name of the function). [bwnot] implements the logical negation.
It returns a fresh vector.
[shiftl] and [shiftr] implement shifts. They return fresh vectors.
[shiftl] moves bits from least to most significant, and [shiftr]
from most to least significant (think [lsl] and [lsr]).
[all_zeros] and [all_ones] respectively test for a vector only
containing zeros and only containing ones. *)
val bw_and : t -> t -> t
val bw_or : t -> t -> t
val bw_xor : t -> t -> t
val bw_not : t -> t
val bw_and_in_place : t -> t -> unit
val bw_or_in_place : t -> t -> unit
val bw_not_in_place : t -> unit
val shiftl : t -> int -> t
val shiftr : t -> int -> t
val all_zeros : t -> bool
val all_ones : t -> bool
(*s {\bf Conversions to and from strings.} *)
With least significant bits first .
module L : sig
val to_string : t -> string
val of_string : string -> t
val print : Format.formatter -> t -> unit
end
With most significant bits first .
module M : sig
val to_string : t -> string
val of_string : string -> t
val print : Format.formatter -> t -> unit
end
s { \bf Input / output in a machine - independent format . }
The following functions export / import a bit vector to / from a channel ,
in a way that is compact , independent of the machine architecture , and
independent of the OCaml version .
For a bit vector of length [ n ] , the number of bytes of this external
representation is 4+ceil(n/8 ) on a 32 - bit machine and 8+ceil(n/8 ) on
a 64 - bit machine .
The following functions export/import a bit vector to/from a channel,
in a way that is compact, independent of the machine architecture, and
independent of the OCaml version.
For a bit vector of length [n], the number of bytes of this external
representation is 4+ceil(n/8) on a 32-bit machine and 8+ceil(n/8) on
a 64-bit machine. *)
val output_bin: out_channel -> t -> unit
val input_bin: in_channel -> t
(*s {\bf Conversions to and from lists of integers.}
The list gives the indices of bits which are set (ie [true]). *)
val to_list : t -> int list
val of_list : int list -> t
val of_list_with_length : int list -> int -> t
s Interpretation of bit vectors as integers . Least significant bit
comes first ( ie is at index 0 in the bit vector ) .
[ to_xxx ] functions truncate when the bit vector is too wide ,
and raise [ Invalid_argument ] when it is too short .
Suffix [ _ s ] means that sign bit is kept ,
and [ _ us ] that it is discarded .
comes first (ie is at index 0 in the bit vector).
[to_xxx] functions truncate when the bit vector is too wide,
and raise [Invalid_argument] when it is too short.
Suffix [_s] means that sign bit is kept,
and [_us] that it is discarded. *)
type [ int ] ( length 31/63 with sign , 30/62 without )
val of_int_s : int -> t
val to_int_s : t -> int
val of_int_us : int -> t
val to_int_us : t -> int
type [ Int32.t ] ( length 32 with sign , 31 without )
val of_int32_s : Int32.t -> t
val to_int32_s : t -> Int32.t
val of_int32_us : Int32.t -> t
val to_int32_us : t -> Int32.t
type [ Int64.t ] ( length 64 with sign , 63 without )
val of_int64_s : Int64.t -> t
val to_int64_s : t -> Int64.t
val of_int64_us : Int64.t -> t
val to_int64_us : t -> Int64.t
type [ Nativeint.t ] ( length 32/64 with sign , 31/63 without )
val of_nativeint_s : Nativeint.t -> t
val to_nativeint_s : t -> Nativeint.t
val of_nativeint_us : Nativeint.t -> t
val to_nativeint_us : t -> Nativeint.t
(*s Only if you know what you are doing... *)
val unsafe_set : t -> int -> bool -> unit
val unsafe_get : t -> int -> bool
| null | https://raw.githubusercontent.com/cubicle-model-checker/cubicle/00f09bb2d4bb496549775e770d7ada08bc1e4866/common/bitv.mli | ocaml | ************************************************************************
License version 2.0
************************************************************************
s [max_length] is the maximum length of a bit vector (System dependent).
s {\bf Copies and concatenations.}
[(Bitv.copy v)] returns a copy of [v],
that is, a fresh vector containing the same elements as
[v]. [(Bitv.append v1 v2)] returns a fresh vector containing the
concatenation of the vectors [v1] and [v2]. [Bitv.concat] is
similar to [Bitv.append], but catenates a list of vectors.
s [iteri_true f v] applies function [f] in turn to all indexes of
the elements of [v] which are set (i.e. [true]); indexes are
visited from least significant to most significant.
s {\bf Conversions to and from strings.}
s {\bf Conversions to and from lists of integers.}
The list gives the indices of bits which are set (ie [true]).
s Only if you know what you are doing... | Cubicle
Copyright ( C ) 2011 - 2014
and
Universite Paris - Sud 11
This file is distributed under the terms of the Apache Software
i $ I d : bitv.mli , v 1.19 2012/08/14 07:26:00 filliatr Exp $ i
s .
This module implements bit vectors , as an abstract datatype [ t ] .
Since bit vectors are particular cases of arrays , this module provides
the same operations as module [ Array ] ( Sections~\ref{barray }
up to \ref{earray } ) . It also provides bitwise operations
( Section~\ref{bitwise } ) and conversions to / from integer types .
In the following , [ false ] stands for bit 0 and [ true ] for bit 1 .
This module implements bit vectors, as an abstract datatype [t].
Since bit vectors are particular cases of arrays, this module provides
the same operations as module [Array] (Sections~\ref{barray}
up to \ref{earray}). It also provides bitwise operations
(Section~\ref{bitwise}) and conversions to/from integer types.
In the following, [false] stands for bit 0 and [true] for bit 1. *)
type t
s { \bf Creation , access and assignment . } \label{barray }
[ ( Bitv.create n b ) ] creates a new bit vector of length [ n ] ,
initialized with [ b ] .
[ ( Bitv.init n f ) ] returns a fresh vector of length [ n ] ,
with bit number [ i ] initialized to the result of [ ( f i ) ] .
[ ( v n b ) ] sets the [ n]th bit of [ v ] to the value [ b ] .
[ ( Bitv.get v n ) ] returns the [ n]th bit of [ v ] .
[ Bitv.length ] returns the length ( number of elements ) of the given
vector .
[(Bitv.create n b)] creates a new bit vector of length [n],
initialized with [b].
[(Bitv.init n f)] returns a fresh vector of length [n],
with bit number [i] initialized to the result of [(f i)].
[(Bitv.set v n b)] sets the [n]th bit of [v] to the value [b].
[(Bitv.get v n)] returns the [n]th bit of [v].
[Bitv.length] returns the length (number of elements) of the given
vector. *)
val create : int -> bool -> t
val init : int -> (int -> bool) -> t
val set : t -> int -> bool -> unit
val get : t -> int -> bool
val length : t -> int
val max_length : int
val copy : t -> t
val append : t -> t -> t
val concat : t list -> t
s { \bf Sub - vectors and filling . }
[ ( Bitv.sub v start len ) ] returns a fresh
vector of length [ len ] , containing the bits number [ start ] to
[ start + len - 1 ] of vector [ v ] . Raise [ Invalid_argument
" Bitv.sub " ] if [ start ] and [ len ] do not designate a valid
subvector of [ v ] ; that is , if [ start < 0 ] , or [ len < 0 ] , or [ start
+ len > Bitv.length a ] .
[ ( Bitv.fill v ofs len b ) ] modifies the vector [ v ] in place ,
storing [ b ] in elements number [ ofs ] to ] . Raise
[ Invalid_argument " Bitv.fill " ] if [ ofs ] and [ len ] do not designate
a valid subvector of [ v ] .
[ ( Bitv.blit v1 o1 v2 o2 len ) ] copies [ len ] elements from vector
[ v1 ] , starting at element number [ o1 ] , to vector [ v2 ] , starting at
element number [ o2 ] . It { \em does not work } correctly if [ v1 ] and [ v2 ] are
the same vector with the source and destination chunks overlapping .
Raise [ Invalid_argument " Bitv.blit " ] if [ o1 ] and [ len ] do not
designate a valid subvector of [ v1 ] , or if [ o2 ] and [ len ] do not
designate a valid subvector of [ v2 ] .
[(Bitv.sub v start len)] returns a fresh
vector of length [len], containing the bits number [start] to
[start + len - 1] of vector [v]. Raise [Invalid_argument
"Bitv.sub"] if [start] and [len] do not designate a valid
subvector of [v]; that is, if [start < 0], or [len < 0], or [start
+ len > Bitv.length a].
[(Bitv.fill v ofs len b)] modifies the vector [v] in place,
storing [b] in elements number [ofs] to [ofs + len - 1]. Raise
[Invalid_argument "Bitv.fill"] if [ofs] and [len] do not designate
a valid subvector of [v].
[(Bitv.blit v1 o1 v2 o2 len)] copies [len] elements from vector
[v1], starting at element number [o1], to vector [v2], starting at
element number [o2]. It {\em does not work} correctly if [v1] and [v2] are
the same vector with the source and destination chunks overlapping.
Raise [Invalid_argument "Bitv.blit"] if [o1] and [len] do not
designate a valid subvector of [v1], or if [o2] and [len] do not
designate a valid subvector of [v2]. *)
val sub : t -> int -> int -> t
val fill : t -> int -> int -> bool -> unit
val blit : t -> int -> t -> int -> int -> unit
s { \bf Iterators . } \label{earray }
[ ( Bitv.iter f v ) ] applies function [ f ] in turn to all
the elements of [ v ] . Given a function [ f ] , [ ( Bitv.map f v ) ] applies
[ f ] to all
the elements of [ v ] , and builds a vector with the results returned
by [ f ] . [ Bitv.iteri ] and [ Bitv.mapi ] are similar to [ Bitv.iter ]
and [ Bitv.map ] respectively , but the function is applied to the
index of the element as first argument , and the element itself as
second argument .
[ ( Bitv.fold_left f x v ) ] computes [ f ( ... ( f ( f x ( get v 0 ) ) ( get
v 1 ) ) ... ) ( get v ( n-1 ) ) ] , where [ n ] is the length of the vector
[ v ] .
[ ( Bitv.fold_right f a x ) ] computes [ f ( get v 0 ) ( f ( get v 1 )
( ... ( f ( get v ( n-1 ) ) x ) ... ) ) ] , where [ n ] is the length of the
vector [ v ] .
[(Bitv.iter f v)] applies function [f] in turn to all
the elements of [v]. Given a function [f], [(Bitv.map f v)] applies
[f] to all
the elements of [v], and builds a vector with the results returned
by [f]. [Bitv.iteri] and [Bitv.mapi] are similar to [Bitv.iter]
and [Bitv.map] respectively, but the function is applied to the
index of the element as first argument, and the element itself as
second argument.
[(Bitv.fold_left f x v)] computes [f (... (f (f x (get v 0)) (get
v 1)) ...) (get v (n-1))], where [n] is the length of the vector
[v].
[(Bitv.fold_right f a x)] computes [f (get v 0) (f (get v 1)
( ... (f (get v (n-1)) x) ...))], where [n] is the length of the
vector [v]. *)
val iter : (bool -> unit) -> t -> unit
val map : (bool -> bool) -> t -> t
val iteri : (int -> bool -> unit) -> t -> unit
val mapi : (int -> bool -> bool) -> t -> t
val fold_left : ('a -> bool -> 'a) -> 'a -> t -> 'a
val fold_right : (bool -> 'a -> 'a) -> t -> 'a -> 'a
val foldi_left : ('a -> int -> bool -> 'a) -> 'a -> t -> 'a
val foldi_right : (int -> bool -> 'a -> 'a) -> t -> 'a -> 'a
val iteri_true : (int -> unit) -> t -> unit
s [ gray_iter f n ] iterates function [ f ] on all bit vectors
of length [ n ] , once each , using a Gray code . The order in which
bit vectors are processed is unspecified .
of length [n], once each, using a Gray code. The order in which
bit vectors are processed is unspecified. *)
val gray_iter : (t -> unit) -> int -> unit
s { \bf Bitwise operations . } } [ bwand ] , [ bwor ] and
[ ] implement logical and , or and exclusive or . They return
fresh vectors and raise [ Invalid_argument " Bitv.xxx " ] if the two
vectors do not have the same length ( where \texttt{xxx } is the
name of the function ) . [ bwnot ] implements the logical negation .
It returns a fresh vector .
[ shiftl ] and [ shiftr ] implement shifts . They return fresh vectors .
[ shiftl ] moves bits from least to most significant , and [ shiftr ]
from most to least significant ( think [ lsl ] and [ lsr ] ) .
[ all_zeros ] and [ all_ones ] respectively test for a vector only
containing zeros and only containing ones .
[bwxor] implement logical and, or and exclusive or. They return
fresh vectors and raise [Invalid_argument "Bitv.xxx"] if the two
vectors do not have the same length (where \texttt{xxx} is the
name of the function). [bwnot] implements the logical negation.
It returns a fresh vector.
[shiftl] and [shiftr] implement shifts. They return fresh vectors.
[shiftl] moves bits from least to most significant, and [shiftr]
from most to least significant (think [lsl] and [lsr]).
[all_zeros] and [all_ones] respectively test for a vector only
containing zeros and only containing ones. *)
val bw_and : t -> t -> t
val bw_or : t -> t -> t
val bw_xor : t -> t -> t
val bw_not : t -> t
val bw_and_in_place : t -> t -> unit
val bw_or_in_place : t -> t -> unit
val bw_not_in_place : t -> unit
val shiftl : t -> int -> t
val shiftr : t -> int -> t
val all_zeros : t -> bool
val all_ones : t -> bool
With least significant bits first .
module L : sig
val to_string : t -> string
val of_string : string -> t
val print : Format.formatter -> t -> unit
end
With most significant bits first .
module M : sig
val to_string : t -> string
val of_string : string -> t
val print : Format.formatter -> t -> unit
end
s { \bf Input / output in a machine - independent format . }
The following functions export / import a bit vector to / from a channel ,
in a way that is compact , independent of the machine architecture , and
independent of the OCaml version .
For a bit vector of length [ n ] , the number of bytes of this external
representation is 4+ceil(n/8 ) on a 32 - bit machine and 8+ceil(n/8 ) on
a 64 - bit machine .
The following functions export/import a bit vector to/from a channel,
in a way that is compact, independent of the machine architecture, and
independent of the OCaml version.
For a bit vector of length [n], the number of bytes of this external
representation is 4+ceil(n/8) on a 32-bit machine and 8+ceil(n/8) on
a 64-bit machine. *)
val output_bin: out_channel -> t -> unit
val input_bin: in_channel -> t
val to_list : t -> int list
val of_list : int list -> t
val of_list_with_length : int list -> int -> t
s Interpretation of bit vectors as integers . Least significant bit
comes first ( ie is at index 0 in the bit vector ) .
[ to_xxx ] functions truncate when the bit vector is too wide ,
and raise [ Invalid_argument ] when it is too short .
Suffix [ _ s ] means that sign bit is kept ,
and [ _ us ] that it is discarded .
comes first (ie is at index 0 in the bit vector).
[to_xxx] functions truncate when the bit vector is too wide,
and raise [Invalid_argument] when it is too short.
Suffix [_s] means that sign bit is kept,
and [_us] that it is discarded. *)
type [ int ] ( length 31/63 with sign , 30/62 without )
val of_int_s : int -> t
val to_int_s : t -> int
val of_int_us : int -> t
val to_int_us : t -> int
type [ Int32.t ] ( length 32 with sign , 31 without )
val of_int32_s : Int32.t -> t
val to_int32_s : t -> Int32.t
val of_int32_us : Int32.t -> t
val to_int32_us : t -> Int32.t
type [ Int64.t ] ( length 64 with sign , 63 without )
val of_int64_s : Int64.t -> t
val to_int64_s : t -> Int64.t
val of_int64_us : Int64.t -> t
val to_int64_us : t -> Int64.t
type [ Nativeint.t ] ( length 32/64 with sign , 31/63 without )
val of_nativeint_s : Nativeint.t -> t
val to_nativeint_s : t -> Nativeint.t
val of_nativeint_us : Nativeint.t -> t
val to_nativeint_us : t -> Nativeint.t
val unsafe_set : t -> int -> bool -> unit
val unsafe_get : t -> int -> bool
|
64a5dda6090925d2b18995c51d4552dfb6480c9f8add69d4ee25d8136ef23a7a | tfausak/patrol | TransactionInfoSpec.hs | # LANGUAGE QuasiQuotes #
module Patrol.Type.TransactionInfoSpec where
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.QQ.Simple as Aeson
import qualified Data.Text as Text
import qualified Patrol.Type.TransactionInfo as TransactionInfo
import qualified Patrol.Type.TransactionSource as TransactionSource
import qualified Test.Hspec as Hspec
spec :: Hspec.Spec
spec = Hspec.describe "Patrol.Type.TransactionInfo" $ do
Hspec.describe "ToJSON" $ do
Hspec.it "works" $ do
let transactionInfo = TransactionInfo.empty
json = [Aeson.aesonQQ| {} |]
Aeson.toJSON transactionInfo `Hspec.shouldBe` json
Hspec.it "works with an original" $ do
let transactionInfo = TransactionInfo.empty {TransactionInfo.original = Text.pack "example-original"}
json = [Aeson.aesonQQ| { "original": "example-original" } |]
Aeson.toJSON transactionInfo `Hspec.shouldBe` json
Hspec.it "works with a source" $ do
let transactionInfo = TransactionInfo.empty {TransactionInfo.source = Just TransactionSource.Unknown}
json = [Aeson.aesonQQ| { "source": "unknown" } |]
Aeson.toJSON transactionInfo `Hspec.shouldBe` json
| null | https://raw.githubusercontent.com/tfausak/patrol/1cae55b3840b328cda7de85ea424333fcab434cb/source/test-suite/Patrol/Type/TransactionInfoSpec.hs | haskell | # LANGUAGE QuasiQuotes #
module Patrol.Type.TransactionInfoSpec where
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.QQ.Simple as Aeson
import qualified Data.Text as Text
import qualified Patrol.Type.TransactionInfo as TransactionInfo
import qualified Patrol.Type.TransactionSource as TransactionSource
import qualified Test.Hspec as Hspec
spec :: Hspec.Spec
spec = Hspec.describe "Patrol.Type.TransactionInfo" $ do
Hspec.describe "ToJSON" $ do
Hspec.it "works" $ do
let transactionInfo = TransactionInfo.empty
json = [Aeson.aesonQQ| {} |]
Aeson.toJSON transactionInfo `Hspec.shouldBe` json
Hspec.it "works with an original" $ do
let transactionInfo = TransactionInfo.empty {TransactionInfo.original = Text.pack "example-original"}
json = [Aeson.aesonQQ| { "original": "example-original" } |]
Aeson.toJSON transactionInfo `Hspec.shouldBe` json
Hspec.it "works with a source" $ do
let transactionInfo = TransactionInfo.empty {TransactionInfo.source = Just TransactionSource.Unknown}
json = [Aeson.aesonQQ| { "source": "unknown" } |]
Aeson.toJSON transactionInfo `Hspec.shouldBe` json
| |
c771d6a22251301cb9b6abf4f38d0539c373776e422a6763398d026502ac9aa4 | plewto/Cadejo | head.clj | (println "--> alias oscillators")
(ns cadejo.instruments.alias.head ;
(:use [overtone.core])
(:require [cadejo.modules.qugen :as qu]))
(def ^:private one 0)
(defcgen fm-select [array src1 depth1 lag1 src2 depth2 lag2]
(:kr
(+ (lag2:kr (* depth1 (select:kr src1 array)) lag1)
(lag2:kr (* depth2 (select:kr src2 array)) lag2))))
;; pre-osc frequency signal processing
;; f0 - reference frequency
;; detune - osc detune ratio
;; bias - osc linear freq shift
;; fm - fm signal - amplitude of fm scaled by other arguments
;;
(defcgen fmproc [f0 detune bias fm]
(:kr
(abs (* (+ 1 fm)
(+ bias (* detune f0)))))
(:ar
(abs (* (+ 1 fm)
(+ bias (* detune f0)))))
(:default :kr))
(defcgen amproc [array db src1 depth1 lag1 src2 depth2 lag2]
(:kr (* (dbamp db)
(lag2:kr
(qu/amp-modulator-depth (select:kr src1 array) depth1)
lag1)
(lag2:kr
(qu/amp-modulator-depth (select:kr src2 array) depth2)
lag2))))
(defsynth AliasHead [freq 440
port-time 0.00
osc1-detune 1.00 ;; osc1 sync-saw
osc1-bias 0.0
osc1-fm1-source one
osc1-fm1-depth 0
osc1-fm1-lag 0
osc1-fm2-source one
osc1-fm2-depth 0
osc1-fm2-lag 0
osc1-wave 0.00
osc1-wave1-source one
osc1-wave1-depth 0
osc1-wave2-source one
osc1-wave2-depth 0
osc1-amp 0 ; db
osc1-amp1-src one
osc1-amp1-depth 0
osc1-amp1-lag 0
osc1-amp2-src one
osc1-amp2-depth 0
osc1-amp2-lag 0
osc1-pan -1.0
osc2-detune 1.00 ;; osc2 pulse
osc2-bias 0.0
osc2-fm1-source one
osc2-fm1-depth 0
osc2-fm1-lag 0
osc2-fm2-source one
osc2-fm2-depth 0
osc2-fm2-lag 0
osc2-wave 0.50
osc2-wave1-source one
osc2-wave1-depth 0
osc2-wave2-source one
osc2-wave2-depth 0
osc2-amp 0 ; db
osc2-amp1-src one
osc2-amp1-depth 0
osc2-amp1-lag 0
osc2-amp2-src one
osc2-amp2-depth 0
osc2-amp2-lag 0
osc2-pan -1.0
osc3-detune 1.00 ;; osc3 pulse
osc3-bias 0.0
osc3-fm1-source one
osc3-fm1-depth 0
osc3-fm1-lag 0
osc3-fm2-source one
osc3-fm2-depth 0
osc3-fm2-lag 0
osc3-wave 0.00
osc3-wave1-source one
osc3-wave1-depth 0
osc3-wave2-source one
osc3-wave2-depth 0
osc3-amp 0 ; db
osc3-amp1-src one
osc3-amp1-depth 0
osc3-amp1-lag 0
osc3-amp2-src one
osc3-amp2-depth 0
osc3-amp2-lag 0
osc3-pan -1.0
noise-param 0.50 ;; noise
noise-lp 10000
noise-hp 10
noise-amp 0 ; db
noise-amp1-src one
noise-amp1-depth 0
noise-amp1-lag 0
noise-amp2-src one
noise-amp2-depth 0
noise-amp2-lag 0
noise-pan +1.0
ringmod -1.0 = osc1 +1 =
ringmod-modulator -1.0 ; -1.0 = osc3 +1 = noise
ringmod-amp 0 ; db
ringmod-amp1-src one
ringmod-amp1-depth 0
ringmod-amp1-lag 0
ringmod-amp2-src one
ringmod-amp2-depth 0
ringmod-amp2-lag 0
ringmod-pan +1.0
mute-amp 0 ; mutes output bus until instrument ready
bend-bus 0 ; buses
a-bus 0
b-bus 0
c-bus 0
d-bus 0
e-bus 0
f-bus 0
g-bus 0
h-bus 0
2 - channel bus
(let [bend (in:kr bend-bus)
a (in:kr a-bus)
b (in:kr b-bus)
c (in:kr c-bus)
d (in:kr d-bus)
e (in:kr e-bus)
f (in:kr f-bus)
g (in:kr g-bus)
h (in:kr h-bus)
sources [1 a b c d e f g h 0]
f0 (* (lag2:kr freq port-time)
bend)
;; OSC1 sync-saw
freq-1 (fmproc f0 osc1-detune osc1-bias
(fm-select sources
osc1-fm1-source osc1-fm1-depth osc1-fm1-lag
osc1-fm2-source osc1-fm2-depth osc1-fm2-lag))
wave-1 (* freq-1
(max 1
(abs
(+ osc1-wave
(* osc1-wave1-depth
(select:kr osc1-wave1-source sources))
(* osc1-wave2-depth
(select:kr osc1-wave2-source sources))))))
amp-1 (amproc sources osc1-amp
osc1-amp1-src osc1-amp1-depth osc1-amp1-lag
osc1-amp2-src osc1-amp2-depth osc1-amp2-lag)
osc1 (sync-saw:ar freq-1 wave-1)
;; OSC2 pulse
freq-2 (fmproc f0 osc2-detune osc2-bias
(fm-select sources
osc2-fm1-source osc2-fm1-depth osc2-fm1-lag
osc2-fm2-source osc2-fm2-depth osc2-fm2-lag))
wave-2 (qu/clamp
(+ osc2-wave
(* osc2-wave1-depth
(select:kr osc2-wave1-source sources))
(* osc2-wave2-depth
(select:kr osc2-wave2-source sources)))
0.05 0.95)
amp-2 (amproc sources osc2-amp
osc2-amp1-src osc2-amp1-depth osc2-amp1-lag
osc2-amp2-src osc2-amp2-depth osc2-amp2-lag)
osc2 (pulse freq-2 wave-2)
OSC3 fm - feedback
freq-3 (fmproc f0 osc3-detune osc3-bias
(fm-select sources
osc3-fm1-source osc3-fm1-depth osc3-fm1-lag
osc3-fm2-source osc3-fm2-depth osc3-fm2-lag))
wave-3 (abs (+ osc3-wave
(* osc3-wave1-depth
(select:kr osc3-wave1-source sources))
(* osc3-wave2-depth
(select:kr osc3-wave2-source sources))))
amp-3 (amproc sources osc3-amp
osc3-amp1-src osc3-amp1-depth osc3-amp1-lag
osc3-amp2-src osc3-amp2-depth osc3-amp2-lag)
osc3 (sin-osc-fb freq-3 wave-3)
;; NOISE
noise-parameter (qu/clamp (+ 1.3 (* 0.7 noise-param)) 1 2)
12
amp-noise (* noise-gain
(amproc sources noise-amp
noise-amp1-src noise-amp1-depth noise-amp1-lag
noise-amp2-src noise-amp2-depth noise-amp2-lag))
noise (lpf (hpf (crackle:ar noise-parameter)
noise-hp)
noise-lp)
;; RINGMODULATOR
rm-carrier (x-fade2:ar osc1 osc2 ringmod-carrier)
rm-modulator (x-fade2:ar osc3 (* (dbamp 15) noise) ringmod-modulator)
amp-rm (amproc sources ringmod-amp
ringmod-amp1-src ringmod-amp1-depth ringmod-amp1-lag
ringmod-amp2-src ringmod-amp2-depth ringmod-amp2-lag)
ringmodulator (* rm-carrier rm-modulator)
;; MIXER
mixer (+ (pan2:ar (* amp-1 osc1) osc1-pan)
(pan2:ar (* amp-2 osc2) osc2-pan)
(pan2:ar (* amp-3 osc3) osc3-pan)
(pan2:ar (* amp-noise noise) noise-pan)
(pan2:ar (* amp-rm ringmodulator) ringmod-pan))]
(out:ar out-bus (* mute-amp mixer))))
| null | https://raw.githubusercontent.com/plewto/Cadejo/2a98610ce1f5fe01dce5f28d986a38c86677fd67/src/cadejo/instruments/alias/head.clj | clojure |
pre-osc frequency signal processing
f0 - reference frequency
detune - osc detune ratio
bias - osc linear freq shift
fm - fm signal - amplitude of fm scaled by other arguments
osc1 sync-saw
db
osc2 pulse
db
osc3 pulse
db
noise
db
-1.0 = osc3 +1 = noise
db
mutes output bus until instrument ready
buses
OSC1 sync-saw
OSC2 pulse
NOISE
RINGMODULATOR
MIXER | (println "--> alias oscillators")
(:use [overtone.core])
(:require [cadejo.modules.qugen :as qu]))
(def ^:private one 0)
(defcgen fm-select [array src1 depth1 lag1 src2 depth2 lag2]
(:kr
(+ (lag2:kr (* depth1 (select:kr src1 array)) lag1)
(lag2:kr (* depth2 (select:kr src2 array)) lag2))))
(defcgen fmproc [f0 detune bias fm]
(:kr
(abs (* (+ 1 fm)
(+ bias (* detune f0)))))
(:ar
(abs (* (+ 1 fm)
(+ bias (* detune f0)))))
(:default :kr))
(defcgen amproc [array db src1 depth1 lag1 src2 depth2 lag2]
(:kr (* (dbamp db)
(lag2:kr
(qu/amp-modulator-depth (select:kr src1 array) depth1)
lag1)
(lag2:kr
(qu/amp-modulator-depth (select:kr src2 array) depth2)
lag2))))
(defsynth AliasHead [freq 440
port-time 0.00
osc1-bias 0.0
osc1-fm1-source one
osc1-fm1-depth 0
osc1-fm1-lag 0
osc1-fm2-source one
osc1-fm2-depth 0
osc1-fm2-lag 0
osc1-wave 0.00
osc1-wave1-source one
osc1-wave1-depth 0
osc1-wave2-source one
osc1-wave2-depth 0
osc1-amp1-src one
osc1-amp1-depth 0
osc1-amp1-lag 0
osc1-amp2-src one
osc1-amp2-depth 0
osc1-amp2-lag 0
osc1-pan -1.0
osc2-bias 0.0
osc2-fm1-source one
osc2-fm1-depth 0
osc2-fm1-lag 0
osc2-fm2-source one
osc2-fm2-depth 0
osc2-fm2-lag 0
osc2-wave 0.50
osc2-wave1-source one
osc2-wave1-depth 0
osc2-wave2-source one
osc2-wave2-depth 0
osc2-amp1-src one
osc2-amp1-depth 0
osc2-amp1-lag 0
osc2-amp2-src one
osc2-amp2-depth 0
osc2-amp2-lag 0
osc2-pan -1.0
osc3-bias 0.0
osc3-fm1-source one
osc3-fm1-depth 0
osc3-fm1-lag 0
osc3-fm2-source one
osc3-fm2-depth 0
osc3-fm2-lag 0
osc3-wave 0.00
osc3-wave1-source one
osc3-wave1-depth 0
osc3-wave2-source one
osc3-wave2-depth 0
osc3-amp1-src one
osc3-amp1-depth 0
osc3-amp1-lag 0
osc3-amp2-src one
osc3-amp2-depth 0
osc3-amp2-lag 0
osc3-pan -1.0
noise-lp 10000
noise-hp 10
noise-amp1-src one
noise-amp1-depth 0
noise-amp1-lag 0
noise-amp2-src one
noise-amp2-depth 0
noise-amp2-lag 0
noise-pan +1.0
ringmod -1.0 = osc1 +1 =
ringmod-amp1-src one
ringmod-amp1-depth 0
ringmod-amp1-lag 0
ringmod-amp2-src one
ringmod-amp2-depth 0
ringmod-amp2-lag 0
ringmod-pan +1.0
a-bus 0
b-bus 0
c-bus 0
d-bus 0
e-bus 0
f-bus 0
g-bus 0
h-bus 0
2 - channel bus
(let [bend (in:kr bend-bus)
a (in:kr a-bus)
b (in:kr b-bus)
c (in:kr c-bus)
d (in:kr d-bus)
e (in:kr e-bus)
f (in:kr f-bus)
g (in:kr g-bus)
h (in:kr h-bus)
sources [1 a b c d e f g h 0]
f0 (* (lag2:kr freq port-time)
bend)
freq-1 (fmproc f0 osc1-detune osc1-bias
(fm-select sources
osc1-fm1-source osc1-fm1-depth osc1-fm1-lag
osc1-fm2-source osc1-fm2-depth osc1-fm2-lag))
wave-1 (* freq-1
(max 1
(abs
(+ osc1-wave
(* osc1-wave1-depth
(select:kr osc1-wave1-source sources))
(* osc1-wave2-depth
(select:kr osc1-wave2-source sources))))))
amp-1 (amproc sources osc1-amp
osc1-amp1-src osc1-amp1-depth osc1-amp1-lag
osc1-amp2-src osc1-amp2-depth osc1-amp2-lag)
osc1 (sync-saw:ar freq-1 wave-1)
freq-2 (fmproc f0 osc2-detune osc2-bias
(fm-select sources
osc2-fm1-source osc2-fm1-depth osc2-fm1-lag
osc2-fm2-source osc2-fm2-depth osc2-fm2-lag))
wave-2 (qu/clamp
(+ osc2-wave
(* osc2-wave1-depth
(select:kr osc2-wave1-source sources))
(* osc2-wave2-depth
(select:kr osc2-wave2-source sources)))
0.05 0.95)
amp-2 (amproc sources osc2-amp
osc2-amp1-src osc2-amp1-depth osc2-amp1-lag
osc2-amp2-src osc2-amp2-depth osc2-amp2-lag)
osc2 (pulse freq-2 wave-2)
OSC3 fm - feedback
freq-3 (fmproc f0 osc3-detune osc3-bias
(fm-select sources
osc3-fm1-source osc3-fm1-depth osc3-fm1-lag
osc3-fm2-source osc3-fm2-depth osc3-fm2-lag))
wave-3 (abs (+ osc3-wave
(* osc3-wave1-depth
(select:kr osc3-wave1-source sources))
(* osc3-wave2-depth
(select:kr osc3-wave2-source sources))))
amp-3 (amproc sources osc3-amp
osc3-amp1-src osc3-amp1-depth osc3-amp1-lag
osc3-amp2-src osc3-amp2-depth osc3-amp2-lag)
osc3 (sin-osc-fb freq-3 wave-3)
noise-parameter (qu/clamp (+ 1.3 (* 0.7 noise-param)) 1 2)
12
amp-noise (* noise-gain
(amproc sources noise-amp
noise-amp1-src noise-amp1-depth noise-amp1-lag
noise-amp2-src noise-amp2-depth noise-amp2-lag))
noise (lpf (hpf (crackle:ar noise-parameter)
noise-hp)
noise-lp)
rm-carrier (x-fade2:ar osc1 osc2 ringmod-carrier)
rm-modulator (x-fade2:ar osc3 (* (dbamp 15) noise) ringmod-modulator)
amp-rm (amproc sources ringmod-amp
ringmod-amp1-src ringmod-amp1-depth ringmod-amp1-lag
ringmod-amp2-src ringmod-amp2-depth ringmod-amp2-lag)
ringmodulator (* rm-carrier rm-modulator)
mixer (+ (pan2:ar (* amp-1 osc1) osc1-pan)
(pan2:ar (* amp-2 osc2) osc2-pan)
(pan2:ar (* amp-3 osc3) osc3-pan)
(pan2:ar (* amp-noise noise) noise-pan)
(pan2:ar (* amp-rm ringmodulator) ringmod-pan))]
(out:ar out-bus (* mute-amp mixer))))
|
d8ec2b9a5c170c192b352a4643be46822371d09402b364cca87ba1ab21a33bd5 | charlieg/Sparser | required.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(CTI-source LISP) -*-
copyright ( c ) 1990,1991 Content Technologies Inc. -- all rights reserved
;;;
;;; File: "required"
;;; Module: "grammar;rules:words:basics:"
Version : 1.1 February 1991
1.1 ( 2/15 v1.8.1 ) Added comma and period .
(in-package :CTI-source)
;;;--------- marking the start and end of the source character stream
(define-punctuation end-of-source
(code-char 0))
;(define-sectionizing-marker
(define-punctuation source-start (code-char 1))
;;;-------- the most frequent word
(define-number-of-spaces one-space " ")
;;---------- newline, etc.
(define-punctuation newline #\return)
(define-punctuation linefeed #\linefeed)
(defparameter *newline-is-a-word* nil
"A flag set within headers and specialized sublanguages.")
;; /// These are referenced (found out the hard way). Have to locate
;; the reference and see if it can be modified.
(define-punctuation comma #\, )
(define-punctuation period #\. )
| null | https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/grammar/rules/words/archive%20--%20words/basics/required.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:(CTI-source LISP) -*-
File: "required"
Module: "grammar;rules:words:basics:"
--------- marking the start and end of the source character stream
(define-sectionizing-marker
-------- the most frequent word
---------- newline, etc.
/// These are referenced (found out the hard way). Have to locate
the reference and see if it can be modified. | copyright ( c ) 1990,1991 Content Technologies Inc. -- all rights reserved
Version : 1.1 February 1991
1.1 ( 2/15 v1.8.1 ) Added comma and period .
(in-package :CTI-source)
(define-punctuation end-of-source
(code-char 0))
(define-punctuation source-start (code-char 1))
(define-number-of-spaces one-space " ")
(define-punctuation newline #\return)
(define-punctuation linefeed #\linefeed)
(defparameter *newline-is-a-word* nil
"A flag set within headers and specialized sublanguages.")
(define-punctuation comma #\, )
(define-punctuation period #\. )
|
7274e81139f2e34a336e5ca12bc23abbc78f3a151f7504351f68295f8cb3c73b | semmons99/clojure-euler | prob-048.clj | problem 048 ; ; ; ; ; ; ; ; ; ;
(use '[clojure.contrib.math :only (expt)])
(defn prob-048 []
(let [n (str (reduce + (map #(expt % %) (range 1 1001))))]
(.substring n (- (count n) 10)))) | null | https://raw.githubusercontent.com/semmons99/clojure-euler/3480bc313b9df7f282dadf6e0b48d96230f1bfc1/prob-048.clj | clojure | ; ; ; ; ; ; ; ; ; | (use '[clojure.contrib.math :only (expt)])
(defn prob-048 []
(let [n (str (reduce + (map #(expt % %) (range 1 1001))))]
(.substring n (- (count n) 10)))) |
b3a55563f40615c74f76b18b44034605e04029cea87251587e3b8c8abb34940c | robstewart57/rdf4h | DCTerms.hs | # LANGUAGE TemplateHaskell #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -Wno - missing - signatures #
module Data.RDF.Vocabulary.DCTerms where
import qualified Data.RDF.Namespace (mkPrefixedNS)
import qualified Data.RDF.Types (unode)
import Data.RDF.Vocabulary.Generator.VocabularyGenerator (genVocabulary)
import qualified Data.Text (pack)
$(genVocabulary "resources/dcterms.ttl")
| null | https://raw.githubusercontent.com/robstewart57/rdf4h/22538a916ec35ad1c46f9946ca66efed24d95c75/src/Data/RDF/Vocabulary/DCTerms.hs | haskell | # LANGUAGE TemplateHaskell #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -Wno - missing - signatures #
module Data.RDF.Vocabulary.DCTerms where
import qualified Data.RDF.Namespace (mkPrefixedNS)
import qualified Data.RDF.Types (unode)
import Data.RDF.Vocabulary.Generator.VocabularyGenerator (genVocabulary)
import qualified Data.Text (pack)
$(genVocabulary "resources/dcterms.ttl")
| |
672b1097832dc4031871a6e2c150bc1b3f08f150487ca1e96a2b9919b45230e6 | losfair/Violet | CoreGen.hs | module Violet.Gen.CoreGen where
import Clash.Prelude
import qualified Violet.Backend.Wiring
import qualified Violet.Frontend.Wiring
import qualified Violet.IP.StaticDM
import qualified Violet.IP.StaticIM
import qualified Violet.Types.Fifo as FifoT
import qualified Violet.Types.Fetch as FetchT
import qualified Violet.Types.Commit as CommitT
import qualified Violet.Types.Ctrl as CtrlT
violetCore :: Clock XilinxSystem
-> Reset XilinxSystem
-> Enable XilinxSystem
-> Signal XilinxSystem CtrlT.SystemBusIn
-> Signal XilinxSystem (CommitT.CommitLog, CtrlT.SystemBusOut)
violetCore = exposeClockResetEnable violetCore'
violetCore' :: HiddenClockResetEnable dom
=> Signal dom CtrlT.SystemBusIn
-> Signal dom (CommitT.CommitLog, CtrlT.SystemBusOut)
violetCore' sysIn = bundle (commitLog, sysOut)
where
frontendOut = Violet.Frontend.Wiring.wiring Violet.IP.StaticIM.issueAccess beCmd fifoPushCap historyUpd
(beCmd, commitLog, fifoPushCap, sysOut, historyUpd, icRefillIn) = unbundle $ Violet.Backend.Wiring.wiring Violet.IP.StaticDM.StaticDM frontendOut sysIn
# ANN violetCore
( Synthesize {
t_name = " VioletCore " ,
t_inputs = [
PortName " clk " ,
PortName " rst " ,
PortName " en " ,
" sysbus_i " [
PortName " fast " ,
PortName " io "
]
] ,
t_output = PortProduct " " [
PortName " commit " ,
" sysbus_o " [
PortName " fast " ,
PortName " io "
]
]
} )
#
(Synthesize {
t_name = "VioletCore",
t_inputs = [
PortName "clk",
PortName "rst",
PortName "en",
PortProduct "sysbus_i" [
PortName "fast",
PortName "io"
]
],
t_output = PortProduct "" [
PortName "commit",
PortProduct "sysbus_o" [
PortName "fast",
PortName "io"
]
]
})
#-}
| null | https://raw.githubusercontent.com/losfair/Violet/dcdd05f8dc08a438a157347f424966da73ccc9b8/src/Violet/Gen/CoreGen.hs | haskell | module Violet.Gen.CoreGen where
import Clash.Prelude
import qualified Violet.Backend.Wiring
import qualified Violet.Frontend.Wiring
import qualified Violet.IP.StaticDM
import qualified Violet.IP.StaticIM
import qualified Violet.Types.Fifo as FifoT
import qualified Violet.Types.Fetch as FetchT
import qualified Violet.Types.Commit as CommitT
import qualified Violet.Types.Ctrl as CtrlT
violetCore :: Clock XilinxSystem
-> Reset XilinxSystem
-> Enable XilinxSystem
-> Signal XilinxSystem CtrlT.SystemBusIn
-> Signal XilinxSystem (CommitT.CommitLog, CtrlT.SystemBusOut)
violetCore = exposeClockResetEnable violetCore'
violetCore' :: HiddenClockResetEnable dom
=> Signal dom CtrlT.SystemBusIn
-> Signal dom (CommitT.CommitLog, CtrlT.SystemBusOut)
violetCore' sysIn = bundle (commitLog, sysOut)
where
frontendOut = Violet.Frontend.Wiring.wiring Violet.IP.StaticIM.issueAccess beCmd fifoPushCap historyUpd
(beCmd, commitLog, fifoPushCap, sysOut, historyUpd, icRefillIn) = unbundle $ Violet.Backend.Wiring.wiring Violet.IP.StaticDM.StaticDM frontendOut sysIn
# ANN violetCore
( Synthesize {
t_name = " VioletCore " ,
t_inputs = [
PortName " clk " ,
PortName " rst " ,
PortName " en " ,
" sysbus_i " [
PortName " fast " ,
PortName " io "
]
] ,
t_output = PortProduct " " [
PortName " commit " ,
" sysbus_o " [
PortName " fast " ,
PortName " io "
]
]
} )
#
(Synthesize {
t_name = "VioletCore",
t_inputs = [
PortName "clk",
PortName "rst",
PortName "en",
PortProduct "sysbus_i" [
PortName "fast",
PortName "io"
]
],
t_output = PortProduct "" [
PortName "commit",
PortProduct "sysbus_o" [
PortName "fast",
PortName "io"
]
]
})
#-}
| |
faa37466887e99d88a2b2733ac2c5edca9db67c06d5e7e77ca97961281489eaa | NethermindEth/horus-checker | Arguments.hs | module Horus.Arguments
( Arguments (..)
, argParser
, fileArgument
, specFileArgument
)
where
import Control.Monad.Except (throwError)
import Data.List (intercalate)
import Data.Text (Text, unpack)
import Options.Applicative
import Horus.Global (Config (..))
import Horus.Preprocessor.Solvers (MultiSolver (..), SingleSolver, SolverSettings (..), cvc5, mathsat, z3)
data Arguments = Arguments
{ arg_fileName :: Maybe FilePath
, arg_specFile :: Maybe FilePath
, arg_config :: Config
}
fileArgument :: Text
fileArgument = "COMPILED_FILE"
specFileArgument :: Text
specFileArgument = "SPECIFICATION"
defaultTimeoutMs :: Int
defaultTimeoutMs = 3000
singleSolverOptions :: [(String, SingleSolver)]
singleSolverOptions = [("z3", z3), ("cvc5", cvc5), ("mathsat", mathsat)]
singleSolverNames :: [String]
singleSolverNames = map fst singleSolverOptions
singleSolverReader :: ReadM SingleSolver
singleSolverReader = eitherReader $ \s -> case lookup s singleSolverOptions of
Just solver -> pure solver
_ ->
throwError
( "Invalid solver name: '"
<> s
<> "'.\n"
<> "Available options are '"
<> intercalate "', '" singleSolverNames
<> "'."
)
singleSolverParser :: Parser SingleSolver
singleSolverParser =
option
singleSolverReader
( long "solver"
<> short 's'
<> metavar "SOLVER"
<> help ("Solver to check the resulting smt queries (options: " <> intercalate ", " singleSolverNames <> ").")
<> completeWith singleSolverNames
)
multiSolverParser :: Parser MultiSolver
multiSolverParser = MultiSolver <$> (some singleSolverParser <|> pure [cvc5])
argParser :: Parser Arguments
argParser =
Arguments
<$> optional (strArgument (metavar (unpack fileArgument)))
<*> optional (strArgument (metavar (unpack specFileArgument)))
<*> configParser
configParser :: Parser Config
configParser =
Config
<$> switch
( long "verbose"
<> short 'v'
<> help "Print all intermediate steps (control flow graph, SMT2 queries, metadata for each module)."
)
<*> optional
( strOption
( long "output-queries"
<> metavar "DIR"
<> help "Stores the (unoptimized) SMT queries for each module in .smt2 files inside DIR."
)
)
<*> optional
( strOption
( long "output-optimized-queries"
<> metavar "DIR"
<> help "Stores the (optimized) SMT queries for each module in .smt2 files inside DIR."
)
)
<*> switch
( long "version"
<> help "Print Horus version."
)
<*> multiSolverParser
<*> ( SolverSettings
TODO : make it work one day :
-- <$> switch
-- ( long "print-models"
< >
< > help " Print models for SAT results . "
-- )
False
<$> option
auto
( long "timeout"
<> short 't'
<> metavar "TIMEOUT"
<> value defaultTimeoutMs
<> help "Time limit (ms) per-query to an SMT solver."
)
)
| null | https://raw.githubusercontent.com/NethermindEth/horus-checker/b4ce60c7739a0d12dab6c9b2ff87719b321f6200/src/Horus/Arguments.hs | haskell | <$> switch
( long "print-models"
) | module Horus.Arguments
( Arguments (..)
, argParser
, fileArgument
, specFileArgument
)
where
import Control.Monad.Except (throwError)
import Data.List (intercalate)
import Data.Text (Text, unpack)
import Options.Applicative
import Horus.Global (Config (..))
import Horus.Preprocessor.Solvers (MultiSolver (..), SingleSolver, SolverSettings (..), cvc5, mathsat, z3)
data Arguments = Arguments
{ arg_fileName :: Maybe FilePath
, arg_specFile :: Maybe FilePath
, arg_config :: Config
}
fileArgument :: Text
fileArgument = "COMPILED_FILE"
specFileArgument :: Text
specFileArgument = "SPECIFICATION"
defaultTimeoutMs :: Int
defaultTimeoutMs = 3000
singleSolverOptions :: [(String, SingleSolver)]
singleSolverOptions = [("z3", z3), ("cvc5", cvc5), ("mathsat", mathsat)]
singleSolverNames :: [String]
singleSolverNames = map fst singleSolverOptions
singleSolverReader :: ReadM SingleSolver
singleSolverReader = eitherReader $ \s -> case lookup s singleSolverOptions of
Just solver -> pure solver
_ ->
throwError
( "Invalid solver name: '"
<> s
<> "'.\n"
<> "Available options are '"
<> intercalate "', '" singleSolverNames
<> "'."
)
singleSolverParser :: Parser SingleSolver
singleSolverParser =
option
singleSolverReader
( long "solver"
<> short 's'
<> metavar "SOLVER"
<> help ("Solver to check the resulting smt queries (options: " <> intercalate ", " singleSolverNames <> ").")
<> completeWith singleSolverNames
)
multiSolverParser :: Parser MultiSolver
multiSolverParser = MultiSolver <$> (some singleSolverParser <|> pure [cvc5])
argParser :: Parser Arguments
argParser =
Arguments
<$> optional (strArgument (metavar (unpack fileArgument)))
<*> optional (strArgument (metavar (unpack specFileArgument)))
<*> configParser
configParser :: Parser Config
configParser =
Config
<$> switch
( long "verbose"
<> short 'v'
<> help "Print all intermediate steps (control flow graph, SMT2 queries, metadata for each module)."
)
<*> optional
( strOption
( long "output-queries"
<> metavar "DIR"
<> help "Stores the (unoptimized) SMT queries for each module in .smt2 files inside DIR."
)
)
<*> optional
( strOption
( long "output-optimized-queries"
<> metavar "DIR"
<> help "Stores the (optimized) SMT queries for each module in .smt2 files inside DIR."
)
)
<*> switch
( long "version"
<> help "Print Horus version."
)
<*> multiSolverParser
<*> ( SolverSettings
TODO : make it work one day :
< >
< > help " Print models for SAT results . "
False
<$> option
auto
( long "timeout"
<> short 't'
<> metavar "TIMEOUT"
<> value defaultTimeoutMs
<> help "Time limit (ms) per-query to an SMT solver."
)
)
|
31e621f7c3652cb169980c0ecf9c6796582f9cd9e04db812f5dbcbe71ce94952 | juspay/fencer | Types.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
| Types used in . We try to keep most types in one module to avoid
-- circular dependencies between modules.
module Fencer.Types
(
-- * Common types
-- $sample-config
DomainId(..)
, unDomainId
, RuleKey(..)
, unRuleKey
, RuleValue(..)
, unRuleValue
, RateLimit(..)
, HasDescriptors(..)
-- * Time units
, TimeUnit(..)
, timeUnitToSeconds
-- * Statistics
, StatsKey(..)
, unStatsKey
, Stats(..)
-- * Rate limit rule configs
, DomainDefinition(..)
, DescriptorDefinition(..)
, descriptorDefinitionKey
, descriptorDefinitionValue
-- * Rate limit rules in tree form
, RuleTree
, RuleBranch(..)
, RuleLeaf(..)
-- * Server
, Port(..)
)
where
import BasePrelude hiding (lookup)
import Data.Hashable (Hashable)
import Data.Text (Text)
import Data.Aeson (FromJSON(..), (.:), (.:?), (.!=), withObject, withText)
import Data.HashMap.Strict (HashMap, lookup)
import qualified System.Metrics.Gauge as Gauge
----------------------------------------------------------------------------
Time units
----------------------------------------------------------------------------
-- | All time units a rate limit could apply to.
data TimeUnit = Second | Minute | Hour | Day
deriving stock (Eq, Generic, Show)
deriving anyclass (Hashable)
instance FromJSON TimeUnit where
parseJSON = withText "TimeUnit" $ \case
"second" -> pure Second
"minute" -> pure Minute
"hour" -> pure Hour
"day" -> pure Day
other -> fail ("unknown time unit: " ++ show other)
-- | Return the duration of a 'TimeUnit'.
timeUnitToSeconds :: TimeUnit -> Int64
timeUnitToSeconds = \case
Second -> 1
Minute -> 60
Hour -> 3600
Day -> 86400
----------------------------------------------------------------------------
-- Counter statistics
----------------------------------------------------------------------------
newtype StatsKey = StatsKey Text
deriving stock (Eq, Ord, Show)
deriving newtype (Hashable, FromJSON)
unStatsKey :: StatsKey -> Text
unStatsKey (StatsKey x) = x
-- | Rule statistics. Can be synchronized to statsd.
data Stats = Stats
{ statsOverLimit :: Gauge.Gauge
, statsTotalHits :: Gauge.Gauge
}
----------------------------------------------------------------------------
-- Rate limiting rules
----------------------------------------------------------------------------
-- $sample-config
--
-- This sample config shows which config fields correspond to which types:
--
-- @
domain : mongo\_cps # ' '
-- descriptors:
-- - key: database # 'RuleKey'
value : users # ' RuleValue '
-- rate\_limit: # 'RateLimit'
unit : second
requests\_per\_unit : 500
-- @
-- | Domain name. Several rate limiting rules can belong to the same domain.
newtype DomainId = DomainId Text
deriving stock (Eq, Ord, Show)
deriving newtype (Hashable, FromJSON)
| Unwrap ' ' .
unDomainId :: DomainId -> Text
unDomainId (DomainId s) = s
-- | A label for a branch in the rate limit rule tree.
newtype RuleKey = RuleKey Text
deriving stock (Eq, Show, Ord)
deriving newtype (Hashable, FromJSON)
-- | Unwrap 'RuleKey'.
unRuleKey :: RuleKey -> Text
unRuleKey (RuleKey s) = s
-- | An optional value associated with a rate limiting rule.
newtype RuleValue = RuleValue Text
deriving stock (Eq, Show, Ord)
deriving newtype (Hashable, FromJSON)
| Unwrap ' RuleValue ' .
unRuleValue :: RuleValue -> Text
unRuleValue (RuleValue s) = s
-- | A specification of the rate limit that should be applied to a branch in
-- the rate limit rule tree.
data RateLimit = RateLimit
{ -- | Rate limit granularity.
rateLimitUnit :: !TimeUnit
-- | How many requests are allowed during each 'rateLimitUnit'.
, rateLimitRequestsPerUnit :: !Word
}
deriving stock (Eq, Show)
instance FromJSON RateLimit where
parseJSON = withObject "RateLimit" $ \o -> do
rateLimitUnit <- o .: "unit"
rateLimitRequestsPerUnit <- o .: "requests_per_unit"
pure RateLimit{..}
----------------------------------------------------------------------------
-- Rate limit rule configs
----------------------------------------------------------------------------
-- | A class describing how to access descriptor definitions within a
-- type, if there are any present at all.
--
-- This class is needed for accessing descriptor definitions in a
-- uniform way both when dealing with domain definitions and when
-- dealing with descriptor definitions.
class HasDescriptors a where
descriptorsOf :: a -> [DescriptorDefinition]
-- | Config for a single domain.
--
Corresponds to one YAML file .
data DomainDefinition = DomainDefinition
{ domainDefinitionId :: !DomainId
, domainDefinitionDescriptors :: ![DescriptorDefinition]
}
deriving stock (Eq, Show)
-- | Config for a single rule tree.
data DescriptorDefinition
=
-- | An inner node with no rate limit
DescriptorDefinitionInnerNode
!RuleKey
!(Maybe RuleValue)
![DescriptorDefinition]
-- | A leaf node with a rate limit
| DescriptorDefinitionLeafNode
!RuleKey
!(Maybe RuleValue)
!RateLimit
deriving stock (Eq, Show)
descriptorDefinitionKey
:: DescriptorDefinition
-> RuleKey
descriptorDefinitionKey (DescriptorDefinitionInnerNode k _ _) = k
descriptorDefinitionKey (DescriptorDefinitionLeafNode k _ _) = k
descriptorDefinitionValue
:: DescriptorDefinition
-> Maybe RuleValue
descriptorDefinitionValue (DescriptorDefinitionInnerNode _ v _) = v
descriptorDefinitionValue (DescriptorDefinitionLeafNode _ v _) = v
instance HasDescriptors DomainDefinition where
descriptorsOf = domainDefinitionDescriptors
instance HasDescriptors DescriptorDefinition where
descriptorsOf (DescriptorDefinitionLeafNode{}) = []
descriptorsOf (DescriptorDefinitionInnerNode _ _ l) = l
instance FromJSON DomainDefinition where
parseJSON = withObject "DomainDefinition" $ \o -> do
domainDefinitionId <- o .: "domain"
when (domainDefinitionId == DomainId "") $
fail "rate limit domain must not be empty"
domainDefinitionDescriptors <- o .:? "descriptors" .!= []
pure DomainDefinition{..}
instance FromJSON DescriptorDefinition where
parseJSON = withObject "DescriptorDefinition" $ \o -> do
key <- o .: "key"
value <- o .:? "value"
case lookup "rate_limit" o of
Just _ -> do
limit <- o .: "rate_limit"
case lookup "descriptors" o of
Nothing -> pure $ DescriptorDefinitionLeafNode key value limit
Just _ -> fail
"A descriptor with a rate limit cannot have a sub-descriptor"
Nothing ->
case lookup "descriptors" o of
Nothing -> fail $
"A descriptor definition must have either a rate limit " ++
"or sub-descriptor(s)"
Just _ -> do
descriptors <- o .: "descriptors"
pure $ DescriptorDefinitionInnerNode key value descriptors
----------------------------------------------------------------------------
-- Rate limit rules in tree form
----------------------------------------------------------------------------
-- | The type for a tree of rules. It is equivalent to a list of
' DescriptorDefinition 's , but uses nested hashmaps and is more convenient
-- to work with.
type RuleTree = HashMap (RuleKey, Maybe RuleValue) RuleBranch
| A single branch in a rule tree , containing several ( or perhaps zero )
-- nested rules.
data RuleBranch
= RuleBranchTree !RuleTree
| RuleBranchLeaf !RuleLeaf
-- | A leaf of the rule tree.
data RuleLeaf = RuleLeaf
{ -- | Statistics counter key, including the domain
ruleLeafStatsKey :: !StatsKey
, -- | Current limit
ruleLeafLimit :: !RateLimit
}
----------------------------------------------------------------------------
-- Fencer server
----------------------------------------------------------------------------
-- | A network port wrapper
newtype Port = Port { unPort :: Word }
deriving newtype (Eq, Show, Enum)
| null | https://raw.githubusercontent.com/juspay/fencer/db7c64ff848446d247dc8d59a1df5b50cdc104f6/lib/Fencer/Types.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
circular dependencies between modules.
* Common types
$sample-config
* Time units
* Statistics
* Rate limit rule configs
* Rate limit rules in tree form
* Server
--------------------------------------------------------------------------
--------------------------------------------------------------------------
| All time units a rate limit could apply to.
| Return the duration of a 'TimeUnit'.
--------------------------------------------------------------------------
Counter statistics
--------------------------------------------------------------------------
| Rule statistics. Can be synchronized to statsd.
--------------------------------------------------------------------------
Rate limiting rules
--------------------------------------------------------------------------
$sample-config
This sample config shows which config fields correspond to which types:
@
descriptors:
- key: database # 'RuleKey'
rate\_limit: # 'RateLimit'
@
| Domain name. Several rate limiting rules can belong to the same domain.
| A label for a branch in the rate limit rule tree.
| Unwrap 'RuleKey'.
| An optional value associated with a rate limiting rule.
| A specification of the rate limit that should be applied to a branch in
the rate limit rule tree.
| Rate limit granularity.
| How many requests are allowed during each 'rateLimitUnit'.
--------------------------------------------------------------------------
Rate limit rule configs
--------------------------------------------------------------------------
| A class describing how to access descriptor definitions within a
type, if there are any present at all.
This class is needed for accessing descriptor definitions in a
uniform way both when dealing with domain definitions and when
dealing with descriptor definitions.
| Config for a single domain.
| Config for a single rule tree.
| An inner node with no rate limit
| A leaf node with a rate limit
--------------------------------------------------------------------------
Rate limit rules in tree form
--------------------------------------------------------------------------
| The type for a tree of rules. It is equivalent to a list of
to work with.
nested rules.
| A leaf of the rule tree.
| Statistics counter key, including the domain
| Current limit
--------------------------------------------------------------------------
Fencer server
--------------------------------------------------------------------------
| A network port wrapper | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RecordWildCards #
| Types used in . We try to keep most types in one module to avoid
module Fencer.Types
(
DomainId(..)
, unDomainId
, RuleKey(..)
, unRuleKey
, RuleValue(..)
, unRuleValue
, RateLimit(..)
, HasDescriptors(..)
, TimeUnit(..)
, timeUnitToSeconds
, StatsKey(..)
, unStatsKey
, Stats(..)
, DomainDefinition(..)
, DescriptorDefinition(..)
, descriptorDefinitionKey
, descriptorDefinitionValue
, RuleTree
, RuleBranch(..)
, RuleLeaf(..)
, Port(..)
)
where
import BasePrelude hiding (lookup)
import Data.Hashable (Hashable)
import Data.Text (Text)
import Data.Aeson (FromJSON(..), (.:), (.:?), (.!=), withObject, withText)
import Data.HashMap.Strict (HashMap, lookup)
import qualified System.Metrics.Gauge as Gauge
Time units
data TimeUnit = Second | Minute | Hour | Day
deriving stock (Eq, Generic, Show)
deriving anyclass (Hashable)
instance FromJSON TimeUnit where
parseJSON = withText "TimeUnit" $ \case
"second" -> pure Second
"minute" -> pure Minute
"hour" -> pure Hour
"day" -> pure Day
other -> fail ("unknown time unit: " ++ show other)
timeUnitToSeconds :: TimeUnit -> Int64
timeUnitToSeconds = \case
Second -> 1
Minute -> 60
Hour -> 3600
Day -> 86400
newtype StatsKey = StatsKey Text
deriving stock (Eq, Ord, Show)
deriving newtype (Hashable, FromJSON)
unStatsKey :: StatsKey -> Text
unStatsKey (StatsKey x) = x
data Stats = Stats
{ statsOverLimit :: Gauge.Gauge
, statsTotalHits :: Gauge.Gauge
}
domain : mongo\_cps # ' '
value : users # ' RuleValue '
unit : second
requests\_per\_unit : 500
newtype DomainId = DomainId Text
deriving stock (Eq, Ord, Show)
deriving newtype (Hashable, FromJSON)
| Unwrap ' ' .
unDomainId :: DomainId -> Text
unDomainId (DomainId s) = s
newtype RuleKey = RuleKey Text
deriving stock (Eq, Show, Ord)
deriving newtype (Hashable, FromJSON)
unRuleKey :: RuleKey -> Text
unRuleKey (RuleKey s) = s
newtype RuleValue = RuleValue Text
deriving stock (Eq, Show, Ord)
deriving newtype (Hashable, FromJSON)
| Unwrap ' RuleValue ' .
unRuleValue :: RuleValue -> Text
unRuleValue (RuleValue s) = s
data RateLimit = RateLimit
rateLimitUnit :: !TimeUnit
, rateLimitRequestsPerUnit :: !Word
}
deriving stock (Eq, Show)
instance FromJSON RateLimit where
parseJSON = withObject "RateLimit" $ \o -> do
rateLimitUnit <- o .: "unit"
rateLimitRequestsPerUnit <- o .: "requests_per_unit"
pure RateLimit{..}
class HasDescriptors a where
descriptorsOf :: a -> [DescriptorDefinition]
Corresponds to one YAML file .
data DomainDefinition = DomainDefinition
{ domainDefinitionId :: !DomainId
, domainDefinitionDescriptors :: ![DescriptorDefinition]
}
deriving stock (Eq, Show)
data DescriptorDefinition
=
DescriptorDefinitionInnerNode
!RuleKey
!(Maybe RuleValue)
![DescriptorDefinition]
| DescriptorDefinitionLeafNode
!RuleKey
!(Maybe RuleValue)
!RateLimit
deriving stock (Eq, Show)
descriptorDefinitionKey
:: DescriptorDefinition
-> RuleKey
descriptorDefinitionKey (DescriptorDefinitionInnerNode k _ _) = k
descriptorDefinitionKey (DescriptorDefinitionLeafNode k _ _) = k
descriptorDefinitionValue
:: DescriptorDefinition
-> Maybe RuleValue
descriptorDefinitionValue (DescriptorDefinitionInnerNode _ v _) = v
descriptorDefinitionValue (DescriptorDefinitionLeafNode _ v _) = v
instance HasDescriptors DomainDefinition where
descriptorsOf = domainDefinitionDescriptors
instance HasDescriptors DescriptorDefinition where
descriptorsOf (DescriptorDefinitionLeafNode{}) = []
descriptorsOf (DescriptorDefinitionInnerNode _ _ l) = l
instance FromJSON DomainDefinition where
parseJSON = withObject "DomainDefinition" $ \o -> do
domainDefinitionId <- o .: "domain"
when (domainDefinitionId == DomainId "") $
fail "rate limit domain must not be empty"
domainDefinitionDescriptors <- o .:? "descriptors" .!= []
pure DomainDefinition{..}
instance FromJSON DescriptorDefinition where
parseJSON = withObject "DescriptorDefinition" $ \o -> do
key <- o .: "key"
value <- o .:? "value"
case lookup "rate_limit" o of
Just _ -> do
limit <- o .: "rate_limit"
case lookup "descriptors" o of
Nothing -> pure $ DescriptorDefinitionLeafNode key value limit
Just _ -> fail
"A descriptor with a rate limit cannot have a sub-descriptor"
Nothing ->
case lookup "descriptors" o of
Nothing -> fail $
"A descriptor definition must have either a rate limit " ++
"or sub-descriptor(s)"
Just _ -> do
descriptors <- o .: "descriptors"
pure $ DescriptorDefinitionInnerNode key value descriptors
' DescriptorDefinition 's , but uses nested hashmaps and is more convenient
type RuleTree = HashMap (RuleKey, Maybe RuleValue) RuleBranch
| A single branch in a rule tree , containing several ( or perhaps zero )
data RuleBranch
= RuleBranchTree !RuleTree
| RuleBranchLeaf !RuleLeaf
data RuleLeaf = RuleLeaf
ruleLeafStatsKey :: !StatsKey
ruleLeafLimit :: !RateLimit
}
newtype Port = Port { unPort :: Word }
deriving newtype (Eq, Show, Enum)
|
1ba4aca36dd35576014c51078c37db1aa8f725f86d10163bed6b2fb7af137c65 | phylogeography/spread | graphql.cljs | (ns ui.events.graphql
(:require [ajax.core :as ajax]
[camel-snake-kebab.core :as camel-snake]
[camel-snake-kebab.extras :as camel-snake-extras]
[clojure.core.match :refer [match]]
[clojure.set :refer [rename-keys]]
[clojure.string :as string]
[re-frame.core :as re-frame]
[taoensso.timbre :as log]
[ui.router.queries :as router-queries]
[ui.utils :refer [>evt dissoc-in round]]))
(defn gql-name->kw [gql-name]
(when gql-name
(let [k (name gql-name)]
(if (string/starts-with? k "__")
(keyword k)
(let [k (if (string/ends-with? k "_")
(str (.slice k 0 -1) "?")
k)
parts (string/split k "_")
parts (if (< 2 (count parts))
[(string/join "." (butlast parts)) (last parts)]
parts)]
(apply keyword (map camel-snake/->kebab-case parts)))))))
(defn gql->clj [m]
(->> m
(js->clj)
(camel-snake-extras/transform-keys gql-name->kw)))
(defn- with-safe-date
"turns YYYY/mm/dd representation to a js/Date that can be used with the date component
NOTE: we should revisit how we treat this argument to avoid going bakc and forth between representations"
[{:keys [most-recent-sampling-date] :as analysis}]
(let [js-date (when most-recent-sampling-date
(new js/Date most-recent-sampling-date))]
(assoc analysis :most-recent-sampling-date js-date)))
(defmulti handler
(fn [_ key value]
(cond
(:error value) :api/error
(vector? key) (first key)
:else key)))
(defn- update-db [cofx fx]
(if-let [db (:db fx)]
(assoc cofx :db db)
cofx))
(defn- safe-merge [fx new-fx]
(reduce (fn [merged-fx [k v]]
(when (= :db k)
(assoc merged-fx :db v)))
fx
new-fx))
(defn- do-reduce-handlers
[{:keys [db] :as cofx} f coll]
(reduce (fn [fxs element]
(let [updated-cofx (update-db cofx fxs)]
(if element
(safe-merge fxs (f updated-cofx element))
fxs)))
{:db db}
coll))
(defn reduce-handlers
[cofx response]
(do-reduce-handlers cofx
(fn [fxs [k v]]
(handler fxs k v))
response))
(defn response [cofx [_ {:keys [data errors]}]]
(when errors
(log/error "Error in graphql response" {:error errors}))
(reduce-handlers cofx (gql->clj data)))
(defn query
[{:keys [db localstorage]} [_ {:keys [query variables on-success]
:or {on-success [:graphql/response]}}]]
(let [url (get-in db [:config :graphql :url])
access-token (:access-token localstorage)]
{:http-xhrio {:method :post
:uri url
:headers (merge {"Content-Type" "application/json"
"Accept" "application/json"}
(when access-token
{"Authorization" (str "Bearer " access-token)}))
:body (js/JSON.stringify
(clj->js {:query query
:variables variables}))
:timeout 8000
:response-format (ajax/json-response-format {:keywords? true})
:on-success on-success
:on-failure [:log-error]}}))
(defn ws-authorize [{:keys [localstorage]} [_ {:keys [on-timeout]}]]
(let [access-token (:access-token localstorage)]
{:dispatch [:websocket/request :default
{:message
{:type "connection_init"
:payload {"Authorization"
(str "Bearer " access-token)}}
:on-response [:graphql/ws-authorized]
:on-timeout on-timeout
:timeout 3000}]}))
(defn ws-authorize-failed [_ [_ why?]]
(log/warn "Failed to authorize websocket connection" {:error why?})
{:dispatch [:router/navigate :route/splash]})
(defn subscription-response [cofx [_ response]]
(reduce-handlers cofx (gql->clj (get-in response [:payload :data]))))
(defn subscription [_ [_ {:keys [id query variables]}]]
{:dispatch [:websocket/subscribe :default (name id)
{:message
{:type "start"
:payload {:variables variables
:extensions {}
:operationName nil
:query query}}
:on-message [:graphql/subscription-response]}]})
(defn unsubscribe [_ [_ {:keys [id]}]]
{:dispatch [:websocket/unsubscribe :default (name id)]})
(defmethod handler :default
[cofx k values]
;; NOTE: this is the default handler that is intented for queries and mutations
;; that have nothing to do besides reducing over their response values
(log/debug "default handler" {:k k})
(reduce-handlers cofx values))
(defmethod handler :upload-continuous-tree
[{:keys [db]} _ {:keys [id] :as analysis}]
;; start the status subscription for an ongoing analysis
(>evt [:graphql/subscription {:id id
:query "subscription SubscriptionRoot($id: ID!) {
parserStatus(id: $id) {
id
readableName
status
progress
ofType
}
}"
:variables {:id id}}])
{:db (-> db
(assoc-in [:new-analysis :continuous-mcc-tree :id] id)
(update-in [:analysis id] merge analysis))})
(defmethod handler :upload-custom-map
[{:keys [db]} _ {:keys [analysis-id] :as custom-map}]
(js/console.log "Custom map uploaded" custom-map)
{:db (assoc-in db [:analysis analysis-id :custom-map] custom-map)})
(defmethod handler :delete-custom-map
[{:keys [db]} _ analysis-id]
(js/console.log "Custom map deleter" analysis-id)
{:db (update-in db [:analysis analysis-id] dissoc :custom-map)})
(defmethod handler :update-continuous-tree
[{:keys [db]} _ {:keys [id] :as analysis}]
;; NOTE : parse date to an internal representation
{:db (update-in db [:analysis id] merge (with-safe-date analysis))})
(defmethod handler :start-continuous-tree-parser
[{:keys [db]} _ {:keys [id] :as analysis}]
{:db (update-in db [:analysis id] merge (with-safe-date analysis))})
(defmethod handler :get-continuous-tree
[{:keys [db]} _ {:keys [id most-recent-sampling-date] :as analysis}]
(let [most-recent-sampling-date (when most-recent-sampling-date
(new js/Date most-recent-sampling-date))]
{:db (-> db
(update-in [:analysis id] merge (:analysis analysis))
(update-in [:analysis id] merge analysis)
(assoc-in [:analysis id :most-recent-sampling-date] most-recent-sampling-date))}))
(defmethod handler :upload-discrete-tree
[{:keys [db]} _ {:keys [id] :as analysis}]
(>evt [:graphql/subscription {:id id
:query "subscription SubscriptionRoot($id: ID!) {
parserStatus(id: $id) {
id
readableName
status
progress
ofType
}
}"
:variables {:id id}}])
{:db (-> db
;; NOTE: id is the link between the ongoing analysis
;; and what we store under the `:analysis` key
(assoc-in [:new-analysis :discrete-mcc-tree :id] id)
(update-in [:analysis id] merge analysis))})
(defmethod handler :get-discrete-tree
[{:keys [db]} _ {:keys [id most-recent-sampling-date] :as analysis}]
;; NOTE : parse date to an internal representation
(let [most-recent-sampling-date (when most-recent-sampling-date
(new js/Date most-recent-sampling-date))]
{:db (-> db
(update-in [:analysis id] merge (:analysis analysis))
(update-in [:analysis id] merge analysis)
(assoc-in [:analysis id :most-recent-sampling-date] most-recent-sampling-date))}))
(defmethod handler :update-discrete-tree
[{:keys [db]} _ {:keys [id most-recent-sampling-date] :as analysis}]
;; NOTE : parse date to an internal representation
(let [most-recent-sampling-date (when most-recent-sampling-date
(new js/Date most-recent-sampling-date))]
{:db (-> db
(update-in [:analysis id] merge analysis)
(assoc-in [:analysis id :most-recent-sampling-date] most-recent-sampling-date))}))
(defmethod handler :start-discrete-tree-parser
[{:keys [db]} _ {:keys [id] :as analysis}]
{:db (update-in db [:analysis id] merge (with-safe-date analysis))})
(defmethod handler :upload-bayes-factor-analysis
[{:keys [db]} _ {:keys [id] :as analysis}]
(>evt [:graphql/subscription {:id id
:query "subscription SubscriptionRoot($id: ID!) {
parserStatus(id: $id) {
id
readableName
status
progress
ofType
}}"
:variables {:id id}}])
{:db (-> db
;; NOTE: id is the link between the ongoing analysis
;; and what we store under the `:analysis` key
(assoc-in [:new-analysis :bayes-factor :id] id)
(update-in [:analysis id] merge analysis))})
(defmethod handler :update-bayes-factor-analysis
[{:keys [db]} _ {:keys [id] :as analysis}]
{:db (update-in db [:analysis id] merge analysis)})
(defmethod handler :get-bayes-factor-analysis
[{:keys [db]} _ {:keys [id burn-in] :as analysis}]
(let [;; fix for weird JS behaviour, where it will parse floats with full precision
burn-in (round burn-in 2)]
{:db (-> db
(update-in [:analysis id] merge (:analysis analysis))
(update-in [:analysis id] merge analysis)
(assoc-in [:analysis id :burn-in] burn-in))}))
(defmethod handler :start-bayes-factor-parser
[{:keys [db]} _ {:keys [id] :as analysis}]
{:db (update-in db [:analysis id] merge analysis)})
(defmethod handler :parser-status
[{:keys [db]} _ {:keys [id status of-type] :as parser}]
(log/debug "parser-status handler" parser)
(match [status of-type]
["ATTRIBUTES_PARSED" "CONTINUOUS_TREE"]
;; when worker has parsed attributes we can query them
(let [ongoing-analysis-id (-> db :new-analysis :continuous-mcc-tree :id)]
;; NOTE : guard so that it does not continuosly query if the subscriptions is running
(when-not (get-in db [:analysis ongoing-analysis-id :attribute-names])
(>evt [:graphql/query {:query "query GetContinuousTree($id: ID!) {
getContinuousTree(id: $id) {
id
attributeNames
}
}"
:variables {:id id}}])))
["ATTRIBUTES_PARSED" "DISCRETE_TREE"]
;; if worker parsed attributes query them
;; NOTE : guard so that it does not continuosly query if the subscriptions is running
(let [ongoing-analysis-id (-> db :new-analysis :discrete-mcc-tree :id)]
(when-not (get-in db [:analysis ongoing-analysis-id :attribute-names])
(>evt [:graphql/query {:query "query GetDiscreteTree($id: ID!) {
getDiscreteTree(id: $id) {
id
attributeNames
}
}"
:variables {:id id}}])))
[(:or "SUCCEEDED" "ERROR") _]
;; if analysis ended stop the subscription
(>evt [:graphql/unsubscribe {:id id}])
:else nil)
{:db (update-in db [:analysis id]
merge
;; NOTE we can optimistically assume analysis is new
;; since there is an ongoing subscription for it
(assoc parser :new? true))})
(defmethod handler :upload-time-slicer
[{:keys [db]} _ {:keys [continuous-tree-id] :as analysis}]
{:db (-> db
(update-in [:analysis continuous-tree-id :time-slicer] merge analysis))})
(defmethod handler :get-user-analysis
[{:keys [db]} _ analysis]
(let [analysis (map #(rename-keys % {:is-new :new?}) analysis)]
(>evt [:user-analysis-loaded])
{:db (assoc db :analysis (zipmap (map :id analysis) analysis))}))
(defmethod handler :get-authorized-user
[{:keys [db]} _ {:keys [id] :as user}]
{:db (-> db
(assoc-in [:users :authorized-user] user)
(assoc-in [:users id] user))})
(defmethod handler :touch-analysis
[{:keys [db]} _ {:keys [id is-new]}]
{:db (assoc-in db [:analysis id :new?] is-new)})
(defmethod handler :delete-analysis
[{:keys [db]} _ {:keys [id]}]
(let [{active-route-name :name query :query} (router-queries/active-page db)]
;; if on results page for this analysis we need to nav back to home
(when (and (= :route/analysis-results active-route-name)
(= id (:id query)))
(>evt [:router/navigate :route/home]))
{:db (dissoc-in db [:analysis id])}))
(defmethod handler :delete-file
[_ _ _]
;; nothing to do
)
(defmethod handler :delete-user-data
[{:keys [db]} _ _]
(>evt [:router/navigate :route/home])
{:db (-> db
(dissoc :analysis)
(dissoc :new-analysis))})
(defmethod handler :delete-user-account
[{:keys [db]} _ {:keys [user-id]}]
(>evt [:general/logout])
(>evt [:router/navigate :route/splash])
{:db (-> db
(dissoc-in [:users :authorized-user])
(dissoc-in [:users user-id]))})
(defmethod handler :send-login-email
[_ _ _]
;; TODO : create subscription for email status (when its implemented on the API side)
)
(defmethod handler :email-login
[_ _ {:keys [access-token]}]
(re-frame/dispatch [:splash/login-success access-token]))
(defmethod handler :google-login
[_ _ {:keys [access-token]}]
(re-frame/dispatch [:splash/login-success access-token]))
(defmethod handler :api/error
[_ _ _]
;; NOTE: this handler is here only to catch errors
)
(comment
(>evt [:utils/app-db])
(>evt [:graphql/query {:query "query GetContinuousTree($id: ID!) {
getContinuousTree(id: $id) {
id
attributeNames
}
}"
:variables {:id "19512998-11cb-468a-9c13-f497a0920737"}}]))
| null | https://raw.githubusercontent.com/phylogeography/spread/56f3500e6d83e0ebd50041dc336ffa0697d7baf8/src/cljs/ui/events/graphql.cljs | clojure | NOTE: this is the default handler that is intented for queries and mutations
that have nothing to do besides reducing over their response values
start the status subscription for an ongoing analysis
NOTE : parse date to an internal representation
NOTE: id is the link between the ongoing analysis
and what we store under the `:analysis` key
NOTE : parse date to an internal representation
NOTE : parse date to an internal representation
NOTE: id is the link between the ongoing analysis
and what we store under the `:analysis` key
fix for weird JS behaviour, where it will parse floats with full precision
when worker has parsed attributes we can query them
NOTE : guard so that it does not continuosly query if the subscriptions is running
if worker parsed attributes query them
NOTE : guard so that it does not continuosly query if the subscriptions is running
if analysis ended stop the subscription
NOTE we can optimistically assume analysis is new
since there is an ongoing subscription for it
if on results page for this analysis we need to nav back to home
nothing to do
TODO : create subscription for email status (when its implemented on the API side)
NOTE: this handler is here only to catch errors | (ns ui.events.graphql
(:require [ajax.core :as ajax]
[camel-snake-kebab.core :as camel-snake]
[camel-snake-kebab.extras :as camel-snake-extras]
[clojure.core.match :refer [match]]
[clojure.set :refer [rename-keys]]
[clojure.string :as string]
[re-frame.core :as re-frame]
[taoensso.timbre :as log]
[ui.router.queries :as router-queries]
[ui.utils :refer [>evt dissoc-in round]]))
(defn gql-name->kw [gql-name]
(when gql-name
(let [k (name gql-name)]
(if (string/starts-with? k "__")
(keyword k)
(let [k (if (string/ends-with? k "_")
(str (.slice k 0 -1) "?")
k)
parts (string/split k "_")
parts (if (< 2 (count parts))
[(string/join "." (butlast parts)) (last parts)]
parts)]
(apply keyword (map camel-snake/->kebab-case parts)))))))
(defn gql->clj [m]
(->> m
(js->clj)
(camel-snake-extras/transform-keys gql-name->kw)))
(defn- with-safe-date
"turns YYYY/mm/dd representation to a js/Date that can be used with the date component
NOTE: we should revisit how we treat this argument to avoid going bakc and forth between representations"
[{:keys [most-recent-sampling-date] :as analysis}]
(let [js-date (when most-recent-sampling-date
(new js/Date most-recent-sampling-date))]
(assoc analysis :most-recent-sampling-date js-date)))
(defmulti handler
(fn [_ key value]
(cond
(:error value) :api/error
(vector? key) (first key)
:else key)))
(defn- update-db [cofx fx]
(if-let [db (:db fx)]
(assoc cofx :db db)
cofx))
(defn- safe-merge [fx new-fx]
(reduce (fn [merged-fx [k v]]
(when (= :db k)
(assoc merged-fx :db v)))
fx
new-fx))
(defn- do-reduce-handlers
[{:keys [db] :as cofx} f coll]
(reduce (fn [fxs element]
(let [updated-cofx (update-db cofx fxs)]
(if element
(safe-merge fxs (f updated-cofx element))
fxs)))
{:db db}
coll))
(defn reduce-handlers
[cofx response]
(do-reduce-handlers cofx
(fn [fxs [k v]]
(handler fxs k v))
response))
(defn response [cofx [_ {:keys [data errors]}]]
(when errors
(log/error "Error in graphql response" {:error errors}))
(reduce-handlers cofx (gql->clj data)))
(defn query
[{:keys [db localstorage]} [_ {:keys [query variables on-success]
:or {on-success [:graphql/response]}}]]
(let [url (get-in db [:config :graphql :url])
access-token (:access-token localstorage)]
{:http-xhrio {:method :post
:uri url
:headers (merge {"Content-Type" "application/json"
"Accept" "application/json"}
(when access-token
{"Authorization" (str "Bearer " access-token)}))
:body (js/JSON.stringify
(clj->js {:query query
:variables variables}))
:timeout 8000
:response-format (ajax/json-response-format {:keywords? true})
:on-success on-success
:on-failure [:log-error]}}))
(defn ws-authorize [{:keys [localstorage]} [_ {:keys [on-timeout]}]]
(let [access-token (:access-token localstorage)]
{:dispatch [:websocket/request :default
{:message
{:type "connection_init"
:payload {"Authorization"
(str "Bearer " access-token)}}
:on-response [:graphql/ws-authorized]
:on-timeout on-timeout
:timeout 3000}]}))
(defn ws-authorize-failed [_ [_ why?]]
(log/warn "Failed to authorize websocket connection" {:error why?})
{:dispatch [:router/navigate :route/splash]})
(defn subscription-response [cofx [_ response]]
(reduce-handlers cofx (gql->clj (get-in response [:payload :data]))))
(defn subscription [_ [_ {:keys [id query variables]}]]
{:dispatch [:websocket/subscribe :default (name id)
{:message
{:type "start"
:payload {:variables variables
:extensions {}
:operationName nil
:query query}}
:on-message [:graphql/subscription-response]}]})
(defn unsubscribe [_ [_ {:keys [id]}]]
{:dispatch [:websocket/unsubscribe :default (name id)]})
(defmethod handler :default
[cofx k values]
(log/debug "default handler" {:k k})
(reduce-handlers cofx values))
(defmethod handler :upload-continuous-tree
[{:keys [db]} _ {:keys [id] :as analysis}]
(>evt [:graphql/subscription {:id id
:query "subscription SubscriptionRoot($id: ID!) {
parserStatus(id: $id) {
id
readableName
status
progress
ofType
}
}"
:variables {:id id}}])
{:db (-> db
(assoc-in [:new-analysis :continuous-mcc-tree :id] id)
(update-in [:analysis id] merge analysis))})
(defmethod handler :upload-custom-map
[{:keys [db]} _ {:keys [analysis-id] :as custom-map}]
(js/console.log "Custom map uploaded" custom-map)
{:db (assoc-in db [:analysis analysis-id :custom-map] custom-map)})
(defmethod handler :delete-custom-map
[{:keys [db]} _ analysis-id]
(js/console.log "Custom map deleter" analysis-id)
{:db (update-in db [:analysis analysis-id] dissoc :custom-map)})
(defmethod handler :update-continuous-tree
[{:keys [db]} _ {:keys [id] :as analysis}]
{:db (update-in db [:analysis id] merge (with-safe-date analysis))})
(defmethod handler :start-continuous-tree-parser
[{:keys [db]} _ {:keys [id] :as analysis}]
{:db (update-in db [:analysis id] merge (with-safe-date analysis))})
(defmethod handler :get-continuous-tree
[{:keys [db]} _ {:keys [id most-recent-sampling-date] :as analysis}]
(let [most-recent-sampling-date (when most-recent-sampling-date
(new js/Date most-recent-sampling-date))]
{:db (-> db
(update-in [:analysis id] merge (:analysis analysis))
(update-in [:analysis id] merge analysis)
(assoc-in [:analysis id :most-recent-sampling-date] most-recent-sampling-date))}))
(defmethod handler :upload-discrete-tree
[{:keys [db]} _ {:keys [id] :as analysis}]
(>evt [:graphql/subscription {:id id
:query "subscription SubscriptionRoot($id: ID!) {
parserStatus(id: $id) {
id
readableName
status
progress
ofType
}
}"
:variables {:id id}}])
{:db (-> db
(assoc-in [:new-analysis :discrete-mcc-tree :id] id)
(update-in [:analysis id] merge analysis))})
(defmethod handler :get-discrete-tree
[{:keys [db]} _ {:keys [id most-recent-sampling-date] :as analysis}]
(let [most-recent-sampling-date (when most-recent-sampling-date
(new js/Date most-recent-sampling-date))]
{:db (-> db
(update-in [:analysis id] merge (:analysis analysis))
(update-in [:analysis id] merge analysis)
(assoc-in [:analysis id :most-recent-sampling-date] most-recent-sampling-date))}))
(defmethod handler :update-discrete-tree
[{:keys [db]} _ {:keys [id most-recent-sampling-date] :as analysis}]
(let [most-recent-sampling-date (when most-recent-sampling-date
(new js/Date most-recent-sampling-date))]
{:db (-> db
(update-in [:analysis id] merge analysis)
(assoc-in [:analysis id :most-recent-sampling-date] most-recent-sampling-date))}))
(defmethod handler :start-discrete-tree-parser
[{:keys [db]} _ {:keys [id] :as analysis}]
{:db (update-in db [:analysis id] merge (with-safe-date analysis))})
(defmethod handler :upload-bayes-factor-analysis
[{:keys [db]} _ {:keys [id] :as analysis}]
(>evt [:graphql/subscription {:id id
:query "subscription SubscriptionRoot($id: ID!) {
parserStatus(id: $id) {
id
readableName
status
progress
ofType
}}"
:variables {:id id}}])
{:db (-> db
(assoc-in [:new-analysis :bayes-factor :id] id)
(update-in [:analysis id] merge analysis))})
(defmethod handler :update-bayes-factor-analysis
[{:keys [db]} _ {:keys [id] :as analysis}]
{:db (update-in db [:analysis id] merge analysis)})
(defmethod handler :get-bayes-factor-analysis
[{:keys [db]} _ {:keys [id burn-in] :as analysis}]
burn-in (round burn-in 2)]
{:db (-> db
(update-in [:analysis id] merge (:analysis analysis))
(update-in [:analysis id] merge analysis)
(assoc-in [:analysis id :burn-in] burn-in))}))
(defmethod handler :start-bayes-factor-parser
[{:keys [db]} _ {:keys [id] :as analysis}]
{:db (update-in db [:analysis id] merge analysis)})
(defmethod handler :parser-status
[{:keys [db]} _ {:keys [id status of-type] :as parser}]
(log/debug "parser-status handler" parser)
(match [status of-type]
["ATTRIBUTES_PARSED" "CONTINUOUS_TREE"]
(let [ongoing-analysis-id (-> db :new-analysis :continuous-mcc-tree :id)]
(when-not (get-in db [:analysis ongoing-analysis-id :attribute-names])
(>evt [:graphql/query {:query "query GetContinuousTree($id: ID!) {
getContinuousTree(id: $id) {
id
attributeNames
}
}"
:variables {:id id}}])))
["ATTRIBUTES_PARSED" "DISCRETE_TREE"]
(let [ongoing-analysis-id (-> db :new-analysis :discrete-mcc-tree :id)]
(when-not (get-in db [:analysis ongoing-analysis-id :attribute-names])
(>evt [:graphql/query {:query "query GetDiscreteTree($id: ID!) {
getDiscreteTree(id: $id) {
id
attributeNames
}
}"
:variables {:id id}}])))
[(:or "SUCCEEDED" "ERROR") _]
(>evt [:graphql/unsubscribe {:id id}])
:else nil)
{:db (update-in db [:analysis id]
merge
(assoc parser :new? true))})
(defmethod handler :upload-time-slicer
[{:keys [db]} _ {:keys [continuous-tree-id] :as analysis}]
{:db (-> db
(update-in [:analysis continuous-tree-id :time-slicer] merge analysis))})
(defmethod handler :get-user-analysis
[{:keys [db]} _ analysis]
(let [analysis (map #(rename-keys % {:is-new :new?}) analysis)]
(>evt [:user-analysis-loaded])
{:db (assoc db :analysis (zipmap (map :id analysis) analysis))}))
(defmethod handler :get-authorized-user
[{:keys [db]} _ {:keys [id] :as user}]
{:db (-> db
(assoc-in [:users :authorized-user] user)
(assoc-in [:users id] user))})
(defmethod handler :touch-analysis
[{:keys [db]} _ {:keys [id is-new]}]
{:db (assoc-in db [:analysis id :new?] is-new)})
(defmethod handler :delete-analysis
[{:keys [db]} _ {:keys [id]}]
(let [{active-route-name :name query :query} (router-queries/active-page db)]
(when (and (= :route/analysis-results active-route-name)
(= id (:id query)))
(>evt [:router/navigate :route/home]))
{:db (dissoc-in db [:analysis id])}))
(defmethod handler :delete-file
[_ _ _]
)
(defmethod handler :delete-user-data
[{:keys [db]} _ _]
(>evt [:router/navigate :route/home])
{:db (-> db
(dissoc :analysis)
(dissoc :new-analysis))})
(defmethod handler :delete-user-account
[{:keys [db]} _ {:keys [user-id]}]
(>evt [:general/logout])
(>evt [:router/navigate :route/splash])
{:db (-> db
(dissoc-in [:users :authorized-user])
(dissoc-in [:users user-id]))})
(defmethod handler :send-login-email
[_ _ _]
)
(defmethod handler :email-login
[_ _ {:keys [access-token]}]
(re-frame/dispatch [:splash/login-success access-token]))
(defmethod handler :google-login
[_ _ {:keys [access-token]}]
(re-frame/dispatch [:splash/login-success access-token]))
(defmethod handler :api/error
[_ _ _]
)
(comment
(>evt [:utils/app-db])
(>evt [:graphql/query {:query "query GetContinuousTree($id: ID!) {
getContinuousTree(id: $id) {
id
attributeNames
}
}"
:variables {:id "19512998-11cb-468a-9c13-f497a0920737"}}]))
|
b2c8c5eed467e4bc2c555672784f5738090b2c09a4ed2218950ce67ab019930b | manuel-serrano/hop | tabslider.scm | ;*=====================================================================*/
* serrano / prgm / project / hop / hop / widget / tabslider.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Thu Aug 18 10:01:02 2005 * /
* Last change : Sun Apr 28 11:01:01 2019 ( serrano ) * /
;* ------------------------------------------------------------- */
* The HOP implementation of TABSLIDER . * /
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __hopwidget-tabslider
(library hop)
(static (class html-tabslider::xml-element
(clazz (default #f))
(width (default #f))
(height (default #f))
(index (default 0))
(onchange (default #f))
(history read-only (default #t)))
(class html-tspan::xml-element)
(class html-tshead::xml-element))
(export (<TABSLIDER> . ::obj)
(<TSPAN> . ::obj)
(<TSHEAD> . ::obj)))
;*---------------------------------------------------------------------*/
;* object-serializer ::html-foldlist ... */
;*---------------------------------------------------------------------*/
(define (serialize o ctx)
(let ((p (open-output-string)))
(obj->javascript-expr o p ctx)
(close-output-port p)))
(define (unserialize o ctx)
o)
(register-class-serialization! html-tabslider serialize unserialize)
(register-class-serialization! html-tspan serialize unserialize)
(register-class-serialization! html-tshead serialize unserialize)
;*---------------------------------------------------------------------*/
;* <TABSLIDER> ... */
;*---------------------------------------------------------------------*/
(define-tag <TABSLIDER> ((id #unspecified string)
(class #unspecified string)
(width #f)
(height #f)
(index 0)
(onchange #f)
(history #unspecified)
body)
Verify that the body is a list of < TSPAN >
(for-each (lambda (x)
(unless (and (isa? x xml-element)
(with-access::xml-element x (tag)
(eq? tag 'tspan)))
(error "<TABSLIDER>" "Component is not a <TSPAN>" x)))
body)
(instantiate::html-tabslider
(tag 'tabslider)
(id (xml-make-id id 'TABSLIDER))
(clazz (if (string? class)
(string-append class " uninitialized")
"uninitialized"))
(width width)
(height height)
(index index)
(onchange onchange)
(history (if (boolean? history) history (not (eq? id #unspecified))))
(body body)))
;*---------------------------------------------------------------------*/
;* xml-write ::html-tabslider ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::html-tabslider p backend)
(with-access::html-tabslider obj (clazz id width height body index history onchange)
(fprintf p "<div hssclass='hop-tabslider' class='~a' id='~a'" clazz id)
(when (or width height)
(fprintf p " style=\"~a~a\""
(if width (format "width: ~a;" width) "")
(if height (format "height: ~a;" height) "")))
(display ">" p)
(xml-write body p backend)
(display "</div>" p)
(fprintf p
"<script type='~a'>hop_tabslider_init('~a', ~a, ~a, ~a)</script>"
(hop-mime-type)
id index
(if history "true" "false")
(hop->js-callback onchange))))
;*---------------------------------------------------------------------*/
;* <TSPAN> ... */
;*---------------------------------------------------------------------*/
(define-tag <TSPAN> ((id #unspecified string)
(onselect #f)
body)
(define (tspan-onselect id onselect)
(when onselect
(<SCRIPT>
(format "document.getElementById('~a').onselect=~a;"
id (hop->js-callback onselect)))))
(let ((id (xml-make-id id 'TSPAN)))
;; Check that body is well formed
(cond
((or (null? body) (null? (cdr body)))
(error "<TSPAN>" "Illegal body, at least two elements needed" body))
((and (isa? (cadr body) xml-delay) (null? (cddr body)))
;; a delayed tspan
(with-access::xml-delay (cadr body) (thunk)
(instantiate::html-tspan
(tag 'tspan)
(body (list (car body)
(<DIV>
:id id
:hssclass "hop-tabslider-pan"
:class "inactive"
:lang "delay"
:onkeyup (secure-javascript-attr
(format "return ~a;"
(call-with-output-string
(lambda (op)
(obj->javascript-attr
(procedure->service
thunk)
op)))))
(tspan-onselect id onselect)
"delayed tab"))))))
(else
;; an eager static tspan
(instantiate::html-tspan
(tag 'tspan)
(body (list (car body)
(apply <DIV>
:id id
:hssclass "hop-tabslider-pan"
:class "inactive"
(tspan-onselect id onselect)
(cdr body)))))))))
;*---------------------------------------------------------------------*/
;* xml-write ::html-tspan ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::html-tspan p backend)
(with-access::html-tspan obj (body)
(xml-write body p backend)))
;*---------------------------------------------------------------------*/
;* <TSHEAD> ... */
;*---------------------------------------------------------------------*/
(define-xml-alias <TSHEAD> <DIV>
:hssclass "hop-tabslider-head"
:class "inactive"
:onclick (secure-javascript-attr "hop_tabslider_select( this )"))
| null | https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/widget/tabslider.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* object-serializer ::html-foldlist ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* <TABSLIDER> ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::html-tabslider ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* <TSPAN> ... */
*---------------------------------------------------------------------*/
Check that body is well formed
a delayed tspan
an eager static tspan
*---------------------------------------------------------------------*/
* xml-write ::html-tspan ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* <TSHEAD> ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / hop / hop / widget / tabslider.scm * /
* Author : * /
* Creation : Thu Aug 18 10:01:02 2005 * /
* Last change : Sun Apr 28 11:01:01 2019 ( serrano ) * /
* The HOP implementation of TABSLIDER . * /
(module __hopwidget-tabslider
(library hop)
(static (class html-tabslider::xml-element
(clazz (default #f))
(width (default #f))
(height (default #f))
(index (default 0))
(onchange (default #f))
(history read-only (default #t)))
(class html-tspan::xml-element)
(class html-tshead::xml-element))
(export (<TABSLIDER> . ::obj)
(<TSPAN> . ::obj)
(<TSHEAD> . ::obj)))
(define (serialize o ctx)
(let ((p (open-output-string)))
(obj->javascript-expr o p ctx)
(close-output-port p)))
(define (unserialize o ctx)
o)
(register-class-serialization! html-tabslider serialize unserialize)
(register-class-serialization! html-tspan serialize unserialize)
(register-class-serialization! html-tshead serialize unserialize)
(define-tag <TABSLIDER> ((id #unspecified string)
(class #unspecified string)
(width #f)
(height #f)
(index 0)
(onchange #f)
(history #unspecified)
body)
Verify that the body is a list of < TSPAN >
(for-each (lambda (x)
(unless (and (isa? x xml-element)
(with-access::xml-element x (tag)
(eq? tag 'tspan)))
(error "<TABSLIDER>" "Component is not a <TSPAN>" x)))
body)
(instantiate::html-tabslider
(tag 'tabslider)
(id (xml-make-id id 'TABSLIDER))
(clazz (if (string? class)
(string-append class " uninitialized")
"uninitialized"))
(width width)
(height height)
(index index)
(onchange onchange)
(history (if (boolean? history) history (not (eq? id #unspecified))))
(body body)))
(define-method (xml-write obj::html-tabslider p backend)
(with-access::html-tabslider obj (clazz id width height body index history onchange)
(fprintf p "<div hssclass='hop-tabslider' class='~a' id='~a'" clazz id)
(when (or width height)
(fprintf p " style=\"~a~a\""
(if width (format "width: ~a;" width) "")
(if height (format "height: ~a;" height) "")))
(display ">" p)
(xml-write body p backend)
(display "</div>" p)
(fprintf p
"<script type='~a'>hop_tabslider_init('~a', ~a, ~a, ~a)</script>"
(hop-mime-type)
id index
(if history "true" "false")
(hop->js-callback onchange))))
(define-tag <TSPAN> ((id #unspecified string)
(onselect #f)
body)
(define (tspan-onselect id onselect)
(when onselect
(<SCRIPT>
(format "document.getElementById('~a').onselect=~a;"
id (hop->js-callback onselect)))))
(let ((id (xml-make-id id 'TSPAN)))
(cond
((or (null? body) (null? (cdr body)))
(error "<TSPAN>" "Illegal body, at least two elements needed" body))
((and (isa? (cadr body) xml-delay) (null? (cddr body)))
(with-access::xml-delay (cadr body) (thunk)
(instantiate::html-tspan
(tag 'tspan)
(body (list (car body)
(<DIV>
:id id
:hssclass "hop-tabslider-pan"
:class "inactive"
:lang "delay"
:onkeyup (secure-javascript-attr
(format "return ~a;"
(call-with-output-string
(lambda (op)
(obj->javascript-attr
(procedure->service
thunk)
op)))))
(tspan-onselect id onselect)
"delayed tab"))))))
(else
(instantiate::html-tspan
(tag 'tspan)
(body (list (car body)
(apply <DIV>
:id id
:hssclass "hop-tabslider-pan"
:class "inactive"
(tspan-onselect id onselect)
(cdr body)))))))))
(define-method (xml-write obj::html-tspan p backend)
(with-access::html-tspan obj (body)
(xml-write body p backend)))
(define-xml-alias <TSHEAD> <DIV>
:hssclass "hop-tabslider-head"
:class "inactive"
:onclick (secure-javascript-attr "hop_tabslider_select( this )"))
|
87a40ad081623f456be86e21f117a8d9a4bad4a3b691afa5445d84b285a094c6 | fragnix/fragnix | Control.Concurrent.Lifted.hs | # LANGUAGE Haskell98 #
# LINE 1 " Control / Concurrent / Lifted.hs " #
# LANGUAGE CPP , NoImplicitPrelude , FlexibleContexts , RankNTypes #
{-# LANGUAGE Safe #-}
|
Module : Control . Concurrent . Lifted
Copyright : : BSD - style
Maintainer : < >
Stability : experimental
This is a wrapped version of " Control . Concurrent " with types generalized
from ' IO ' to all monads in either ' MonadBase ' or ' MonadBaseControl ' .
Module : Control.Concurrent.Lifted
Copyright : Bas van Dijk
License : BSD-style
Maintainer : Bas van Dijk <>
Stability : experimental
This is a wrapped version of "Control.Concurrent" with types generalized
from 'IO' to all monads in either 'MonadBase' or 'MonadBaseControl'.
-}
module Control.Concurrent.Lifted
( -- * Concurrent Haskell
ThreadId
-- * Basic concurrency operations
, myThreadId
, fork
, forkWithUnmask
, forkFinally
, killThread
, throwTo
-- ** Threads with affinity
, forkOn
, forkOnWithUnmask
, getNumCapabilities
, setNumCapabilities
, threadCapability
-- * Scheduling
, yield
-- ** Blocking
-- ** Waiting
, threadDelay
, threadWaitRead
, threadWaitWrite
-- * Communication abstractions
, module Control.Concurrent.MVar.Lifted
, module Control.Concurrent.Chan.Lifted
, module Control.Concurrent.QSem.Lifted
, module Control.Concurrent.QSemN.Lifted
-- * Bound Threads
, C.rtsSupportsBoundThreads
, forkOS
, isCurrentThreadBound
, runInBoundThread
, runInUnboundThread
-- * Weak references to ThreadIds
, mkWeakThreadId
) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
-- from base:
import Prelude ( (.) )
import Data.Bool ( Bool )
import Data.Int ( Int )
import Data.Function ( ($) )
import System.IO ( IO )
import System.Posix.Types ( Fd )
import Control.Monad ( (>>=) )
import Data.Either ( Either )
import System.Mem.Weak ( Weak )
import Control.Concurrent ( ThreadId )
import qualified Control.Concurrent as C
-- from transformers-base:
import Control.Monad.Base ( MonadBase, liftBase )
-- from monad-control:
import Control.Monad.Trans.Control ( MonadBaseControl, liftBaseOp_, liftBaseDiscard )
import Control.Monad.Trans.Control ( liftBaseWith )
import Control.Monad ( void )
-- from lifted-base (this package):
import Control.Concurrent.MVar.Lifted
import Control.Concurrent.Chan.Lifted
import Control.Concurrent.QSem.Lifted
import Control.Concurrent.QSemN.Lifted
import Control.Exception.Lifted ( throwTo
, SomeException, try, mask
)
--------------------------------------------------------------------------------
-- Control.Concurrent
--------------------------------------------------------------------------------
-- | Generalized version of 'C.myThreadId'.
myThreadId :: MonadBase IO m => m ThreadId
myThreadId = liftBase C.myThreadId
# INLINABLE myThreadId #
-- | Generalized version of 'C.forkIO'.
--
-- Note that, while the forked computation @m ()@ has access to the captured
-- state, all its side-effects in @m@ are discarded. It is run only for its
-- side-effects in 'IO'.
fork :: MonadBaseControl IO m => m () -> m ThreadId
fork = liftBaseDiscard C.forkIO
# INLINABLE fork #
-- | Generalized version of 'C.forkIOWithUnmask'.
--
-- Note that, while the forked computation @m ()@ has access to the captured
-- state, all its side-effects in @m@ are discarded. It is run only for its
-- side-effects in 'IO'.
forkWithUnmask :: MonadBaseControl IO m => ((forall a. m a -> m a) -> m ()) -> m ThreadId
forkWithUnmask f = liftBaseWith $ \runInIO ->
C.forkIOWithUnmask $ \unmask ->
void $ runInIO $ f $ liftBaseOp_ unmask
# INLINABLE forkWithUnmask #
| Generalized version of ' C.forkFinally ' .
--
-- Note that in @forkFinally action and_then@, while the forked
-- @action@ and the @and_then@ function have access to the captured
-- state, all their side-effects in @m@ are discarded. They're run
-- only for their side-effects in 'IO'.
forkFinally :: MonadBaseControl IO m
=> m a -> (Either SomeException a -> m ()) -> m ThreadId
forkFinally action and_then =
mask $ \restore ->
fork $ try (restore action) >>= and_then
# INLINABLE forkFinally #
-- | Generalized version of 'C.killThread'.
killThread :: MonadBase IO m => ThreadId -> m ()
killThread = liftBase . C.killThread
# INLINABLE killThread #
-- | Generalized version of 'C.forkOn'.
--
-- Note that, while the forked computation @m ()@ has access to the captured
-- state, all its side-effects in @m@ are discarded. It is run only for its
-- side-effects in 'IO'.
forkOn :: MonadBaseControl IO m => Int -> m () -> m ThreadId
forkOn = liftBaseDiscard . C.forkOn
# INLINABLE forkOn #
| Generalized version of ' C.forkOnWithUnmask ' .
--
-- Note that, while the forked computation @m ()@ has access to the captured
-- state, all its side-effects in @m@ are discarded. It is run only for its
-- side-effects in 'IO'.
forkOnWithUnmask :: MonadBaseControl IO m => Int -> ((forall a. m a -> m a) -> m ()) -> m ThreadId
forkOnWithUnmask cap f = liftBaseWith $ \runInIO ->
C.forkOnWithUnmask cap $ \unmask ->
void $ runInIO $ f $ liftBaseOp_ unmask
# INLINABLE forkOnWithUnmask #
-- | Generalized version of 'C.getNumCapabilities'.
getNumCapabilities :: MonadBase IO m => m Int
getNumCapabilities = liftBase C.getNumCapabilities
# INLINABLE getNumCapabilities #
-- | Generalized version of 'C.setNumCapabilities'.
setNumCapabilities :: MonadBase IO m => Int -> m ()
setNumCapabilities = liftBase . C.setNumCapabilities
# INLINABLE setNumCapabilities #
-- | Generalized version of 'C.threadCapability'.
threadCapability :: MonadBase IO m => ThreadId -> m (Int, Bool)
threadCapability = liftBase . C.threadCapability
# INLINABLE threadCapability #
-- | Generalized version of 'C.yield'.
yield :: MonadBase IO m => m ()
yield = liftBase C.yield
# INLINABLE yield #
| Generalized version of ' C.threadDelay ' .
threadDelay :: MonadBase IO m => Int -> m ()
threadDelay = liftBase . C.threadDelay
# INLINABLE threadDelay #
| Generalized version of ' ' .
threadWaitRead :: MonadBase IO m => Fd -> m ()
threadWaitRead = liftBase . C.threadWaitRead
# INLINABLE threadWaitRead #
-- | Generalized version of 'C.threadWaitWrite'.
threadWaitWrite :: MonadBase IO m => Fd -> m ()
threadWaitWrite = liftBase . C.threadWaitWrite
# INLINABLE threadWaitWrite #
| Generalized version of ' ' .
--
-- Note that, while the forked computation @m ()@ has access to the captured
-- state, all its side-effects in @m@ are discarded. It is run only for its
-- side-effects in 'IO'.
forkOS :: MonadBaseControl IO m => m () -> m ThreadId
forkOS = liftBaseDiscard C.forkOS
{-# INLINABLE forkOS #-}
-- | Generalized version of 'C.isCurrentThreadBound'.
isCurrentThreadBound :: MonadBase IO m => m Bool
isCurrentThreadBound = liftBase C.isCurrentThreadBound
{-# INLINABLE isCurrentThreadBound #-}
-- | Generalized version of 'C.runInBoundThread'.
runInBoundThread :: MonadBaseControl IO m => m a -> m a
runInBoundThread = liftBaseOp_ C.runInBoundThread
# INLINABLE runInBoundThread #
-- | Generalized version of 'C.runInUnboundThread'.
runInUnboundThread :: MonadBaseControl IO m => m a -> m a
runInUnboundThread = liftBaseOp_ C.runInUnboundThread
# INLINABLE runInUnboundThread #
-- | Generalized versio of 'C.mkWeakThreadId'.
mkWeakThreadId :: MonadBase IO m => ThreadId -> m (Weak ThreadId)
mkWeakThreadId = liftBase . C.mkWeakThreadId
{-# INLINABLE mkWeakThreadId #-}
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/application/Control.Concurrent.Lifted.hs | haskell | # LANGUAGE Safe #
* Concurrent Haskell
* Basic concurrency operations
** Threads with affinity
* Scheduling
** Blocking
** Waiting
* Communication abstractions
* Bound Threads
* Weak references to ThreadIds
------------------------------------------------------------------------------
Imports
------------------------------------------------------------------------------
from base:
from transformers-base:
from monad-control:
from lifted-base (this package):
------------------------------------------------------------------------------
Control.Concurrent
------------------------------------------------------------------------------
| Generalized version of 'C.myThreadId'.
| Generalized version of 'C.forkIO'.
Note that, while the forked computation @m ()@ has access to the captured
state, all its side-effects in @m@ are discarded. It is run only for its
side-effects in 'IO'.
| Generalized version of 'C.forkIOWithUnmask'.
Note that, while the forked computation @m ()@ has access to the captured
state, all its side-effects in @m@ are discarded. It is run only for its
side-effects in 'IO'.
Note that in @forkFinally action and_then@, while the forked
@action@ and the @and_then@ function have access to the captured
state, all their side-effects in @m@ are discarded. They're run
only for their side-effects in 'IO'.
| Generalized version of 'C.killThread'.
| Generalized version of 'C.forkOn'.
Note that, while the forked computation @m ()@ has access to the captured
state, all its side-effects in @m@ are discarded. It is run only for its
side-effects in 'IO'.
Note that, while the forked computation @m ()@ has access to the captured
state, all its side-effects in @m@ are discarded. It is run only for its
side-effects in 'IO'.
| Generalized version of 'C.getNumCapabilities'.
| Generalized version of 'C.setNumCapabilities'.
| Generalized version of 'C.threadCapability'.
| Generalized version of 'C.yield'.
| Generalized version of 'C.threadWaitWrite'.
Note that, while the forked computation @m ()@ has access to the captured
state, all its side-effects in @m@ are discarded. It is run only for its
side-effects in 'IO'.
# INLINABLE forkOS #
| Generalized version of 'C.isCurrentThreadBound'.
# INLINABLE isCurrentThreadBound #
| Generalized version of 'C.runInBoundThread'.
| Generalized version of 'C.runInUnboundThread'.
| Generalized versio of 'C.mkWeakThreadId'.
# INLINABLE mkWeakThreadId # | # LANGUAGE Haskell98 #
# LINE 1 " Control / Concurrent / Lifted.hs " #
# LANGUAGE CPP , NoImplicitPrelude , FlexibleContexts , RankNTypes #
|
Module : Control . Concurrent . Lifted
Copyright : : BSD - style
Maintainer : < >
Stability : experimental
This is a wrapped version of " Control . Concurrent " with types generalized
from ' IO ' to all monads in either ' MonadBase ' or ' MonadBaseControl ' .
Module : Control.Concurrent.Lifted
Copyright : Bas van Dijk
License : BSD-style
Maintainer : Bas van Dijk <>
Stability : experimental
This is a wrapped version of "Control.Concurrent" with types generalized
from 'IO' to all monads in either 'MonadBase' or 'MonadBaseControl'.
-}
module Control.Concurrent.Lifted
ThreadId
, myThreadId
, fork
, forkWithUnmask
, forkFinally
, killThread
, throwTo
, forkOn
, forkOnWithUnmask
, getNumCapabilities
, setNumCapabilities
, threadCapability
, yield
, threadDelay
, threadWaitRead
, threadWaitWrite
, module Control.Concurrent.MVar.Lifted
, module Control.Concurrent.Chan.Lifted
, module Control.Concurrent.QSem.Lifted
, module Control.Concurrent.QSemN.Lifted
, C.rtsSupportsBoundThreads
, forkOS
, isCurrentThreadBound
, runInBoundThread
, runInUnboundThread
, mkWeakThreadId
) where
import Prelude ( (.) )
import Data.Bool ( Bool )
import Data.Int ( Int )
import Data.Function ( ($) )
import System.IO ( IO )
import System.Posix.Types ( Fd )
import Control.Monad ( (>>=) )
import Data.Either ( Either )
import System.Mem.Weak ( Weak )
import Control.Concurrent ( ThreadId )
import qualified Control.Concurrent as C
import Control.Monad.Base ( MonadBase, liftBase )
import Control.Monad.Trans.Control ( MonadBaseControl, liftBaseOp_, liftBaseDiscard )
import Control.Monad.Trans.Control ( liftBaseWith )
import Control.Monad ( void )
import Control.Concurrent.MVar.Lifted
import Control.Concurrent.Chan.Lifted
import Control.Concurrent.QSem.Lifted
import Control.Concurrent.QSemN.Lifted
import Control.Exception.Lifted ( throwTo
, SomeException, try, mask
)
myThreadId :: MonadBase IO m => m ThreadId
myThreadId = liftBase C.myThreadId
# INLINABLE myThreadId #
fork :: MonadBaseControl IO m => m () -> m ThreadId
fork = liftBaseDiscard C.forkIO
# INLINABLE fork #
forkWithUnmask :: MonadBaseControl IO m => ((forall a. m a -> m a) -> m ()) -> m ThreadId
forkWithUnmask f = liftBaseWith $ \runInIO ->
C.forkIOWithUnmask $ \unmask ->
void $ runInIO $ f $ liftBaseOp_ unmask
# INLINABLE forkWithUnmask #
| Generalized version of ' C.forkFinally ' .
forkFinally :: MonadBaseControl IO m
=> m a -> (Either SomeException a -> m ()) -> m ThreadId
forkFinally action and_then =
mask $ \restore ->
fork $ try (restore action) >>= and_then
# INLINABLE forkFinally #
killThread :: MonadBase IO m => ThreadId -> m ()
killThread = liftBase . C.killThread
# INLINABLE killThread #
forkOn :: MonadBaseControl IO m => Int -> m () -> m ThreadId
forkOn = liftBaseDiscard . C.forkOn
# INLINABLE forkOn #
| Generalized version of ' C.forkOnWithUnmask ' .
forkOnWithUnmask :: MonadBaseControl IO m => Int -> ((forall a. m a -> m a) -> m ()) -> m ThreadId
forkOnWithUnmask cap f = liftBaseWith $ \runInIO ->
C.forkOnWithUnmask cap $ \unmask ->
void $ runInIO $ f $ liftBaseOp_ unmask
# INLINABLE forkOnWithUnmask #
getNumCapabilities :: MonadBase IO m => m Int
getNumCapabilities = liftBase C.getNumCapabilities
# INLINABLE getNumCapabilities #
setNumCapabilities :: MonadBase IO m => Int -> m ()
setNumCapabilities = liftBase . C.setNumCapabilities
# INLINABLE setNumCapabilities #
threadCapability :: MonadBase IO m => ThreadId -> m (Int, Bool)
threadCapability = liftBase . C.threadCapability
# INLINABLE threadCapability #
yield :: MonadBase IO m => m ()
yield = liftBase C.yield
# INLINABLE yield #
| Generalized version of ' C.threadDelay ' .
threadDelay :: MonadBase IO m => Int -> m ()
threadDelay = liftBase . C.threadDelay
# INLINABLE threadDelay #
| Generalized version of ' ' .
threadWaitRead :: MonadBase IO m => Fd -> m ()
threadWaitRead = liftBase . C.threadWaitRead
# INLINABLE threadWaitRead #
threadWaitWrite :: MonadBase IO m => Fd -> m ()
threadWaitWrite = liftBase . C.threadWaitWrite
# INLINABLE threadWaitWrite #
| Generalized version of ' ' .
forkOS :: MonadBaseControl IO m => m () -> m ThreadId
forkOS = liftBaseDiscard C.forkOS
isCurrentThreadBound :: MonadBase IO m => m Bool
isCurrentThreadBound = liftBase C.isCurrentThreadBound
runInBoundThread :: MonadBaseControl IO m => m a -> m a
runInBoundThread = liftBaseOp_ C.runInBoundThread
# INLINABLE runInBoundThread #
runInUnboundThread :: MonadBaseControl IO m => m a -> m a
runInUnboundThread = liftBaseOp_ C.runInUnboundThread
# INLINABLE runInUnboundThread #
mkWeakThreadId :: MonadBase IO m => ThreadId -> m (Weak ThreadId)
mkWeakThreadId = liftBase . C.mkWeakThreadId
|
f3daf81387e86871bfb26567a4e093ac5c7593141360da10128d256af2c0a3ab | facebookarchive/duckling_old | time.clj | (
;; generic
"intersect"
sequence of two tokens with a time dimension
(intersect %1 %2)
same thing , with " of " in between like " Sunday of last week "
"intersect by \"of\", \"from\", \"'s\""
sequence of two tokens with a time fn
(intersect %1 %3)
mostly for January 12 , 2005
; this is a separate rule, because commas separate very specific tokens
; so we want this rule's classifier to learn this
"intersect by \",\""
sequence of two tokens with a time fn
(intersect %1 %3)
on We d , March 23
[#"(?i)den|på" (dim :time)]
%2 ; does NOT dissoc latent
on a sunday
[#"(?i)på en" {:form :day-of-week}]
%2 ; does NOT dissoc latent
;;;;;;;;;;;;;;;;;;;
;; Named things
"named-day"
#"(?i)mandag|man\.?"
(day-of-week 1)
"named-day"
#"(?i)tirsdag|tirs?\.?"
(day-of-week 2)
"named-day"
#"(?i)onsdag|ons\.?"
(day-of-week 3)
"named-day"
#"(?i)torsdag|tors?\.?"
(day-of-week 4)
"named-day"
#"(?i)fredag|fre\.?"
(day-of-week 5)
"named-day"
#"(?i)lørdag|lør\.?"
(day-of-week 6)
"named-day"
#"(?i)søndag|søn\.?"
(day-of-week 7)
"named-month"
#"(?i)januar|jan\.?"
(month 1)
"named-month"
#"(?i)februar|feb\.?"
(month 2)
"named-month"
#"(?i)mars|mar\.?"
(month 3)
"named-month"
#"(?i)april|apr\.?"
(month 4)
"named-month"
#"(?i)mai"
(month 5)
"named-month"
#"(?i)juni|jun\.?"
(month 6)
"named-month"
#"(?i)juli|jul\.?"
(month 7)
"named-month"
#"(?i)august|aug\.?"
(month 8)
"named-month"
#"(?i)september|sept?\.?"
(month 9)
"named-month"
#"(?i)oktober|okt\.?"
(month 10)
"named-month"
#"(?i)november|nov\.?"
(month 11)
"named-month"
#"(?i)desember|des\.?"
(month 12)
Holiday TODO : check online holidays
or define dynamic rule ( last thursday of october .. )
"christmas"
#"(?i)((1\.?)|første)? ?juledag"
(month-day 12 25)
"christmas eve"
#"(?i)julaften?"
(month-day 12 24)
"new year's eve"
#"(?i)nyttårsaften?"
(month-day 12 31)
"new year's day"
#"(?i)nyttårsdag"
(month-day 1 1)
"valentine's day"
#"(?i)valentine'?s?( dag)?"
(month-day 2 14)
17th of may in Norway
#"(?i)grunnlovsdag(en)"
(month-day 5 17)
second Sunday of November
#"(?i)farsdag"
(intersect (day-of-week 7) (month 11) (cycle-nth-after :week 1 (month-day 11 1)))
second Sunday of February .
#"(?i)morsdag"
(intersect (day-of-week 7) (month 2) (cycle-nth-after :week 1 (month-day 2 1)))
"halloween day"
#"(?i)hall?owe?en"
(month-day 10 31)
"absorption of , after named day"
[{:form :day-of-week} #","]
%1
"now"
#"(?i)akkurat nå|nå|(i )?dette øyeblikk"
(cycle-nth :second 0)
"today"
#"(?i)i dag|idag"
(cycle-nth :day 0)
"tomorrow"
#"(?i)i morgen|imorgen"
(cycle-nth :day 1)
"the day after tomorrow"
#"(?i)i overimorgen"
(cycle-nth :day 2)
"yesterday"
#"(?i)i går|igår"
(cycle-nth :day -1)
"the day before yesterday"
#"(?i)i forigårs"
(cycle-nth :day -2)
"EOM|End of month"
#"(?i)EOM" ; TO BE IMPROVED
(cycle-nth :month 1)
"EOY|End of year"
#"(?i)EOY"
(cycle-nth :year 1)
"Last year"
#"(?i)i fjor"
(cycle-nth :year -1)
;;
This , Next , Last
;; assumed to be strictly in the future:
" this Monday " = > next week if today is Monday
"this|next <day-of-week>"
[#"(?i)(kommende|neste)" {:form :day-of-week}]
(pred-nth-not-immediate %2 0)
for other , it can be immediate :
" this month " = > now is part of it
See also : cycles in en.cycles.clj
"this <time>"
[#"(?i)(denne|dette|i|den her)" (dim :time)]
(pred-nth %2 0)
"next <time>"
[#"(?i)neste|kommende" (dim :time #(not (:latent %)))]
(pred-nth-not-immediate %2 0)
"last <time>"
[#"(?i)(siste|sist|forrige|seneste)" (dim :time)]
(pred-nth %2 -1)
"<time> after next"
[#"(?i)neste" (dim :time) #"(?i)igjen"]
(pred-nth-not-immediate %2 1)
"<time> before last"
[#"(?i)siste" (dim :time) #"(?i)igjen"]
(pred-nth %2 -2)
"last <day-of-week> of <time>"
[#"(?i)siste" {:form :day-of-week} #"(?i)av|i" (dim :time)]
(pred-last-of %2 %4)
"last <cycle> of <time>"
[#"(?i)siste" (dim :cycle) #"(?i)av|i" (dim :time)]
(cycle-last-of %2 %4)
; Ordinals
"nth <time> of <time>"
[(dim :ordinal) (dim :time) #"(?i)av|i" (dim :time)]
(pred-nth (intersect %4 %2) (dec (:value %1)))
"nth <time> of <time>"
[#"(?i)den" (dim :ordinal) (dim :time) #"(?i)af|i" (dim :time)]
(pred-nth (intersect %5 %3) (dec (:value %2)))
"nth <time> after <time>"
[(dim :ordinal) (dim :time) #"(?i)etter" (dim :time)]
(pred-nth-after %2 %4 (dec (:value %1)))
"nth <time> after <time>"
[#"(?i)den" (dim :ordinal) (dim :time) #"(?i)etter" (dim :time)]
(pred-nth-after %3 %5 (dec (:value %2)))
Years
Between 1000 and 2100 we assume it 's a year
; Outside of this, it's safer to consider it's latent
"year"
(integer 1000 2100)
(year (:value %1))
"year (latent)"
(integer -10000 999)
(assoc (year (:value %1)) :latent true)
"year (latent)"
(integer 2101 10000)
(assoc (year (:value %1)) :latent true)
Day of month appears in the following context :
; - the nth
; - March nth
- nth of March
; - mm/dd (and other numerical formats like yyyy-mm-dd etc.)
In general we are flexible and accept both ordinals ( 3rd ) and numbers ( 3 )
"the <day-of-month> (ordinal)" ; this one is not latent
[#"(?i)den" (dim :ordinal #(<= 1 (:value %) 31))]
(day-of-month (:value %2))
"<day-of-month> (ordinal)" ; this one is latent
[(dim :ordinal #(<= 1 (:value %) 31))]
(assoc (day-of-month (:value %1)) :latent true)
"the <day-of-month> (non ordinal)" ; this one is latent
[#"(?i)den" (integer 1 31)]
(assoc (day-of-month (:value %2)) :latent true)
march 12th
[{:form :month} (dim :ordinal #(<= 1 (:value %) 31))]
(intersect %1 (day-of-month (:value %2)))
march 12
[{:form :month} (integer 1 31)]
(intersect %1 (day-of-month (:value %2)))
"<day-of-month> (ordinal) of <named-month>"
[(dim :ordinal #(<= 1 (:value %) 31)) #"(?i)av|i" {:form :month}]
(intersect %3 (day-of-month (:value %1)))
"<day-of-month> (non ordinal) of <named-month>"
[(integer 1 31) #"(?i)av|i" {:form :month}]
(intersect %3 (day-of-month (:value %1)))
12 mars
[(integer 1 31) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
"<day-of-month>(ordinal) <named-month>" ; 12nd mars
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
12nd mars 12
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month} #"(\d{2,4})"]
(intersect %2 (day-of-month (:value %1)) (year (Integer/parseInt(first (:groups %3)))))
the ides of march 13th for most months , but on the 15th for March , May , July , and October
[#"(?i)midten af" {:form :month}]
(intersect %2 (day-of-month (if (#{3 5 7 10} (:month %2)) 15 13)))
;; Hours and minutes (absolute time)
"time-of-day (latent)"
(integer 0 23)
(assoc (hour (:value %1) false) :latent true)
"<time-of-day> o'clock"
[#(:full-hour %) #"(?i)h"]
(dissoc %1 :latent)
at four
[#"(?i)klokken|kl.|@" {:form :time-of-day}]
(dissoc %2 :latent)
"hh:mm"
#"(?i)((?:[01]?\d)|(?:2[0-3]))[:.]([0-5]\d)"
(hour-minute (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
false)
"hh:mm:ss"
#"(?i)((?:[01]?\d)|(?:2[0-3]))[:.]([0-5]\d)[:.]([0-5]\d)"
(hour-minute-second (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
(Integer/parseInt (second (next (:groups %1))))
false)
" hhmm ( military ) " not sure if used and in conflict with year 1954
; #"(?i)((?:[01]?\d)|(?:2[0-3]))([0-5]\d)"
( - > ( hour - minute ( Integer / parseInt ( first (: groups % 1 ) ) )
( Integer / parseInt ( second (: groups % 1 ) ) )
false ) ; not a 12 - hour clock )
; (assoc :latent true))
"noon"
#"(?i)middag|(kl(\.|okken)?)? tolv"
(hour 12 false)
"midnight|EOD|end of day"
#"(?i)midnatt|EOD"
(hour 0 false)
"quarter (relative minutes)"
#"(?i)(et)? ?(kvart)(er)?"
{:relative-minutes 15}
"half (relative minutes)"
#"halv time"
{:relative-minutes 30}
"number (as relative minutes)"
(integer 1 59)
{:relative-minutes (:value %1)}
"<hour-of-day> <integer> (as relative minutes)"
[(dim :time :full-hour) #(:relative-minutes %)]
(hour-relativemin (:full-hour %1) (:relative-minutes %2) true)
"relative minutes to|till|before <integer> (hour-of-day)"
[#(:relative-minutes %) #"(?i)på" (dim :time :full-hour)]
(hour-relativemin (:full-hour %3) (- (:relative-minutes %1)) true)
"relative minutes after|past <integer> (hour-of-day)"
[#(:relative-minutes %) #"(?i)over" (dim :time :full-hour)]
(hour-relativemin (:full-hour %3) (:relative-minutes %1) true)
; Formatted dates and times
"dd/mm/yyyy"
#"(3[01]|[12]\d|0?[1-9])[\/-](0?[1-9]|1[0-2])[\/-](\d{2,4})"
(parse-dmy (first (:groups %1)) (second (:groups %1)) (nth (:groups %1) 2) true)
"yyyy-mm-dd"
#"(\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\d|0?[1-9])"
(parse-dmy (nth (:groups %1) 2) (second (:groups %1)) (first (:groups %1)) true)
"dd/mm"
#"(3[01]|[12]\d|0?[1-9])[\/-](0?[1-9]|1[0-2])"
(parse-dmy (first (:groups %1)) (second (:groups %1)) nil true)
; Part of day (morning, evening...). They are intervals.
TODO " 3 am this morning " wo n't work since morning starts at 4 ...
[#"(?i)morgen(en)?"]
(assoc (interval (hour 4 false) (hour 12 false) false) :form :part-of-day :latent true)
"afternoon"
[#"(?i)ettermiddag(en)?"]
(assoc (interval (hour 12 false) (hour 19 false) false) :form :part-of-day :latent true)
"evening"
[#"(?i)kveld(en)?"]
(assoc (interval (hour 18 false) (hour 0 false) false) :form :part-of-day :latent true)
"night"
[#"(?i)natt(en)?"]
(assoc (interval (hour 0 false) (hour 4 false) false) :form :part-of-day :latent true)
"lunch"
[#"(?i)(til )?middag"]
(assoc (interval (hour 12 false) (hour 14 false) false) :form :part-of-day :latent true)
"in|during the <part-of-day>" ;; removes latent
[#"(?i)om|i" {:form :part-of-day}]
(dissoc %2 :latent)
"in|during the <part-of-day>" ;; removes latent
[#"(?i)om|i" {:form :part-of-day} #"(?i)en|ten" ]
(dissoc %2 :latent)
"this <part-of-day>"
[#"(?i)i|denne" {:form :part-of-day}]
(assoc (intersect (cycle-nth :day 0) %2) :form :part-of-day) ;; removes :latent
"tonight"
#"(?i)i kveld"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 18 false) (hour 0 false) false))
:form :part-of-day) ; no :latent
"after lunch"
#"(?i)etter (frokost|middag|lunsj|lunch)"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 13 false) (hour 17 false) false))
:form :part-of-day) ; no :latent
"after work"
#"(?i)etter jobb"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 17 false) (hour 21 false) false))
:form :part-of-day) ; no :latent
since " morning " " evening " etc . are latent , general time+time is blocked
[(dim :time) {:form :part-of-day}]
(intersect %2 %1)
since " morning " " evening " etc . are latent , general time+time is blocked
[{:form :part-of-day} #"(?i)(en |ten )?den" (dim :time)]
(intersect %1 %3)
Other intervals : week - end , seasons
from Friday 6 pm to Sunday midnight
#"(?i)((week(\s|-)?end)|helg)(en|a)?"
(interval (intersect (day-of-week 5) (hour 18 false))
(intersect (day-of-week 1) (hour 0 false))
false)
"season"
could be smarter and take the exact hour into account ... also some years the day can change
(interval (month-day 6 21) (month-day 9 23) false)
; "season"
; #"(?i)etterår"
( interval ( month - day 9 23 ) ( month - day 12 21 ) false )
"season"
#"(?i)vinter(en)"
(interval (month-day 12 21) (month-day 3 20) false)
; "season"
; #"(?i)forår"
( interval ( month - day 3 20 ) ( month - day 6 21 ) false )
"christmas days"
#"(?i)romjul(a|en)"
(interval (month-day 12 24) (month-day 12 30) false)
Time zones
"timezone"
#"(?i)\b(YEKT|YEKST|YAPT|YAKT|YAKST|WT|WST|WITA|WIT|WIB|WGT|WGST|WFT|WEZ|WET|WESZ|WEST|WAT|WAST|VUT|VLAT|VLAST|VET|UZT|UYT|UYST|UTC|ULAT|TVT|TMT|TLT|TKT|TJT|TFT|TAHT|SST|SRT|SGT|SCT|SBT|SAST|SAMT|RET|PYT|PYST|PWT|PT|PST|PONT|PMST|PMDT|PKT|PHT|PHOT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|NCT|MYT|MVT|MUT|MST|MSK|MSD|MMT|MHT|MEZ|MESZ|MDT|MAWT|MART|MAGT|MAGST|LINT|LHST|LHDT|KUYT|KST|KRAT|KRAST|KGT|JST|IST|IRST|IRKT|IRKST|IRDT|IOT|IDT|ICT|HOVT|HNY|HNT|HNR|HNP|HNE|HNC|HNA|HLV|HKT|HAY|HAT|HAST|HAR|HAP|HAE|HADT|HAC|HAA|GYT|GST|GMT|GILT|GFT|GET|GAMT|GALT|FNT|FKT|FKST|FJT|FJST|ET|EST|EGT|EGST|EET|EEST|EDT|ECT|EAT|EAST|EASST|DAVT|ChST|CXT|CVT|CST|COT|CLT|CLST|CKT|CHAST|CHADT|CET|CEST|CDT|CCT|CAT|CAST|BTT|BST|BRT|BRST|BOT|BNT|AZT|AZST|AZOT|AZOST|AWST|AWDT|AST|ART|AQTT|ANAT|ANAST|AMT|AMST|ALMT|AKST|AKDT|AFT|AEST|AEDT|ADT|ACST|ACDT)\b"
{:dim :timezone
:value (-> %1 :groups first .toUpperCase)}
"<time> timezone"
[(dim :time) (dim :timezone)]
(set-timezone %1 (:value %2))
; Precision
FIXME
; - should be applied to all dims not just time-of-day
;- shouldn't remove latency, except maybe -ish
7ish
[{:form :time-of-day} #"(?i)(cirka|ca\.|-?ish)"]
(-> %1
(dissoc :latent)
(merge {:precision "approximate"}))
"<time-of-day> sharp" ; sharp
[{:form :time-of-day} #"(?i)(sharp|presis)"]
(-> %1
(dissoc :latent)
(merge {:precision "exact"}))
"about <time-of-day>" ; about
[#"(?i)(omkring|cirka|ca\.)( kl\.| klokken)?" {:form :time-of-day}]
(-> %2
(dissoc :latent)
(merge {:precision "approximate"}))
"exactly <time-of-day>" ; sharp
[#"(?i)presis( kl.| klokken)?" {:form :time-of-day} ]
(-> %2
(dissoc :latent)
(merge {:precision "exact"}))
; Intervals
"<month> dd-dd (interval)"
[ #"([012]?\d|30|31)(ter|\.)?" #"\-|til" #"([012]?\d|30|31)(ter|\.)?" {:form :month}]
(interval (intersect %4 (day-of-month (Integer/parseInt (-> %1 :groups first))))
(intersect %4 (day-of-month (Integer/parseInt (-> %3 :groups first))))
true)
Blocked for : latent time . May need to accept certain latents only , like hours
"<datetime> - <datetime> (interval)"
[(dim :time #(not (:latent %))) #"\-|til|tilogmed" (dim :time #(not (:latent %)))]
(interval %1 %3 true)
"from <datetime> - <datetime> (interval)"
[#"(?i)fra" (dim :time) #"\-|til|tilogmed" (dim :time)]
(interval %2 %4 true)
"between <datetime> and <datetime> (interval)"
[#"(?i)mellom" (dim :time) #"og" (dim :time)]
(interval %2 %4 true)
; Specific for time-of-day, to help resolve ambiguities
"<time-of-day> - <time-of-day> (interval)"
Prevent set alarm 1 to 5 pm
(interval %1 %3 true)
"from <time-of-day> - <time-of-day> (interval)"
[#"(?i)(etter|fra)" {:form :time-of-day} #"((men )?før)|\-|tilogmed|til" {:form :time-of-day}]
(interval %2 %4 true)
"between <time-of-day> and <time-of-day> (interval)"
[#"(?i)mellom" {:form :time-of-day} #"og" {:form :time-of-day}]
(interval %2 %4 true)
; Specific for within duration... Would need to be reworked
"within <duration>"
[#"(?i)innenfor" (dim :duration)]
(interval (cycle-nth :second 0) (in-duration (:value %2)) false)
in this case take the end of the time ( by the end of next week = by the end of next sunday )
[#"(?i)i slutten av" (dim :time)]
(interval (cycle-nth :second 0) %2 true)
One - sided Intervals
"until <time-of-day>"
[#"(?i)(engang )?innen|før|opptil" (dim :time)]
(merge %2 {:direction :before})
"after <time-of-day>"
[#"(?i)(engang )?etter" (dim :time)]
(merge %2 {:direction :after})
; ;; In this special case, the upper limit is exclusive
; "<hour-of-day> - <hour-of-day> (interval)"
; [{:form :time-of-day} #"-|to|th?ru|through|until" #(and (= :time-of-day (:form %))
; (not (:latent %)))]
( interval % 1 % 3 : exclusive )
; "from <hour-of-day> - <hour-of-day> (interval)"
; [#"(?i)from" {:form :time-of-day} #"-|to|th?ru|through|until" #(and (= :time-of-day (:form %))
; (not (:latent %)))]
( interval % 2 % 4 : exclusive )
; "time => time2 (experiment)"
; (dim :time)
; (assoc %1 :dim :time2)
)
| null | https://raw.githubusercontent.com/facebookarchive/duckling_old/bf5bb9758c36313b56e136a28ba401696eeff10b/resources/languages/nb/rules/time.clj | clojure | generic
this is a separate rule, because commas separate very specific tokens
so we want this rule's classifier to learn this
does NOT dissoc latent
does NOT dissoc latent
Named things
TO BE IMPROVED
assumed to be strictly in the future:
Ordinals
Outside of this, it's safer to consider it's latent
- the nth
- March nth
- mm/dd (and other numerical formats like yyyy-mm-dd etc.)
this one is not latent
this one is latent
this one is latent
12nd mars
Hours and minutes (absolute time)
#"(?i)((?:[01]?\d)|(?:2[0-3]))([0-5]\d)"
not a 12 - hour clock )
(assoc :latent true))
Formatted dates and times
Part of day (morning, evening...). They are intervals.
removes latent
removes latent
removes :latent
no :latent
no :latent
no :latent
"season"
#"(?i)etterår"
"season"
#"(?i)forår"
Precision
- should be applied to all dims not just time-of-day
- shouldn't remove latency, except maybe -ish
sharp
about
sharp
Intervals
Specific for time-of-day, to help resolve ambiguities
Specific for within duration... Would need to be reworked
;; In this special case, the upper limit is exclusive
"<hour-of-day> - <hour-of-day> (interval)"
[{:form :time-of-day} #"-|to|th?ru|through|until" #(and (= :time-of-day (:form %))
(not (:latent %)))]
"from <hour-of-day> - <hour-of-day> (interval)"
[#"(?i)from" {:form :time-of-day} #"-|to|th?ru|through|until" #(and (= :time-of-day (:form %))
(not (:latent %)))]
"time => time2 (experiment)"
(dim :time)
(assoc %1 :dim :time2) | (
"intersect"
sequence of two tokens with a time dimension
(intersect %1 %2)
same thing , with " of " in between like " Sunday of last week "
"intersect by \"of\", \"from\", \"'s\""
sequence of two tokens with a time fn
(intersect %1 %3)
mostly for January 12 , 2005
"intersect by \",\""
sequence of two tokens with a time fn
(intersect %1 %3)
on We d , March 23
[#"(?i)den|på" (dim :time)]
on a sunday
[#"(?i)på en" {:form :day-of-week}]
"named-day"
#"(?i)mandag|man\.?"
(day-of-week 1)
"named-day"
#"(?i)tirsdag|tirs?\.?"
(day-of-week 2)
"named-day"
#"(?i)onsdag|ons\.?"
(day-of-week 3)
"named-day"
#"(?i)torsdag|tors?\.?"
(day-of-week 4)
"named-day"
#"(?i)fredag|fre\.?"
(day-of-week 5)
"named-day"
#"(?i)lørdag|lør\.?"
(day-of-week 6)
"named-day"
#"(?i)søndag|søn\.?"
(day-of-week 7)
"named-month"
#"(?i)januar|jan\.?"
(month 1)
"named-month"
#"(?i)februar|feb\.?"
(month 2)
"named-month"
#"(?i)mars|mar\.?"
(month 3)
"named-month"
#"(?i)april|apr\.?"
(month 4)
"named-month"
#"(?i)mai"
(month 5)
"named-month"
#"(?i)juni|jun\.?"
(month 6)
"named-month"
#"(?i)juli|jul\.?"
(month 7)
"named-month"
#"(?i)august|aug\.?"
(month 8)
"named-month"
#"(?i)september|sept?\.?"
(month 9)
"named-month"
#"(?i)oktober|okt\.?"
(month 10)
"named-month"
#"(?i)november|nov\.?"
(month 11)
"named-month"
#"(?i)desember|des\.?"
(month 12)
Holiday TODO : check online holidays
or define dynamic rule ( last thursday of october .. )
"christmas"
#"(?i)((1\.?)|første)? ?juledag"
(month-day 12 25)
"christmas eve"
#"(?i)julaften?"
(month-day 12 24)
"new year's eve"
#"(?i)nyttårsaften?"
(month-day 12 31)
"new year's day"
#"(?i)nyttårsdag"
(month-day 1 1)
"valentine's day"
#"(?i)valentine'?s?( dag)?"
(month-day 2 14)
17th of may in Norway
#"(?i)grunnlovsdag(en)"
(month-day 5 17)
second Sunday of November
#"(?i)farsdag"
(intersect (day-of-week 7) (month 11) (cycle-nth-after :week 1 (month-day 11 1)))
second Sunday of February .
#"(?i)morsdag"
(intersect (day-of-week 7) (month 2) (cycle-nth-after :week 1 (month-day 2 1)))
"halloween day"
#"(?i)hall?owe?en"
(month-day 10 31)
"absorption of , after named day"
[{:form :day-of-week} #","]
%1
"now"
#"(?i)akkurat nå|nå|(i )?dette øyeblikk"
(cycle-nth :second 0)
"today"
#"(?i)i dag|idag"
(cycle-nth :day 0)
"tomorrow"
#"(?i)i morgen|imorgen"
(cycle-nth :day 1)
"the day after tomorrow"
#"(?i)i overimorgen"
(cycle-nth :day 2)
"yesterday"
#"(?i)i går|igår"
(cycle-nth :day -1)
"the day before yesterday"
#"(?i)i forigårs"
(cycle-nth :day -2)
"EOM|End of month"
(cycle-nth :month 1)
"EOY|End of year"
#"(?i)EOY"
(cycle-nth :year 1)
"Last year"
#"(?i)i fjor"
(cycle-nth :year -1)
This , Next , Last
" this Monday " = > next week if today is Monday
"this|next <day-of-week>"
[#"(?i)(kommende|neste)" {:form :day-of-week}]
(pred-nth-not-immediate %2 0)
for other , it can be immediate :
" this month " = > now is part of it
See also : cycles in en.cycles.clj
"this <time>"
[#"(?i)(denne|dette|i|den her)" (dim :time)]
(pred-nth %2 0)
"next <time>"
[#"(?i)neste|kommende" (dim :time #(not (:latent %)))]
(pred-nth-not-immediate %2 0)
"last <time>"
[#"(?i)(siste|sist|forrige|seneste)" (dim :time)]
(pred-nth %2 -1)
"<time> after next"
[#"(?i)neste" (dim :time) #"(?i)igjen"]
(pred-nth-not-immediate %2 1)
"<time> before last"
[#"(?i)siste" (dim :time) #"(?i)igjen"]
(pred-nth %2 -2)
"last <day-of-week> of <time>"
[#"(?i)siste" {:form :day-of-week} #"(?i)av|i" (dim :time)]
(pred-last-of %2 %4)
"last <cycle> of <time>"
[#"(?i)siste" (dim :cycle) #"(?i)av|i" (dim :time)]
(cycle-last-of %2 %4)
"nth <time> of <time>"
[(dim :ordinal) (dim :time) #"(?i)av|i" (dim :time)]
(pred-nth (intersect %4 %2) (dec (:value %1)))
"nth <time> of <time>"
[#"(?i)den" (dim :ordinal) (dim :time) #"(?i)af|i" (dim :time)]
(pred-nth (intersect %5 %3) (dec (:value %2)))
"nth <time> after <time>"
[(dim :ordinal) (dim :time) #"(?i)etter" (dim :time)]
(pred-nth-after %2 %4 (dec (:value %1)))
"nth <time> after <time>"
[#"(?i)den" (dim :ordinal) (dim :time) #"(?i)etter" (dim :time)]
(pred-nth-after %3 %5 (dec (:value %2)))
Years
Between 1000 and 2100 we assume it 's a year
"year"
(integer 1000 2100)
(year (:value %1))
"year (latent)"
(integer -10000 999)
(assoc (year (:value %1)) :latent true)
"year (latent)"
(integer 2101 10000)
(assoc (year (:value %1)) :latent true)
Day of month appears in the following context :
- nth of March
In general we are flexible and accept both ordinals ( 3rd ) and numbers ( 3 )
[#"(?i)den" (dim :ordinal #(<= 1 (:value %) 31))]
(day-of-month (:value %2))
[(dim :ordinal #(<= 1 (:value %) 31))]
(assoc (day-of-month (:value %1)) :latent true)
[#"(?i)den" (integer 1 31)]
(assoc (day-of-month (:value %2)) :latent true)
march 12th
[{:form :month} (dim :ordinal #(<= 1 (:value %) 31))]
(intersect %1 (day-of-month (:value %2)))
march 12
[{:form :month} (integer 1 31)]
(intersect %1 (day-of-month (:value %2)))
"<day-of-month> (ordinal) of <named-month>"
[(dim :ordinal #(<= 1 (:value %) 31)) #"(?i)av|i" {:form :month}]
(intersect %3 (day-of-month (:value %1)))
"<day-of-month> (non ordinal) of <named-month>"
[(integer 1 31) #"(?i)av|i" {:form :month}]
(intersect %3 (day-of-month (:value %1)))
12 mars
[(integer 1 31) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
12nd mars 12
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month} #"(\d{2,4})"]
(intersect %2 (day-of-month (:value %1)) (year (Integer/parseInt(first (:groups %3)))))
the ides of march 13th for most months , but on the 15th for March , May , July , and October
[#"(?i)midten af" {:form :month}]
(intersect %2 (day-of-month (if (#{3 5 7 10} (:month %2)) 15 13)))
"time-of-day (latent)"
(integer 0 23)
(assoc (hour (:value %1) false) :latent true)
"<time-of-day> o'clock"
[#(:full-hour %) #"(?i)h"]
(dissoc %1 :latent)
at four
[#"(?i)klokken|kl.|@" {:form :time-of-day}]
(dissoc %2 :latent)
"hh:mm"
#"(?i)((?:[01]?\d)|(?:2[0-3]))[:.]([0-5]\d)"
(hour-minute (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
false)
"hh:mm:ss"
#"(?i)((?:[01]?\d)|(?:2[0-3]))[:.]([0-5]\d)[:.]([0-5]\d)"
(hour-minute-second (Integer/parseInt (first (:groups %1)))
(Integer/parseInt (second (:groups %1)))
(Integer/parseInt (second (next (:groups %1))))
false)
" hhmm ( military ) " not sure if used and in conflict with year 1954
( - > ( hour - minute ( Integer / parseInt ( first (: groups % 1 ) ) )
( Integer / parseInt ( second (: groups % 1 ) ) )
"noon"
#"(?i)middag|(kl(\.|okken)?)? tolv"
(hour 12 false)
"midnight|EOD|end of day"
#"(?i)midnatt|EOD"
(hour 0 false)
"quarter (relative minutes)"
#"(?i)(et)? ?(kvart)(er)?"
{:relative-minutes 15}
"half (relative minutes)"
#"halv time"
{:relative-minutes 30}
"number (as relative minutes)"
(integer 1 59)
{:relative-minutes (:value %1)}
"<hour-of-day> <integer> (as relative minutes)"
[(dim :time :full-hour) #(:relative-minutes %)]
(hour-relativemin (:full-hour %1) (:relative-minutes %2) true)
"relative minutes to|till|before <integer> (hour-of-day)"
[#(:relative-minutes %) #"(?i)på" (dim :time :full-hour)]
(hour-relativemin (:full-hour %3) (- (:relative-minutes %1)) true)
"relative minutes after|past <integer> (hour-of-day)"
[#(:relative-minutes %) #"(?i)over" (dim :time :full-hour)]
(hour-relativemin (:full-hour %3) (:relative-minutes %1) true)
"dd/mm/yyyy"
#"(3[01]|[12]\d|0?[1-9])[\/-](0?[1-9]|1[0-2])[\/-](\d{2,4})"
(parse-dmy (first (:groups %1)) (second (:groups %1)) (nth (:groups %1) 2) true)
"yyyy-mm-dd"
#"(\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\d|0?[1-9])"
(parse-dmy (nth (:groups %1) 2) (second (:groups %1)) (first (:groups %1)) true)
"dd/mm"
#"(3[01]|[12]\d|0?[1-9])[\/-](0?[1-9]|1[0-2])"
(parse-dmy (first (:groups %1)) (second (:groups %1)) nil true)
TODO " 3 am this morning " wo n't work since morning starts at 4 ...
[#"(?i)morgen(en)?"]
(assoc (interval (hour 4 false) (hour 12 false) false) :form :part-of-day :latent true)
"afternoon"
[#"(?i)ettermiddag(en)?"]
(assoc (interval (hour 12 false) (hour 19 false) false) :form :part-of-day :latent true)
"evening"
[#"(?i)kveld(en)?"]
(assoc (interval (hour 18 false) (hour 0 false) false) :form :part-of-day :latent true)
"night"
[#"(?i)natt(en)?"]
(assoc (interval (hour 0 false) (hour 4 false) false) :form :part-of-day :latent true)
"lunch"
[#"(?i)(til )?middag"]
(assoc (interval (hour 12 false) (hour 14 false) false) :form :part-of-day :latent true)
[#"(?i)om|i" {:form :part-of-day}]
(dissoc %2 :latent)
[#"(?i)om|i" {:form :part-of-day} #"(?i)en|ten" ]
(dissoc %2 :latent)
"this <part-of-day>"
[#"(?i)i|denne" {:form :part-of-day}]
"tonight"
#"(?i)i kveld"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 18 false) (hour 0 false) false))
"after lunch"
#"(?i)etter (frokost|middag|lunsj|lunch)"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 13 false) (hour 17 false) false))
"after work"
#"(?i)etter jobb"
(assoc (intersect (cycle-nth :day 0)
(interval (hour 17 false) (hour 21 false) false))
since " morning " " evening " etc . are latent , general time+time is blocked
[(dim :time) {:form :part-of-day}]
(intersect %2 %1)
since " morning " " evening " etc . are latent , general time+time is blocked
[{:form :part-of-day} #"(?i)(en |ten )?den" (dim :time)]
(intersect %1 %3)
Other intervals : week - end , seasons
from Friday 6 pm to Sunday midnight
#"(?i)((week(\s|-)?end)|helg)(en|a)?"
(interval (intersect (day-of-week 5) (hour 18 false))
(intersect (day-of-week 1) (hour 0 false))
false)
"season"
could be smarter and take the exact hour into account ... also some years the day can change
(interval (month-day 6 21) (month-day 9 23) false)
( interval ( month - day 9 23 ) ( month - day 12 21 ) false )
"season"
#"(?i)vinter(en)"
(interval (month-day 12 21) (month-day 3 20) false)
( interval ( month - day 3 20 ) ( month - day 6 21 ) false )
"christmas days"
#"(?i)romjul(a|en)"
(interval (month-day 12 24) (month-day 12 30) false)
Time zones
"timezone"
#"(?i)\b(YEKT|YEKST|YAPT|YAKT|YAKST|WT|WST|WITA|WIT|WIB|WGT|WGST|WFT|WEZ|WET|WESZ|WEST|WAT|WAST|VUT|VLAT|VLAST|VET|UZT|UYT|UYST|UTC|ULAT|TVT|TMT|TLT|TKT|TJT|TFT|TAHT|SST|SRT|SGT|SCT|SBT|SAST|SAMT|RET|PYT|PYST|PWT|PT|PST|PONT|PMST|PMDT|PKT|PHT|PHOT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|NCT|MYT|MVT|MUT|MST|MSK|MSD|MMT|MHT|MEZ|MESZ|MDT|MAWT|MART|MAGT|MAGST|LINT|LHST|LHDT|KUYT|KST|KRAT|KRAST|KGT|JST|IST|IRST|IRKT|IRKST|IRDT|IOT|IDT|ICT|HOVT|HNY|HNT|HNR|HNP|HNE|HNC|HNA|HLV|HKT|HAY|HAT|HAST|HAR|HAP|HAE|HADT|HAC|HAA|GYT|GST|GMT|GILT|GFT|GET|GAMT|GALT|FNT|FKT|FKST|FJT|FJST|ET|EST|EGT|EGST|EET|EEST|EDT|ECT|EAT|EAST|EASST|DAVT|ChST|CXT|CVT|CST|COT|CLT|CLST|CKT|CHAST|CHADT|CET|CEST|CDT|CCT|CAT|CAST|BTT|BST|BRT|BRST|BOT|BNT|AZT|AZST|AZOT|AZOST|AWST|AWDT|AST|ART|AQTT|ANAT|ANAST|AMT|AMST|ALMT|AKST|AKDT|AFT|AEST|AEDT|ADT|ACST|ACDT)\b"
{:dim :timezone
:value (-> %1 :groups first .toUpperCase)}
"<time> timezone"
[(dim :time) (dim :timezone)]
(set-timezone %1 (:value %2))
FIXME
7ish
[{:form :time-of-day} #"(?i)(cirka|ca\.|-?ish)"]
(-> %1
(dissoc :latent)
(merge {:precision "approximate"}))
[{:form :time-of-day} #"(?i)(sharp|presis)"]
(-> %1
(dissoc :latent)
(merge {:precision "exact"}))
[#"(?i)(omkring|cirka|ca\.)( kl\.| klokken)?" {:form :time-of-day}]
(-> %2
(dissoc :latent)
(merge {:precision "approximate"}))
[#"(?i)presis( kl.| klokken)?" {:form :time-of-day} ]
(-> %2
(dissoc :latent)
(merge {:precision "exact"}))
"<month> dd-dd (interval)"
[ #"([012]?\d|30|31)(ter|\.)?" #"\-|til" #"([012]?\d|30|31)(ter|\.)?" {:form :month}]
(interval (intersect %4 (day-of-month (Integer/parseInt (-> %1 :groups first))))
(intersect %4 (day-of-month (Integer/parseInt (-> %3 :groups first))))
true)
Blocked for : latent time . May need to accept certain latents only , like hours
"<datetime> - <datetime> (interval)"
[(dim :time #(not (:latent %))) #"\-|til|tilogmed" (dim :time #(not (:latent %)))]
(interval %1 %3 true)
"from <datetime> - <datetime> (interval)"
[#"(?i)fra" (dim :time) #"\-|til|tilogmed" (dim :time)]
(interval %2 %4 true)
"between <datetime> and <datetime> (interval)"
[#"(?i)mellom" (dim :time) #"og" (dim :time)]
(interval %2 %4 true)
"<time-of-day> - <time-of-day> (interval)"
Prevent set alarm 1 to 5 pm
(interval %1 %3 true)
"from <time-of-day> - <time-of-day> (interval)"
[#"(?i)(etter|fra)" {:form :time-of-day} #"((men )?før)|\-|tilogmed|til" {:form :time-of-day}]
(interval %2 %4 true)
"between <time-of-day> and <time-of-day> (interval)"
[#"(?i)mellom" {:form :time-of-day} #"og" {:form :time-of-day}]
(interval %2 %4 true)
"within <duration>"
[#"(?i)innenfor" (dim :duration)]
(interval (cycle-nth :second 0) (in-duration (:value %2)) false)
in this case take the end of the time ( by the end of next week = by the end of next sunday )
[#"(?i)i slutten av" (dim :time)]
(interval (cycle-nth :second 0) %2 true)
One - sided Intervals
"until <time-of-day>"
[#"(?i)(engang )?innen|før|opptil" (dim :time)]
(merge %2 {:direction :before})
"after <time-of-day>"
[#"(?i)(engang )?etter" (dim :time)]
(merge %2 {:direction :after})
( interval % 1 % 3 : exclusive )
( interval % 2 % 4 : exclusive )
)
|
fac8960008ff59679fac797b245fc3ce3442e0c3df1903bf246d514e49a06f32 | tommaisey/aeon | zero-crossing.help.scm | ( zero - crossing in )
Zero crossing frequency follower .
;; outputs a frequency based upon the distance between interceptions
;; of the X axis. The X intercepts are determined via linear
;; interpolation so this gives better than just integer wavelength
;; resolution. This is a very crude pitch follower, but can be useful
;; in some situations.
;; in - input signal.
(let* ((a (mul (sin-osc ar (mul-add (sin-osc kr 1 0) 600 700) 0) 0.1))
(b (mul (impulse ar (zero-crossing a) 0) 0.25)))
(audition (out 0 (mce2 a b))))
| null | https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/analysis/zero-crossing.help.scm | scheme | outputs a frequency based upon the distance between interceptions
of the X axis. The X intercepts are determined via linear
interpolation so this gives better than just integer wavelength
resolution. This is a very crude pitch follower, but can be useful
in some situations.
in - input signal. | ( zero - crossing in )
Zero crossing frequency follower .
(let* ((a (mul (sin-osc ar (mul-add (sin-osc kr 1 0) 600 700) 0) 0.1))
(b (mul (impulse ar (zero-crossing a) 0) 0.25)))
(audition (out 0 (mce2 a b))))
|
35bbbed5d7d63b871807fe678e4c4cdba70a34654d625f00a238640aa0d8c470 | input-output-hk/project-icarus-importer | ConstantsSpec.hs | -- | This module tests some invariants on constants.
module Test.Pos.ConstantsSpec
( spec
) where
import Universum
import Pos.Core (SystemTag (..))
import Pos.Update.Configuration (HasUpdateConfiguration, ourSystemTag)
import Test.Hspec (Expectation, Spec, describe, it, shouldSatisfy)
import Test.Pos.Configuration (withDefUpdateConfiguration)
| @currentSystemTag@ is a value obtained at compile time with TemplateHaskell
-- that represents that current system's platform (i.e. where it was compiled).
-- As of the @cardano-sl-1.0.4@, the only officially supported systems are @win64@ and
-- @macos64@ (@linux64@ can be built and used from source).
If @currentSystemTag@ is not one of these two when this test is ran with
-- @cardano-sl-1.0.4@, something has gone wrong.
systemTagCheck :: HasUpdateConfiguration => Expectation
systemTagCheck = do
let sysTags = map SystemTag ["linux64", "macos64", "win64"]
felem = flip elem
ourSystemTag `shouldSatisfy` felem sysTags
spec :: Spec
spec = withDefUpdateConfiguration $ describe "Constants" $ do
describe "Configuration constants" $ do
it "currentSystemTag" $ systemTagCheck
| null | https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/lib/test/Test/Pos/ConstantsSpec.hs | haskell | | This module tests some invariants on constants.
that represents that current system's platform (i.e. where it was compiled).
As of the @cardano-sl-1.0.4@, the only officially supported systems are @win64@ and
@macos64@ (@linux64@ can be built and used from source).
@cardano-sl-1.0.4@, something has gone wrong. |
module Test.Pos.ConstantsSpec
( spec
) where
import Universum
import Pos.Core (SystemTag (..))
import Pos.Update.Configuration (HasUpdateConfiguration, ourSystemTag)
import Test.Hspec (Expectation, Spec, describe, it, shouldSatisfy)
import Test.Pos.Configuration (withDefUpdateConfiguration)
| @currentSystemTag@ is a value obtained at compile time with TemplateHaskell
If @currentSystemTag@ is not one of these two when this test is ran with
systemTagCheck :: HasUpdateConfiguration => Expectation
systemTagCheck = do
let sysTags = map SystemTag ["linux64", "macos64", "win64"]
felem = flip elem
ourSystemTag `shouldSatisfy` felem sysTags
spec :: Spec
spec = withDefUpdateConfiguration $ describe "Constants" $ do
describe "Configuration constants" $ do
it "currentSystemTag" $ systemTagCheck
|
4c76d20ea5580e6d02da7914a94890dba34b03e71ed3facca54f5c85e826dab7 | maitria/avi | core.clj | (ns avi.core
(:import [avi.terminal Terminal])
(:require [packthread.core :refer :all]
[avi.editor :as e]
[clojure.stacktrace :as st]
[avi.main]
[avi.world :refer :all])
(:gen-class))
(defn- event-stream
([world]
(event-stream world (terminal-size world)))
([world current-size]
(lazy-seq
(let [keystroke (read-key world)
new-size (terminal-size world)]
(cond->> (event-stream world new-size)
true
(cons [:keystroke keystroke])
(not= current-size new-size)
(cons [:resize new-size]))))))
(defn- editor-stream
[world args]
(let [responder (avi.main/responder true)
initial-editor (avi.main/initial-editor (terminal-size world) args)]
(->> (event-stream world)
(reductions responder initial-editor)
(take-while (complement :finished?)))))
(defn- perform-effects!
[editor]
(when (:avi.editor/beep? editor)
(beep *world*))
(update-terminal *world* (:rendition editor)))
(defn- run
[world args]
(binding [*world* world]
(setup *world*)
(doseq [editor (editor-stream *world* args)]
(perform-effects! editor))
(cleanup *world*)))
(defn- clean-exit
[world]
(binding [*world* world]
(cleanup *world*)))
(defn -main
[& args]
(let [world (reify
World
(setup [_] (Terminal/start))
(cleanup [_] (Terminal/stop))
(read-key [_] (Terminal/getKey))
(beep [_] (Terminal/beep))
(terminal-size [_]
(let [size (Terminal/size)]
[(get size 0) (get size 1)]))
(update-terminal [_ {chars :chars,
attrs :attrs,
width :width,
[i j] :point}]
(Terminal/refresh i j width chars attrs))
(read-file [_ filename]
(slurp filename))
(write-file [_ filename contents]
(spit filename contents)))]
(try
(run world args)
(catch Exception e ((clean-exit world)
(println "============================================================")
(println "You have caught a bug in Avi")
(println "Stacktrace for the issue follows:")
(st/print-stack-trace e)
(println "============================================================")
(println "Issue can be logged for avi at:")
(println "")
(println "Do also provide the exact steps to reproduce the issue there")
(println "============================================================"))))))
| null | https://raw.githubusercontent.com/maitria/avi/c641e9e32af4300ea7273a41e86b4f47d0f2c092/src/avi/core.clj | clojure | (ns avi.core
(:import [avi.terminal Terminal])
(:require [packthread.core :refer :all]
[avi.editor :as e]
[clojure.stacktrace :as st]
[avi.main]
[avi.world :refer :all])
(:gen-class))
(defn- event-stream
([world]
(event-stream world (terminal-size world)))
([world current-size]
(lazy-seq
(let [keystroke (read-key world)
new-size (terminal-size world)]
(cond->> (event-stream world new-size)
true
(cons [:keystroke keystroke])
(not= current-size new-size)
(cons [:resize new-size]))))))
(defn- editor-stream
[world args]
(let [responder (avi.main/responder true)
initial-editor (avi.main/initial-editor (terminal-size world) args)]
(->> (event-stream world)
(reductions responder initial-editor)
(take-while (complement :finished?)))))
(defn- perform-effects!
[editor]
(when (:avi.editor/beep? editor)
(beep *world*))
(update-terminal *world* (:rendition editor)))
(defn- run
[world args]
(binding [*world* world]
(setup *world*)
(doseq [editor (editor-stream *world* args)]
(perform-effects! editor))
(cleanup *world*)))
(defn- clean-exit
[world]
(binding [*world* world]
(cleanup *world*)))
(defn -main
[& args]
(let [world (reify
World
(setup [_] (Terminal/start))
(cleanup [_] (Terminal/stop))
(read-key [_] (Terminal/getKey))
(beep [_] (Terminal/beep))
(terminal-size [_]
(let [size (Terminal/size)]
[(get size 0) (get size 1)]))
(update-terminal [_ {chars :chars,
attrs :attrs,
width :width,
[i j] :point}]
(Terminal/refresh i j width chars attrs))
(read-file [_ filename]
(slurp filename))
(write-file [_ filename contents]
(spit filename contents)))]
(try
(run world args)
(catch Exception e ((clean-exit world)
(println "============================================================")
(println "You have caught a bug in Avi")
(println "Stacktrace for the issue follows:")
(st/print-stack-trace e)
(println "============================================================")
(println "Issue can be logged for avi at:")
(println "")
(println "Do also provide the exact steps to reproduce the issue there")
(println "============================================================"))))))
| |
d687555d6ff519fd573e470d202eeb9eff98746bd1ed2a13d241cf942b4fe35a | janestreet/bonsai | bonsai_web_ui_not_connected_warning_box.ml | open! Core
open Virtual_dom
open Bonsai.Let_syntax
module Style =
[%css
stylesheet
{|
.connected {
display: none;
}
.warning {
font-size: 1.5rem;
font-weight: bold;
}
|}]
let message_for_async_durable time_span =
sprintf
"You've been disconnected from the server for %s. There is no need to refresh the \
page, since the web client will reconnect automatically when the server becomes \
available again."
(Time_ns.Span.to_string_hum ~decimals:0 time_span)
;;
let component ?(styles = Vdom.Attr.empty) ~create_message is_connected =
if%sub is_connected
then Bonsai.const (Vdom.Node.div ~attr:Style.connected [])
else (
let%sub activation_time, set_activation_time =
Bonsai.state_opt (module Time_ns.Alternate_sexp)
in
let%sub now = Bonsai.Clock.approx_now ~tick_every:(Time_ns.Span.of_sec 1.0) in
let%sub () =
Bonsai.Edge.lifecycle
~on_activate:(set_activation_time <*> (now >>| Option.some))
()
in
let%arr now = now
and activation_time = activation_time in
let duration_of_visibility =
Time_ns.diff now (Option.value ~default:now activation_time)
in
Vdom.Node.div
~attr:styles
[ Vdom.Node.div ~attr:Style.warning [ Vdom.Node.text "Warning!" ]
; Vdom.Node.div [ Vdom.Node.text (create_message duration_of_visibility) ]
])
;;
| null | https://raw.githubusercontent.com/janestreet/bonsai/8643e8b3717b035386ac36f2bcfa4a05bca0d64f/web_ui/not_connected_warning_box/src/bonsai_web_ui_not_connected_warning_box.ml | ocaml | open! Core
open Virtual_dom
open Bonsai.Let_syntax
module Style =
[%css
stylesheet
{|
.connected {
display: none;
}
.warning {
font-size: 1.5rem;
font-weight: bold;
}
|}]
let message_for_async_durable time_span =
sprintf
"You've been disconnected from the server for %s. There is no need to refresh the \
page, since the web client will reconnect automatically when the server becomes \
available again."
(Time_ns.Span.to_string_hum ~decimals:0 time_span)
;;
let component ?(styles = Vdom.Attr.empty) ~create_message is_connected =
if%sub is_connected
then Bonsai.const (Vdom.Node.div ~attr:Style.connected [])
else (
let%sub activation_time, set_activation_time =
Bonsai.state_opt (module Time_ns.Alternate_sexp)
in
let%sub now = Bonsai.Clock.approx_now ~tick_every:(Time_ns.Span.of_sec 1.0) in
let%sub () =
Bonsai.Edge.lifecycle
~on_activate:(set_activation_time <*> (now >>| Option.some))
()
in
let%arr now = now
and activation_time = activation_time in
let duration_of_visibility =
Time_ns.diff now (Option.value ~default:now activation_time)
in
Vdom.Node.div
~attr:styles
[ Vdom.Node.div ~attr:Style.warning [ Vdom.Node.text "Warning!" ]
; Vdom.Node.div [ Vdom.Node.text (create_message duration_of_visibility) ]
])
;;
| |
2de3369fc4e01cb49129944a100bdac63a75073b511630ce66c1f42c3adb31fa | facebook/flow | prefix.mli |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(*****************************************************************************)
(* The prefix is used to guarantee that we are not mixing different kind of
* keys in the heap.
* It just creates a new prefix every time its called.
*)
(*****************************************************************************)
type t (* Better make the type abstract *)
val make : unit -> t
(* Given a prefix and a key make me a prefixed key *)
val make_key : t -> string -> string
(* Removes the prefix from a key *)
val remove : t -> string -> string
| null | https://raw.githubusercontent.com/facebook/flow/741104e69c43057ebd32804dd6bcc1b5e97548ea/src/heap/prefix.mli | ocaml | ***************************************************************************
The prefix is used to guarantee that we are not mixing different kind of
* keys in the heap.
* It just creates a new prefix every time its called.
***************************************************************************
Better make the type abstract
Given a prefix and a key make me a prefixed key
Removes the prefix from a key |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
val make : unit -> t
val make_key : t -> string -> string
val remove : t -> string -> string
|
7ab6fbbcd1298778c5f916b31b4e425f3cb78347469ee8a20662cb6a0b348850 | bobatkey/CS316-18 | Lec20.hs | module Main where
LECTURE 20 : CONCURRENCY
import Control.Concurrent
import Control.Monad (forever, forM_)
import Network
import System.IO
import Text.Printf
forkIO : : IO ( ) - > IO ThreadId
muddle :: IO ()
muddle = do
hSetBuffering stdout NoBuffering
forkIO (forM_ [1..1000] (\_ -> putChar 'A'))
forM_ [1..1000] (\_ -> putChar 'B')
-- threadDelay :: Int -> IO ()
setReminder :: String -> IO ()
setReminder s = do
let t = read s :: Int
printf "Ok, I'll remind you in %d seconds\n" t
threadDelay (10^6 * t)
printf "REMINDER!!! %d seconds are up\a\a\a\n" t
reminderMain :: IO ()
reminderMain = loop
where
loop = do
s <- getLine
if s == "end" then return ()
else do forkIO (setReminder s)
loop
PART II : MVARS
interface
newEmptyMVar : : IO ( MVar a )
newMVar : : a - > IO ( MVar a )
takeMVar : : MVar a - > IO a
putMVar : : MVar a - > a - > IO ( )
newIORef : : a - > IO ( IORef a )
getIORef : : IORef a - > IO a
putIORef : : IORef a - > a - > IO ( )
newEmptyMVar :: IO (MVar a)
newMVar :: a -> IO (MVar a)
takeMVar :: MVar a -> IO a
putMVar :: MVar a -> a -> IO ()
newIORef :: a -> IO (IORef a)
getIORef :: IORef a -> IO a
putIORef :: IORef a -> a -> IO ()
-}
mvar1 = do
m <- newEmptyMVar
forkIO $ putMVar m 'x'
r <- takeMVar m
print r
mvar2 = do
m <- newEmptyMVar
forkIO $ do putMVar m 'x'
putMVar m 'y'
r <- takeMVar m
print r
r <- takeMVar m
print r
-- Logger example
data Logger
initLogger : : IO Logger
logMessage : : Logger - > String - > IO ( )
logStop : : Logger - > IO ( )
data Logger
initLogger :: IO Logger
logMessage :: Logger -> String -> IO ()
logStop :: Logger -> IO ()
-}
data Logger = Logger (MVar LogCommand)
data LogCommand = Message String | Stop (MVar ())
initLogger :: IO Logger
initLogger = do
m <- newEmptyMVar
let l = Logger m
forkIO (logger l)
return l
logger :: Logger -> IO ()
logger (Logger m) = loop
where
loop = do
threadDelay (10^6 * 1)
cmd <- takeMVar m
case cmd of
Message msg -> do
putStrLn ("LOG: " ++ msg)
loop
Stop s -> do
putStrLn "Stopping logger"
putMVar s ()
logStop :: Logger -> () -> IO ()
logStop (Logger m) () = do
s <- newEmptyMVar
putMVar m (Stop s)
takeMVar s
logMessage :: Logger -> String -> IO ()
logMessage (Logger m) s = putMVar m (Message s)
loggerMain :: IO ()
loggerMain = do
l <- initLogger
l `logMessage` "hello"
putStrLn "We didn't wait for the log message"
l `logMessage` "bye"
l `logStop` ()
putStrLn "End of program"
----------------------------------------------------------------------
-- A server
data CountingMsg = Inc | GetCount (MVar Int)
newtype Counter = MkCounter (MVar CountingMsg)
makeCounter :: IO Counter
makeCounter = do
m <- newEmptyMVar
forkIO (loop m (0 :: Int))
return (MkCounter m)
where
loop m c = do
cmd <- takeMVar m
case cmd of
Inc -> do
printf "New doubling served! %d doublings so far!\n" (c+1)
loop m (c+1)
GetCount r -> do
putMVar r c
loop m c
msgCounter :: Counter -> CountingMsg -> IO ()
msgCounter (MkCounter m) msg =
putMVar m msg
----------------------------------------------------------------------
-- A Key-Value server
updateMap :: MVar [(String,Int)] -> String -> Int -> IO ()
updateMap m k v = do
kvs <- takeMVar m
putMVar m ((k,v):kvs)
readMap :: MVar [(String,Int)] -> String -> IO (Maybe Int)
readMap m k = do
kvs <- takeMVar m
putMVar m kvs
return (lookup k kvs)
----------------------------------------------------------------------
talk :: Handle -> Counter -> IO ()
talk h c =
do hSetBuffering h LineBuffering
hSetNewlineMode h (NewlineMode { inputNL = CRLF, outputNL = CRLF })
loop
where
loop =
do line <- hGetLine h
case line of
"end" ->
hPutStrLn h "Bye!"
"count" -> do
r <- newEmptyMVar
c `msgCounter` (GetCount r)
c <- takeMVar r
hPutStrLn h ("Count is " ++ show c)
loop
line -> do
hPutStrLn h (show (2 * read line :: Integer))
c `msgCounter` Inc
loop
main = do
c <- makeCounter
sock <- listenOn (PortNumber 1234)
printf "Listening...\n"
forever $ do
(handle, host, port) <- accept sock
printf "Accepted connection (%s:%s)\n" host (show port)
forkFinally (talk handle c)
(\_ -> do printf "Connection closed (%s:%s)\n" host (show port)
hClose handle)
| null | https://raw.githubusercontent.com/bobatkey/CS316-18/282dc3c876527c14acfed7bd38f24c9ff048627a/lectures/Lec20.hs | haskell | threadDelay :: Int -> IO ()
Logger example
--------------------------------------------------------------------
A server
--------------------------------------------------------------------
A Key-Value server
-------------------------------------------------------------------- | module Main where
LECTURE 20 : CONCURRENCY
import Control.Concurrent
import Control.Monad (forever, forM_)
import Network
import System.IO
import Text.Printf
forkIO : : IO ( ) - > IO ThreadId
muddle :: IO ()
muddle = do
hSetBuffering stdout NoBuffering
forkIO (forM_ [1..1000] (\_ -> putChar 'A'))
forM_ [1..1000] (\_ -> putChar 'B')
setReminder :: String -> IO ()
setReminder s = do
let t = read s :: Int
printf "Ok, I'll remind you in %d seconds\n" t
threadDelay (10^6 * t)
printf "REMINDER!!! %d seconds are up\a\a\a\n" t
reminderMain :: IO ()
reminderMain = loop
where
loop = do
s <- getLine
if s == "end" then return ()
else do forkIO (setReminder s)
loop
PART II : MVARS
interface
newEmptyMVar : : IO ( MVar a )
newMVar : : a - > IO ( MVar a )
takeMVar : : MVar a - > IO a
putMVar : : MVar a - > a - > IO ( )
newIORef : : a - > IO ( IORef a )
getIORef : : IORef a - > IO a
putIORef : : IORef a - > a - > IO ( )
newEmptyMVar :: IO (MVar a)
newMVar :: a -> IO (MVar a)
takeMVar :: MVar a -> IO a
putMVar :: MVar a -> a -> IO ()
newIORef :: a -> IO (IORef a)
getIORef :: IORef a -> IO a
putIORef :: IORef a -> a -> IO ()
-}
mvar1 = do
m <- newEmptyMVar
forkIO $ putMVar m 'x'
r <- takeMVar m
print r
mvar2 = do
m <- newEmptyMVar
forkIO $ do putMVar m 'x'
putMVar m 'y'
r <- takeMVar m
print r
r <- takeMVar m
print r
data Logger
initLogger : : IO Logger
logMessage : : Logger - > String - > IO ( )
logStop : : Logger - > IO ( )
data Logger
initLogger :: IO Logger
logMessage :: Logger -> String -> IO ()
logStop :: Logger -> IO ()
-}
data Logger = Logger (MVar LogCommand)
data LogCommand = Message String | Stop (MVar ())
initLogger :: IO Logger
initLogger = do
m <- newEmptyMVar
let l = Logger m
forkIO (logger l)
return l
logger :: Logger -> IO ()
logger (Logger m) = loop
where
loop = do
threadDelay (10^6 * 1)
cmd <- takeMVar m
case cmd of
Message msg -> do
putStrLn ("LOG: " ++ msg)
loop
Stop s -> do
putStrLn "Stopping logger"
putMVar s ()
logStop :: Logger -> () -> IO ()
logStop (Logger m) () = do
s <- newEmptyMVar
putMVar m (Stop s)
takeMVar s
logMessage :: Logger -> String -> IO ()
logMessage (Logger m) s = putMVar m (Message s)
loggerMain :: IO ()
loggerMain = do
l <- initLogger
l `logMessage` "hello"
putStrLn "We didn't wait for the log message"
l `logMessage` "bye"
l `logStop` ()
putStrLn "End of program"
data CountingMsg = Inc | GetCount (MVar Int)
newtype Counter = MkCounter (MVar CountingMsg)
makeCounter :: IO Counter
makeCounter = do
m <- newEmptyMVar
forkIO (loop m (0 :: Int))
return (MkCounter m)
where
loop m c = do
cmd <- takeMVar m
case cmd of
Inc -> do
printf "New doubling served! %d doublings so far!\n" (c+1)
loop m (c+1)
GetCount r -> do
putMVar r c
loop m c
msgCounter :: Counter -> CountingMsg -> IO ()
msgCounter (MkCounter m) msg =
putMVar m msg
updateMap :: MVar [(String,Int)] -> String -> Int -> IO ()
updateMap m k v = do
kvs <- takeMVar m
putMVar m ((k,v):kvs)
readMap :: MVar [(String,Int)] -> String -> IO (Maybe Int)
readMap m k = do
kvs <- takeMVar m
putMVar m kvs
return (lookup k kvs)
talk :: Handle -> Counter -> IO ()
talk h c =
do hSetBuffering h LineBuffering
hSetNewlineMode h (NewlineMode { inputNL = CRLF, outputNL = CRLF })
loop
where
loop =
do line <- hGetLine h
case line of
"end" ->
hPutStrLn h "Bye!"
"count" -> do
r <- newEmptyMVar
c `msgCounter` (GetCount r)
c <- takeMVar r
hPutStrLn h ("Count is " ++ show c)
loop
line -> do
hPutStrLn h (show (2 * read line :: Integer))
c `msgCounter` Inc
loop
main = do
c <- makeCounter
sock <- listenOn (PortNumber 1234)
printf "Listening...\n"
forever $ do
(handle, host, port) <- accept sock
printf "Accepted connection (%s:%s)\n" host (show port)
forkFinally (talk handle c)
(\_ -> do printf "Connection closed (%s:%s)\n" host (show port)
hClose handle)
|
68c76d5ac9beb9470b08113bb7b76bb9054a9810808193c8a9dc0f7a02df3670 | flipstone/haskell-for-beginners | 2_an_intro_to_lists.hs | Construct the word Gazump as a string in 4 different
-- ways and prove they are equal
Write a function that totals top 3 numbers in a
list ( assuming the list is sorted with highest first )
-- Write a function to extract a portion of a string
-- based on position and length
Write a function to tell if a list 's length is > 4
-- (it should return a boolean)
-- Write a function like the one above *without* referring
-- to the list's length
-- Write safe versions of tail and init that return
-- empty list if the list is empty
-- Write safe versions of head and last that take a
-- default value to return if the list is empty
-- write a function to tell if either the sum or product
-- of a list is in another list
-- write a function that reverses a section of a string
-- based on position and length. Use your substring function
-- from earlier to help.
| null | https://raw.githubusercontent.com/flipstone/haskell-for-beginners/e586a1f3ef08f21d5181171fe7a7b27057391f0b/problems/chapter_02/2_an_intro_to_lists.hs | haskell | ways and prove they are equal
Write a function to extract a portion of a string
based on position and length
(it should return a boolean)
Write a function like the one above *without* referring
to the list's length
Write safe versions of tail and init that return
empty list if the list is empty
Write safe versions of head and last that take a
default value to return if the list is empty
write a function to tell if either the sum or product
of a list is in another list
write a function that reverses a section of a string
based on position and length. Use your substring function
from earlier to help. | Construct the word Gazump as a string in 4 different
Write a function that totals top 3 numbers in a
list ( assuming the list is sorted with highest first )
Write a function to tell if a list 's length is > 4
|
8697f75a6b8912db46b6d6e87755fb69b651331ff06fdb4fe4022f3063f21f4b | perf101/rage | utils.ml | open! Core.Std
let debug msg =
output_string stderr (msg ^ "\n");
flush stderr
let index l x =
let rec aux i = function
| [] -> failwith "index []"
| x'::xs -> if x = x' then i else aux (i+1) xs
in aux 0 l
let concat ?(sep = ",") l =
String.concat ~sep
(List.filter l ~f:(fun s -> not (String.is_empty s)))
let string_of_int_list is =
concat (List.map ~f:string_of_int is)
let rec print_concat ?(sep = ",") = function
| [] -> ()
| [e] -> print_string e
| e::l -> print_string e; print_string sep; print_concat l
let concat_array ?(sep = ",") a =
String.concat_array ~sep
(Array.filter a ~f:(fun s -> not (String.is_empty s)))
let merge_table_into src dst =
String.Table.merge_into ~src ~dst
~f:(fun ~key:_ src_v dst_v_opt ->
match dst_v_opt with None -> Some src_v | vo -> vo)
let cat filename =
print_string (In_channel.with_file ~f:In_channel.input_all filename)
(* DATABASE INTERACTION *)
let get_value r row col null_val =
if r#getisnull row col then null_val else r#getvalue row col
let combine_maps conn tbls f =
let m = String.Table.create () in
List.iter tbls ~f:(fun t -> merge_table_into (f conn t) m);
m
let get_column_types conn tbl =
String.Table.of_alist_exn (Sql.get_col_types_lst ~conn ~tbl)
let get_column_types_many conn tbls = combine_maps conn tbls get_column_types
let get_column_fqns conn tbl =
let col_names = Sql.get_col_names ~conn ~tbl in
let nameToFqn = String.Table.create () in
let process_column name =
let fqn = tbl ^ "." ^ name in
String.Table.replace nameToFqn ~key:name ~data:fqn
in List.iter col_names ~f:process_column;
nameToFqn
let get_column_fqns_many conn tbls = combine_maps conn tbls get_column_fqns
let hex_of_char c =
let i = int_of_char c in
if i < int_of_char 'A'
then i - (int_of_char '0')
else i - (int_of_char 'A') + 10
let decode_html s =
let s = Str.global_replace (Str.regexp "+") " " s in
let re = Str.regexp "%[0-9A-F][0-9A-F]" in
let rec aux s start len =
try
let b = Str.search_forward re s start in
let e = Str.match_end () in
let x, y = String.get s (b+1), String.get s (b+2) in
let x_h, y_h = hex_of_char x, hex_of_char y in
let c = char_of_int (x_h * 16 + y_h) in
let prefix = String.sub s ~pos:0 ~len:b in
let suffix = String.sub s ~pos:e ~len:(len - e) in
let s = prefix ^ (String.make 1 c) ^ suffix in
aux s (b + 1) (len - 2)
with Not_found -> s
in
aux s 0 (String.length s)
let extract_filter col_fqns col_types params key_prefix =
let m = String.Table.create () in
let update_m v vs_opt =
let vs = Option.value vs_opt ~default:[] in Some (v::vs) in
let filter_insert (k, v) =
if v = "ALL" then () else
if String.is_prefix k ~prefix:key_prefix then begin
let k2 = String.chop_prefix_exn k ~prefix:key_prefix in
String.Table.change m k2 (update_m v)
end in
List.iter params ~f:filter_insert;
let l = String.Table.to_alist m in
let conds = List.map l
~f:(fun (k, vs) ->
let vs = List.map vs ~f:decode_html in
let has_null = List.mem vs "(NULL)" in
let vs = if has_null then List.filter vs ~f:((<>) "(NULL)") else vs in
let ty = String.Table.find_exn col_types k in
let quote = Sql.Type.is_quoted ty in
let vs_oq =
if quote then List.map vs ~f:(fun v -> "'" ^ v ^ "'") else vs in
let fqn = String.Table.find_exn col_fqns k in
let val_list = concat vs_oq in
let in_cond = sprintf "%s IN (%s)" fqn val_list in
let null_cond = if has_null then sprintf "%s IS NULL" fqn else "" in
if List.is_empty vs then null_cond else
if has_null then sprintf "(%s OR %s)" in_cond null_cond else
in_cond
) in
concat ~sep:" AND " conds
(* PRINTING HTML *)
let print_select ?(td=false) ?(label="") ?(selected=[]) ?(attrs=[]) options =
if td then printf "<td>\n";
if label <> "" then printf "<b>%s</b>:\n" label;
printf "<select";
List.iter attrs ~f:(fun (k, v) -> printf " %s='%s'" k v);
printf ">\n";
let print_option (l, v) =
printf "<option value='%s'" v;
if List.mem selected l then printf " selected='selected'";
printf ">%s</option>\n" l
in List.iter options ~f:print_option;
printf "</select>\n";
if td then printf "</td>\n"
let print_select_list ?(td=false) ?(label="") ?(selected=[]) ?(attrs=[]) l =
print_select ~td ~label ~selected ~attrs (List.map l ~f:(fun x -> (x, x)))
let get_options_for_field db_result ~data col =
let nRows = db_result#ntuples - 1 in
let ftype = db_result#ftype col in
let rec aux acc = function
| -1 -> acc
| i ->
let elem =
if db_result#getisnull i col then "(NULL)" else data.(i).(col)
in aux (elem::acc) (i-1)
in
let cmp x y =
try
if ftype = Postgresql.INT4
then compare (int_of_string x) (int_of_string y)
else compare x y
with _ -> 0
in
List.sort ~cmp (List.dedup (aux [] nRows))
let get_options_for_field_once db_result col =
let data = db_result#get_all in
get_options_for_field db_result ~data col
let get_options_for_field_once_byname db_result col_name =
let col_names = db_result#get_fnames_lst in
let col = match List.findi ~f:(fun _ c -> c = col_name) col_names with
| Some (i, _) -> i
| _ -> failwith (sprintf "could not find column '%s' amongst [%s]" col_name (String.concat ~sep:"; " col_names))
in
let data = db_result#get_all in
get_options_for_field db_result ~data col
let print_options_for_field namespace db_result col =
let fname = db_result#fname col in
let opts = get_options_for_field_once db_result col in
let form_name = sprintf "%s_%s" namespace fname in
printf "<table border='1' class='filter_table'>";
printf "<tr><th>%s</th></tr><tr>" fname;
print_select_list ~td:true ~selected:["ALL"]
~attrs:[("name", form_name); ("multiple", "multiple"); ("size", "3");
("class", "multiselect")]
("ALL"::opts);
printf "</tr><tr>";
print_select ~td:true ~selected:["SPLIT_BY_GRAPH"]
~attrs:[("name", form_name ^ "_split")]
[("DON'T SPLIT", "dont_split"); ("SPLIT BY GRAPH", "split_by_graph");
("SPLIT BY LINE", "split_by_line")];
printf "</tr></table>"
let print_options_for_fields conn tbl namespace =
let query = "SELECT * FROM " ^ tbl in
let result = Sql.exec_exn ~conn ~query in
List.iter ~f:(print_options_for_field namespace result)
(List.range 1 result#nfields);
printf "<br style='clear: both' />\n"
(* RAGE-specific helper methods. *)
let filter_prefix = "f_"
let filter_by_value = "1"
let values_prefix = "v_"
(* Names of fields in the tc_config table *)
let tc_config_fields = [
"dom0_memory_static_max";
"dom0_memory_target";
"cc_restrictions";
"redo_log";
"network_backend";
"option_clone_on_boot";
"force_non_debug_xen";
"cpufreq_governor";
"xen_cmdline";
"kernel_cmdline";
"xenrt_pq_name";
"xenrt_version";
"xenrt_internal_version";
"xenrt_pq_version";
"dom0_vcpus";
"host_pcpus";
"live_patching";
"host_type";
]
let build_fields = [
"product";
"branch";
"build_number";
"build_date";
"build_tag";
]
let job_fields = [
"job_id";
]
let som_config_tbl_exists ~conn som_id =
let som_config_tbl = sprintf "som_config_%d" som_id in
som_config_tbl, Sql.tbl_exists ~conn ~tbl:som_config_tbl
let get_std_xy_choices ~conn =
let machine_field_lst =
List.tl_exn (Sql.get_col_names ~conn ~tbl:"machines") in
job_fields @ build_fields @ tc_config_fields @ machine_field_lst
let get_xy_choices ~conn configs som_configs_opt =
let som_configs_lst = match som_configs_opt with
| None -> []
| Some som_configs -> List.tl_exn som_configs#get_fnames_lst
in get_std_xy_choices ~conn @ configs#get_fnames_lst @ som_configs_lst
let print_axis_choice ?(multiselect=false) label id choices =
printf "<div id='%s' style='display: inline-block'>\n" id;
let attrs = [("name", id)] in
let attrs = (if multiselect then ("multiple", "multiple")::attrs else attrs) in
print_select_list ~label ~attrs:attrs choices;
printf "</div>\n"
let print_empty_x_axis_choice ~conn =
print_axis_choice "X axis" "xaxis" [] ~multiselect:true
let print_empty_y_axis_choice ~conn =
print_axis_choice "Y axis" "yaxis" []
let print_x_axis_choice ~conn configs som_configs_opt =
print_axis_choice "X axis" "xaxis" ~multiselect:true
(get_xy_choices ~conn configs som_configs_opt)
let print_y_axis_choice ~conn configs som_configs_opt =
print_axis_choice "Y axis" "yaxis"
("result" :: (get_xy_choices ~conn configs som_configs_opt))
let get_tc_config_tbl_name conn som_id =
let query = "SELECT tc_fqn FROM soms " ^
"WHERE som_id = " ^ (string_of_int som_id) in
let result = Sql.exec_exn ~conn ~query in
let tc_fqn = String.lowercase (result#getvalue 0 0) in
(tc_fqn, "tc_config_" ^ tc_fqn)
(* WEBSERVER INTERACTION *)
let server_name () =
(* We use HTTP_HOST, which comes from the client, rather than SERVER_NAME,
* which is defined by the webserver, in case it contains a port number *)
Sys.getenv_exn "HTTP_HOST"
| null | https://raw.githubusercontent.com/perf101/rage/e8630659b2754b6621df7c49f3663fa7c4fac5eb/src/utils.ml | ocaml | DATABASE INTERACTION
PRINTING HTML
RAGE-specific helper methods.
Names of fields in the tc_config table
WEBSERVER INTERACTION
We use HTTP_HOST, which comes from the client, rather than SERVER_NAME,
* which is defined by the webserver, in case it contains a port number | open! Core.Std
let debug msg =
output_string stderr (msg ^ "\n");
flush stderr
let index l x =
let rec aux i = function
| [] -> failwith "index []"
| x'::xs -> if x = x' then i else aux (i+1) xs
in aux 0 l
let concat ?(sep = ",") l =
String.concat ~sep
(List.filter l ~f:(fun s -> not (String.is_empty s)))
let string_of_int_list is =
concat (List.map ~f:string_of_int is)
let rec print_concat ?(sep = ",") = function
| [] -> ()
| [e] -> print_string e
| e::l -> print_string e; print_string sep; print_concat l
let concat_array ?(sep = ",") a =
String.concat_array ~sep
(Array.filter a ~f:(fun s -> not (String.is_empty s)))
let merge_table_into src dst =
String.Table.merge_into ~src ~dst
~f:(fun ~key:_ src_v dst_v_opt ->
match dst_v_opt with None -> Some src_v | vo -> vo)
let cat filename =
print_string (In_channel.with_file ~f:In_channel.input_all filename)
let get_value r row col null_val =
if r#getisnull row col then null_val else r#getvalue row col
let combine_maps conn tbls f =
let m = String.Table.create () in
List.iter tbls ~f:(fun t -> merge_table_into (f conn t) m);
m
let get_column_types conn tbl =
String.Table.of_alist_exn (Sql.get_col_types_lst ~conn ~tbl)
let get_column_types_many conn tbls = combine_maps conn tbls get_column_types
let get_column_fqns conn tbl =
let col_names = Sql.get_col_names ~conn ~tbl in
let nameToFqn = String.Table.create () in
let process_column name =
let fqn = tbl ^ "." ^ name in
String.Table.replace nameToFqn ~key:name ~data:fqn
in List.iter col_names ~f:process_column;
nameToFqn
let get_column_fqns_many conn tbls = combine_maps conn tbls get_column_fqns
let hex_of_char c =
let i = int_of_char c in
if i < int_of_char 'A'
then i - (int_of_char '0')
else i - (int_of_char 'A') + 10
let decode_html s =
let s = Str.global_replace (Str.regexp "+") " " s in
let re = Str.regexp "%[0-9A-F][0-9A-F]" in
let rec aux s start len =
try
let b = Str.search_forward re s start in
let e = Str.match_end () in
let x, y = String.get s (b+1), String.get s (b+2) in
let x_h, y_h = hex_of_char x, hex_of_char y in
let c = char_of_int (x_h * 16 + y_h) in
let prefix = String.sub s ~pos:0 ~len:b in
let suffix = String.sub s ~pos:e ~len:(len - e) in
let s = prefix ^ (String.make 1 c) ^ suffix in
aux s (b + 1) (len - 2)
with Not_found -> s
in
aux s 0 (String.length s)
let extract_filter col_fqns col_types params key_prefix =
let m = String.Table.create () in
let update_m v vs_opt =
let vs = Option.value vs_opt ~default:[] in Some (v::vs) in
let filter_insert (k, v) =
if v = "ALL" then () else
if String.is_prefix k ~prefix:key_prefix then begin
let k2 = String.chop_prefix_exn k ~prefix:key_prefix in
String.Table.change m k2 (update_m v)
end in
List.iter params ~f:filter_insert;
let l = String.Table.to_alist m in
let conds = List.map l
~f:(fun (k, vs) ->
let vs = List.map vs ~f:decode_html in
let has_null = List.mem vs "(NULL)" in
let vs = if has_null then List.filter vs ~f:((<>) "(NULL)") else vs in
let ty = String.Table.find_exn col_types k in
let quote = Sql.Type.is_quoted ty in
let vs_oq =
if quote then List.map vs ~f:(fun v -> "'" ^ v ^ "'") else vs in
let fqn = String.Table.find_exn col_fqns k in
let val_list = concat vs_oq in
let in_cond = sprintf "%s IN (%s)" fqn val_list in
let null_cond = if has_null then sprintf "%s IS NULL" fqn else "" in
if List.is_empty vs then null_cond else
if has_null then sprintf "(%s OR %s)" in_cond null_cond else
in_cond
) in
concat ~sep:" AND " conds
let print_select ?(td=false) ?(label="") ?(selected=[]) ?(attrs=[]) options =
if td then printf "<td>\n";
if label <> "" then printf "<b>%s</b>:\n" label;
printf "<select";
List.iter attrs ~f:(fun (k, v) -> printf " %s='%s'" k v);
printf ">\n";
let print_option (l, v) =
printf "<option value='%s'" v;
if List.mem selected l then printf " selected='selected'";
printf ">%s</option>\n" l
in List.iter options ~f:print_option;
printf "</select>\n";
if td then printf "</td>\n"
let print_select_list ?(td=false) ?(label="") ?(selected=[]) ?(attrs=[]) l =
print_select ~td ~label ~selected ~attrs (List.map l ~f:(fun x -> (x, x)))
let get_options_for_field db_result ~data col =
let nRows = db_result#ntuples - 1 in
let ftype = db_result#ftype col in
let rec aux acc = function
| -1 -> acc
| i ->
let elem =
if db_result#getisnull i col then "(NULL)" else data.(i).(col)
in aux (elem::acc) (i-1)
in
let cmp x y =
try
if ftype = Postgresql.INT4
then compare (int_of_string x) (int_of_string y)
else compare x y
with _ -> 0
in
List.sort ~cmp (List.dedup (aux [] nRows))
let get_options_for_field_once db_result col =
let data = db_result#get_all in
get_options_for_field db_result ~data col
let get_options_for_field_once_byname db_result col_name =
let col_names = db_result#get_fnames_lst in
let col = match List.findi ~f:(fun _ c -> c = col_name) col_names with
| Some (i, _) -> i
| _ -> failwith (sprintf "could not find column '%s' amongst [%s]" col_name (String.concat ~sep:"; " col_names))
in
let data = db_result#get_all in
get_options_for_field db_result ~data col
let print_options_for_field namespace db_result col =
let fname = db_result#fname col in
let opts = get_options_for_field_once db_result col in
let form_name = sprintf "%s_%s" namespace fname in
printf "<table border='1' class='filter_table'>";
printf "<tr><th>%s</th></tr><tr>" fname;
print_select_list ~td:true ~selected:["ALL"]
~attrs:[("name", form_name); ("multiple", "multiple"); ("size", "3");
("class", "multiselect")]
("ALL"::opts);
printf "</tr><tr>";
print_select ~td:true ~selected:["SPLIT_BY_GRAPH"]
~attrs:[("name", form_name ^ "_split")]
[("DON'T SPLIT", "dont_split"); ("SPLIT BY GRAPH", "split_by_graph");
("SPLIT BY LINE", "split_by_line")];
printf "</tr></table>"
let print_options_for_fields conn tbl namespace =
let query = "SELECT * FROM " ^ tbl in
let result = Sql.exec_exn ~conn ~query in
List.iter ~f:(print_options_for_field namespace result)
(List.range 1 result#nfields);
printf "<br style='clear: both' />\n"
let filter_prefix = "f_"
let filter_by_value = "1"
let values_prefix = "v_"
let tc_config_fields = [
"dom0_memory_static_max";
"dom0_memory_target";
"cc_restrictions";
"redo_log";
"network_backend";
"option_clone_on_boot";
"force_non_debug_xen";
"cpufreq_governor";
"xen_cmdline";
"kernel_cmdline";
"xenrt_pq_name";
"xenrt_version";
"xenrt_internal_version";
"xenrt_pq_version";
"dom0_vcpus";
"host_pcpus";
"live_patching";
"host_type";
]
let build_fields = [
"product";
"branch";
"build_number";
"build_date";
"build_tag";
]
let job_fields = [
"job_id";
]
let som_config_tbl_exists ~conn som_id =
let som_config_tbl = sprintf "som_config_%d" som_id in
som_config_tbl, Sql.tbl_exists ~conn ~tbl:som_config_tbl
let get_std_xy_choices ~conn =
let machine_field_lst =
List.tl_exn (Sql.get_col_names ~conn ~tbl:"machines") in
job_fields @ build_fields @ tc_config_fields @ machine_field_lst
let get_xy_choices ~conn configs som_configs_opt =
let som_configs_lst = match som_configs_opt with
| None -> []
| Some som_configs -> List.tl_exn som_configs#get_fnames_lst
in get_std_xy_choices ~conn @ configs#get_fnames_lst @ som_configs_lst
let print_axis_choice ?(multiselect=false) label id choices =
printf "<div id='%s' style='display: inline-block'>\n" id;
let attrs = [("name", id)] in
let attrs = (if multiselect then ("multiple", "multiple")::attrs else attrs) in
print_select_list ~label ~attrs:attrs choices;
printf "</div>\n"
let print_empty_x_axis_choice ~conn =
print_axis_choice "X axis" "xaxis" [] ~multiselect:true
let print_empty_y_axis_choice ~conn =
print_axis_choice "Y axis" "yaxis" []
let print_x_axis_choice ~conn configs som_configs_opt =
print_axis_choice "X axis" "xaxis" ~multiselect:true
(get_xy_choices ~conn configs som_configs_opt)
let print_y_axis_choice ~conn configs som_configs_opt =
print_axis_choice "Y axis" "yaxis"
("result" :: (get_xy_choices ~conn configs som_configs_opt))
let get_tc_config_tbl_name conn som_id =
let query = "SELECT tc_fqn FROM soms " ^
"WHERE som_id = " ^ (string_of_int som_id) in
let result = Sql.exec_exn ~conn ~query in
let tc_fqn = String.lowercase (result#getvalue 0 0) in
(tc_fqn, "tc_config_" ^ tc_fqn)
let server_name () =
Sys.getenv_exn "HTTP_HOST"
|
3b61bf5ca9ee7a0f6a93f309fd845923a51b2cae189c31078ec4518a23817ceb | garrigue/lablgtk | gtkdoc.ml | (**************************************************************************)
(* Lablgtk *)
(* *)
(* This program is free software; you can redistribute it *)
and/or modify it under the terms of the GNU Library General
Public License as published by the Free Software Foundation
version 2 , with the exception described in file COPYING which
(* comes with the library. *)
(* *)
(* 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 Library General Public License for more details .
(* *)
You should have received a copy of the GNU Library 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
(* *)
(* *)
(**************************************************************************)
let default_base_uri = "-old.gnome.org/gtk3/stable"
let base_uri = ref default_base_uri
let _ =
Odoc_args.add_option
("-base-uri", Arg.String ((:=) base_uri),
"base URI of the GTK/GNOME documentation")
let may ov f =
match ov with
| None -> ()
| Some v -> f v
ocamldoc generates tons of < link > tags . This seriously inflates the
size of the HTML pages so here we redefine the function to only define the
' Start ' ' next ' and ' Up ' links .
size of the HTML pages so here we redefine the function to only define the
'Start' 'next' and 'Up' links. *)
let make_prepare_header style index _module_list =
fun b ?(nav=None) ?comments:_ t ->
let link l dest =
Printf.bprintf b "<link rel=\"%s\" href=\"%s\">\n" l dest in
let link_file l dest =
link l (fst (Odoc_html.Naming.html_files dest)) in
Buffer.add_string b "<head>\n" ;
Buffer.add_string b style ;
link "Start" index ;
may nav
(fun (pre_opt, post_opt, name) ->
may pre_opt (link_file "previous") ;
may post_opt (link_file "next") ;
match Odoc_info.Name.father name with
| "" -> link "Up" index
| s -> link_file "Up" s
) ;
Printf.bprintf b "<title>%s</title>\n</head>\n" t
let gtkdoc = function
| Odoc_info.Raw name :: _ ->
begin match Str.split (Str.regexp "[ \t]+") name with
| dir :: widget :: _ ->
let dir =
if !base_uri = default_base_uri
then dir ^ "/stable"
else dir in
Printf.sprintf
"<small>GTK documentation: \
<a href=\"%s/%s/%s.html\">%s</a>\
</small>"
!base_uri dir widget widget
| _ -> failwith "bad @gtkdoc format"
end
| _ -> failwith "bad @gtkdoc format"
module Generator (G : Odoc_html.Html_generator) =
struct
class html =
object (self)
inherit G.html as super
method! prepare_header module_list =
header <-
make_prepare_header style self#index module_list
method! html_of_class b ?complete ?with_link c =
super#html_of_class b ?complete ?with_link c ;
Buffer.add_string b "<br>"
initializer
tag_functions <- ("gtkdoc", gtkdoc) :: tag_functions
end
end
let _ =
Odoc_args.extend_html_generator
(module Generator : Odoc_gen.Html_functor)
| null | https://raw.githubusercontent.com/garrigue/lablgtk/89383e96d768148622df4e163c3189429eccbef0/tools/gtkdoc.ml | ocaml | ************************************************************************
Lablgtk
This program is free software; you can redistribute it
comes with the library.
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
************************************************************************ | and/or modify it under the terms of the GNU Library General
Public License as published by the Free Software Foundation
version 2 , with the exception described in file COPYING which
GNU Library General Public License for more details .
You should have received a copy of the GNU Library 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
let default_base_uri = "-old.gnome.org/gtk3/stable"
let base_uri = ref default_base_uri
let _ =
Odoc_args.add_option
("-base-uri", Arg.String ((:=) base_uri),
"base URI of the GTK/GNOME documentation")
let may ov f =
match ov with
| None -> ()
| Some v -> f v
ocamldoc generates tons of < link > tags . This seriously inflates the
size of the HTML pages so here we redefine the function to only define the
' Start ' ' next ' and ' Up ' links .
size of the HTML pages so here we redefine the function to only define the
'Start' 'next' and 'Up' links. *)
let make_prepare_header style index _module_list =
fun b ?(nav=None) ?comments:_ t ->
let link l dest =
Printf.bprintf b "<link rel=\"%s\" href=\"%s\">\n" l dest in
let link_file l dest =
link l (fst (Odoc_html.Naming.html_files dest)) in
Buffer.add_string b "<head>\n" ;
Buffer.add_string b style ;
link "Start" index ;
may nav
(fun (pre_opt, post_opt, name) ->
may pre_opt (link_file "previous") ;
may post_opt (link_file "next") ;
match Odoc_info.Name.father name with
| "" -> link "Up" index
| s -> link_file "Up" s
) ;
Printf.bprintf b "<title>%s</title>\n</head>\n" t
let gtkdoc = function
| Odoc_info.Raw name :: _ ->
begin match Str.split (Str.regexp "[ \t]+") name with
| dir :: widget :: _ ->
let dir =
if !base_uri = default_base_uri
then dir ^ "/stable"
else dir in
Printf.sprintf
"<small>GTK documentation: \
<a href=\"%s/%s/%s.html\">%s</a>\
</small>"
!base_uri dir widget widget
| _ -> failwith "bad @gtkdoc format"
end
| _ -> failwith "bad @gtkdoc format"
module Generator (G : Odoc_html.Html_generator) =
struct
class html =
object (self)
inherit G.html as super
method! prepare_header module_list =
header <-
make_prepare_header style self#index module_list
method! html_of_class b ?complete ?with_link c =
super#html_of_class b ?complete ?with_link c ;
Buffer.add_string b "<br>"
initializer
tag_functions <- ("gtkdoc", gtkdoc) :: tag_functions
end
end
let _ =
Odoc_args.extend_html_generator
(module Generator : Odoc_gen.Html_functor)
|
7ff499614addd0d096314e7bc685a8650db321cda5a0fd83a569ce85a58060a0 | TyOverby/mono | body.ml | { { { Copyright ( c ) 2014
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
} } }
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
}}}*)
open Sexplib0.Sexp_conv
type t = [
| `Empty
| `String of string
| `Strings of string list
] [@@deriving sexp]
let empty = `Empty
let is_empty = function
| `Empty
| `String ""
| `Strings [] -> true
| `String _
| `Strings _ -> false
let to_string = function
| `Empty -> ""
| `String s -> s
| `Strings sl -> String.concat "" sl
let to_string_list = function
| `Empty -> []
| `String s -> [s]
| `Strings sl -> sl
let of_string s = `String s
let of_string_list s = `Strings s
let transfer_encoding = function
| `Empty -> Transfer.Fixed 0L
| `String s -> Transfer.Fixed (Int64.of_int (String.length s))
| `Strings _ -> Transfer.Chunked
let length = function
| `Empty -> 0L
| `String s -> Int64.of_int (String.length s)
| `Strings sl ->
sl
|> List.fold_left (fun a b ->
b |> String.length |> Int64.of_int |> Int64.add a) 0L
let map f = function
| `Empty -> `Empty
| `String s -> `String (f s)
| `Strings sl -> `Strings (List.map f sl)
(* TODO: maybe add a functor here that uses IO.S *)
| null | https://raw.githubusercontent.com/TyOverby/mono/8d6b3484d5db63f2f5472c7367986ea30290764d/vendor/mirage-ocaml-cohttp/cohttp/src/body.ml | ocaml | TODO: maybe add a functor here that uses IO.S | { { { Copyright ( c ) 2014
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
} } }
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
}}}*)
open Sexplib0.Sexp_conv
type t = [
| `Empty
| `String of string
| `Strings of string list
] [@@deriving sexp]
let empty = `Empty
let is_empty = function
| `Empty
| `String ""
| `Strings [] -> true
| `String _
| `Strings _ -> false
let to_string = function
| `Empty -> ""
| `String s -> s
| `Strings sl -> String.concat "" sl
let to_string_list = function
| `Empty -> []
| `String s -> [s]
| `Strings sl -> sl
let of_string s = `String s
let of_string_list s = `Strings s
let transfer_encoding = function
| `Empty -> Transfer.Fixed 0L
| `String s -> Transfer.Fixed (Int64.of_int (String.length s))
| `Strings _ -> Transfer.Chunked
let length = function
| `Empty -> 0L
| `String s -> Int64.of_int (String.length s)
| `Strings sl ->
sl
|> List.fold_left (fun a b ->
b |> String.length |> Int64.of_int |> Int64.add a) 0L
let map f = function
| `Empty -> `Empty
| `String s -> `String (f s)
| `Strings sl -> `Strings (List.map f sl)
|
58376994d29e88b3ec513984fdbef1128a695d06866377c258838d32dcea2ca6 | kupl/FixML | sub36.ml | type aexp =
| Const of int
| Var of string
| Power of string * int
| Times of aexp list
| Sum of aexp list
let rec diff : aexp * string -> aexp
=fun (aexp,x) ->
match aexp with
Const i-> Const 0
|Var a-> if a="x" then Const 1 else Const 0
|Power (a,i)-> Times[Const i; Power (a,i-1)]
|Times (h::t)-> Times (h::[diff (Sum t,x)])
|Sum (h::t)-> Sum ((diff (h,x))::[diff (Sum t,x)])
|_-> Const 0
| null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/differentiate/diff1/submissions/sub36.ml | ocaml | type aexp =
| Const of int
| Var of string
| Power of string * int
| Times of aexp list
| Sum of aexp list
let rec diff : aexp * string -> aexp
=fun (aexp,x) ->
match aexp with
Const i-> Const 0
|Var a-> if a="x" then Const 1 else Const 0
|Power (a,i)-> Times[Const i; Power (a,i-1)]
|Times (h::t)-> Times (h::[diff (Sum t,x)])
|Sum (h::t)-> Sum ((diff (h,x))::[diff (Sum t,x)])
|_-> Const 0
| |
7daa4beb79e9c43c67f4e497147d6cddcb6199f2647e362070b9235ef1739249 | exercism/scheme | test.scm | (load "test-util.ss")
(define test-cases
`((test-success "basic" equal? acronym
'("Portable Network Graphics") "PNG")
(test-success "lowercase words" equal? acronym
'("Ruby on Rails") "ROR")
(test-success "punctuation" equal? acronym
'("First In, First Out") "FIFO")
(test-success "all caps word" equal? acronym
'("GNU Image Manipulation Program") "GIMP")
(test-success "colon" equal? acronym
'("PHP: Hypertext Preprocessor") "PHP")
(test-success "punctuation without whitespace" equal? acronym
'("Complementary metal-oxide semiconductor") "CMOS")
(test-success "very long abbreviation" equal? acronym
'("Rolling On The Floor Laughing So Hard That My Dogs Came Over And Licked Me")
"ROTFLSHTMDCOALM")
(test-success "consecutive delimiters" equal? acronym
'("Something - I made up from thin air") "SIMUFTA")
(test-success "apostrophes" equal? acronym
'("Halley's Comet") "HC")
(test-success "underscore emphasis" equal? acronym
'("The Road _Not_ Taken") "TRNT")))
(run-with-cli "acronym.scm" (list test-cases))
| null | https://raw.githubusercontent.com/exercism/scheme/2064dd5e5d5a03a06417d28c33c5349bec97dad7/exercises/practice/acronym/test.scm | scheme | (load "test-util.ss")
(define test-cases
`((test-success "basic" equal? acronym
'("Portable Network Graphics") "PNG")
(test-success "lowercase words" equal? acronym
'("Ruby on Rails") "ROR")
(test-success "punctuation" equal? acronym
'("First In, First Out") "FIFO")
(test-success "all caps word" equal? acronym
'("GNU Image Manipulation Program") "GIMP")
(test-success "colon" equal? acronym
'("PHP: Hypertext Preprocessor") "PHP")
(test-success "punctuation without whitespace" equal? acronym
'("Complementary metal-oxide semiconductor") "CMOS")
(test-success "very long abbreviation" equal? acronym
'("Rolling On The Floor Laughing So Hard That My Dogs Came Over And Licked Me")
"ROTFLSHTMDCOALM")
(test-success "consecutive delimiters" equal? acronym
'("Something - I made up from thin air") "SIMUFTA")
(test-success "apostrophes" equal? acronym
'("Halley's Comet") "HC")
(test-success "underscore emphasis" equal? acronym
'("The Road _Not_ Taken") "TRNT")))
(run-with-cli "acronym.scm" (list test-cases))
| |
5f4428599077aee1d173513559e08c3ad9428bc172ee36927974d812e8c9bd8f | avsm/platform | react.mli | ---------------------------------------------------------------------------
Copyright ( c ) 2009 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2009 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
* Declarative events and signals .
React is a module for functional reactive programming ( frp ) . It
provides support to program with time varying values : declarative
{ { ! } and { { ! S}signals } . React
does n't define any primitive event or signal , this lets the client
choose the concrete timeline .
Consult the { { ! sem}semantics } , the { { ! basics}basics } and
{ { ! ex}examples } . Open the module to use it , this defines only two
types and modules in your scope .
{ e Release % % VERSION%% - % % MAINTAINER%% }
React is a module for functional reactive programming (frp). It
provides support to program with time varying values : declarative
{{!E}events} and {{!S}signals}. React
doesn't define any primitive event or signal, this lets the client
choose the concrete timeline.
Consult the {{!sem}semantics}, the {{!basics}basics} and
{{!ex}examples}. Open the module to use it, this defines only two
types and modules in your scope.
{e Release %%VERSION%% - %%MAINTAINER%% } *)
(** {1 Interface} *)
type 'a event
(** The type for events of type ['a]. *)
type 'a signal
(** The type for signals of type ['a]. *)
type step
(** The type for update steps. *)
(** Event combinators.
Consult their {{!evsem}semantics.} *)
module E : sig
* { 1 : prim Primitive and basics }
type 'a t = 'a event
(** The type for events with occurrences of type ['a]. *)
val never : 'a event
(** A never occuring event. For all t, \[[never]\]{_t} [= None]. *)
val create : unit -> 'a event * (?step:step -> 'a -> unit)
* [ create ( ) ] is a primitive event [ e ] and a [ send ] function . The
function [ send ] is such that :
{ ul
{ - [ send v ] generates an occurrence [ v ] of [ e ] at the time it is called
and triggers an { { ! steps}update step } . }
{ - [ send ~step v ] generates an occurence [ v ] of [ e ] on the step [ step ]
when [ step ] is { { ! Step.execute}executed } . }
{ - [ send ~step v ] raises [ Invalid_argument ] if it was previously
called with a step and this step has not executed yet or if
the given [ step ] was already executed . } }
{ b Warning . } [ send ] must not be executed inside an update step .
function [send] is such that:
{ul
{- [send v] generates an occurrence [v] of [e] at the time it is called
and triggers an {{!steps}update step}.}
{- [send ~step v] generates an occurence [v] of [e] on the step [step]
when [step] is {{!Step.execute}executed}.}
{- [send ~step v] raises [Invalid_argument] if it was previously
called with a step and this step has not executed yet or if
the given [step] was already executed.}}
{b Warning.} [send] must not be executed inside an update step. *)
val retain : 'a event -> (unit -> unit) -> [ `R of (unit -> unit) ]
(** [retain e c] keeps a reference to the closure [c] in [e] and
returns the previously retained value. [c] will {e never} be
invoked.
{b Raises.} [Invalid_argument] on {!E.never}. *)
val stop : ?strong:bool -> 'a event -> unit
* [ stop e ] stops [ e ] from occuring . It conceptually becomes
{ ! never } and can not be restarted . Allows to
disable { { ! sideeffects}effectful } events .
The [ strong ] argument should only be used on platforms
where weak arrays have a strong semantics ( i.e. JavaScript ) .
See { { ! strongstop}details } .
{ b Note . } If executed in an { { ! steps}update step }
the event may still occur in the step .
{!never} and cannot be restarted. Allows to
disable {{!sideeffects}effectful} events.
The [strong] argument should only be used on platforms
where weak arrays have a strong semantics (i.e. JavaScript).
See {{!strongstop}details}.
{b Note.} If executed in an {{!steps}update step}
the event may still occur in the step. *)
val equal : 'a event -> 'a event -> bool
(** [equal e e'] is [true] iff [e] and [e'] are equal. If both events are
different from {!never}, physical equality is used. *)
val trace : ?iff:bool signal -> ('a -> unit) -> 'a event -> 'a event
(** [trace iff tr e] is [e] except [tr] is invoked with e's
occurence when [iff] is [true] (defaults to [S.const true]).
For all t where \[[e]\]{_t} [= Some v] and \[[iff]\]{_t} =
[true], [tr] is invoked with [v]. *)
* { 1 : transf Transforming and filtering }
val once : 'a event -> 'a event
(** [once e] is [e] with only its next occurence.
{ul
{- \[[once e]\]{_t} [= Some v] if \[[e]\]{_t} [= Some v] and
\[[e]\]{_<t} [= None].}
{- \[[once e]\]{_t} [= None] otherwise.}} *)
val drop_once : 'a event -> 'a event
(** [drop_once e] is [e] without its next occurrence.
{ul
{- \[[drop_once e]\]{_t} [= Some v] if \[[e]\]{_t} [= Some v] and
\[[e]\]{_<t} [= Some _].}
{- \[[drop_once e]\]{_t} [= None] otherwise.}} *)
val app : ('a -> 'b) event -> 'a event -> 'b event
(** [app ef e] occurs when both [ef] and [e] occur
{{!simultaneity}simultaneously}.
The value is [ef]'s occurence applied to [e]'s one.
{ul
{- \[[app ef e]\]{_t} [= Some v'] if \[[ef]\]{_t} [= Some f] and
\[[e]\]{_t} [= Some v] and [f v = v'].}
{- \[[app ef e]\]{_t} [= None] otherwise.}} *)
val map : ('a -> 'b) -> 'a event -> 'b event
(** [map f e] applies [f] to [e]'s occurrences.
{ul
{- \[[map f e]\]{_t} [= Some (f v)] if \[[e]\]{_t} [= Some v].}
{- \[[map f e]\]{_t} [= None] otherwise.}} *)
val stamp : 'b event -> 'a -> 'a event
(** [stamp e v] is [map (fun _ -> v) e]. *)
val filter : ('a -> bool) -> 'a event -> 'a event
(** [filter p e] are [e]'s occurrences that satisfy [p].
{ul
{- \[[filter p e]\]{_t} [= Some v] if \[[e]\]{_t} [= Some v] and
[p v = true]}
{- \[[filter p e]\]{_t} [= None] otherwise.}} *)
val fmap : ('a -> 'b option) -> 'a event -> 'b event
* [ fmap fm e ] are [ e ] 's occurrences filtered and mapped by [ fm ] .
{ ul
{ - \[[fmap fm e]\]{_t } [= Some v ] if [ fm ] \[[e]\]{_t } [= Some v ] }
{ - \[[fmap fm e]\]{_t } [= None ] otherwise . } }
{ul
{- \[[fmap fm e]\]{_t} [= Some v] if [fm] \[[e]\]{_t} [= Some v]}
{- \[[fmap fm e]\]{_t} [= None] otherwise.}} *)
val diff : ('a -> 'a -> 'b) -> 'a event -> 'b event
(** [diff f e] occurs whenever [e] occurs except on the next occurence.
Occurences are [f v v'] where [v] is [e]'s current
occurrence and [v'] the previous one.
{ul
{- \[[diff f e]\]{_t} [= Some r] if \[[e]\]{_t} [= Some v],
\[[e]\]{_<t} [= Some v'] and [f v v' = r].}
{- \[[diff f e]\]{_t} [= None] otherwise.}} *)
val changes : ?eq:('a -> 'a -> bool) -> 'a event -> 'a event
(** [changes eq e] is [e]'s occurrences with occurences equal to
the previous one dropped. Equality is tested with [eq] (defaults to
structural equality).
{ul
{- \[[changes eq e]\]{_t} [= Some v] if \[[e]\]{_t} [= Some v]
and either \[[e]\]{_<t} [= None] or \[[e]\]{_<t} [= Some v'] and
[eq v v' = false].}
{- \[[changes eq e]\]{_t} [= None] otherwise.}} *)
val on : bool signal -> 'a event -> 'a event
(** [on c e] is the occurrences of [e] when [c] is [true].
{ul
{- \[[on c e]\]{_t} [= Some v]
if \[[c]\]{_t} [= true] and \[[e]\]{_t} [= Some v].}
{- \[[on c e]\]{_t} [= None] otherwise.}} *)
val when_ : bool signal -> 'a event -> 'a event
(** @deprecated Use {!on}. *)
val dismiss : 'b event -> 'a event -> 'a event
* [ dismiss c e ] is the occurences of [ e ] except the ones when [ c ] occurs .
{ ul
c e]\]{_t } [= Some v ]
if \[[c]\]{_t } [= None ] and \[[e]\]{_t } [= Some v ] . }
c e]\]{_t } [= None ] otherwise . } }
{ul
{- \[[dimiss c e]\]{_t} [= Some v]
if \[[c]\]{_t} [= None] and \[[e]\]{_t} [= Some v].}
{- \[[dimiss c e]\]{_t} [= None] otherwise.}} *)
val until : 'a event -> 'b event -> 'b event
* [ until c e ] is [ e ] 's occurences until [ c ] occurs .
{ ul
{ - \[[until c e]\]{_t } [= Some v ] if \[[e]\]{_t } [= Some v ] and
} [= None ] }
{ - \[[until c e]\]{_t } [= None ] otherwise . } }
{ul
{- \[[until c e]\]{_t} [= Some v] if \[[e]\]{_t} [= Some v] and
\[[c]\]{_<=t} [= None]}
{- \[[until c e]\]{_t} [= None] otherwise.}} *)
* { 1 : accum Accumulating }
val accum : ('a -> 'a) event -> 'a -> 'a event
* [ accum ef i ] accumulates a value , starting with [ i ] , using [ e ] 's
functional occurrences .
{ ul
{ - \[[accum ef i]\]{_t } [= Some ( f i ) ] if \[[ef]\]{_t } [= Some f ]
and \[[ef]\]{_<t } [= None ] .
}
{ - \[[accum ef i]\]{_t } [= Some ( f acc ) ] if \[[ef]\]{_t } [= Some f ]
and \[[accum ef i]\]{_<t } [= Some acc ] . }
{ - \[[accum ef i]\ ] [= None ] otherwise . } }
functional occurrences.
{ul
{- \[[accum ef i]\]{_t} [= Some (f i)] if \[[ef]\]{_t} [= Some f]
and \[[ef]\]{_<t} [= None].
}
{- \[[accum ef i]\]{_t} [= Some (f acc)] if \[[ef]\]{_t} [= Some f]
and \[[accum ef i]\]{_<t} [= Some acc].}
{- \[[accum ef i]\] [= None] otherwise.}} *)
val fold : ('a -> 'b -> 'a) -> 'a -> 'b event -> 'a event
* [ fold f i e ] accumulates [ e ] 's occurrences with [ f ] starting with [ i ] .
{ ul
{ - \[[fold f i e]\]{_t } [= Some ( f i v ) ] if
\[[e]\]{_t } [= Some v ] and \[[e]\]{_<t } [= None ] . }
{ - \[[fold f i e]\]{_t } [= Some ( f acc v ) ] if
\[[e]\]{_t } [= Some v ] and \[[fold f i e]\]{_<t } [= Some acc ] . }
{ - \[[fold f i e]\]{_t } [= None ] otherwise . } }
{ul
{- \[[fold f i e]\]{_t} [= Some (f i v)] if
\[[e]\]{_t} [= Some v] and \[[e]\]{_<t} [= None].}
{- \[[fold f i e]\]{_t} [= Some (f acc v)] if
\[[e]\]{_t} [= Some v] and \[[fold f i e]\]{_<t} [= Some acc].}
{- \[[fold f i e]\]{_t} [= None] otherwise.}} *)
* { 1 : combine Combining }
val select : 'a event list -> 'a event
* [ select el ] is the occurrences of every event in [ el ] .
If more than one event occurs { { ! simultaneity}simultaneously }
the leftmost is taken and the others are lost .
{ ul
{ - \[[select el]\ ] { _ t } [ =] \[[List.find ( fun e - > ] \[[e]\]{_t }
[ < > None ) el]\]{_t } . }
{ - \[[select el]\ ] { _ t } [= None ] otherwise . } }
If more than one event occurs {{!simultaneity}simultaneously}
the leftmost is taken and the others are lost.
{ul
{- \[[select el]\]{_ t} [=] \[[List.find (fun e -> ]\[[e]\]{_t}
[<> None) el]\]{_t}.}
{- \[[select el]\]{_ t} [= None] otherwise.}} *)
val merge : ('a -> 'b -> 'a) -> 'a -> 'b event list -> 'a event
* [ merge f a el ] merges the { { ! simultaneity}simultaneous }
occurrences of every event in [ el ] using [ f ] and the accumulator [ a ] .
\[[merge f a el]\ ] { _ t }
[= List.fold_left f a ( ( fun o - > o < > None )
( List.map ] \[\]{_t } [ el ) ) ] .
occurrences of every event in [el] using [f] and the accumulator [a].
\[[merge f a el]\]{_ t}
[= List.fold_left f a (List.filter (fun o -> o <> None)
(List.map] \[\]{_t}[ el))]. *)
val switch : 'a event -> 'a event event -> 'a event
(** [switch e ee] is [e]'s occurrences until there is an
occurrence [e'] on [ee], the occurrences of [e'] are then used
until there is a new occurrence on [ee], etc..
{ul
{- \[[switch e ee]\]{_ t} [=] \[[e]\]{_t} if \[[ee]\]{_<=t} [= None].}
{- \[[switch e ee]\]{_ t} [=] \[[e']\]{_t} if \[[ee]\]{_<=t}
[= Some e'].}} *)
val fix : ('a event -> 'a event * 'b) -> 'b
(** [fix ef] allows to refer to the value an event had an
infinitesimal amount of time before.
In [fix ef], [ef] is called with an event [e] that represents
the event returned by [ef] delayed by an infinitesimal amount of
time. If [e', r = ef e] then [r] is returned by [fix] and [e]
is such that :
{ul
{- \[[e]\]{_ t} [=] [None] if t = 0 }
{- \[[e]\]{_ t} [=] \[[e']\]{_t-dt} otherwise}}
{b Raises.} [Invalid_argument] if [e'] is directly a delayed event (i.e.
an event given to a fixing function). *)
(** {1 Lifting}
Lifting combinators. For a given [n] the semantics is:
{ul
{- \[[ln f e1 ... en]\]{_t} [= Some (f v1 ... vn)] if for all
i : \[[ei]\]{_t} [= Some vi].}
{- \[[ln f e1 ... en]\]{_t} [= None] otherwise.}} *)
val l1 : ('a -> 'b) -> 'a event -> 'b event
val l2 : ('a -> 'b -> 'c) -> 'a event -> 'b event -> 'c event
val l3 : ('a -> 'b -> 'c -> 'd) -> 'a event -> 'b event -> 'c event ->
'd event
val l4 : ('a -> 'b -> 'c -> 'd -> 'e) -> 'a event -> 'b event -> 'c event ->
'd event -> 'e event
val l5 : ('a -> 'b -> 'c -> 'd -> 'e -> 'f) -> 'a event -> 'b event ->
'c event -> 'd event -> 'e event -> 'f event
val l6 : ('a -> 'b -> 'c -> 'd -> 'e -> 'f -> 'g) -> 'a event -> 'b event ->
'c event -> 'd event -> 'e event -> 'f event -> 'g event
* { 1 Pervasives support }
(** Events with option occurences. *)
module Option : sig
val some : 'a event -> 'a option event
(** [some e] is [map (fun v -> Some v) e]. *)
val value : ?default:'a signal -> 'a option event -> 'a event
(** [value default e] either silences [None] occurences if [default] is
unspecified or replaces them by the value of [default] at the occurence
time.
{ul
{- \[[value ~default e]\]{_t}[ = v] if \[[e]\]{_t} [= Some (Some v)].}
{- \[[value ?default:None e]\]{_t}[ = None] if \[[e]\]{_t} = [None].}
{- \[[value ?default:(Some s) e]\]{_t}[ = v]
if \[[e]\]{_t} = [None] and \[[s]\]{_t} [= v].}} *)
end
end
(** Signal combinators.
Consult their {{!sigsem}semantics.} *)
module S : sig
* { 1 : prim Primitive and basics }
type 'a t = 'a signal
(** The type for signals of type ['a]. *)
val const : 'a -> 'a signal
(** [const v] is always [v], \[[const v]\]{_t} [= v]. *)
val create : ?eq:('a -> 'a -> bool) -> 'a ->
'a signal * (?step:step -> 'a -> unit)
* [ create i ] is a primitive signal [ s ] set to [ i ] and a
[ set ] function . The function [ set ] is such that :
{ ul
{ - [ set v ] sets the signal 's value to [ v ] at the time it is called and
triggers an { { ! steps}update step } . }
{ - [ set ~step v ] sets the signal 's value to [ v ] at the time it is
called and updates it dependencies when [ step ] is
{ { ! Step.execute}executed } }
{ - [ set ~step v ] raises [ Invalid_argument ] if it was previously
called with a step and this step has not executed yet or if
the given [ step ] was already executed . } }
{ b Warning . } [ set ] must not be executed inside an update step .
[set] function. The function [set] is such that:
{ul
{- [set v] sets the signal's value to [v] at the time it is called and
triggers an {{!steps}update step}.}
{- [set ~step v] sets the signal's value to [v] at the time it is
called and updates it dependencies when [step] is
{{!Step.execute}executed}}
{- [set ~step v] raises [Invalid_argument] if it was previously
called with a step and this step has not executed yet or if
the given [step] was already executed.}}
{b Warning.} [set] must not be executed inside an update step. *)
val value : 'a signal -> 'a
(** [value s] is [s]'s current value.
{b Warning.} If executed in an {{!steps}update
step} may return a non up-to-date value or raise [Failure] if
the signal is not yet initialized. *)
val retain : 'a signal -> (unit -> unit) -> [ `R of (unit -> unit) ]
(** [retain s c] keeps a reference to the closure [c] in [s] and
returns the previously retained value. [c] will {e never} be
invoked.
{b Raises.} [Invalid_argument] on constant signals. *)
(**/**)
val eq_fun : 'a signal -> ('a -> 'a -> bool) option
(**/**)
val stop : ?strong:bool -> 'a signal -> unit
* [ stop s ] , stops updating [ s ] . It conceptually becomes { ! const }
with the signal 's last value and can not be restarted . Allows to
disable { { ! sideeffects}effectful } signals .
The [ strong ] argument should only be used on platforms
where weak arrays have a strong semantics ( i.e. JavaScript ) .
See { { ! strongstop}details } .
{ b Note . } If executed in an update step the signal may
still update in the step .
with the signal's last value and cannot be restarted. Allows to
disable {{!sideeffects}effectful} signals.
The [strong] argument should only be used on platforms
where weak arrays have a strong semantics (i.e. JavaScript).
See {{!strongstop}details}.
{b Note.} If executed in an update step the signal may
still update in the step. *)
val equal : ?eq:('a -> 'a -> bool) -> 'a signal -> 'a signal -> bool
(** [equal s s'] is [true] iff [s] and [s'] are equal. If both
signals are {!const}ant [eq] is used between their value
(defauts to structural equality). If both signals are not
{!const}ant, physical equality is used.*)
val trace : ?iff:bool t -> ('a -> unit) -> 'a signal -> 'a signal
(** [trace iff tr s] is [s] except [tr] is invoked with [s]'s
current value and on [s] changes when [iff] is [true] (defaults
to [S.const true]). For all t where \[[s]\]{_t} [= v] and (t = 0
or (\[[s]\]{_t-dt}[= v'] and [eq v v' = false])) and
\[[iff]\]{_t} = [true], [tr] is invoked with [v]. *)
* { 1 From events }
val hold : ?eq:('a -> 'a -> bool) -> 'a -> 'a event -> 'a signal
(** [hold i e] has the value of [e]'s last occurrence or [i] if there
wasn't any.
{ul
{- \[[hold i e]\]{_t} [= i] if \[[e]\]{_<=t} [= None]}
{- \[[hold i e]\]{_t} [= v] if \[[e]\]{_<=t} [= Some v]}} *)
* { 1 : tr Transforming and filtering }
val app : ?eq:('b -> 'b -> bool) -> ('a -> 'b) signal -> 'a signal ->
'b signal
* [ app sf s ] holds the value of [ sf ] applied
to the value of [ s ] , \[[app sf s]\]{_t }
[ =] \[[sf]\]{_t } \[[s]\]{_t } .
to the value of [s], \[[app sf s]\]{_t}
[=] \[[sf]\]{_t} \[[s]\]{_t}. *)
val map : ?eq:('b -> 'b -> bool) -> ('a -> 'b) -> 'a signal -> 'b signal
(** [map f s] is [s] transformed by [f], \[[map f s]\]{_t} = [f] \[[s]\]{_t}.
*)
val filter : ?eq:('a -> 'a -> bool) -> ('a -> bool) -> 'a -> 'a signal ->
'a signal
(** [filter f i s] is [s]'s values that satisfy [p]. If a value does not
satisfy [p] it holds the last value that was satisfied or [i] if
there is none.
{ul
{- \[[filter p s]\]{_t} [=] \[[s]\]{_t} if [p] \[[s]\]{_t}[ = true].}
{- \[[filter p s]\]{_t} [=] \[[s]\]{_t'} if [p] \[[s]\]{_t}[ = false]
and t' is the greatest t' < t with [p] \[[s]\]{_t'}[ = true].}
{- \[[filter p e]\]{_t} [= i] otherwise.}} *)
val fmap : ?eq:('b -> 'b -> bool) -> ('a -> 'b option) -> 'b -> 'a signal ->
'b signal
* [ fmap fm i s ] is [ s ] filtered and mapped by [ fm ] .
{ ul
{ - \[[fmap fm i s]\]{_t } [ =] v if [ fm ] \[[s]\]{_t } [ = Some v ] . }
{ - \[[fmap fm i s]\]{_t } [ =] \[[fmap fm i s]\]{_t ' } if [ fm ]
\[[s]\]{_t } [= None ] and t ' is the greatest t ' < t with [ fm ]
\[[s]\]{_t ' } [ < > None ] . }
{ - \[[fmap fm i s]\]{_t } [= i ] otherwise . } }
{ul
{- \[[fmap fm i s]\]{_t} [=] v if [fm] \[[s]\]{_t}[ = Some v].}
{- \[[fmap fm i s]\]{_t} [=] \[[fmap fm i s]\]{_t'} if [fm]
\[[s]\]{_t} [= None] and t' is the greatest t' < t with [fm]
\[[s]\]{_t'} [<> None].}
{- \[[fmap fm i s]\]{_t} [= i] otherwise.}} *)
val diff : ('a -> 'a -> 'b) -> 'a signal -> 'b event
(** [diff f s] is an event with occurrences whenever [s] changes from
[v'] to [v] and [eq v v'] is [false] ([eq] is the signal's equality
function). The value of the occurrence is [f v v'].
{ul
{- \[[diff f s]\]{_t} [= Some d]
if \[[s]\]{_t} [= v] and \[[s]\]{_t-dt} [= v'] and [eq v v' = false]
and [f v v' = d].}
{- \[[diff f s]\]{_t} [= None] otherwise.}} *)
val changes : 'a signal -> 'a event
(** [changes s] is [diff (fun v _ -> v) s]. *)
val sample : ('b -> 'a -> 'c) -> 'b event -> 'a signal -> 'c event
* [ sample f e s ] samples [ s ] at [ e ] 's occurrences .
{ ul
} [= Some ( f ev sv ) ] if \[[e]\]{_t } [= Some ev ]
and \[[s]\]{_t } [= sv ] . }
{ - \[[sample e s]\]{_t } [= None ] otherwise . } }
{ul
{- \[[sample f e s]\]{_t} [= Some (f ev sv)] if \[[e]\]{_t} [= Some ev]
and \[[s]\]{_t} [= sv].}
{- \[[sample e s]\]{_t} [= None] otherwise.}} *)
val on : ?eq:('a -> 'a -> bool) -> bool signal -> 'a -> 'a signal ->
'a signal
(** [on c i s] is the signal [s] whenever [c] is [true].
When [c] is [false] it holds the last value [s] had when
[c] was the last time [true] or [i] if it never was.
{ul
{- \[[on c i s]\]{_t} [=] \[[s]\]{_t} if \[[c]\]{_t} [= true]}
{- \[[on c i s]\]{_t} [=] \[[s]\]{_t'} if \[[c]\]{_t} [= false]
where t' is the greatest t' < t with \[[c]\]{_t'} [= true].}
{- \[[on c i s]\]{_t} [=] [i] otherwise.}} *)
val when_ : ?eq:('a -> 'a -> bool) -> bool signal -> 'a -> 'a signal ->
'a signal
(** @deprecated Use {!on}. *)
val dismiss : ?eq:('a -> 'a -> bool) -> 'b event -> 'a -> 'a signal ->
'a signal
* [ dismiss c i s ] is the signal [ s ] except changes when [ c ] occurs
are ignored . If [ c ] occurs initially [ i ] is used .
{ ul
{ - \[[dismiss c i s]\]{_t } [ =] \[[s]\]{_t ' }
where t ' is the greatest t ' < = t with \[[c]\]{_t ' } [= None ] and
\[[s]\]{_t'-dt } [ < > ] \[[s]\]{_t ' } }
{ - \[[dismiss _ c i s]\]{_0 } [ =] [ v ] where [ v = i ] if
\[[c]\]{_0 } [= Some _ ] and [ v =] \[[s]\]{_0 } otherwise . } }
are ignored. If [c] occurs initially [i] is used.
{ul
{- \[[dismiss c i s]\]{_t} [=] \[[s]\]{_t'}
where t' is the greatest t' <= t with \[[c]\]{_t'} [= None] and
\[[s]\]{_t'-dt} [<>] \[[s]\]{_t'}}
{- \[[dismiss_ c i s]\]{_0} [=] [v] where [v = i] if
\[[c]\]{_0} [= Some _] and [v =] \[[s]\]{_0} otherwise.}} *)
* { 1 : acc Accumulating }
val accum : ?eq:('a -> 'a -> bool) -> ('a -> 'a) event -> 'a -> 'a signal
(** [accum e i] is [S.hold i (]{!E.accum}[ e i)]. *)
val fold : ?eq:('a -> 'a -> bool) -> ('a -> 'b -> 'a) -> 'a -> 'b event ->
'a signal
(** [fold f i e] is [S.hold i (]{!E.fold}[ f i e)]. *)
* { 1 : combine Combining }
val merge : ?eq:('a -> 'a -> bool) -> ('a -> 'b -> 'a) -> 'a ->
'b signal list -> 'a signal
* [ merge f a sl ] merges the value of every signal in [ sl ]
using [ f ] and the accumulator [ a ] .
\[[merge f a sl]\ ] { _ t }
[= List.fold_left f a ( List.map ] \[\]{_t } [ sl ) ] .
using [f] and the accumulator [a].
\[[merge f a sl]\]{_ t}
[= List.fold_left f a (List.map] \[\]{_t}[ sl)]. *)
val switch : ?eq:('a -> 'a -> bool) -> 'a signal signal -> 'a signal
(** [switch ss] is the inner signal of [ss].
{ul
{- \[[switch ss]\]{_ t} [=] \[\[[ss]\]{_t}\]{_t}.}} *)
val bind : ?eq:('b -> 'b -> bool) -> 'a signal -> ('a -> 'b signal) ->
'b signal
* [ bind s sf ] is [ switch ( map ~eq :( = = ) sf s ) ] .
val fix : ?eq:('a -> 'a -> bool) -> 'a -> ('a signal -> 'a signal * 'b) -> 'b
* [ fix i sf ] allow to refer to the value a signal had an
infinitesimal amount of time before .
In [ fix sf ] , [ sf ] is called with a signal [ s ] that represents
the signal returned by [ sf ] delayed by an infinitesimal amount
time . If [ s ' , r = sf s ] then [ r ] is returned by [ fix ] and [ s ]
is such that :
{ ul
{ - \[[s]\ ] { _ t } [ =] [ i ] for t = 0 . }
{ - \[[s]\ ] { _ t } [ =] \[[s']\]{_t - dt } otherwise . } }
[ eq ] is the equality used by [ s ] .
{ b Raises . } [ Invalid_argument ] if [ s ' ] is directly a delayed signal ( i.e.
a signal given to a fixing function ) .
{ b Note . } Regarding values depending on the result [ r ] of
[ s ' , r = sf s ] the following two cases need to be distinguished :
{ ul
{ - After [ sf s ] is applied , [ s ' ] does not depend on
a value that is in a step and [ s ] has no dependents in a step ( e.g
in the simple case where [ fix ] is applied outside a step ) .
In that case if the initial value of [ s ' ] differs from [ i ] ,
[ s ] and its dependents need to be updated and a special
update step will be triggered for this . Values
depending on the result [ r ] will be created only after this
special update step has finished ( e.g. they wo n't see
the [ i ] of [ s ] if [ r = s ] ) . }
{ - Otherwise , values depending on [ r ] will be created in the same
step as [ s ] and [ s ' ] ( e.g. they will see the [ i ] of [ s ] if [ r = s ] ) . } }
infinitesimal amount of time before.
In [fix sf], [sf] is called with a signal [s] that represents
the signal returned by [sf] delayed by an infinitesimal amount
time. If [s', r = sf s] then [r] is returned by [fix] and [s]
is such that :
{ul
{- \[[s]\]{_ t} [=] [i] for t = 0. }
{- \[[s]\]{_ t} [=] \[[s']\]{_t-dt} otherwise.}}
[eq] is the equality used by [s].
{b Raises.} [Invalid_argument] if [s'] is directly a delayed signal (i.e.
a signal given to a fixing function).
{b Note.} Regarding values depending on the result [r] of
[s', r = sf s] the following two cases need to be distinguished :
{ul
{- After [sf s] is applied, [s'] does not depend on
a value that is in a step and [s] has no dependents in a step (e.g
in the simple case where [fix] is applied outside a step).
In that case if the initial value of [s'] differs from [i],
[s] and its dependents need to be updated and a special
update step will be triggered for this. Values
depending on the result [r] will be created only after this
special update step has finished (e.g. they won't see
the [i] of [s] if [r = s]).}
{- Otherwise, values depending on [r] will be created in the same
step as [s] and [s'] (e.g. they will see the [i] of [s] if [r = s]).}}
*)
* { 1 : lifting Lifting }
Lifting combinators . For a given [ n ] the semantics is :
\[[ln f a1 ] ... [ an]\]{_t } = f \[[a1]\]{_t } ... \[[an]\]{_t }
Lifting combinators. For a given [n] the semantics is :
\[[ln f a1] ... [an]\]{_t} = f \[[a1]\]{_t} ... \[[an]\]{_t} *)
val l1 : ?eq:('b -> 'b -> bool) -> ('a -> 'b) -> ('a signal -> 'b signal)
val l2 : ?eq:('c -> 'c -> bool) ->
('a -> 'b -> 'c) -> ('a signal -> 'b signal -> 'c signal)
val l3 : ?eq:('d -> 'd -> bool) ->
('a -> 'b -> 'c -> 'd) -> ('a signal -> 'b signal -> 'c signal -> 'd signal)
val l4 : ?eq:('e -> 'e -> bool) ->
('a -> 'b -> 'c -> 'd -> 'e) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal)
val l5 : ?eq:('f -> 'f -> bool) ->
('a -> 'b -> 'c -> 'd -> 'e -> 'f) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal ->
'f signal)
val l6 : ?eq:('g -> 'g -> bool) ->
('a -> 'b -> 'c -> 'd -> 'e -> 'f -> 'g) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal ->
'f signal -> 'g signal)
(** The following modules lift some of [Pervasives] functions and
operators. *)
module Bool : sig
val zero : bool signal
val one : bool signal
val not : bool signal -> bool signal
val ( && ) : bool signal -> bool signal -> bool signal
val ( || ) : bool signal -> bool signal -> bool signal
val edge : bool signal -> bool event
(** [edge s] is [changes s]. *)
val rise : bool signal -> unit event
* [ rise s ] is [ E.fmap ( fun b - > if b then Some ( ) else None ) ( edge s ) ] .
val fall : bool signal -> unit event
* [ fall s ] is [ E.fmap ( fun b - > if b then None else Some ( ) ) ( edge s ) ] .
val flip : bool -> 'a event -> bool signal
(** [flip b e] is a signal whose boolean value flips each time
[e] occurs. [b] is the initial signal value.
{ul
{- \[[flip b e]\]{_0} [= not b] if \[[e]\]{_0} [= Some _]}
{- \[[flip b e]\]{_t} [= b] if \[[e]\]{_<=t} [= None]}
{- \[[flip b e]\]{_t} [=] [not] \[[flip b e]\]{_t-dt}
if \[[e]\]{_t} [= Some _]}}
*)
end
module Int : sig
val zero : int signal
val one : int signal
val minus_one : int signal
val ( ~- ) : int signal -> int signal
val succ : int signal -> int signal
val pred : int signal -> int signal
val ( + ) : int signal -> int signal -> int signal
val ( - ) : int signal -> int signal -> int signal
val ( * ) : int signal -> int signal -> int signal
val ( mod ) : int signal -> int signal -> int signal
val abs : int signal -> int signal
val max_int : int signal
val min_int : int signal
val ( land ) : int signal -> int signal -> int signal
val ( lor ) : int signal -> int signal -> int signal
val ( lxor ) : int signal -> int signal -> int signal
val lnot : int signal -> int signal
val ( lsl ) : int signal -> int signal -> int signal
val ( lsr ) : int signal -> int signal -> int signal
val ( asr ) : int signal -> int signal -> int signal
end
module Float : sig
val zero : float signal
val one : float signal
val minus_one : float signal
val ( ~-. ) : float signal -> float signal
val ( +. ) : float signal -> float signal -> float signal
val ( -. ) : float signal -> float signal -> float signal
val ( *. ) : float signal -> float signal -> float signal
val ( /. ) : float signal -> float signal -> float signal
val ( ** ) : float signal -> float signal -> float signal
val sqrt : float signal -> float signal
val exp : float signal -> float signal
val log : float signal -> float signal
val log10 : float signal -> float signal
val cos : float signal -> float signal
val sin : float signal -> float signal
val tan : float signal -> float signal
val acos : float signal -> float signal
val asin : float signal -> float signal
val atan : float signal -> float signal
val atan2 : float signal -> float signal -> float signal
val cosh : float signal -> float signal
val sinh : float signal -> float signal
val tanh : float signal -> float signal
val ceil : float signal -> float signal
val floor : float signal -> float signal
val abs_float : float signal -> float signal
val mod_float : float signal -> float signal -> float signal
val frexp : float signal -> (float * int) signal
val ldexp : float signal -> int signal -> float signal
val modf : float signal -> (float * float) signal
val float : int signal -> float signal
val float_of_int : int signal -> float signal
val truncate : float signal -> int signal
val int_of_float : float signal -> int signal
val infinity : float signal
val neg_infinity : float signal
val nan : float signal
val max_float : float signal
val min_float : float signal
val epsilon_float : float signal
val classify_float : float signal -> fpclass signal
end
module Pair : sig
val pair : ?eq:(('a * 'b) -> ('a * 'b) -> bool)->
'a signal -> 'b signal -> ('a * 'b) signal
val fst : ?eq:('a -> 'a -> bool) -> ('a * 'b) signal -> 'a signal
val snd : ?eq:('a -> 'a -> bool) -> ('b * 'a) signal -> 'a signal
end
module Option : sig
val none : 'a option signal
(** [none] is [S.const None]. *)
val some : 'a signal -> 'a option signal
(** [some s] is [S.map ~eq (fun v -> Some v) None], where [eq] uses
[s]'s equality function to test the [Some v]'s equalities. *)
val value : ?eq:('a -> 'a -> bool) ->
default:[`Init of 'a signal | `Always of 'a signal ] ->
'a option signal -> 'a signal
* [ value default s ] is [ s ] with only its [ Some v ] values .
Whenever [ s ] is [ None ] , if [ default ] is [ ` Always dv ] then
the current value of [ dv ] is used instead . If [ default ]
is [ ` Init dv ] the current value of [ dv ] is only used
if there 's no value at creation time , otherwise the last
[ Some v ] value of [ s ] is used .
{ ul
{ - \[[value [= v ] if \[[s]\]{_t } [= Some v ] }
{ - \[[value ~default:(`Always d ) s]\]{_t } [ =] \[[d]\]{_t }
if \[[s]\]{_t } [= None ] }
{ - \[[value ~default:(`Init d ) s]\]{_0 } [ =] \[[d]\]{_0 }
if \[[s]\]{_0 } [= None ] }
{ - \[[value ~default:(`Init d ) s]\]{_t } [ =]
\[[value ~default:(`Init d ) s]\]{_t ' }
if \[[s]\]{_t } [= None ] and t ' is the greatest t ' < t
with \[[s]\]{_t ' } [ < > None ] or 0 if there is no such [ t ' ] . } }
Whenever [s] is [None], if [default] is [`Always dv] then
the current value of [dv] is used instead. If [default]
is [`Init dv] the current value of [dv] is only used
if there's no value at creation time, otherwise the last
[Some v] value of [s] is used.
{ul
{- \[[value ~default s]\]{_t} [= v] if \[[s]\]{_t} [= Some v]}
{- \[[value ~default:(`Always d) s]\]{_t} [=] \[[d]\]{_t}
if \[[s]\]{_t} [= None]}
{- \[[value ~default:(`Init d) s]\]{_0} [=] \[[d]\]{_0}
if \[[s]\]{_0} [= None]}
{- \[[value ~default:(`Init d) s]\]{_t} [=]
\[[value ~default:(`Init d) s]\]{_t'}
if \[[s]\]{_t} [= None] and t' is the greatest t' < t
with \[[s]\]{_t'} [<> None] or 0 if there is no such [t'].}} *)
end
module Compare : sig
val ( = ) : 'a signal -> 'a signal -> bool signal
val ( <> ) : 'a signal -> 'a signal -> bool signal
val ( < ) : 'a signal -> 'a signal -> bool signal
val ( > ) : 'a signal -> 'a signal -> bool signal
val ( <= ) : 'a signal -> 'a signal -> bool signal
val ( >= ) : 'a signal -> 'a signal -> bool signal
val compare : 'a signal -> 'a signal -> int signal
val ( == ) : 'a signal -> 'a signal -> bool signal
val ( != ) : 'a signal -> 'a signal -> bool signal
end
* { 1 : special Combinator specialization }
Given an equality function [ equal ] and a type [ t ] , the functor
{ ! Make } automatically applies the [ eq ] parameter of the combinators .
The outcome is combinators whose { e results } are signals with
values in [ t ] .
Basic types are already specialized in the module { ! Special } , open
this module to use them .
Given an equality function [equal] and a type [t], the functor
{!Make} automatically applies the [eq] parameter of the combinators.
The outcome is combinators whose {e results} are signals with
values in [t].
Basic types are already specialized in the module {!Special}, open
this module to use them. *)
(** Input signature of {!Make} *)
module type EqType = sig
type 'a t
val equal : 'a t -> 'a t -> bool
end
(** Output signature of {!Make} *)
module type S = sig
type 'a v
val create : 'a v -> 'a v signal * (?step:step -> 'a v -> unit)
val equal : 'a v signal -> 'a v signal -> bool
val hold : 'a v -> 'a v event -> 'a v signal
val app : ('a -> 'b v) signal -> 'a signal -> 'b v signal
val map : ('a -> 'b v) -> 'a signal -> 'b v signal
val filter : ('a v -> bool) -> 'a v -> 'a v signal -> 'a v signal
val fmap : ('a -> 'b v option) -> 'b v -> 'a signal -> 'b v signal
val when_ : bool signal -> 'a v -> 'a v signal -> 'a v signal
val dismiss : 'b event -> 'a v -> 'a v signal -> 'a v signal
val accum : ('a v -> 'a v) event -> 'a v -> 'a v signal
val fold : ('a v -> 'b -> 'a v) -> 'a v -> 'b event -> 'a v signal
val merge : ('a v -> 'b -> 'a v) -> 'a v -> 'b signal list -> 'a v signal
val switch : 'a v signal signal -> 'a v signal
val bind : 'b signal -> ('b -> 'a v signal) -> 'a v signal
val fix : 'a v -> ('a v signal -> 'a v signal * 'b) -> 'b
val l1 : ('a -> 'b v) -> ('a signal -> 'b v signal)
val l2 : ('a -> 'b -> 'c v) -> ('a signal -> 'b signal -> 'c v signal)
val l3 : ('a -> 'b -> 'c -> 'd v) -> ('a signal -> 'b signal ->
'c signal -> 'd v signal)
val l4 : ('a -> 'b -> 'c -> 'd -> 'e v) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e v signal)
val l5 : ('a -> 'b -> 'c -> 'd -> 'e -> 'f v) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal ->
'f v signal)
val l6 : ('a -> 'b -> 'c -> 'd -> 'e -> 'f -> 'g v) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal ->
'f signal -> 'g v signal)
end
(** Functor specializing the combinators for the given signal value type *)
module Make (Eq : EqType) : S with type 'a v = 'a Eq.t
* Specialization for booleans , integers and floats .
Open this module to use it .
Open this module to use it. *)
module Special : sig
(** Specialization for booleans. *)
module Sb : S with type 'a v = bool
(** Specialization for integers. *)
module Si : S with type 'a v = int
(** Specialization for floats. *)
module Sf : S with type 'a v = float
end
end
(** Update steps.
Update functions returned by {!S.create} and {!E.create}
implicitely create and execute update steps when used without
specifying their [step] argument.
Using explicit {!step} values with these functions gives more control on
the time when the update step is perfomed and allows to perform
simultaneous {{!primitives}primitive} signal updates and event
occurences. See also the documentation about {{!steps}update steps} and
{{!simultaneity}simultaneous events}. *)
module Step : sig
(** {1 Steps} *)
type t = step
(** The type for update steps. *)
val create : unit -> step
(** [create ()] is a new update step. *)
val execute : step -> unit
(** [execute step] executes the update step.
@raise Invalid_argument if [step] was already executed. *)
end
* { 1 : sem Semantics }
The following notations are used to give precise meaning to the
combinators . It is important to note that in these semantic
descriptions the origin of time t = 0 is { e always } fixed at
the time at which the combinator creates the event or the signal and
the semantics of the dependents is evaluated relative to this timeline .
We use dt to denote an infinitesimal amount of time .
{ 2 : evsem Events }
An event is a value with discrete occurrences over time .
The semantic function \[\ ] [: ' a event - > time - > ' a option ] gives
meaning to an event [ e ] by mapping it to a function of time
\[[e]\ ] returning [ Some v ] whenever the event occurs with value
[ v ] and [ None ] otherwise . We write \[[e]\]{_t } the evaluation of
this { e semantic } function at time t.
As a shortcut notation we also define } [: ' a event - > ' a option ]
( resp . \[\]{_<=t } ) to denote the last occurrence , if any , of an
event before ( resp . before or at ) [ t ] . More precisely :
{ ul
{ - \[[e]\]{_<t } [ =] \[[e]\]{_t ' } with t ' the greatest t ' < t
( resp . [ < =] ) such that
\[[e]\]{_t ' } [ < > None ] . }
{ - \[[e]\]{_<t } [= None ] if there is no such t ' . } }
{ 2 : sigsem Signals }
A signal is a value that varies continuously over time . In
contrast to { { ! evsem}events } which occur at specific point
in time , a signal has a value at every point in time .
The semantic function \[\ ] [: ' a signal - > time - > ' a ] gives
meaning to a signal [ s ] by mapping it to a function of time
\[[s]\ ] that returns its value at a given time . We write \[[s]\]{_t }
the evaluation of this { e semantic } function at time t.
{ 3 : sigeq Equality }
Most signal combinators have an optional [ eq ] parameter that
defaults to structural equality . [ eq ] specifies the equality
function used to detect changes in the value of the resulting
signal . This function is needed for the efficient update of
signals and to deal correctly with signals that perform
{ { ! sideeffects}side effects } .
Given an equality function on a type the combinators can be automatically
{ { ! } via a functor .
{ 3 : sigcont Continuity }
Ultimately signal updates depend on
{ { ! primitives}primitives } updates . Thus a signal can
only approximate a real continuous signal . The accuracy of the
approximation depends on the variation rate of the real signal and
the primitive 's update frequency .
{ 1 : basics Basics }
{ 2 : primitives Primitive events and signals }
React does n't define primitive events and signals , they must be
created and updated by the client .
Primitive events are created with { ! E.create } . This function
returns a new event and an update function that generates an
occurrence for the event at the time it is called . The following
code creates a primitive integer event [ x ] and generates three
occurrences with value [ 1 ] , [ 2 ] , [ 3 ] . Those occurrences are printed
on stdout by the effectful event [ pr_x ] . { [ open React ; ;
let x , send_x = E.create ( )
let pr_x = E.map print_int x
let ( ) = List.iter send_x [ 1 ; 2 ; 3 ] ] }
Primitive signals are created with { ! S.create } . This function
returns a new signal and an update function that sets the signal 's value
at the time it is called . The following code creates an
integer signal [ x ] initially set to [ 1 ] and updates it three time with
values [ 2 ] , [ 2 ] , [ 3 ] . The signal 's values are printed on stdout by the
effectful signal [ pr_x ] . Note that only updates that change
the signal 's value are printed , hence the program prints [ 123 ] , not [ 1223 ] .
See the discussion on
{ { ! sideeffects}side effects } for more details .
{ [ open React ; ;
let x , set_x = S.create 1
let pr_x = S.map print_int x
let ( ) = List.iter set_x [ 2 ; 2 ; 3 ] ] }
The { { ! clock}clock } example shows how a realtime time
flow can be defined .
{ 2 : steps Update steps }
The { ! E.create } and { ! S.create } functions return update functions
used to generate primitive event occurences and set the value of
primitive signals . Upon invocation as in the preceding section
these functions immediatly create and invoke an update step .
The { e update step } automatically updates events and signals that
transitively depend on the updated primitive . The dependents of a
signal are updated iff the signal 's value changed according to its
{ { ! sigeq}equality function } .
The update functions have an optional [ step ] argument . If they are
given a concrete [ step ] value created with { ! Step.create } , then it
updates the event or signal but does n't update its dependencies . It
will only do so whenever [ step ] is executed with
{ ! Step.execute } . This allows to make primitive event occurences and
signal changes simultaneous . See next section for an example .
{ 2 : simultaneity Simultaneous events }
{ { ! steps}Update steps } are made under a
{ { : -6423(92)90005-V}synchrony hypothesis } :
the update step takes no time , it is instantenous . Two event occurrences
are { e simultaneous } if they occur in the same update step .
In the code below [ w ] , [ x ] and [ y ] will always have simultaneous
occurrences . They { e may } have simulatenous occurences with [ z ]
if [ send_w ] and [ send_z ] are used with the same update step .
{ [ let w , send_w = E.create ( )
let x = E.map succ w
let y = E.map succ x
let z , send_z = E.create ( )
let ( ) =
let ( ) = send_w 3 ( * w x y occur simultaneously , z does n't occur
The following notations are used to give precise meaning to the
combinators. It is important to note that in these semantic
descriptions the origin of time t = 0 is {e always} fixed at
the time at which the combinator creates the event or the signal and
the semantics of the dependents is evaluated relative to this timeline.
We use dt to denote an infinitesimal amount of time.
{2:evsem Events}
An event is a value with discrete occurrences over time.
The semantic function \[\] [: 'a event -> time -> 'a option] gives
meaning to an event [e] by mapping it to a function of time
\[[e]\] returning [Some v] whenever the event occurs with value
[v] and [None] otherwise. We write \[[e]\]{_t} the evaluation of
this {e semantic} function at time t.
As a shortcut notation we also define \[\]{_<t} [: 'a event -> 'a option]
(resp. \[\]{_<=t}) to denote the last occurrence, if any, of an
event before (resp. before or at) [t]. More precisely :
{ul
{- \[[e]\]{_<t} [=] \[[e]\]{_t'} with t' the greatest t' < t
(resp. [<=]) such that
\[[e]\]{_t'} [<> None].}
{- \[[e]\]{_<t} [= None] if there is no such t'.}}
{2:sigsem Signals}
A signal is a value that varies continuously over time. In
contrast to {{!evsem}events} which occur at specific point
in time, a signal has a value at every point in time.
The semantic function \[\] [: 'a signal -> time -> 'a] gives
meaning to a signal [s] by mapping it to a function of time
\[[s]\] that returns its value at a given time. We write \[[s]\]{_t}
the evaluation of this {e semantic} function at time t.
{3:sigeq Equality}
Most signal combinators have an optional [eq] parameter that
defaults to structural equality. [eq] specifies the equality
function used to detect changes in the value of the resulting
signal. This function is needed for the efficient update of
signals and to deal correctly with signals that perform
{{!sideeffects}side effects}.
Given an equality function on a type the combinators can be automatically
{{!S.special}specialized} via a functor.
{3:sigcont Continuity}
Ultimately signal updates depend on
{{!primitives}primitives} updates. Thus a signal can
only approximate a real continuous signal. The accuracy of the
approximation depends on the variation rate of the real signal and
the primitive's update frequency.
{1:basics Basics}
{2:primitives Primitive events and signals}
React doesn't define primitive events and signals, they must be
created and updated by the client.
Primitive events are created with {!E.create}. This function
returns a new event and an update function that generates an
occurrence for the event at the time it is called. The following
code creates a primitive integer event [x] and generates three
occurrences with value [1], [2], [3]. Those occurrences are printed
on stdout by the effectful event [pr_x]. {[open React;;
let x, send_x = E.create ()
let pr_x = E.map print_int x
let () = List.iter send_x [1; 2; 3]]}
Primitive signals are created with {!S.create}. This function
returns a new signal and an update function that sets the signal's value
at the time it is called. The following code creates an
integer signal [x] initially set to [1] and updates it three time with
values [2], [2], [3]. The signal's values are printed on stdout by the
effectful signal [pr_x]. Note that only updates that change
the signal's value are printed, hence the program prints [123], not [1223].
See the discussion on
{{!sideeffects}side effects} for more details.
{[open React;;
let x, set_x = S.create 1
let pr_x = S.map print_int x
let () = List.iter set_x [2; 2; 3]]}
The {{!clock}clock} example shows how a realtime time
flow can be defined.
{2:steps Update steps}
The {!E.create} and {!S.create} functions return update functions
used to generate primitive event occurences and set the value of
primitive signals. Upon invocation as in the preceding section
these functions immediatly create and invoke an update step.
The {e update step} automatically updates events and signals that
transitively depend on the updated primitive. The dependents of a
signal are updated iff the signal's value changed according to its
{{!sigeq}equality function}.
The update functions have an optional [step] argument. If they are
given a concrete [step] value created with {!Step.create}, then it
updates the event or signal but doesn't update its dependencies. It
will only do so whenever [step] is executed with
{!Step.execute}. This allows to make primitive event occurences and
signal changes simultaneous. See next section for an example.
{2:simultaneity Simultaneous events}
{{!steps}Update steps} are made under a
{{:-6423(92)90005-V}synchrony hypothesis} :
the update step takes no time, it is instantenous. Two event occurrences
are {e simultaneous} if they occur in the same update step.
In the code below [w], [x] and [y] will always have simultaneous
occurrences. They {e may} have simulatenous occurences with [z]
if [send_w] and [send_z] are used with the same update step.
{[let w, send_w = E.create ()
let x = E.map succ w
let y = E.map succ x
let z, send_z = E.create ()
let () =
let () = send_w 3 (* w x y occur simultaneously, z doesn't occur *) in
let step = Step.create () in
send_w ~step 3;
send_z ~step 4;
Step.execute step (* w x z y occur simultaneously *)
]}
{2:update The update step and thread safety}
{{!primitives}Primitives} are the only mean to drive the reactive
system and they are entirely under the control of the client. When
the client invokes a primitive's update function without the
[step] argument or when it invokes {!Step.execute} on a [step]
value, React performs an update step.
To ensure correctness in the presence of threads, update steps
must be executed in a critical section. Let uset([p]) be the set
of events and signals that need to be updated whenever the
primitive [p] is updated. Updating two primitives [p] and [p']
concurrently is only allowed if uset([p]) and uset([p']) are
disjoint. Otherwise the updates must be properly serialized.
Below, concurrent, updates to [x] and [y] must be serialized (or
performed on the same step if it makes sense semantically), but z
can be updated concurently to both [x] and [y].
{[open React;;
let x, set_x = S.create 0
let y, send_y = E.create ()
let z, set_z = S.create 0
let max_xy = S.l2 (fun x y -> if x > y then x else y) x (S.hold 0 y)
let succ_z = S.map succ z]}
{2:sideeffects Side effects}
Effectful events and signals perform their side effect
exactly {e once} in each {{!steps}update step} in which there
is an update of at least one of the event or signal it depends on.
Remember that a signal updates in a step iff its
{{!sigeq}equality function} determined that the signal
value changed. Signal initialization is unconditionally considered as
an update.
It is important to keep references on effectful events and
signals. Otherwise they may be reclaimed by the garbage collector.
The following program prints only a [1].
{[let x, set_x = S.create 1
let () = ignore (S.map print_int x)
let () = Gc.full_major (); List.iter set_x [2; 2; 3]]}
{2:lifting Lifting}
Lifting transforms a regular function to make it act on signals.
The combinators
{!S.const} and {!S.app} allow to lift functions of arbitrary arity n,
but this involves the inefficient creation of n-1 intermediary
closure signals. The fixed arity {{!S.lifting}lifting
functions} are more efficient. For example :
{[let f x y = x mod y
let fl x y = S.app (S.app ~eq:(==) (S.const f) x) y (* inefficient *)
let fl' x y = S.l2 f x y (* efficient *)
]}
Besides, some of [Pervasives]'s functions and operators are
already lifted and availables in submodules of {!S}. They can be
be opened in specific scopes. For example if you are dealing with
float signals you can open {!S.Float}.
{[open React
open React.S.Float
let f t = sqrt t *. sin t (* f is defined on float signals *)
...
open Pervasives (* back to pervasives floats *)
]}
If you are using OCaml 3.12 or later you can also use the [let open]
construct
{[let open React.S.Float in
let f t = sqrt t *. sin t in (* f is defined on float signals *)
...
]}
{2:recursion Mutual and self reference}
Mutual and self reference among time varying values occurs naturally
in programs. However a mutually recursive definition of two signals
in which both need the value of the other at time t to define
their value at time t has no least fixed point. To break this
tight loop one signal must depend on the value the other had at time
t-dt where dt is an infinitesimal delay.
The fixed point combinators {!E.fix} and {!S.fix} allow to refer to
the value an event or signal had an infinitesimal amount of time
before. These fixed point combinators act on a function [f] that takes
as argument the infinitesimally delayed event or signal that [f]
itself returns.
In the example below [history s] returns a signal whose value
is the history of [s] as a list.
{[let history ?(eq = ( = )) s =
let push v = function
| [] -> [ v ]
| v' :: _ as l when eq v v' -> l
| l -> v :: l
in
let define h =
let h' = S.l2 push s h in
h', h'
in
S.fix [] define]}
When a program has infinitesimally delayed values a
{{!primitives}primitive} may trigger more than one update
step. For example if a signal [s] is infinitesimally delayed, then
its update in a step [c] will trigger a new step [c'] at the end
of the step in which the delayed signal of [s] will have the value
[s] had in [c]. This means that the recursion occuring between a
signal (or event) and its infinitesimally delayed counterpart must
be well-founded otherwise this may trigger an infinite number
of update steps, like in the following examples.
{[let start, send_start = E.create ()
let diverge =
let define e =
let e' = E.select [e; start] in
e', e'
in
E.fix define
let () = send_start () (* diverges *)
let diverge = (* diverges *)
let define s =
let s' = S.Int.succ s in
s', s'
in
S.fix 0 define]}
For technical reasons, delayed events and signals (those given to
fixing functions) are not allowed to directly depend on each
other. Fixed point combinators will raise [Invalid_argument] if
such dependencies are created. This limitation can be
circumvented by mapping these values with the identity.
{2:strongstop Strong stops}
Strong stops should only be used on platforms where weak arrays have
a strong semantics (i.e. JavaScript). You can safely ignore that
section and the [strong] argument of {!E.stop} and {!S.stop}
if that's not the case.
Whenever {!E.stop} and {!S.stop} is called with [~strong:true] on a
reactive value [v], it is first stopped and then it walks over the
list [prods] of events and signals that it depends on and
unregisters itself from these ones as a dependent (something that is
normally automatically done when [v] is garbage collected since
dependents are stored in a weak array). Then for each element of
[prod] that has no dependents anymore and is not a primitive it
stops them aswell and recursively.
A stop call with [~strong:true] is more involved. But it allows to
prevent memory leaks when used judiciously on the leaves of the
reactive system that are no longer used.
{b Warning.} It should be noted that if direct references are kept
on an intermediate event or signal of the reactive system it may
suddenly stop updating if all its dependents were strongly stopped. In
the example below, [e1] will {e never} occur:
{[let e, e_send = E.create ()
let e1 = E.map (fun x -> x + 1) e (* never occurs *)
let () =
let e2 = E.map (fun x -> x + 1) e1 in
E.stop ~strong:true e2
]}
This can be side stepped by making an artificial dependency to keep
the reference:
{[let e, e_send = E.create ()
let e1 = E.map (fun x -> x + 1) e (* may still occur *)
let e1_ref = E.map (fun x -> x) e1
let () =
let e2 = E.map (fun x -> x + 1) e1 in
E.stop ~strong:true e2
]}
{1:ex Examples}
{2:clock Clock}
The following program defines a primitive event [seconds] holding
the UNIX time and occuring on every second. An effectful event
converts these occurences to local time and prints them on stdout
along with an
{{:-international.org/publications/standards/Ecma-048.htm}ANSI
escape sequence} to control the cursor position.
{[let pr_time t =
let tm = Unix.localtime t in
Printf.printf "\x1B[8D%02d:%02d:%02d%!"
tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec
open React;;
let seconds, run =
let e, send = E.create () in
let run () =
while true do send (Unix.gettimeofday ()); Unix.sleep 1 done
in
e, run
let printer = E.map pr_time seconds
let () = run ()]}
*)
---------------------------------------------------------------------------
Copyright ( c ) 2009
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2009 Daniel C. Bünzli
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/react.1.2.1%2Bdune/src/react.mli | ocaml | * {1 Interface}
* The type for events of type ['a].
* The type for signals of type ['a].
* The type for update steps.
* Event combinators.
Consult their {{!evsem}semantics.}
* The type for events with occurrences of type ['a].
* A never occuring event. For all t, \[[never]\]{_t} [= None].
* [retain e c] keeps a reference to the closure [c] in [e] and
returns the previously retained value. [c] will {e never} be
invoked.
{b Raises.} [Invalid_argument] on {!E.never}.
* [equal e e'] is [true] iff [e] and [e'] are equal. If both events are
different from {!never}, physical equality is used.
* [trace iff tr e] is [e] except [tr] is invoked with e's
occurence when [iff] is [true] (defaults to [S.const true]).
For all t where \[[e]\]{_t} [= Some v] and \[[iff]\]{_t} =
[true], [tr] is invoked with [v].
* [once e] is [e] with only its next occurence.
{ul
{- \[[once e]\]{_t} [= Some v] if \[[e]\]{_t} [= Some v] and
\[[e]\]{_<t} [= None].}
{- \[[once e]\]{_t} [= None] otherwise.}}
* [drop_once e] is [e] without its next occurrence.
{ul
{- \[[drop_once e]\]{_t} [= Some v] if \[[e]\]{_t} [= Some v] and
\[[e]\]{_<t} [= Some _].}
{- \[[drop_once e]\]{_t} [= None] otherwise.}}
* [app ef e] occurs when both [ef] and [e] occur
{{!simultaneity}simultaneously}.
The value is [ef]'s occurence applied to [e]'s one.
{ul
{- \[[app ef e]\]{_t} [= Some v'] if \[[ef]\]{_t} [= Some f] and
\[[e]\]{_t} [= Some v] and [f v = v'].}
{- \[[app ef e]\]{_t} [= None] otherwise.}}
* [map f e] applies [f] to [e]'s occurrences.
{ul
{- \[[map f e]\]{_t} [= Some (f v)] if \[[e]\]{_t} [= Some v].}
{- \[[map f e]\]{_t} [= None] otherwise.}}
* [stamp e v] is [map (fun _ -> v) e].
* [filter p e] are [e]'s occurrences that satisfy [p].
{ul
{- \[[filter p e]\]{_t} [= Some v] if \[[e]\]{_t} [= Some v] and
[p v = true]}
{- \[[filter p e]\]{_t} [= None] otherwise.}}
* [diff f e] occurs whenever [e] occurs except on the next occurence.
Occurences are [f v v'] where [v] is [e]'s current
occurrence and [v'] the previous one.
{ul
{- \[[diff f e]\]{_t} [= Some r] if \[[e]\]{_t} [= Some v],
\[[e]\]{_<t} [= Some v'] and [f v v' = r].}
{- \[[diff f e]\]{_t} [= None] otherwise.}}
* [changes eq e] is [e]'s occurrences with occurences equal to
the previous one dropped. Equality is tested with [eq] (defaults to
structural equality).
{ul
{- \[[changes eq e]\]{_t} [= Some v] if \[[e]\]{_t} [= Some v]
and either \[[e]\]{_<t} [= None] or \[[e]\]{_<t} [= Some v'] and
[eq v v' = false].}
{- \[[changes eq e]\]{_t} [= None] otherwise.}}
* [on c e] is the occurrences of [e] when [c] is [true].
{ul
{- \[[on c e]\]{_t} [= Some v]
if \[[c]\]{_t} [= true] and \[[e]\]{_t} [= Some v].}
{- \[[on c e]\]{_t} [= None] otherwise.}}
* @deprecated Use {!on}.
* [switch e ee] is [e]'s occurrences until there is an
occurrence [e'] on [ee], the occurrences of [e'] are then used
until there is a new occurrence on [ee], etc..
{ul
{- \[[switch e ee]\]{_ t} [=] \[[e]\]{_t} if \[[ee]\]{_<=t} [= None].}
{- \[[switch e ee]\]{_ t} [=] \[[e']\]{_t} if \[[ee]\]{_<=t}
[= Some e'].}}
* [fix ef] allows to refer to the value an event had an
infinitesimal amount of time before.
In [fix ef], [ef] is called with an event [e] that represents
the event returned by [ef] delayed by an infinitesimal amount of
time. If [e', r = ef e] then [r] is returned by [fix] and [e]
is such that :
{ul
{- \[[e]\]{_ t} [=] [None] if t = 0 }
{- \[[e]\]{_ t} [=] \[[e']\]{_t-dt} otherwise}}
{b Raises.} [Invalid_argument] if [e'] is directly a delayed event (i.e.
an event given to a fixing function).
* {1 Lifting}
Lifting combinators. For a given [n] the semantics is:
{ul
{- \[[ln f e1 ... en]\]{_t} [= Some (f v1 ... vn)] if for all
i : \[[ei]\]{_t} [= Some vi].}
{- \[[ln f e1 ... en]\]{_t} [= None] otherwise.}}
* Events with option occurences.
* [some e] is [map (fun v -> Some v) e].
* [value default e] either silences [None] occurences if [default] is
unspecified or replaces them by the value of [default] at the occurence
time.
{ul
{- \[[value ~default e]\]{_t}[ = v] if \[[e]\]{_t} [= Some (Some v)].}
{- \[[value ?default:None e]\]{_t}[ = None] if \[[e]\]{_t} = [None].}
{- \[[value ?default:(Some s) e]\]{_t}[ = v]
if \[[e]\]{_t} = [None] and \[[s]\]{_t} [= v].}}
* Signal combinators.
Consult their {{!sigsem}semantics.}
* The type for signals of type ['a].
* [const v] is always [v], \[[const v]\]{_t} [= v].
* [value s] is [s]'s current value.
{b Warning.} If executed in an {{!steps}update
step} may return a non up-to-date value or raise [Failure] if
the signal is not yet initialized.
* [retain s c] keeps a reference to the closure [c] in [s] and
returns the previously retained value. [c] will {e never} be
invoked.
{b Raises.} [Invalid_argument] on constant signals.
*/*
*/*
* [equal s s'] is [true] iff [s] and [s'] are equal. If both
signals are {!const}ant [eq] is used between their value
(defauts to structural equality). If both signals are not
{!const}ant, physical equality is used.
* [trace iff tr s] is [s] except [tr] is invoked with [s]'s
current value and on [s] changes when [iff] is [true] (defaults
to [S.const true]). For all t where \[[s]\]{_t} [= v] and (t = 0
or (\[[s]\]{_t-dt}[= v'] and [eq v v' = false])) and
\[[iff]\]{_t} = [true], [tr] is invoked with [v].
* [hold i e] has the value of [e]'s last occurrence or [i] if there
wasn't any.
{ul
{- \[[hold i e]\]{_t} [= i] if \[[e]\]{_<=t} [= None]}
{- \[[hold i e]\]{_t} [= v] if \[[e]\]{_<=t} [= Some v]}}
* [map f s] is [s] transformed by [f], \[[map f s]\]{_t} = [f] \[[s]\]{_t}.
* [filter f i s] is [s]'s values that satisfy [p]. If a value does not
satisfy [p] it holds the last value that was satisfied or [i] if
there is none.
{ul
{- \[[filter p s]\]{_t} [=] \[[s]\]{_t} if [p] \[[s]\]{_t}[ = true].}
{- \[[filter p s]\]{_t} [=] \[[s]\]{_t'} if [p] \[[s]\]{_t}[ = false]
and t' is the greatest t' < t with [p] \[[s]\]{_t'}[ = true].}
{- \[[filter p e]\]{_t} [= i] otherwise.}}
* [diff f s] is an event with occurrences whenever [s] changes from
[v'] to [v] and [eq v v'] is [false] ([eq] is the signal's equality
function). The value of the occurrence is [f v v'].
{ul
{- \[[diff f s]\]{_t} [= Some d]
if \[[s]\]{_t} [= v] and \[[s]\]{_t-dt} [= v'] and [eq v v' = false]
and [f v v' = d].}
{- \[[diff f s]\]{_t} [= None] otherwise.}}
* [changes s] is [diff (fun v _ -> v) s].
* [on c i s] is the signal [s] whenever [c] is [true].
When [c] is [false] it holds the last value [s] had when
[c] was the last time [true] or [i] if it never was.
{ul
{- \[[on c i s]\]{_t} [=] \[[s]\]{_t} if \[[c]\]{_t} [= true]}
{- \[[on c i s]\]{_t} [=] \[[s]\]{_t'} if \[[c]\]{_t} [= false]
where t' is the greatest t' < t with \[[c]\]{_t'} [= true].}
{- \[[on c i s]\]{_t} [=] [i] otherwise.}}
* @deprecated Use {!on}.
* [accum e i] is [S.hold i (]{!E.accum}[ e i)].
* [fold f i e] is [S.hold i (]{!E.fold}[ f i e)].
* [switch ss] is the inner signal of [ss].
{ul
{- \[[switch ss]\]{_ t} [=] \[\[[ss]\]{_t}\]{_t}.}}
* The following modules lift some of [Pervasives] functions and
operators.
* [edge s] is [changes s].
* [flip b e] is a signal whose boolean value flips each time
[e] occurs. [b] is the initial signal value.
{ul
{- \[[flip b e]\]{_0} [= not b] if \[[e]\]{_0} [= Some _]}
{- \[[flip b e]\]{_t} [= b] if \[[e]\]{_<=t} [= None]}
{- \[[flip b e]\]{_t} [=] [not] \[[flip b e]\]{_t-dt}
if \[[e]\]{_t} [= Some _]}}
* [none] is [S.const None].
* [some s] is [S.map ~eq (fun v -> Some v) None], where [eq] uses
[s]'s equality function to test the [Some v]'s equalities.
* Input signature of {!Make}
* Output signature of {!Make}
* Functor specializing the combinators for the given signal value type
* Specialization for booleans.
* Specialization for integers.
* Specialization for floats.
* Update steps.
Update functions returned by {!S.create} and {!E.create}
implicitely create and execute update steps when used without
specifying their [step] argument.
Using explicit {!step} values with these functions gives more control on
the time when the update step is perfomed and allows to perform
simultaneous {{!primitives}primitive} signal updates and event
occurences. See also the documentation about {{!steps}update steps} and
{{!simultaneity}simultaneous events}.
* {1 Steps}
* The type for update steps.
* [create ()] is a new update step.
* [execute step] executes the update step.
@raise Invalid_argument if [step] was already executed.
w x y occur simultaneously, z doesn't occur
w x z y occur simultaneously
inefficient
efficient
f is defined on float signals
back to pervasives floats
f is defined on float signals
diverges
diverges
never occurs
may still occur | ---------------------------------------------------------------------------
Copyright ( c ) 2009 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
% % NAME%% % % ---------------------------------------------------------------------------
Copyright (c) 2009 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
%%NAME%% %%VERSION%%
---------------------------------------------------------------------------*)
* Declarative events and signals .
React is a module for functional reactive programming ( frp ) . It
provides support to program with time varying values : declarative
{ { ! } and { { ! S}signals } . React
does n't define any primitive event or signal , this lets the client
choose the concrete timeline .
Consult the { { ! sem}semantics } , the { { ! basics}basics } and
{ { ! ex}examples } . Open the module to use it , this defines only two
types and modules in your scope .
{ e Release % % VERSION%% - % % MAINTAINER%% }
React is a module for functional reactive programming (frp). It
provides support to program with time varying values : declarative
{{!E}events} and {{!S}signals}. React
doesn't define any primitive event or signal, this lets the client
choose the concrete timeline.
Consult the {{!sem}semantics}, the {{!basics}basics} and
{{!ex}examples}. Open the module to use it, this defines only two
types and modules in your scope.
{e Release %%VERSION%% - %%MAINTAINER%% } *)
type 'a event
type 'a signal
type step
module E : sig
* { 1 : prim Primitive and basics }
type 'a t = 'a event
val never : 'a event
val create : unit -> 'a event * (?step:step -> 'a -> unit)
* [ create ( ) ] is a primitive event [ e ] and a [ send ] function . The
function [ send ] is such that :
{ ul
{ - [ send v ] generates an occurrence [ v ] of [ e ] at the time it is called
and triggers an { { ! steps}update step } . }
{ - [ send ~step v ] generates an occurence [ v ] of [ e ] on the step [ step ]
when [ step ] is { { ! Step.execute}executed } . }
{ - [ send ~step v ] raises [ Invalid_argument ] if it was previously
called with a step and this step has not executed yet or if
the given [ step ] was already executed . } }
{ b Warning . } [ send ] must not be executed inside an update step .
function [send] is such that:
{ul
{- [send v] generates an occurrence [v] of [e] at the time it is called
and triggers an {{!steps}update step}.}
{- [send ~step v] generates an occurence [v] of [e] on the step [step]
when [step] is {{!Step.execute}executed}.}
{- [send ~step v] raises [Invalid_argument] if it was previously
called with a step and this step has not executed yet or if
the given [step] was already executed.}}
{b Warning.} [send] must not be executed inside an update step. *)
val retain : 'a event -> (unit -> unit) -> [ `R of (unit -> unit) ]
val stop : ?strong:bool -> 'a event -> unit
* [ stop e ] stops [ e ] from occuring . It conceptually becomes
{ ! never } and can not be restarted . Allows to
disable { { ! sideeffects}effectful } events .
The [ strong ] argument should only be used on platforms
where weak arrays have a strong semantics ( i.e. JavaScript ) .
See { { ! strongstop}details } .
{ b Note . } If executed in an { { ! steps}update step }
the event may still occur in the step .
{!never} and cannot be restarted. Allows to
disable {{!sideeffects}effectful} events.
The [strong] argument should only be used on platforms
where weak arrays have a strong semantics (i.e. JavaScript).
See {{!strongstop}details}.
{b Note.} If executed in an {{!steps}update step}
the event may still occur in the step. *)
val equal : 'a event -> 'a event -> bool
val trace : ?iff:bool signal -> ('a -> unit) -> 'a event -> 'a event
* { 1 : transf Transforming and filtering }
val once : 'a event -> 'a event
val drop_once : 'a event -> 'a event
val app : ('a -> 'b) event -> 'a event -> 'b event
val map : ('a -> 'b) -> 'a event -> 'b event
val stamp : 'b event -> 'a -> 'a event
val filter : ('a -> bool) -> 'a event -> 'a event
val fmap : ('a -> 'b option) -> 'a event -> 'b event
* [ fmap fm e ] are [ e ] 's occurrences filtered and mapped by [ fm ] .
{ ul
{ - \[[fmap fm e]\]{_t } [= Some v ] if [ fm ] \[[e]\]{_t } [= Some v ] }
{ - \[[fmap fm e]\]{_t } [= None ] otherwise . } }
{ul
{- \[[fmap fm e]\]{_t} [= Some v] if [fm] \[[e]\]{_t} [= Some v]}
{- \[[fmap fm e]\]{_t} [= None] otherwise.}} *)
val diff : ('a -> 'a -> 'b) -> 'a event -> 'b event
val changes : ?eq:('a -> 'a -> bool) -> 'a event -> 'a event
val on : bool signal -> 'a event -> 'a event
val when_ : bool signal -> 'a event -> 'a event
val dismiss : 'b event -> 'a event -> 'a event
* [ dismiss c e ] is the occurences of [ e ] except the ones when [ c ] occurs .
{ ul
c e]\]{_t } [= Some v ]
if \[[c]\]{_t } [= None ] and \[[e]\]{_t } [= Some v ] . }
c e]\]{_t } [= None ] otherwise . } }
{ul
{- \[[dimiss c e]\]{_t} [= Some v]
if \[[c]\]{_t} [= None] and \[[e]\]{_t} [= Some v].}
{- \[[dimiss c e]\]{_t} [= None] otherwise.}} *)
val until : 'a event -> 'b event -> 'b event
* [ until c e ] is [ e ] 's occurences until [ c ] occurs .
{ ul
{ - \[[until c e]\]{_t } [= Some v ] if \[[e]\]{_t } [= Some v ] and
} [= None ] }
{ - \[[until c e]\]{_t } [= None ] otherwise . } }
{ul
{- \[[until c e]\]{_t} [= Some v] if \[[e]\]{_t} [= Some v] and
\[[c]\]{_<=t} [= None]}
{- \[[until c e]\]{_t} [= None] otherwise.}} *)
* { 1 : accum Accumulating }
val accum : ('a -> 'a) event -> 'a -> 'a event
* [ accum ef i ] accumulates a value , starting with [ i ] , using [ e ] 's
functional occurrences .
{ ul
{ - \[[accum ef i]\]{_t } [= Some ( f i ) ] if \[[ef]\]{_t } [= Some f ]
and \[[ef]\]{_<t } [= None ] .
}
{ - \[[accum ef i]\]{_t } [= Some ( f acc ) ] if \[[ef]\]{_t } [= Some f ]
and \[[accum ef i]\]{_<t } [= Some acc ] . }
{ - \[[accum ef i]\ ] [= None ] otherwise . } }
functional occurrences.
{ul
{- \[[accum ef i]\]{_t} [= Some (f i)] if \[[ef]\]{_t} [= Some f]
and \[[ef]\]{_<t} [= None].
}
{- \[[accum ef i]\]{_t} [= Some (f acc)] if \[[ef]\]{_t} [= Some f]
and \[[accum ef i]\]{_<t} [= Some acc].}
{- \[[accum ef i]\] [= None] otherwise.}} *)
val fold : ('a -> 'b -> 'a) -> 'a -> 'b event -> 'a event
* [ fold f i e ] accumulates [ e ] 's occurrences with [ f ] starting with [ i ] .
{ ul
{ - \[[fold f i e]\]{_t } [= Some ( f i v ) ] if
\[[e]\]{_t } [= Some v ] and \[[e]\]{_<t } [= None ] . }
{ - \[[fold f i e]\]{_t } [= Some ( f acc v ) ] if
\[[e]\]{_t } [= Some v ] and \[[fold f i e]\]{_<t } [= Some acc ] . }
{ - \[[fold f i e]\]{_t } [= None ] otherwise . } }
{ul
{- \[[fold f i e]\]{_t} [= Some (f i v)] if
\[[e]\]{_t} [= Some v] and \[[e]\]{_<t} [= None].}
{- \[[fold f i e]\]{_t} [= Some (f acc v)] if
\[[e]\]{_t} [= Some v] and \[[fold f i e]\]{_<t} [= Some acc].}
{- \[[fold f i e]\]{_t} [= None] otherwise.}} *)
* { 1 : combine Combining }
val select : 'a event list -> 'a event
* [ select el ] is the occurrences of every event in [ el ] .
If more than one event occurs { { ! simultaneity}simultaneously }
the leftmost is taken and the others are lost .
{ ul
{ - \[[select el]\ ] { _ t } [ =] \[[List.find ( fun e - > ] \[[e]\]{_t }
[ < > None ) el]\]{_t } . }
{ - \[[select el]\ ] { _ t } [= None ] otherwise . } }
If more than one event occurs {{!simultaneity}simultaneously}
the leftmost is taken and the others are lost.
{ul
{- \[[select el]\]{_ t} [=] \[[List.find (fun e -> ]\[[e]\]{_t}
[<> None) el]\]{_t}.}
{- \[[select el]\]{_ t} [= None] otherwise.}} *)
val merge : ('a -> 'b -> 'a) -> 'a -> 'b event list -> 'a event
* [ merge f a el ] merges the { { ! simultaneity}simultaneous }
occurrences of every event in [ el ] using [ f ] and the accumulator [ a ] .
\[[merge f a el]\ ] { _ t }
[= List.fold_left f a ( ( fun o - > o < > None )
( List.map ] \[\]{_t } [ el ) ) ] .
occurrences of every event in [el] using [f] and the accumulator [a].
\[[merge f a el]\]{_ t}
[= List.fold_left f a (List.filter (fun o -> o <> None)
(List.map] \[\]{_t}[ el))]. *)
val switch : 'a event -> 'a event event -> 'a event
val fix : ('a event -> 'a event * 'b) -> 'b
val l1 : ('a -> 'b) -> 'a event -> 'b event
val l2 : ('a -> 'b -> 'c) -> 'a event -> 'b event -> 'c event
val l3 : ('a -> 'b -> 'c -> 'd) -> 'a event -> 'b event -> 'c event ->
'd event
val l4 : ('a -> 'b -> 'c -> 'd -> 'e) -> 'a event -> 'b event -> 'c event ->
'd event -> 'e event
val l5 : ('a -> 'b -> 'c -> 'd -> 'e -> 'f) -> 'a event -> 'b event ->
'c event -> 'd event -> 'e event -> 'f event
val l6 : ('a -> 'b -> 'c -> 'd -> 'e -> 'f -> 'g) -> 'a event -> 'b event ->
'c event -> 'd event -> 'e event -> 'f event -> 'g event
* { 1 Pervasives support }
module Option : sig
val some : 'a event -> 'a option event
val value : ?default:'a signal -> 'a option event -> 'a event
end
end
module S : sig
* { 1 : prim Primitive and basics }
type 'a t = 'a signal
val const : 'a -> 'a signal
val create : ?eq:('a -> 'a -> bool) -> 'a ->
'a signal * (?step:step -> 'a -> unit)
* [ create i ] is a primitive signal [ s ] set to [ i ] and a
[ set ] function . The function [ set ] is such that :
{ ul
{ - [ set v ] sets the signal 's value to [ v ] at the time it is called and
triggers an { { ! steps}update step } . }
{ - [ set ~step v ] sets the signal 's value to [ v ] at the time it is
called and updates it dependencies when [ step ] is
{ { ! Step.execute}executed } }
{ - [ set ~step v ] raises [ Invalid_argument ] if it was previously
called with a step and this step has not executed yet or if
the given [ step ] was already executed . } }
{ b Warning . } [ set ] must not be executed inside an update step .
[set] function. The function [set] is such that:
{ul
{- [set v] sets the signal's value to [v] at the time it is called and
triggers an {{!steps}update step}.}
{- [set ~step v] sets the signal's value to [v] at the time it is
called and updates it dependencies when [step] is
{{!Step.execute}executed}}
{- [set ~step v] raises [Invalid_argument] if it was previously
called with a step and this step has not executed yet or if
the given [step] was already executed.}}
{b Warning.} [set] must not be executed inside an update step. *)
val value : 'a signal -> 'a
val retain : 'a signal -> (unit -> unit) -> [ `R of (unit -> unit) ]
val eq_fun : 'a signal -> ('a -> 'a -> bool) option
val stop : ?strong:bool -> 'a signal -> unit
* [ stop s ] , stops updating [ s ] . It conceptually becomes { ! const }
with the signal 's last value and can not be restarted . Allows to
disable { { ! sideeffects}effectful } signals .
The [ strong ] argument should only be used on platforms
where weak arrays have a strong semantics ( i.e. JavaScript ) .
See { { ! strongstop}details } .
{ b Note . } If executed in an update step the signal may
still update in the step .
with the signal's last value and cannot be restarted. Allows to
disable {{!sideeffects}effectful} signals.
The [strong] argument should only be used on platforms
where weak arrays have a strong semantics (i.e. JavaScript).
See {{!strongstop}details}.
{b Note.} If executed in an update step the signal may
still update in the step. *)
val equal : ?eq:('a -> 'a -> bool) -> 'a signal -> 'a signal -> bool
val trace : ?iff:bool t -> ('a -> unit) -> 'a signal -> 'a signal
* { 1 From events }
val hold : ?eq:('a -> 'a -> bool) -> 'a -> 'a event -> 'a signal
* { 1 : tr Transforming and filtering }
val app : ?eq:('b -> 'b -> bool) -> ('a -> 'b) signal -> 'a signal ->
'b signal
* [ app sf s ] holds the value of [ sf ] applied
to the value of [ s ] , \[[app sf s]\]{_t }
[ =] \[[sf]\]{_t } \[[s]\]{_t } .
to the value of [s], \[[app sf s]\]{_t}
[=] \[[sf]\]{_t} \[[s]\]{_t}. *)
val map : ?eq:('b -> 'b -> bool) -> ('a -> 'b) -> 'a signal -> 'b signal
val filter : ?eq:('a -> 'a -> bool) -> ('a -> bool) -> 'a -> 'a signal ->
'a signal
val fmap : ?eq:('b -> 'b -> bool) -> ('a -> 'b option) -> 'b -> 'a signal ->
'b signal
* [ fmap fm i s ] is [ s ] filtered and mapped by [ fm ] .
{ ul
{ - \[[fmap fm i s]\]{_t } [ =] v if [ fm ] \[[s]\]{_t } [ = Some v ] . }
{ - \[[fmap fm i s]\]{_t } [ =] \[[fmap fm i s]\]{_t ' } if [ fm ]
\[[s]\]{_t } [= None ] and t ' is the greatest t ' < t with [ fm ]
\[[s]\]{_t ' } [ < > None ] . }
{ - \[[fmap fm i s]\]{_t } [= i ] otherwise . } }
{ul
{- \[[fmap fm i s]\]{_t} [=] v if [fm] \[[s]\]{_t}[ = Some v].}
{- \[[fmap fm i s]\]{_t} [=] \[[fmap fm i s]\]{_t'} if [fm]
\[[s]\]{_t} [= None] and t' is the greatest t' < t with [fm]
\[[s]\]{_t'} [<> None].}
{- \[[fmap fm i s]\]{_t} [= i] otherwise.}} *)
val diff : ('a -> 'a -> 'b) -> 'a signal -> 'b event
val changes : 'a signal -> 'a event
val sample : ('b -> 'a -> 'c) -> 'b event -> 'a signal -> 'c event
* [ sample f e s ] samples [ s ] at [ e ] 's occurrences .
{ ul
} [= Some ( f ev sv ) ] if \[[e]\]{_t } [= Some ev ]
and \[[s]\]{_t } [= sv ] . }
{ - \[[sample e s]\]{_t } [= None ] otherwise . } }
{ul
{- \[[sample f e s]\]{_t} [= Some (f ev sv)] if \[[e]\]{_t} [= Some ev]
and \[[s]\]{_t} [= sv].}
{- \[[sample e s]\]{_t} [= None] otherwise.}} *)
val on : ?eq:('a -> 'a -> bool) -> bool signal -> 'a -> 'a signal ->
'a signal
val when_ : ?eq:('a -> 'a -> bool) -> bool signal -> 'a -> 'a signal ->
'a signal
val dismiss : ?eq:('a -> 'a -> bool) -> 'b event -> 'a -> 'a signal ->
'a signal
* [ dismiss c i s ] is the signal [ s ] except changes when [ c ] occurs
are ignored . If [ c ] occurs initially [ i ] is used .
{ ul
{ - \[[dismiss c i s]\]{_t } [ =] \[[s]\]{_t ' }
where t ' is the greatest t ' < = t with \[[c]\]{_t ' } [= None ] and
\[[s]\]{_t'-dt } [ < > ] \[[s]\]{_t ' } }
{ - \[[dismiss _ c i s]\]{_0 } [ =] [ v ] where [ v = i ] if
\[[c]\]{_0 } [= Some _ ] and [ v =] \[[s]\]{_0 } otherwise . } }
are ignored. If [c] occurs initially [i] is used.
{ul
{- \[[dismiss c i s]\]{_t} [=] \[[s]\]{_t'}
where t' is the greatest t' <= t with \[[c]\]{_t'} [= None] and
\[[s]\]{_t'-dt} [<>] \[[s]\]{_t'}}
{- \[[dismiss_ c i s]\]{_0} [=] [v] where [v = i] if
\[[c]\]{_0} [= Some _] and [v =] \[[s]\]{_0} otherwise.}} *)
* { 1 : acc Accumulating }
val accum : ?eq:('a -> 'a -> bool) -> ('a -> 'a) event -> 'a -> 'a signal
val fold : ?eq:('a -> 'a -> bool) -> ('a -> 'b -> 'a) -> 'a -> 'b event ->
'a signal
* { 1 : combine Combining }
val merge : ?eq:('a -> 'a -> bool) -> ('a -> 'b -> 'a) -> 'a ->
'b signal list -> 'a signal
* [ merge f a sl ] merges the value of every signal in [ sl ]
using [ f ] and the accumulator [ a ] .
\[[merge f a sl]\ ] { _ t }
[= List.fold_left f a ( List.map ] \[\]{_t } [ sl ) ] .
using [f] and the accumulator [a].
\[[merge f a sl]\]{_ t}
[= List.fold_left f a (List.map] \[\]{_t}[ sl)]. *)
val switch : ?eq:('a -> 'a -> bool) -> 'a signal signal -> 'a signal
val bind : ?eq:('b -> 'b -> bool) -> 'a signal -> ('a -> 'b signal) ->
'b signal
* [ bind s sf ] is [ switch ( map ~eq :( = = ) sf s ) ] .
val fix : ?eq:('a -> 'a -> bool) -> 'a -> ('a signal -> 'a signal * 'b) -> 'b
* [ fix i sf ] allow to refer to the value a signal had an
infinitesimal amount of time before .
In [ fix sf ] , [ sf ] is called with a signal [ s ] that represents
the signal returned by [ sf ] delayed by an infinitesimal amount
time . If [ s ' , r = sf s ] then [ r ] is returned by [ fix ] and [ s ]
is such that :
{ ul
{ - \[[s]\ ] { _ t } [ =] [ i ] for t = 0 . }
{ - \[[s]\ ] { _ t } [ =] \[[s']\]{_t - dt } otherwise . } }
[ eq ] is the equality used by [ s ] .
{ b Raises . } [ Invalid_argument ] if [ s ' ] is directly a delayed signal ( i.e.
a signal given to a fixing function ) .
{ b Note . } Regarding values depending on the result [ r ] of
[ s ' , r = sf s ] the following two cases need to be distinguished :
{ ul
{ - After [ sf s ] is applied , [ s ' ] does not depend on
a value that is in a step and [ s ] has no dependents in a step ( e.g
in the simple case where [ fix ] is applied outside a step ) .
In that case if the initial value of [ s ' ] differs from [ i ] ,
[ s ] and its dependents need to be updated and a special
update step will be triggered for this . Values
depending on the result [ r ] will be created only after this
special update step has finished ( e.g. they wo n't see
the [ i ] of [ s ] if [ r = s ] ) . }
{ - Otherwise , values depending on [ r ] will be created in the same
step as [ s ] and [ s ' ] ( e.g. they will see the [ i ] of [ s ] if [ r = s ] ) . } }
infinitesimal amount of time before.
In [fix sf], [sf] is called with a signal [s] that represents
the signal returned by [sf] delayed by an infinitesimal amount
time. If [s', r = sf s] then [r] is returned by [fix] and [s]
is such that :
{ul
{- \[[s]\]{_ t} [=] [i] for t = 0. }
{- \[[s]\]{_ t} [=] \[[s']\]{_t-dt} otherwise.}}
[eq] is the equality used by [s].
{b Raises.} [Invalid_argument] if [s'] is directly a delayed signal (i.e.
a signal given to a fixing function).
{b Note.} Regarding values depending on the result [r] of
[s', r = sf s] the following two cases need to be distinguished :
{ul
{- After [sf s] is applied, [s'] does not depend on
a value that is in a step and [s] has no dependents in a step (e.g
in the simple case where [fix] is applied outside a step).
In that case if the initial value of [s'] differs from [i],
[s] and its dependents need to be updated and a special
update step will be triggered for this. Values
depending on the result [r] will be created only after this
special update step has finished (e.g. they won't see
the [i] of [s] if [r = s]).}
{- Otherwise, values depending on [r] will be created in the same
step as [s] and [s'] (e.g. they will see the [i] of [s] if [r = s]).}}
*)
* { 1 : lifting Lifting }
Lifting combinators . For a given [ n ] the semantics is :
\[[ln f a1 ] ... [ an]\]{_t } = f \[[a1]\]{_t } ... \[[an]\]{_t }
Lifting combinators. For a given [n] the semantics is :
\[[ln f a1] ... [an]\]{_t} = f \[[a1]\]{_t} ... \[[an]\]{_t} *)
val l1 : ?eq:('b -> 'b -> bool) -> ('a -> 'b) -> ('a signal -> 'b signal)
val l2 : ?eq:('c -> 'c -> bool) ->
('a -> 'b -> 'c) -> ('a signal -> 'b signal -> 'c signal)
val l3 : ?eq:('d -> 'd -> bool) ->
('a -> 'b -> 'c -> 'd) -> ('a signal -> 'b signal -> 'c signal -> 'd signal)
val l4 : ?eq:('e -> 'e -> bool) ->
('a -> 'b -> 'c -> 'd -> 'e) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal)
val l5 : ?eq:('f -> 'f -> bool) ->
('a -> 'b -> 'c -> 'd -> 'e -> 'f) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal ->
'f signal)
val l6 : ?eq:('g -> 'g -> bool) ->
('a -> 'b -> 'c -> 'd -> 'e -> 'f -> 'g) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal ->
'f signal -> 'g signal)
module Bool : sig
val zero : bool signal
val one : bool signal
val not : bool signal -> bool signal
val ( && ) : bool signal -> bool signal -> bool signal
val ( || ) : bool signal -> bool signal -> bool signal
val edge : bool signal -> bool event
val rise : bool signal -> unit event
* [ rise s ] is [ E.fmap ( fun b - > if b then Some ( ) else None ) ( edge s ) ] .
val fall : bool signal -> unit event
* [ fall s ] is [ E.fmap ( fun b - > if b then None else Some ( ) ) ( edge s ) ] .
val flip : bool -> 'a event -> bool signal
end
module Int : sig
val zero : int signal
val one : int signal
val minus_one : int signal
val ( ~- ) : int signal -> int signal
val succ : int signal -> int signal
val pred : int signal -> int signal
val ( + ) : int signal -> int signal -> int signal
val ( - ) : int signal -> int signal -> int signal
val ( * ) : int signal -> int signal -> int signal
val ( mod ) : int signal -> int signal -> int signal
val abs : int signal -> int signal
val max_int : int signal
val min_int : int signal
val ( land ) : int signal -> int signal -> int signal
val ( lor ) : int signal -> int signal -> int signal
val ( lxor ) : int signal -> int signal -> int signal
val lnot : int signal -> int signal
val ( lsl ) : int signal -> int signal -> int signal
val ( lsr ) : int signal -> int signal -> int signal
val ( asr ) : int signal -> int signal -> int signal
end
module Float : sig
val zero : float signal
val one : float signal
val minus_one : float signal
val ( ~-. ) : float signal -> float signal
val ( +. ) : float signal -> float signal -> float signal
val ( -. ) : float signal -> float signal -> float signal
val ( *. ) : float signal -> float signal -> float signal
val ( /. ) : float signal -> float signal -> float signal
val ( ** ) : float signal -> float signal -> float signal
val sqrt : float signal -> float signal
val exp : float signal -> float signal
val log : float signal -> float signal
val log10 : float signal -> float signal
val cos : float signal -> float signal
val sin : float signal -> float signal
val tan : float signal -> float signal
val acos : float signal -> float signal
val asin : float signal -> float signal
val atan : float signal -> float signal
val atan2 : float signal -> float signal -> float signal
val cosh : float signal -> float signal
val sinh : float signal -> float signal
val tanh : float signal -> float signal
val ceil : float signal -> float signal
val floor : float signal -> float signal
val abs_float : float signal -> float signal
val mod_float : float signal -> float signal -> float signal
val frexp : float signal -> (float * int) signal
val ldexp : float signal -> int signal -> float signal
val modf : float signal -> (float * float) signal
val float : int signal -> float signal
val float_of_int : int signal -> float signal
val truncate : float signal -> int signal
val int_of_float : float signal -> int signal
val infinity : float signal
val neg_infinity : float signal
val nan : float signal
val max_float : float signal
val min_float : float signal
val epsilon_float : float signal
val classify_float : float signal -> fpclass signal
end
module Pair : sig
val pair : ?eq:(('a * 'b) -> ('a * 'b) -> bool)->
'a signal -> 'b signal -> ('a * 'b) signal
val fst : ?eq:('a -> 'a -> bool) -> ('a * 'b) signal -> 'a signal
val snd : ?eq:('a -> 'a -> bool) -> ('b * 'a) signal -> 'a signal
end
module Option : sig
val none : 'a option signal
val some : 'a signal -> 'a option signal
val value : ?eq:('a -> 'a -> bool) ->
default:[`Init of 'a signal | `Always of 'a signal ] ->
'a option signal -> 'a signal
* [ value default s ] is [ s ] with only its [ Some v ] values .
Whenever [ s ] is [ None ] , if [ default ] is [ ` Always dv ] then
the current value of [ dv ] is used instead . If [ default ]
is [ ` Init dv ] the current value of [ dv ] is only used
if there 's no value at creation time , otherwise the last
[ Some v ] value of [ s ] is used .
{ ul
{ - \[[value [= v ] if \[[s]\]{_t } [= Some v ] }
{ - \[[value ~default:(`Always d ) s]\]{_t } [ =] \[[d]\]{_t }
if \[[s]\]{_t } [= None ] }
{ - \[[value ~default:(`Init d ) s]\]{_0 } [ =] \[[d]\]{_0 }
if \[[s]\]{_0 } [= None ] }
{ - \[[value ~default:(`Init d ) s]\]{_t } [ =]
\[[value ~default:(`Init d ) s]\]{_t ' }
if \[[s]\]{_t } [= None ] and t ' is the greatest t ' < t
with \[[s]\]{_t ' } [ < > None ] or 0 if there is no such [ t ' ] . } }
Whenever [s] is [None], if [default] is [`Always dv] then
the current value of [dv] is used instead. If [default]
is [`Init dv] the current value of [dv] is only used
if there's no value at creation time, otherwise the last
[Some v] value of [s] is used.
{ul
{- \[[value ~default s]\]{_t} [= v] if \[[s]\]{_t} [= Some v]}
{- \[[value ~default:(`Always d) s]\]{_t} [=] \[[d]\]{_t}
if \[[s]\]{_t} [= None]}
{- \[[value ~default:(`Init d) s]\]{_0} [=] \[[d]\]{_0}
if \[[s]\]{_0} [= None]}
{- \[[value ~default:(`Init d) s]\]{_t} [=]
\[[value ~default:(`Init d) s]\]{_t'}
if \[[s]\]{_t} [= None] and t' is the greatest t' < t
with \[[s]\]{_t'} [<> None] or 0 if there is no such [t'].}} *)
end
module Compare : sig
val ( = ) : 'a signal -> 'a signal -> bool signal
val ( <> ) : 'a signal -> 'a signal -> bool signal
val ( < ) : 'a signal -> 'a signal -> bool signal
val ( > ) : 'a signal -> 'a signal -> bool signal
val ( <= ) : 'a signal -> 'a signal -> bool signal
val ( >= ) : 'a signal -> 'a signal -> bool signal
val compare : 'a signal -> 'a signal -> int signal
val ( == ) : 'a signal -> 'a signal -> bool signal
val ( != ) : 'a signal -> 'a signal -> bool signal
end
* { 1 : special Combinator specialization }
Given an equality function [ equal ] and a type [ t ] , the functor
{ ! Make } automatically applies the [ eq ] parameter of the combinators .
The outcome is combinators whose { e results } are signals with
values in [ t ] .
Basic types are already specialized in the module { ! Special } , open
this module to use them .
Given an equality function [equal] and a type [t], the functor
{!Make} automatically applies the [eq] parameter of the combinators.
The outcome is combinators whose {e results} are signals with
values in [t].
Basic types are already specialized in the module {!Special}, open
this module to use them. *)
module type EqType = sig
type 'a t
val equal : 'a t -> 'a t -> bool
end
module type S = sig
type 'a v
val create : 'a v -> 'a v signal * (?step:step -> 'a v -> unit)
val equal : 'a v signal -> 'a v signal -> bool
val hold : 'a v -> 'a v event -> 'a v signal
val app : ('a -> 'b v) signal -> 'a signal -> 'b v signal
val map : ('a -> 'b v) -> 'a signal -> 'b v signal
val filter : ('a v -> bool) -> 'a v -> 'a v signal -> 'a v signal
val fmap : ('a -> 'b v option) -> 'b v -> 'a signal -> 'b v signal
val when_ : bool signal -> 'a v -> 'a v signal -> 'a v signal
val dismiss : 'b event -> 'a v -> 'a v signal -> 'a v signal
val accum : ('a v -> 'a v) event -> 'a v -> 'a v signal
val fold : ('a v -> 'b -> 'a v) -> 'a v -> 'b event -> 'a v signal
val merge : ('a v -> 'b -> 'a v) -> 'a v -> 'b signal list -> 'a v signal
val switch : 'a v signal signal -> 'a v signal
val bind : 'b signal -> ('b -> 'a v signal) -> 'a v signal
val fix : 'a v -> ('a v signal -> 'a v signal * 'b) -> 'b
val l1 : ('a -> 'b v) -> ('a signal -> 'b v signal)
val l2 : ('a -> 'b -> 'c v) -> ('a signal -> 'b signal -> 'c v signal)
val l3 : ('a -> 'b -> 'c -> 'd v) -> ('a signal -> 'b signal ->
'c signal -> 'd v signal)
val l4 : ('a -> 'b -> 'c -> 'd -> 'e v) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e v signal)
val l5 : ('a -> 'b -> 'c -> 'd -> 'e -> 'f v) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal ->
'f v signal)
val l6 : ('a -> 'b -> 'c -> 'd -> 'e -> 'f -> 'g v) ->
('a signal -> 'b signal -> 'c signal -> 'd signal -> 'e signal ->
'f signal -> 'g v signal)
end
module Make (Eq : EqType) : S with type 'a v = 'a Eq.t
* Specialization for booleans , integers and floats .
Open this module to use it .
Open this module to use it. *)
module Special : sig
module Sb : S with type 'a v = bool
module Si : S with type 'a v = int
module Sf : S with type 'a v = float
end
end
module Step : sig
type t = step
val create : unit -> step
val execute : step -> unit
end
* { 1 : sem Semantics }
The following notations are used to give precise meaning to the
combinators . It is important to note that in these semantic
descriptions the origin of time t = 0 is { e always } fixed at
the time at which the combinator creates the event or the signal and
the semantics of the dependents is evaluated relative to this timeline .
We use dt to denote an infinitesimal amount of time .
{ 2 : evsem Events }
An event is a value with discrete occurrences over time .
The semantic function \[\ ] [: ' a event - > time - > ' a option ] gives
meaning to an event [ e ] by mapping it to a function of time
\[[e]\ ] returning [ Some v ] whenever the event occurs with value
[ v ] and [ None ] otherwise . We write \[[e]\]{_t } the evaluation of
this { e semantic } function at time t.
As a shortcut notation we also define } [: ' a event - > ' a option ]
( resp . \[\]{_<=t } ) to denote the last occurrence , if any , of an
event before ( resp . before or at ) [ t ] . More precisely :
{ ul
{ - \[[e]\]{_<t } [ =] \[[e]\]{_t ' } with t ' the greatest t ' < t
( resp . [ < =] ) such that
\[[e]\]{_t ' } [ < > None ] . }
{ - \[[e]\]{_<t } [= None ] if there is no such t ' . } }
{ 2 : sigsem Signals }
A signal is a value that varies continuously over time . In
contrast to { { ! evsem}events } which occur at specific point
in time , a signal has a value at every point in time .
The semantic function \[\ ] [: ' a signal - > time - > ' a ] gives
meaning to a signal [ s ] by mapping it to a function of time
\[[s]\ ] that returns its value at a given time . We write \[[s]\]{_t }
the evaluation of this { e semantic } function at time t.
{ 3 : sigeq Equality }
Most signal combinators have an optional [ eq ] parameter that
defaults to structural equality . [ eq ] specifies the equality
function used to detect changes in the value of the resulting
signal . This function is needed for the efficient update of
signals and to deal correctly with signals that perform
{ { ! sideeffects}side effects } .
Given an equality function on a type the combinators can be automatically
{ { ! } via a functor .
{ 3 : sigcont Continuity }
Ultimately signal updates depend on
{ { ! primitives}primitives } updates . Thus a signal can
only approximate a real continuous signal . The accuracy of the
approximation depends on the variation rate of the real signal and
the primitive 's update frequency .
{ 1 : basics Basics }
{ 2 : primitives Primitive events and signals }
React does n't define primitive events and signals , they must be
created and updated by the client .
Primitive events are created with { ! E.create } . This function
returns a new event and an update function that generates an
occurrence for the event at the time it is called . The following
code creates a primitive integer event [ x ] and generates three
occurrences with value [ 1 ] , [ 2 ] , [ 3 ] . Those occurrences are printed
on stdout by the effectful event [ pr_x ] . { [ open React ; ;
let x , send_x = E.create ( )
let pr_x = E.map print_int x
let ( ) = List.iter send_x [ 1 ; 2 ; 3 ] ] }
Primitive signals are created with { ! S.create } . This function
returns a new signal and an update function that sets the signal 's value
at the time it is called . The following code creates an
integer signal [ x ] initially set to [ 1 ] and updates it three time with
values [ 2 ] , [ 2 ] , [ 3 ] . The signal 's values are printed on stdout by the
effectful signal [ pr_x ] . Note that only updates that change
the signal 's value are printed , hence the program prints [ 123 ] , not [ 1223 ] .
See the discussion on
{ { ! sideeffects}side effects } for more details .
{ [ open React ; ;
let x , set_x = S.create 1
let pr_x = S.map print_int x
let ( ) = List.iter set_x [ 2 ; 2 ; 3 ] ] }
The { { ! clock}clock } example shows how a realtime time
flow can be defined .
{ 2 : steps Update steps }
The { ! E.create } and { ! S.create } functions return update functions
used to generate primitive event occurences and set the value of
primitive signals . Upon invocation as in the preceding section
these functions immediatly create and invoke an update step .
The { e update step } automatically updates events and signals that
transitively depend on the updated primitive . The dependents of a
signal are updated iff the signal 's value changed according to its
{ { ! sigeq}equality function } .
The update functions have an optional [ step ] argument . If they are
given a concrete [ step ] value created with { ! Step.create } , then it
updates the event or signal but does n't update its dependencies . It
will only do so whenever [ step ] is executed with
{ ! Step.execute } . This allows to make primitive event occurences and
signal changes simultaneous . See next section for an example .
{ 2 : simultaneity Simultaneous events }
{ { ! steps}Update steps } are made under a
{ { : -6423(92)90005-V}synchrony hypothesis } :
the update step takes no time , it is instantenous . Two event occurrences
are { e simultaneous } if they occur in the same update step .
In the code below [ w ] , [ x ] and [ y ] will always have simultaneous
occurrences . They { e may } have simulatenous occurences with [ z ]
if [ send_w ] and [ send_z ] are used with the same update step .
{ [ let w , send_w = E.create ( )
let x = E.map succ w
let y = E.map succ x
let z , send_z = E.create ( )
let ( ) =
let ( ) = send_w 3 ( * w x y occur simultaneously , z does n't occur
The following notations are used to give precise meaning to the
combinators. It is important to note that in these semantic
descriptions the origin of time t = 0 is {e always} fixed at
the time at which the combinator creates the event or the signal and
the semantics of the dependents is evaluated relative to this timeline.
We use dt to denote an infinitesimal amount of time.
{2:evsem Events}
An event is a value with discrete occurrences over time.
The semantic function \[\] [: 'a event -> time -> 'a option] gives
meaning to an event [e] by mapping it to a function of time
\[[e]\] returning [Some v] whenever the event occurs with value
[v] and [None] otherwise. We write \[[e]\]{_t} the evaluation of
this {e semantic} function at time t.
As a shortcut notation we also define \[\]{_<t} [: 'a event -> 'a option]
(resp. \[\]{_<=t}) to denote the last occurrence, if any, of an
event before (resp. before or at) [t]. More precisely :
{ul
{- \[[e]\]{_<t} [=] \[[e]\]{_t'} with t' the greatest t' < t
(resp. [<=]) such that
\[[e]\]{_t'} [<> None].}
{- \[[e]\]{_<t} [= None] if there is no such t'.}}
{2:sigsem Signals}
A signal is a value that varies continuously over time. In
contrast to {{!evsem}events} which occur at specific point
in time, a signal has a value at every point in time.
The semantic function \[\] [: 'a signal -> time -> 'a] gives
meaning to a signal [s] by mapping it to a function of time
\[[s]\] that returns its value at a given time. We write \[[s]\]{_t}
the evaluation of this {e semantic} function at time t.
{3:sigeq Equality}
Most signal combinators have an optional [eq] parameter that
defaults to structural equality. [eq] specifies the equality
function used to detect changes in the value of the resulting
signal. This function is needed for the efficient update of
signals and to deal correctly with signals that perform
{{!sideeffects}side effects}.
Given an equality function on a type the combinators can be automatically
{{!S.special}specialized} via a functor.
{3:sigcont Continuity}
Ultimately signal updates depend on
{{!primitives}primitives} updates. Thus a signal can
only approximate a real continuous signal. The accuracy of the
approximation depends on the variation rate of the real signal and
the primitive's update frequency.
{1:basics Basics}
{2:primitives Primitive events and signals}
React doesn't define primitive events and signals, they must be
created and updated by the client.
Primitive events are created with {!E.create}. This function
returns a new event and an update function that generates an
occurrence for the event at the time it is called. The following
code creates a primitive integer event [x] and generates three
occurrences with value [1], [2], [3]. Those occurrences are printed
on stdout by the effectful event [pr_x]. {[open React;;
let x, send_x = E.create ()
let pr_x = E.map print_int x
let () = List.iter send_x [1; 2; 3]]}
Primitive signals are created with {!S.create}. This function
returns a new signal and an update function that sets the signal's value
at the time it is called. The following code creates an
integer signal [x] initially set to [1] and updates it three time with
values [2], [2], [3]. The signal's values are printed on stdout by the
effectful signal [pr_x]. Note that only updates that change
the signal's value are printed, hence the program prints [123], not [1223].
See the discussion on
{{!sideeffects}side effects} for more details.
{[open React;;
let x, set_x = S.create 1
let pr_x = S.map print_int x
let () = List.iter set_x [2; 2; 3]]}
The {{!clock}clock} example shows how a realtime time
flow can be defined.
{2:steps Update steps}
The {!E.create} and {!S.create} functions return update functions
used to generate primitive event occurences and set the value of
primitive signals. Upon invocation as in the preceding section
these functions immediatly create and invoke an update step.
The {e update step} automatically updates events and signals that
transitively depend on the updated primitive. The dependents of a
signal are updated iff the signal's value changed according to its
{{!sigeq}equality function}.
The update functions have an optional [step] argument. If they are
given a concrete [step] value created with {!Step.create}, then it
updates the event or signal but doesn't update its dependencies. It
will only do so whenever [step] is executed with
{!Step.execute}. This allows to make primitive event occurences and
signal changes simultaneous. See next section for an example.
{2:simultaneity Simultaneous events}
{{!steps}Update steps} are made under a
{{:-6423(92)90005-V}synchrony hypothesis} :
the update step takes no time, it is instantenous. Two event occurrences
are {e simultaneous} if they occur in the same update step.
In the code below [w], [x] and [y] will always have simultaneous
occurrences. They {e may} have simulatenous occurences with [z]
if [send_w] and [send_z] are used with the same update step.
{[let w, send_w = E.create ()
let x = E.map succ w
let y = E.map succ x
let z, send_z = E.create ()
let () =
let step = Step.create () in
send_w ~step 3;
send_z ~step 4;
]}
{2:update The update step and thread safety}
{{!primitives}Primitives} are the only mean to drive the reactive
system and they are entirely under the control of the client. When
the client invokes a primitive's update function without the
[step] argument or when it invokes {!Step.execute} on a [step]
value, React performs an update step.
To ensure correctness in the presence of threads, update steps
must be executed in a critical section. Let uset([p]) be the set
of events and signals that need to be updated whenever the
primitive [p] is updated. Updating two primitives [p] and [p']
concurrently is only allowed if uset([p]) and uset([p']) are
disjoint. Otherwise the updates must be properly serialized.
Below, concurrent, updates to [x] and [y] must be serialized (or
performed on the same step if it makes sense semantically), but z
can be updated concurently to both [x] and [y].
{[open React;;
let x, set_x = S.create 0
let y, send_y = E.create ()
let z, set_z = S.create 0
let max_xy = S.l2 (fun x y -> if x > y then x else y) x (S.hold 0 y)
let succ_z = S.map succ z]}
{2:sideeffects Side effects}
Effectful events and signals perform their side effect
exactly {e once} in each {{!steps}update step} in which there
is an update of at least one of the event or signal it depends on.
Remember that a signal updates in a step iff its
{{!sigeq}equality function} determined that the signal
value changed. Signal initialization is unconditionally considered as
an update.
It is important to keep references on effectful events and
signals. Otherwise they may be reclaimed by the garbage collector.
The following program prints only a [1].
{[let x, set_x = S.create 1
let () = ignore (S.map print_int x)
let () = Gc.full_major (); List.iter set_x [2; 2; 3]]}
{2:lifting Lifting}
Lifting transforms a regular function to make it act on signals.
The combinators
{!S.const} and {!S.app} allow to lift functions of arbitrary arity n,
but this involves the inefficient creation of n-1 intermediary
closure signals. The fixed arity {{!S.lifting}lifting
functions} are more efficient. For example :
{[let f x y = x mod y
]}
Besides, some of [Pervasives]'s functions and operators are
already lifted and availables in submodules of {!S}. They can be
be opened in specific scopes. For example if you are dealing with
float signals you can open {!S.Float}.
{[open React
open React.S.Float
...
]}
If you are using OCaml 3.12 or later you can also use the [let open]
construct
{[let open React.S.Float in
...
]}
{2:recursion Mutual and self reference}
Mutual and self reference among time varying values occurs naturally
in programs. However a mutually recursive definition of two signals
in which both need the value of the other at time t to define
their value at time t has no least fixed point. To break this
tight loop one signal must depend on the value the other had at time
t-dt where dt is an infinitesimal delay.
The fixed point combinators {!E.fix} and {!S.fix} allow to refer to
the value an event or signal had an infinitesimal amount of time
before. These fixed point combinators act on a function [f] that takes
as argument the infinitesimally delayed event or signal that [f]
itself returns.
In the example below [history s] returns a signal whose value
is the history of [s] as a list.
{[let history ?(eq = ( = )) s =
let push v = function
| [] -> [ v ]
| v' :: _ as l when eq v v' -> l
| l -> v :: l
in
let define h =
let h' = S.l2 push s h in
h', h'
in
S.fix [] define]}
When a program has infinitesimally delayed values a
{{!primitives}primitive} may trigger more than one update
step. For example if a signal [s] is infinitesimally delayed, then
its update in a step [c] will trigger a new step [c'] at the end
of the step in which the delayed signal of [s] will have the value
[s] had in [c]. This means that the recursion occuring between a
signal (or event) and its infinitesimally delayed counterpart must
be well-founded otherwise this may trigger an infinite number
of update steps, like in the following examples.
{[let start, send_start = E.create ()
let diverge =
let define e =
let e' = E.select [e; start] in
e', e'
in
E.fix define
let define s =
let s' = S.Int.succ s in
s', s'
in
S.fix 0 define]}
For technical reasons, delayed events and signals (those given to
fixing functions) are not allowed to directly depend on each
other. Fixed point combinators will raise [Invalid_argument] if
such dependencies are created. This limitation can be
circumvented by mapping these values with the identity.
{2:strongstop Strong stops}
Strong stops should only be used on platforms where weak arrays have
a strong semantics (i.e. JavaScript). You can safely ignore that
section and the [strong] argument of {!E.stop} and {!S.stop}
if that's not the case.
Whenever {!E.stop} and {!S.stop} is called with [~strong:true] on a
reactive value [v], it is first stopped and then it walks over the
list [prods] of events and signals that it depends on and
unregisters itself from these ones as a dependent (something that is
normally automatically done when [v] is garbage collected since
dependents are stored in a weak array). Then for each element of
[prod] that has no dependents anymore and is not a primitive it
stops them aswell and recursively.
A stop call with [~strong:true] is more involved. But it allows to
prevent memory leaks when used judiciously on the leaves of the
reactive system that are no longer used.
{b Warning.} It should be noted that if direct references are kept
on an intermediate event or signal of the reactive system it may
suddenly stop updating if all its dependents were strongly stopped. In
the example below, [e1] will {e never} occur:
{[let e, e_send = E.create ()
let () =
let e2 = E.map (fun x -> x + 1) e1 in
E.stop ~strong:true e2
]}
This can be side stepped by making an artificial dependency to keep
the reference:
{[let e, e_send = E.create ()
let e1_ref = E.map (fun x -> x) e1
let () =
let e2 = E.map (fun x -> x + 1) e1 in
E.stop ~strong:true e2
]}
{1:ex Examples}
{2:clock Clock}
The following program defines a primitive event [seconds] holding
the UNIX time and occuring on every second. An effectful event
converts these occurences to local time and prints them on stdout
along with an
{{:-international.org/publications/standards/Ecma-048.htm}ANSI
escape sequence} to control the cursor position.
{[let pr_time t =
let tm = Unix.localtime t in
Printf.printf "\x1B[8D%02d:%02d:%02d%!"
tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec
open React;;
let seconds, run =
let e, send = E.create () in
let run () =
while true do send (Unix.gettimeofday ()); Unix.sleep 1 done
in
e, run
let printer = E.map pr_time seconds
let () = run ()]}
*)
---------------------------------------------------------------------------
Copyright ( c ) 2009
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2009 Daniel C. Bünzli
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
|
a786bb3e9459c834e173242face5ed704a681604e7306066e726e288f458874e | rnewman/clj-sip | processing.clj | (ns com.twinql.clojure.sip.processing
(:refer-clojure)
(:use com.twinql.clojure.sip.responses)
(:import
(java.lang Exception)
(javax.servlet ServletException ServletInputStream)
(javax.servlet.sip
SipApplicationSession
SipServlet
SipServletMessage
SipServletRequest
SipServletResponse)))
;; SIP accessors.
(defn application-session-state [#^SipApplicationSession app-session]
(.getAttribute app-session "state"))
(defn set-application-session-state! [#^SipApplicationSession app-session, state]
(.setAttribute app-session "state" state))
(defn message-method [#^SipServletMessage message]
(keyword (.toLowerCase (.getMethod message))))
;; SIP response code analysis.
(defn code->response [status]
(*sip-code-map* status))
(defn response->code [response]
(*sip-code-reverse-map* response))
(defn make-class-state-method-dispatcher
"Dispatches on the servlet class, the current state, and the message method."
[default-state]
(fn [servlet app-session message]
[(class servlet)
(or
(application-session-state app-session)
(do
(set-application-session-state! app-session default-state)
default-state))
(message-method message)]))
(defn make-class-state-code-method-dispatcher
[default-state]
(fn [servlet app-session code message]
[(class servlet)
(or
(application-session-state app-session)
(do
(set-application-session-state! app-session default-state)
default-state))
(code->response code)
(message-method message)]))
(defmacro defservlet
"Your defservlet form must be in compiled code."
([name request-method-name response-method-name]
`(defservlet ~name ~request-method-name ~response-method-name {}))
([name request-method-name response-method-name gen-class-options]
`(do
(gen-class
:name ~name
:extends SipServlet
;; Inline the keyword arguments.
~@(mapcat identity gen-class-options))
(let [response-fn#
(fn [this#, #^SipServletResponse res#]
(~response-method-name this#
(.getApplicationSession res#)
(.getStatus res#)
res#))]
(defn ~'-doRequest [this#, #^SipServletRequest req#]
(~request-method-name this#
(.getApplicationSession req#)
req#))
(def ~'-doProvisionalResponse response-fn#)
(def ~'-doSuccessResponse response-fn#)
(def ~'-doRedirectResponse response-fn#)
(def ~'-doErrorResponse response-fn#)))))
| null | https://raw.githubusercontent.com/rnewman/clj-sip/0e883c13c0b4a978f0655d163b249ae61081ded7/src/com/twinql/clojure/sip/processing.clj | clojure | SIP accessors.
SIP response code analysis.
Inline the keyword arguments. | (ns com.twinql.clojure.sip.processing
(:refer-clojure)
(:use com.twinql.clojure.sip.responses)
(:import
(java.lang Exception)
(javax.servlet ServletException ServletInputStream)
(javax.servlet.sip
SipApplicationSession
SipServlet
SipServletMessage
SipServletRequest
SipServletResponse)))
(defn application-session-state [#^SipApplicationSession app-session]
(.getAttribute app-session "state"))
(defn set-application-session-state! [#^SipApplicationSession app-session, state]
(.setAttribute app-session "state" state))
(defn message-method [#^SipServletMessage message]
(keyword (.toLowerCase (.getMethod message))))
(defn code->response [status]
(*sip-code-map* status))
(defn response->code [response]
(*sip-code-reverse-map* response))
(defn make-class-state-method-dispatcher
"Dispatches on the servlet class, the current state, and the message method."
[default-state]
(fn [servlet app-session message]
[(class servlet)
(or
(application-session-state app-session)
(do
(set-application-session-state! app-session default-state)
default-state))
(message-method message)]))
(defn make-class-state-code-method-dispatcher
[default-state]
(fn [servlet app-session code message]
[(class servlet)
(or
(application-session-state app-session)
(do
(set-application-session-state! app-session default-state)
default-state))
(code->response code)
(message-method message)]))
(defmacro defservlet
"Your defservlet form must be in compiled code."
([name request-method-name response-method-name]
`(defservlet ~name ~request-method-name ~response-method-name {}))
([name request-method-name response-method-name gen-class-options]
`(do
(gen-class
:name ~name
:extends SipServlet
~@(mapcat identity gen-class-options))
(let [response-fn#
(fn [this#, #^SipServletResponse res#]
(~response-method-name this#
(.getApplicationSession res#)
(.getStatus res#)
res#))]
(defn ~'-doRequest [this#, #^SipServletRequest req#]
(~request-method-name this#
(.getApplicationSession req#)
req#))
(def ~'-doProvisionalResponse response-fn#)
(def ~'-doSuccessResponse response-fn#)
(def ~'-doRedirectResponse response-fn#)
(def ~'-doErrorResponse response-fn#)))))
|
4cd898d0a954ba5a98c82dc82229cebf3d9fa72cc0c1d68aa93e8daadb464436 | Haskell-Things/ImplicitCAD | Benchmark.hs | {- ORMOLU_DISABLE -}
Implicit CAD . Copyright ( C ) 2011 , ( )
Copyright ( C ) 2014 2015 2016 , ( )
-- Released under the GNU AGPLV3+, see LICENSE
-- Our benchmarking suite.
-- Let's be explicit about where things come from :)
import Prelude (pure, ($), (*), (/), String, IO, cos, pi, fmap, zip3, Either(Left, Right), fromIntegral, (<>), (<$>))
-- Use criterion for benchmarking. see </>
import Criterion.Main (Benchmark, bgroup, bench, nf, nfAppIO, defaultMain)
The parts of ImplicitCAD we know how to benchmark .
import Graphics.Implicit (union, circle, sphere, SymbolicObj2, SymbolicObj3, ExtrudeMScale(C1), writeDXF2, writeSVG, writePNG2, writeSTL, writeBinSTL, unionR, translate, difference, extrudeM, rect3, withRounding)
import Graphics.Implicit.Definitions (defaultObjectContext)
import Graphics.Implicit.Export.SymbolicObj2 (symbolicGetContour)
import Graphics.Implicit.Export.SymbolicObj3 (symbolicGetMesh)
-- The variables defining distance and counting in our world.
import Graphics.Implicit.Definitions (ℝ, Fastℕ)
-- Vectors.
import Linear(V2(V2), V3(V3))
-- Haskell representations of objects to benchmark.
-- FIXME: move each of these objects into seperate compilable files.
-- | What we extrude in the example on the website.
obj2d_1 :: SymbolicObj2
obj2d_1 =
unionR 8
[ circle 10
, translate (V2 22 0) $ circle 10
, translate (V2 0 22) $ circle 10
, translate (V2 (-22) 0) $ circle 10
, translate (V2 0 (-22)) $ circle 10
]
| An extruded version of obj2d_1 , should be identical to the website 's example , and example5.escad .
object1 :: SymbolicObj3
object1 = extrudeM (Right twist) (C1 1) (Left (V2 0 0)) obj2d_1 (Left 40)
where
twist :: ℝ -> ℝ
twist h = 35*cos(h*2*pi/60)
-- | another 3D object, for benchmarking.
object2 :: SymbolicObj3
object2 = squarePipe (10,10,10) 1 100
where
squarePipe :: (ℝ,ℝ,ℝ) -> ℝ -> ℝ -> SymbolicObj3
squarePipe (x,y,z) diameter precision =
union
((\(a, b, c)-> translate (V3 a b c)
$ rect3 (pure 0) (pure diameter)
)
<$>
zip3 (fmap (\n->(fromIntegral n/precision)*x) [0..100::Fastℕ])
(fmap (\n->(fromIntegral n/precision)*y) [0..100::Fastℕ])
(fmap (\n->(fromIntegral n/precision)*z) [0..100::Fastℕ]))
| A third 3d object to benchmark .
object3 :: SymbolicObj3
object3 =
withRounding 1 $ difference (rect3 (pure (-1)) (pure 1)) [ rect3 (pure 0) (pure 2)]
| Example 13 - the rounded union of a cube and a sphere .
object4 :: SymbolicObj3
object4 = union [
rect3 (pure 0) (pure 20),
translate (pure 20) (sphere 15) ]
-- | Benchmark a 2D object.
obj2Benchmarks :: String -> String -> SymbolicObj2 -> Benchmark
obj2Benchmarks name filename obj =
bgroup name
[
bench "SVG write" $ nfAppIO (writeSVG 1 $ filename <> ".svg") obj,
bench "PNG write" $ nfAppIO (writePNG2 1 $ filename <> ".png") obj,
bench "DXF write" $ nfAppIO (writeDXF2 1 $ filename <> ".dxf") obj,
bench "Get contour" $ nf (symbolicGetContour 1 defaultObjectContext) obj
]
-- | Benchmark a 3D object.
obj3Benchmarks :: String -> String -> SymbolicObj3 -> Benchmark
obj3Benchmarks name filename obj =
bgroup name
[
bench " PNG write " $ writePNG3 1 " benchmark.png " obj
bench "STLTEXT write" $ nfAppIO (writeSTL 1 $ filename <> ".stl.text") obj,
bench "STL write" $ nfAppIO (writeBinSTL 1 $ filename <> ".stl") obj,
bench "Get mesh" $ nf (symbolicGetMesh 1) obj
]
-- | Benchmark all of our objects.
benchmarks :: [Benchmark]
benchmarks =
[ obj3Benchmarks "Object 1" "example5" object1
, obj3Benchmarks "Object 2" "object2" object2
, obj3Benchmarks "Object 3" "object3" object3
, obj3Benchmarks "Object 4" "object4" object4
, obj2Benchmarks "Object 2d 1" "example18" obj2d_1
]
-- | Our entrypoint. Runs all benchmarks.
main :: IO ()
main = defaultMain benchmarks
| null | https://raw.githubusercontent.com/Haskell-Things/ImplicitCAD/87f2aee4b3c958d11e988022f512d065b812f6b0/programs/Benchmark.hs | haskell | ORMOLU_DISABLE
Released under the GNU AGPLV3+, see LICENSE
Our benchmarking suite.
Let's be explicit about where things come from :)
Use criterion for benchmarking. see </>
The variables defining distance and counting in our world.
Vectors.
Haskell representations of objects to benchmark.
FIXME: move each of these objects into seperate compilable files.
| What we extrude in the example on the website.
| another 3D object, for benchmarking.
| Benchmark a 2D object.
| Benchmark a 3D object.
| Benchmark all of our objects.
| Our entrypoint. Runs all benchmarks. | Implicit CAD . Copyright ( C ) 2011 , ( )
Copyright ( C ) 2014 2015 2016 , ( )
import Prelude (pure, ($), (*), (/), String, IO, cos, pi, fmap, zip3, Either(Left, Right), fromIntegral, (<>), (<$>))
import Criterion.Main (Benchmark, bgroup, bench, nf, nfAppIO, defaultMain)
The parts of ImplicitCAD we know how to benchmark .
import Graphics.Implicit (union, circle, sphere, SymbolicObj2, SymbolicObj3, ExtrudeMScale(C1), writeDXF2, writeSVG, writePNG2, writeSTL, writeBinSTL, unionR, translate, difference, extrudeM, rect3, withRounding)
import Graphics.Implicit.Definitions (defaultObjectContext)
import Graphics.Implicit.Export.SymbolicObj2 (symbolicGetContour)
import Graphics.Implicit.Export.SymbolicObj3 (symbolicGetMesh)
import Graphics.Implicit.Definitions (ℝ, Fastℕ)
import Linear(V2(V2), V3(V3))
obj2d_1 :: SymbolicObj2
obj2d_1 =
unionR 8
[ circle 10
, translate (V2 22 0) $ circle 10
, translate (V2 0 22) $ circle 10
, translate (V2 (-22) 0) $ circle 10
, translate (V2 0 (-22)) $ circle 10
]
| An extruded version of obj2d_1 , should be identical to the website 's example , and example5.escad .
object1 :: SymbolicObj3
object1 = extrudeM (Right twist) (C1 1) (Left (V2 0 0)) obj2d_1 (Left 40)
where
twist :: ℝ -> ℝ
twist h = 35*cos(h*2*pi/60)
object2 :: SymbolicObj3
object2 = squarePipe (10,10,10) 1 100
where
squarePipe :: (ℝ,ℝ,ℝ) -> ℝ -> ℝ -> SymbolicObj3
squarePipe (x,y,z) diameter precision =
union
((\(a, b, c)-> translate (V3 a b c)
$ rect3 (pure 0) (pure diameter)
)
<$>
zip3 (fmap (\n->(fromIntegral n/precision)*x) [0..100::Fastℕ])
(fmap (\n->(fromIntegral n/precision)*y) [0..100::Fastℕ])
(fmap (\n->(fromIntegral n/precision)*z) [0..100::Fastℕ]))
| A third 3d object to benchmark .
object3 :: SymbolicObj3
object3 =
withRounding 1 $ difference (rect3 (pure (-1)) (pure 1)) [ rect3 (pure 0) (pure 2)]
| Example 13 - the rounded union of a cube and a sphere .
object4 :: SymbolicObj3
object4 = union [
rect3 (pure 0) (pure 20),
translate (pure 20) (sphere 15) ]
obj2Benchmarks :: String -> String -> SymbolicObj2 -> Benchmark
obj2Benchmarks name filename obj =
bgroup name
[
bench "SVG write" $ nfAppIO (writeSVG 1 $ filename <> ".svg") obj,
bench "PNG write" $ nfAppIO (writePNG2 1 $ filename <> ".png") obj,
bench "DXF write" $ nfAppIO (writeDXF2 1 $ filename <> ".dxf") obj,
bench "Get contour" $ nf (symbolicGetContour 1 defaultObjectContext) obj
]
obj3Benchmarks :: String -> String -> SymbolicObj3 -> Benchmark
obj3Benchmarks name filename obj =
bgroup name
[
bench " PNG write " $ writePNG3 1 " benchmark.png " obj
bench "STLTEXT write" $ nfAppIO (writeSTL 1 $ filename <> ".stl.text") obj,
bench "STL write" $ nfAppIO (writeBinSTL 1 $ filename <> ".stl") obj,
bench "Get mesh" $ nf (symbolicGetMesh 1) obj
]
benchmarks :: [Benchmark]
benchmarks =
[ obj3Benchmarks "Object 1" "example5" object1
, obj3Benchmarks "Object 2" "object2" object2
, obj3Benchmarks "Object 3" "object3" object3
, obj3Benchmarks "Object 4" "object4" object4
, obj2Benchmarks "Object 2d 1" "example18" obj2d_1
]
main :: IO ()
main = defaultMain benchmarks
|
cafa568840c3db6bcc7405139452f76bcacd6cff446e0978ddd0628f52f221ed | janestreet/base | map.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Apache 2.0 license . See .. /THIRD - PARTY.txt
(* for details. *)
(* *)
(***********************************************************************)
open! Import
module List = List0
include Map_intf
module Finished_or_unfinished = struct
include Map_intf.Finished_or_unfinished
These two functions are tested in [ test_map.ml ] to make sure our use of
[ Stdlib.Obj.magic ] is correct and safe .
[Stdlib.Obj.magic] is correct and safe. *)
let of_continue_or_stop : Continue_or_stop.t -> t = Stdlib.Obj.magic
let to_continue_or_stop : t -> Continue_or_stop.t = Stdlib.Obj.magic
end
module Merge_element = struct
include Map_intf.Merge_element
let left = function
| `Right _ -> None
| `Left left | `Both (left, _) -> Some left
;;
let right = function
| `Left _ -> None
| `Right right | `Both (_, right) -> Some right
;;
let left_value t ~default =
match t with
| `Right _ -> default
| `Left left | `Both (left, _) -> left
;;
let right_value t ~default =
match t with
| `Left _ -> default
| `Right right | `Both (_, right) -> right
;;
let values t ~left_default ~right_default =
match t with
| `Left left -> left, right_default
| `Right right -> left_default, right
| `Both (left, right) -> left, right
;;
end
let with_return = With_return.with_return
exception Duplicate [@@deriving_inline sexp]
let () =
Sexplib0.Sexp_conv.Exn_converter.add [%extension_constructor Duplicate] (function
| Duplicate -> Sexplib0.Sexp.Atom "map.ml.Duplicate"
| _ -> assert false)
;;
[@@@end]
(* [With_length.t] allows us to store length information on the stack while
keeping the tree global. This saves up to O(log n) blocks of heap allocation. *)
module With_length : sig
type 'a t = private
{ tree : 'a
[@global]
; length : int [@global]
}
val with_length : 'a -> int -> ('a t[@local])
val with_length_global : 'a -> int -> 'a t
val globalize : ('a t[@local]) -> 'a t
end = struct
type 'a t =
{ tree : 'a [@global]
; length : int [@global]
}
let with_length tree length = { tree; length }
let with_length_global tree length = { tree; length }
let globalize ({ tree; length } [@local]) = { tree; length }
end
open With_length
module Tree0 = struct
type ('k, 'v) t =
| Empty
| Leaf of 'k * 'v
| Node of ('k, 'v) t * 'k * 'v * ('k, 'v) t * int
type ('k, 'v) tree = ('k, 'v) t
let height = function
| Empty -> 0
| Leaf _ -> 1
| Node (_, _, _, _, h) -> h
;;
let invariants =
let in_range lower upper compare_key k =
(match lower with
| None -> true
| Some lower -> compare_key lower k < 0)
&&
match upper with
| None -> true
| Some upper -> compare_key k upper < 0
in
let rec loop lower upper compare_key t =
match t with
| Empty -> true
| Leaf (k, _) -> in_range lower upper compare_key k
| Node (l, k, _, r, h) ->
let hl = height l
and hr = height r in
abs (hl - hr) <= 2
&& h = max hl hr + 1
&& in_range lower upper compare_key k
&& loop lower (Some k) compare_key l
&& loop (Some k) upper compare_key r
in
fun t ~compare_key -> loop None None compare_key t
;;
precondition : |height(l ) - height(r)| < = 2
let create l x d r =
let hl = height l
and hr = height r in
if hl = 0 && hr = 0
then Leaf (x, d)
else Node (l, x, d, r, if hl >= hr then hl + 1 else hr + 1)
;;
let singleton key data = Leaf (key, data)
(* We must call [f] with increasing indexes, because the bin_prot reader in
Core.Map needs it. *)
let of_increasing_iterator_unchecked ~len ~f =
let rec loop n ~f i : (_, _) t =
match n with
| 0 -> Empty
| 1 ->
let k, v = f i in
Leaf (k, v)
| 2 ->
let kl, vl = f i in
let k, v = f (i + 1) in
Node (Leaf (kl, vl), k, v, Empty, 2)
| 3 ->
let kl, vl = f i in
let k, v = f (i + 1) in
let kr, vr = f (i + 2) in
Node (Leaf (kl, vl), k, v, Leaf (kr, vr), 2)
| n ->
let left_length = n lsr 1 in
let right_length = n - left_length - 1 in
let left = loop left_length ~f i in
let k, v = f (i + left_length) in
let right = loop right_length ~f (i + left_length + 1) in
create left k v right
in
loop len ~f 0
;;
let of_sorted_array_unchecked array ~compare_key =
let array_length = Array.length array in
let next =
if array_length < 2
||
let k0, _ = array.(0) in
let k1, _ = array.(1) in
compare_key k0 k1 < 0
then fun i -> array.(i)
else fun i -> array.(array_length - 1 - i)
in
(with_length
(of_increasing_iterator_unchecked ~len:array_length ~f:next)
array_length)
;;
let of_sorted_array array ~compare_key =
match array with
| [||] | [| _ |] ->
Result.Ok (of_sorted_array_unchecked array ~compare_key |> globalize)
| _ ->
with_return (fun r ->
let increasing =
match compare_key (fst array.(0)) (fst array.(1)) with
| 0 -> r.return (Or_error.error_string "of_sorted_array: duplicated elements")
| i -> i < 0
in
for i = 1 to Array.length array - 2 do
match compare_key (fst array.(i)) (fst array.(i + 1)) with
| 0 -> r.return (Or_error.error_string "of_sorted_array: duplicated elements")
| i ->
if Poly.( <> ) (i < 0) increasing
then
r.return
(Or_error.error_string "of_sorted_array: elements are not ordered")
done;
Result.Ok (of_sorted_array_unchecked array ~compare_key |> globalize))
;;
precondition : |height(l ) - height(r)| < = 3
let bal l x d r =
let hl = height l in
let hr = height r in
if hl > hr + 2
then (
match l with
| Empty -> invalid_arg "Map.bal"
| Leaf _ -> assert false (* height(Leaf) = 1 && 1 is not larger than hr + 2 *)
| Node (ll, lv, ld, lr, _) ->
if height ll >= height lr
then create ll lv ld (create lr x d r)
else (
match lr with
| Empty -> invalid_arg "Map.bal"
| Leaf (lrv, lrd) -> create (create ll lv ld Empty) lrv lrd (create Empty x d r)
| Node (lrl, lrv, lrd, lrr, _) ->
create (create ll lv ld lrl) lrv lrd (create lrr x d r)))
else if hr > hl + 2
then (
match r with
| Empty -> invalid_arg "Map.bal"
| Leaf _ -> assert false (* height(Leaf) = 1 && 1 is not larger than hl + 2 *)
| Node (rl, rv, rd, rr, _) ->
if height rr >= height rl
then create (create l x d rl) rv rd rr
else (
match rl with
| Empty -> invalid_arg "Map.bal"
| Leaf (rlv, rld) -> create (create l x d Empty) rlv rld (create Empty rv rd rr)
| Node (rll, rlv, rld, rlr, _) ->
create (create l x d rll) rlv rld (create rlr rv rd rr)))
else create l x d r
;;
let empty = Empty
let is_empty = function
| Empty -> true
| _ -> false
;;
let raise_key_already_present ~key ~sexp_of_key =
Error.raise_s
(Sexp.message "[Map.add_exn] got key already present" [ "key", key |> sexp_of_key ])
;;
module Add_or_set = struct
type t =
| Add_exn_internal
| Add_exn
| Set
end
let rec find_and_add_or_set
t
~length
~key:x
~data
~compare_key
~sexp_of_key
~(add_or_set : Add_or_set.t)
=
match t with
| Empty -> (with_length (Leaf (x, data)) (length + 1))
| Leaf (v, d) ->
let c = compare_key x v in
if c = 0
then (
match add_or_set with
| Add_exn_internal -> (Exn.raise_without_backtrace Duplicate)
| Add_exn -> (raise_key_already_present ~key:x ~sexp_of_key)
| Set -> (with_length (Leaf (x, data)) length))
else if c < 0
then (with_length (Node (Leaf (x, data), v, d, Empty, 2)) (length + 1))
else (with_length (Node (Empty, v, d, Leaf (x, data), 2)) (length + 1))
| Node (l, v, d, r, h) ->
let c = compare_key x v in
if c = 0
then (
match add_or_set with
| Add_exn_internal -> (Exn.raise_without_backtrace Duplicate)
| Add_exn -> (raise_key_already_present ~key:x ~sexp_of_key)
| Set -> (with_length (Node (l, x, data, r, h)) length))
else if c < 0
then (
let { tree = l; length } =
find_and_add_or_set ~length ~key:x ~data l ~compare_key ~sexp_of_key ~add_or_set
in
(with_length (bal l v d r) length))
else (
let { tree = r; length } =
find_and_add_or_set ~length ~key:x ~data r ~compare_key ~sexp_of_key ~add_or_set
in
(with_length (bal l v d r) length))
;;
(* specialization of [set'] for the case when [key] is less than all the existing keys *)
let rec set_min key data t =
match t with
| Empty -> Leaf (key, data)
| Leaf (v, d) -> Node (Leaf (key, data), v, d, Empty, 2)
| Node (l, v, d, r, _) ->
let l = set_min key data l in
bal l v d r
;;
(* specialization of [set'] for the case when [key] is greater than all the
existing keys *)
let rec set_max t key data =
match t with
| Empty -> Leaf (key, data)
| Leaf (v, d) -> Node (Empty, v, d, Leaf (key, data), 2)
| Node (l, v, d, r, _) ->
let r = set_max r key data in
bal l v d r
;;
let add_exn t ~length ~key ~data ~compare_key ~sexp_of_key =
(find_and_add_or_set
t
~length
~key
~data
~compare_key
~sexp_of_key
~add_or_set:Add_exn)
;;
let add_exn_internal t ~length ~key ~data ~compare_key ~sexp_of_key =
(find_and_add_or_set
t
~length
~key
~data
~compare_key
~sexp_of_key
~add_or_set:Add_exn_internal)
;;
let set t ~length ~key ~data ~compare_key =
(find_and_add_or_set
t
~length
~key
~data
~compare_key
~sexp_of_key:(fun _ -> List [])
~add_or_set:Set)
;;
let set' t key data ~compare_key = (set t ~length:0 ~key ~data ~compare_key).tree
module Build_increasing = struct
module Fragment = struct
type nonrec ('k, 'v) t =
{ left_subtree : ('k, 'v) t
; key : 'k
; data : 'v
}
let singleton_to_tree_exn = function
| { left_subtree = Empty; key; data } -> singleton key data
| _ -> failwith "Map.singleton_to_tree_exn: not a singleton"
;;
let singleton ~key ~data = { left_subtree = Empty; key; data }
precondition : |height(l.left_subtree ) - height(r)| < = 2 ,
max_key(l ) < min_key(r )
max_key(l) < min_key(r)
*)
let collapse l r = create l.left_subtree l.key l.data r
precondition : |height(l.left_subtree ) - height(r.left_subtree)| < = 2 ,
max_key(l ) < min_key(r )
max_key(l) < min_key(r)
*)
let join l r = { r with left_subtree = collapse l r.left_subtree }
let max_key t = t.key
end
* Build trees from singletons in a balanced way by using skew binary encoding .
Each level contains trees of the same height , consecutive levels have consecutive
heights . There are no gaps . The first level are single keys .
Each level contains trees of the same height, consecutive levels have consecutive
heights. There are no gaps. The first level are single keys.
*)
type ('k, 'v) t =
| Zero of unit
(* [unit] to make pattern matching faster *)
| One of ('k, 'v) t * ('k, 'v) Fragment.t
| Two of ('k, 'v) t * ('k, 'v) Fragment.t * ('k, 'v) Fragment.t
let empty = Zero ()
let add_unchecked =
let rec go t x =
match t with
| Zero () -> One (t, x)
| One (t, y) -> Two (t, y, x)
| Two (t, z, y) -> One (go t (Fragment.join z y), x)
in
fun t ~key ~data -> go t (Fragment.singleton ~key ~data)
;;
let to_tree_unchecked =
let rec go t r =
match t with
| Zero () -> r
| One (t, l) -> go t (Fragment.collapse l r)
| Two (t, ll, l) -> go t (Fragment.collapse (Fragment.join ll l) r)
in
function
| Zero () -> Empty
| One (t, r) -> go t (Fragment.singleton_to_tree_exn r)
| Two (t, l, r) -> go (One (t, l)) (Fragment.singleton_to_tree_exn r)
;;
let max_key = function
| Zero () -> None
| One (_, r) | Two (_, _, r) -> Some (Fragment.max_key r)
;;
end
let of_increasing_sequence seq ~compare_key =
with_return (fun { return } ->
let { tree = builder; length } =
Sequence.fold
seq
~init:(with_length_global Build_increasing.empty 0)
~f:(fun { tree = builder; length } (key, data) ->
match Build_increasing.max_key builder with
| Some prev_key when compare_key prev_key key >= 0 ->
return
(Or_error.error_string "of_increasing_sequence: non-increasing key")
| _ ->
with_length_global
(Build_increasing.add_unchecked builder ~key ~data)
(length + 1))
in
Ok (with_length_global (Build_increasing.to_tree_unchecked builder) length))
;;
(* Like [bal] but allows any difference in height between [l] and [r].
O(|height l - height r|) *)
let rec join l k d r =
match l, r with
| Empty, _ -> set_min k d r
| _, Empty -> set_max l k d
| Leaf (lk, ld), _ -> set_min lk ld (set_min k d r)
| _, Leaf (rk, rd) -> set_max (set_max l k d) rk rd
| Node (ll, lk, ld, lr, lh), Node (rl, rk, rd, rr, rh) ->
[ bal ] requires height difference < = 3 .
if lh > rh + 3
[ height lr > = height r ] ,
therefore [ height ( join lr k d r ... ) ] is [ height rl + 1 ] or [ height rl ]
therefore the height difference with [ ll ] will be < = 3
therefore [height (join lr k d r ...)] is [height rl + 1] or [height rl]
therefore the height difference with [ll] will be <= 3 *)
then bal ll lk ld (join lr k d r)
else if rh > lh + 3
then bal (join l k d rl) rk rd rr
else bal l k d r
;;
let[@inline] rec split_gen t x ~compare_key =
match t with
| Empty -> Empty, None, Empty
| Leaf (k, d) ->
let cmp = compare_key k in
if cmp = 0
then Empty, Some (k, d), Empty
else if cmp < 0
then Empty, None, t
else t, None, Empty
| Node (l, k, d, r, _) ->
let cmp = compare_key k in
if cmp = 0
then l, Some (k, d), r
else if cmp < 0
then (
let ll, maybe, lr = split_gen l x ~compare_key in
ll, maybe, join lr k d r)
else (
let rl, maybe, rr = split_gen r x ~compare_key in
join l k d rl, maybe, rr)
;;
let split t x ~compare_key = split_gen t x ~compare_key:(fun y -> compare_key x y)
This function does not really reinsert [ x ] , but just arranges so that [ split ]
produces the equivalent tree in the first place .
produces the equivalent tree in the first place. *)
let split_and_reinsert_boundary t ~into x ~compare_key =
let left, boundary_opt, right =
split_gen
t
x
~compare_key:
(match into with
| `Left ->
fun y ->
(match compare_key x y with
| 0 -> 1
| res -> res)
| `Right ->
fun y ->
(match compare_key x y with
| 0 -> -1
| res -> res))
in
assert (Option.is_none boundary_opt);
left, right
;;
let split_range
t
~(lower_bound : 'a Maybe_bound.t)
~(upper_bound : 'a Maybe_bound.t)
~compare_key
=
if Maybe_bound.bounds_crossed
~compare:compare_key
~lower:lower_bound
~upper:upper_bound
then empty, empty, empty
else (
let left, mid_and_right =
match lower_bound with
| Unbounded -> empty, t
| Incl lb -> split_and_reinsert_boundary ~into:`Right t lb ~compare_key
| Excl lb -> split_and_reinsert_boundary ~into:`Left t lb ~compare_key
in
let mid, right =
match upper_bound with
| Unbounded -> mid_and_right, empty
| Incl lb -> split_and_reinsert_boundary ~into:`Left mid_and_right lb ~compare_key
| Excl lb ->
split_and_reinsert_boundary ~into:`Right mid_and_right lb ~compare_key
in
left, mid, right)
;;
let rec find t x ~compare_key =
match t with
| Empty -> None
| Leaf (v, d) -> if compare_key x v = 0 then Some d else None
| Node (l, v, d, r, _) ->
let c = compare_key x v in
if c = 0 then Some d else find (if c < 0 then l else r) x ~compare_key
;;
let add_multi t ~length ~key ~data ~compare_key =
let data = data :: Option.value (find t key ~compare_key) ~default:[] in
(set ~length ~key ~data t ~compare_key)
;;
let find_multi t x ~compare_key =
match find t x ~compare_key with
| None -> []
| Some l -> l
;;
let find_exn =
let if_not_found key ~sexp_of_key =
raise (Not_found_s (List [ Atom "Map.find_exn: not found"; sexp_of_key key ]))
in
let rec find_exn t x ~compare_key ~sexp_of_key =
match t with
| Empty -> if_not_found x ~sexp_of_key
| Leaf (v, d) -> if compare_key x v = 0 then d else if_not_found x ~sexp_of_key
| Node (l, v, d, r, _) ->
let c = compare_key x v in
if c = 0 then d else find_exn (if c < 0 then l else r) x ~compare_key ~sexp_of_key
in
(* named to preserve symbol in compiled binary *)
find_exn
;;
let mem t x ~compare_key = Option.is_some (find t x ~compare_key)
let rec min_elt = function
| Empty -> None
| Leaf (k, d) -> Some (k, d)
| Node (Empty, k, d, _, _) -> Some (k, d)
| Node (l, _, _, _, _) -> min_elt l
;;
exception Map_min_elt_exn_of_empty_map [@@deriving_inline sexp]
let () =
Sexplib0.Sexp_conv.Exn_converter.add
[%extension_constructor Map_min_elt_exn_of_empty_map]
(function
| Map_min_elt_exn_of_empty_map ->
Sexplib0.Sexp.Atom "map.ml.Tree0.Map_min_elt_exn_of_empty_map"
| _ -> assert false)
;;
[@@@end]
exception Map_max_elt_exn_of_empty_map [@@deriving_inline sexp]
let () =
Sexplib0.Sexp_conv.Exn_converter.add
[%extension_constructor Map_max_elt_exn_of_empty_map]
(function
| Map_max_elt_exn_of_empty_map ->
Sexplib0.Sexp.Atom "map.ml.Tree0.Map_max_elt_exn_of_empty_map"
| _ -> assert false)
;;
[@@@end]
let min_elt_exn t =
match min_elt t with
| None -> raise Map_min_elt_exn_of_empty_map
| Some v -> v
;;
let rec max_elt = function
| Empty -> None
| Leaf (k, d) -> Some (k, d)
| Node (_, k, d, Empty, _) -> Some (k, d)
| Node (_, _, _, r, _) -> max_elt r
;;
let max_elt_exn t =
match max_elt t with
| None -> raise Map_max_elt_exn_of_empty_map
| Some v -> v
;;
let rec remove_min_elt t =
match t with
| Empty -> invalid_arg "Map.remove_min_elt"
| Leaf _ -> Empty
| Node (Empty, _, _, r, _) -> r
| Node (l, x, d, r, _) -> bal (remove_min_elt l) x d r
;;
let append ~lower_part ~upper_part ~compare_key =
match max_elt lower_part, min_elt upper_part with
| None, _ -> `Ok upper_part
| _, None -> `Ok lower_part
| Some (max_lower, _), Some (min_upper, v) when compare_key max_lower min_upper < 0 ->
let upper_part_without_min = remove_min_elt upper_part in
`Ok (join lower_part min_upper v upper_part_without_min)
| _ -> `Overlapping_key_ranges
;;
let fold_range_inclusive =
(* This assumes that min <= max, which is checked by the outer function. *)
let rec go t ~min ~max ~init ~f ~compare_key =
match t with
| Empty -> init
| Leaf (k, d) ->
if compare_key k min < 0 || compare_key k max > 0
then (* k < min || k > max *)
init
else f ~key:k ~data:d init
| Node (l, k, d, r, _) ->
let c_min = compare_key k min in
if c_min < 0
then
(* if k < min, then this node and its left branch are outside our range *)
go r ~min ~max ~init ~f ~compare_key
else if c_min = 0
then
(* if k = min, then this node's left branch is outside our range *)
go r ~min ~max ~init:(f ~key:k ~data:d init) ~f ~compare_key
else (
(* k > min *)
let z = go l ~min ~max ~init ~f ~compare_key in
let c_max = compare_key k max in
(* if k > max, we're done *)
if c_max > 0
then z
else (
let z = f ~key:k ~data:d z in
if k = max , then we fold in this one last value and we 're done
if c_max = 0 then z else go r ~min ~max ~init:z ~f ~compare_key))
in
fun t ~min ~max ~init ~f ~compare_key ->
if compare_key min max <= 0 then go t ~min ~max ~init ~f ~compare_key else init
;;
let range_to_alist t ~min ~max ~compare_key =
List.rev
(fold_range_inclusive
t
~min
~max
~init:[]
~f:(fun ~key ~data l -> (key, data) :: l)
~compare_key)
;;
preconditions :
- all elements in t1 are less than elements in t2
- |height(t1 ) - height(t2)| < = 2
- all elements in t1 are less than elements in t2
- |height(t1) - height(t2)| <= 2 *)
let concat_unchecked t1 t2 =
match t1, t2 with
| Empty, t -> t
| t, Empty -> t
| _, _ ->
let x, d = min_elt_exn t2 in
bal t1 x d (remove_min_elt t2)
;;
(* similar to [concat_unchecked], and balances trees of arbitrary height differences *)
let concat_and_balance_unchecked t1 t2 =
match t1, t2 with
| Empty, t -> t
| t, Empty -> t
| _, _ ->
let x, d = min_elt_exn t2 in
join t1 x d (remove_min_elt t2)
;;
exception Remove_no_op
let remove t x ~length ~compare_key =
let rec remove_loop t x ~length ~compare_key =
match t with
| Empty -> (Exn.raise_without_backtrace Remove_no_op)
| Leaf (v, _) ->
if compare_key x v = 0
then (with_length Empty (length - 1))
else (Exn.raise_without_backtrace Remove_no_op)
| Node (l, v, d, r, _) ->
let c = compare_key x v in
if c = 0
then (with_length (concat_unchecked l r) (length - 1))
else if c < 0
then (
let { tree = l; length } = remove_loop l x ~length ~compare_key in
(with_length (bal l v d r) length))
else (
let { tree = r; length } = remove_loop r x ~length ~compare_key in
(with_length (bal l v d r) length))
in
try (remove_loop t x ~length ~compare_key) with
| Remove_no_op -> (with_length t length)
;;
(* Use exception to avoid tree-rebuild in no-op case *)
exception Change_no_op
let change t key ~f ~length ~compare_key =
let rec change_core t key f =
match t with
| Empty ->
(match f None with
| None ->
(* equivalent to returning: Empty *)
(Exn.raise_without_backtrace Change_no_op)
| Some data -> (with_length (Leaf (key, data)) (length + 1)))
| Leaf (v, d) ->
let c = compare_key key v in
if c = 0
then (
match f (Some d) with
| None -> (with_length Empty (length - 1))
| Some d' -> (with_length (Leaf (v, d')) length))
else if c < 0
then (
let { tree = l; length } = change_core Empty key f in
(with_length (bal l v d Empty) length))
else (
let { tree = r; length } = change_core Empty key f in
(with_length (bal Empty v d r) length))
| Node (l, v, d, r, h) ->
let c = compare_key key v in
if c = 0
then (
match f (Some d) with
| None -> (with_length (concat_unchecked l r) (length - 1))
| Some data -> (with_length (Node (l, key, data, r, h)) length))
else if c < 0
then (
let { tree = l; length } = change_core l key f in
(with_length (bal l v d r) length))
else (
let { tree = r; length } = change_core r key f in
(with_length (bal l v d r) length))
in
try (change_core t key f) with
| Change_no_op -> (with_length t length)
;;
let update t key ~f ~length ~compare_key =
let rec update_core t key f =
match t with
| Empty ->
let data = f None in
(with_length (Leaf (key, data)) (length + 1))
| Leaf (v, d) ->
let c = compare_key key v in
if c = 0
then (
let d' = f (Some d) in
(with_length (Leaf (v, d')) length))
else if c < 0
then (
let { tree = l; length } = update_core Empty key f in
(with_length (bal l v d Empty) length))
else (
let { tree = r; length } = update_core Empty key f in
(with_length (bal Empty v d r) length))
| Node (l, v, d, r, h) ->
let c = compare_key key v in
if c = 0
then (
let data = f (Some d) in
(with_length (Node (l, key, data, r, h)) length))
else if c < 0
then (
let { tree = l; length } = update_core l key f in
(with_length (bal l v d r) length))
else (
let { tree = r; length } = update_core r key f in
(with_length (bal l v d r) length))
in
(update_core t key f)
;;
let remove_multi t key ~length ~compare_key =
(change t key ~length ~compare_key ~f:(function
| None | Some ([] | [ _ ]) -> None
| Some (_ :: (_ :: _ as non_empty_tail)) -> Some non_empty_tail))
;;
let rec iter_keys t ~f =
match t with
| Empty -> ()
| Leaf (v, _) -> f v
| Node (l, v, _, r, _) ->
iter_keys ~f l;
f v;
iter_keys ~f r
;;
let rec iter t ~f =
match t with
| Empty -> ()
| Leaf (_, d) -> f d
| Node (l, _, d, r, _) ->
iter ~f l;
f d;
iter ~f r
;;
let rec iteri t ~f =
match t with
| Empty -> ()
| Leaf (v, d) -> f ~key:v ~data:d
| Node (l, v, d, r, _) ->
iteri ~f l;
f ~key:v ~data:d;
iteri ~f r
;;
let iteri_until =
let rec iteri_until_loop t ~f : Continue_or_stop.t =
match t with
| Empty -> Continue
| Leaf (v, d) -> f ~key:v ~data:d
| Node (l, v, d, r, _) ->
(match iteri_until_loop ~f l with
| Stop -> Stop
| Continue ->
(match f ~key:v ~data:d with
| Stop -> Stop
| Continue -> iteri_until_loop ~f r))
in
fun t ~f -> Finished_or_unfinished.of_continue_or_stop (iteri_until_loop t ~f)
;;
let rec map t ~f =
match t with
| Empty -> Empty
| Leaf (v, d) -> Leaf (v, f d)
| Node (l, v, d, r, h) ->
let l' = map ~f l in
let d' = f d in
let r' = map ~f r in
Node (l', v, d', r', h)
;;
let rec mapi t ~f =
match t with
| Empty -> Empty
| Leaf (v, d) -> Leaf (v, f ~key:v ~data:d)
| Node (l, v, d, r, h) ->
let l' = mapi ~f l in
let d' = f ~key:v ~data:d in
let r' = mapi ~f r in
Node (l', v, d', r', h)
;;
let rec fold t ~init:accu ~f =
match t with
| Empty -> accu
| Leaf (v, d) -> f ~key:v ~data:d accu
| Node (l, v, d, r, _) -> fold ~f r ~init:(f ~key:v ~data:d (fold ~f l ~init:accu))
;;
let fold_until t ~init ~f ~finish =
let rec fold_until_loop t ~acc ~f : (_, _) Container.Continue_or_stop.t =
match t with
| Empty -> Continue acc
| Leaf (v, d) -> f ~key:v ~data:d acc
| Node (l, v, d, r, _) ->
(match fold_until_loop l ~acc ~f with
| Stop final -> Stop final
| Continue acc ->
(match f ~key:v ~data:d acc with
| Stop final -> Stop final
| Continue acc -> fold_until_loop r ~acc ~f))
in
match fold_until_loop t ~acc:init ~f with
| Continue acc -> finish acc [@nontail]
| Stop stop -> stop
;;
let rec fold_right t ~init:accu ~f =
match t with
| Empty -> accu
| Leaf (v, d) -> f ~key:v ~data:d accu
| Node (l, v, d, r, _) ->
fold_right ~f l ~init:(f ~key:v ~data:d (fold_right ~f r ~init:accu))
;;
let rec filter_mapi t ~f ~len =
match t with
| Empty -> Empty
| Leaf (v, d) ->
(match f ~key:v ~data:d with
| Some new_data -> Leaf (v, new_data)
| None ->
decr len;
Empty)
| Node (l, v, d, r, _) ->
let l' = filter_mapi l ~f ~len in
let new_data = f ~key:v ~data:d in
let r' = filter_mapi r ~f ~len in
(match new_data with
| Some new_data -> join l' v new_data r'
| None ->
decr len;
concat_and_balance_unchecked l' r')
;;
let rec filteri t ~f ~len =
match t with
| Empty -> Empty
| Leaf (v, d) ->
(match f ~key:v ~data:d with
| true -> t
| false ->
decr len;
Empty)
| Node (l, v, d, r, _) ->
let l' = filteri l ~f ~len in
let keep_data = f ~key:v ~data:d in
let r' = filteri r ~f ~len in
if phys_equal l l' && keep_data && phys_equal r r'
then t
else (
match keep_data with
| true -> join l' v d r'
| false ->
decr len;
concat_and_balance_unchecked l' r')
;;
let filter t ~f ~len = filteri t ~len ~f:(fun ~key:_ ~data -> f data) [@nontail]
let filter_keys t ~f ~len = filteri t ~len ~f:(fun ~key ~data:_ -> f key) [@nontail]
let filter_map t ~f ~len = filter_mapi t ~len ~f:(fun ~key:_ ~data -> f data) [@nontail]
let partition_mapi t ~f =
let t1, t2 =
fold
t
~init:(Build_increasing.empty, Build_increasing.empty)
~f:(fun ~key ~data (t1, t2) ->
match (f ~key ~data : _ Either.t) with
| First x -> Build_increasing.add_unchecked t1 ~key ~data:x, t2
| Second y -> t1, Build_increasing.add_unchecked t2 ~key ~data:y)
in
Build_increasing.to_tree_unchecked t1, Build_increasing.to_tree_unchecked t2
;;
let partition_map t ~f = partition_mapi t ~f:(fun ~key:_ ~data -> f data) [@nontail]
let partitioni_tf t ~f =
let rec loop t ~f =
match t with
| Empty -> Empty, Empty
| Leaf (v, d) ->
(match f ~key:v ~data:d with
| true -> t, Empty
| false -> Empty, t)
| Node (l, v, d, r, _) ->
let l't, l'f = loop l ~f in
let keep_data_t = f ~key:v ~data:d in
let r't, r'f = loop r ~f in
let mk l' keep_data r' =
if phys_equal l l' && keep_data && phys_equal r r'
then t
else (
match keep_data with
| true -> join l' v d r'
| false -> concat_and_balance_unchecked l' r')
in
mk l't keep_data_t r't, mk l'f (not keep_data_t) r'f
in
loop t ~f
;;
let partition_tf t ~f = partitioni_tf t ~f:(fun ~key:_ ~data -> f data) [@nontail]
module Enum = struct
type increasing
type decreasing
type ('k, 'v, 'direction) t =
| End
| More of 'k * 'v * ('k, 'v) tree * ('k, 'v, 'direction) t
let rec cons t (e : (_, _, increasing) t) : (_, _, increasing) t =
match t with
| Empty -> e
| Leaf (v, d) -> More (v, d, Empty, e)
| Node (l, v, d, r, _) -> cons l (More (v, d, r, e))
;;
let rec cons_right t (e : (_, _, decreasing) t) : (_, _, decreasing) t =
match t with
| Empty -> e
| Leaf (v, d) -> More (v, d, Empty, e)
| Node (l, v, d, r, _) -> cons_right r (More (v, d, l, e))
;;
let of_tree tree : (_, _, increasing) t = cons tree End
let of_tree_right tree : (_, _, decreasing) t = cons_right tree End
let starting_at_increasing t key compare : (_, _, increasing) t =
let rec loop t e =
match t with
| Empty -> e
| Leaf (v, d) -> loop (Node (Empty, v, d, Empty, 1)) e
| Node (_, v, _, r, _) when compare v key < 0 -> loop r e
| Node (l, v, d, r, _) -> loop l (More (v, d, r, e))
in
loop t End
;;
let starting_at_decreasing t key compare : (_, _, decreasing) t =
let rec loop t e =
match t with
| Empty -> e
| Leaf (v, d) -> loop (Node (Empty, v, d, Empty, 1)) e
| Node (l, v, _, _, _) when compare v key > 0 -> loop l e
| Node (l, v, d, r, _) -> loop r (More (v, d, l, e))
in
loop t End
;;
let step_deeper_exn tree e =
match tree with
| Empty -> assert false
| Leaf (v, d) -> Empty, More (v, d, Empty, e)
| Node (l, v, d, r, _) -> l, More (v, d, r, e)
;;
[ drop_phys_equal_prefix tree1 acc1 tree2 acc2 ] drops the largest physically - equal
prefix of and tree2 that they share , and then prepends the remaining data
into acc1 and acc2 , respectively .
This can be asymptotically faster than [ cons ] even if it skips a small proportion
of the tree because [ cons ] is always O(log(n ) ) in the size of the tree , while
this function is O(log(n / m ) ) where [ m ] is the size of the part of the tree that
is skipped .
prefix of tree1 and tree2 that they share, and then prepends the remaining data
into acc1 and acc2, respectively.
This can be asymptotically faster than [cons] even if it skips a small proportion
of the tree because [cons] is always O(log(n)) in the size of the tree, while
this function is O(log(n/m)) where [m] is the size of the part of the tree that
is skipped. *)
let rec drop_phys_equal_prefix tree1 acc1 tree2 acc2 =
if phys_equal tree1 tree2
then acc1, acc2
else (
let h2 = height tree2 in
let h1 = height tree1 in
if h2 = h1
then (
let tree1, acc1 = step_deeper_exn tree1 acc1 in
let tree2, acc2 = step_deeper_exn tree2 acc2 in
drop_phys_equal_prefix tree1 acc1 tree2 acc2)
else if h2 > h1
then (
let tree2, acc2 = step_deeper_exn tree2 acc2 in
drop_phys_equal_prefix tree1 acc1 tree2 acc2)
else (
let tree1, acc1 = step_deeper_exn tree1 acc1 in
drop_phys_equal_prefix tree1 acc1 tree2 acc2))
;;
let compare compare_key compare_data t1 t2 =
let rec loop t1 t2 =
match t1, t2 with
| End, End -> 0
| End, _ -> -1
| _, End -> 1
| More (v1, d1, r1, e1), More (v2, d2, r2, e2) ->
let c = compare_key v1 v2 in
if c <> 0
then c
else (
let c = compare_data d1 d2 in
if c <> 0
then c
else (
let e1, e2 = drop_phys_equal_prefix r1 e1 r2 e2 in
loop e1 e2))
in
loop t1 t2
;;
let equal compare_key data_equal t1 t2 =
let rec loop t1 t2 =
match t1, t2 with
| End, End -> true
| End, _ | _, End -> false
| More (v1, d1, r1, e1), More (v2, d2, r2, e2) ->
compare_key v1 v2 = 0
&& data_equal d1 d2
&&
let e1, e2 = drop_phys_equal_prefix r1 e1 r2 e2 in
loop e1 e2
in
loop t1 t2
;;
let rec fold ~init ~f = function
| End -> init
| More (key, data, tree, enum) ->
let next = f ~key ~data init in
fold (cons tree enum) ~init:next ~f
;;
let fold2 compare_key t1 t2 ~init ~f =
let rec loop t1 t2 curr =
match t1, t2 with
| End, End -> curr
| End, _ ->
fold t2 ~init:curr ~f:(fun ~key ~data acc -> f ~key ~data:(`Right data) acc) [@nontail
]
| _, End ->
fold t1 ~init:curr ~f:(fun ~key ~data acc -> f ~key ~data:(`Left data) acc) [@nontail
]
| More (k1, v1, tree1, enum1), More (k2, v2, tree2, enum2) ->
let compare_result = compare_key k1 k2 in
if compare_result = 0
then (
let next = f ~key:k1 ~data:(`Both (v1, v2)) curr in
loop (cons tree1 enum1) (cons tree2 enum2) next)
else if compare_result < 0
then (
let next = f ~key:k1 ~data:(`Left v1) curr in
loop (cons tree1 enum1) t2 next)
else (
let next = f ~key:k2 ~data:(`Right v2) curr in
loop t1 (cons tree2 enum2) next)
in
loop t1 t2 init [@nontail]
;;
let symmetric_diff t1 t2 ~compare_key ~data_equal =
let step state =
match state with
| End, End -> Sequence.Step.Done
| End, More (key, data, tree, enum) ->
Sequence.Step.Yield { value = key, `Right data; state = End, cons tree enum }
| More (key, data, tree, enum), End ->
Sequence.Step.Yield { value = key, `Left data; state = cons tree enum, End }
| (More (k1, v1, tree1, enum1) as left), (More (k2, v2, tree2, enum2) as right) ->
let compare_result = compare_key k1 k2 in
if compare_result = 0
then (
let next_state = drop_phys_equal_prefix tree1 enum1 tree2 enum2 in
if data_equal v1 v2
then Sequence.Step.Skip { state = next_state }
else Sequence.Step.Yield { value = k1, `Unequal (v1, v2); state = next_state })
else if compare_result < 0
then
Sequence.Step.Yield { value = k1, `Left v1; state = cons tree1 enum1, right }
else
Sequence.Step.Yield { value = k2, `Right v2; state = left, cons tree2 enum2 }
in
Sequence.unfold_step ~init:(drop_phys_equal_prefix t1 End t2 End) ~f:step
;;
let fold_symmetric_diff t1 t2 ~compare_key ~data_equal ~init ~f =
let add acc k v = f acc (k, `Right v) in
let remove acc k v = f acc (k, `Left v) in
let rec loop left right acc =
match left, right with
| End, enum ->
fold enum ~init:acc ~f:(fun ~key ~data acc -> add acc key data) [@nontail]
| enum, End ->
fold enum ~init:acc ~f:(fun ~key ~data acc -> remove acc key data) [@nontail]
| (More (k1, v1, tree1, enum1) as left), (More (k2, v2, tree2, enum2) as right) ->
let compare_result = compare_key k1 k2 in
if compare_result = 0
then (
let acc = if data_equal v1 v2 then acc else f acc (k1, `Unequal (v1, v2)) in
let enum1, enum2 = drop_phys_equal_prefix tree1 enum1 tree2 enum2 in
loop enum1 enum2 acc)
else if compare_result < 0
then (
let acc = remove acc k1 v1 in
loop (cons tree1 enum1) right acc)
else (
let acc = add acc k2 v2 in
loop left (cons tree2 enum2) acc)
in
let left, right = drop_phys_equal_prefix t1 End t2 End in
loop left right init [@nontail]
;;
end
let to_sequence_increasing comparator ~from_key t =
let next enum =
match enum with
| Enum.End -> Sequence.Step.Done
| Enum.More (k, v, t, e) ->
Sequence.Step.Yield { value = k, v; state = Enum.cons t e }
in
let init =
match from_key with
| None -> Enum.of_tree t
| Some key -> Enum.starting_at_increasing t key comparator.Comparator.compare
in
Sequence.unfold_step ~init ~f:next
;;
let to_sequence_decreasing comparator ~from_key t =
let next enum =
match enum with
| Enum.End -> Sequence.Step.Done
| Enum.More (k, v, t, e) ->
Sequence.Step.Yield { value = k, v; state = Enum.cons_right t e }
in
let init =
match from_key with
| None -> Enum.of_tree_right t
| Some key -> Enum.starting_at_decreasing t key comparator.Comparator.compare
in
Sequence.unfold_step ~init ~f:next
;;
let to_sequence
comparator
?(order = `Increasing_key)
?keys_greater_or_equal_to
?keys_less_or_equal_to
t
=
let inclusive_bound side t bound =
let compare_key = comparator.Comparator.compare in
let l, maybe, r = split t bound ~compare_key in
let t = side (l, r) in
match maybe with
| None -> t
| Some (key, data) -> set' t key data ~compare_key
in
match order with
| `Increasing_key ->
let t = Option.fold keys_less_or_equal_to ~init:t ~f:(inclusive_bound fst) in
to_sequence_increasing comparator ~from_key:keys_greater_or_equal_to t
| `Decreasing_key ->
let t = Option.fold keys_greater_or_equal_to ~init:t ~f:(inclusive_bound snd) in
to_sequence_decreasing comparator ~from_key:keys_less_or_equal_to t
;;
let compare compare_key compare_data t1 t2 =
let e1, e2 = Enum.drop_phys_equal_prefix t1 End t2 End in
Enum.compare compare_key compare_data e1 e2
;;
let equal compare_key compare_data t1 t2 =
let e1, e2 = Enum.drop_phys_equal_prefix t1 End t2 End in
Enum.equal compare_key compare_data e1 e2
;;
let iter2 t1 t2 ~f ~compare_key =
Enum.fold2
compare_key
(Enum.of_tree t1)
(Enum.of_tree t2)
~init:()
~f:(fun ~key ~data () -> f ~key ~data) [@nontail]
;;
let fold2 t1 t2 ~init ~f ~compare_key =
Enum.fold2 compare_key (Enum.of_tree t1) (Enum.of_tree t2) ~f ~init
;;
let symmetric_diff = Enum.symmetric_diff
let fold_symmetric_diff t1 t2 ~compare_key ~data_equal ~init ~f =
(* [Enum.fold_diffs] is a correct implementation of this function, but is considerably
slower, as we have to allocate quite a lot of state to track enumeration of a tree.
Avoid if we can.
*)
let slow x y ~init = Enum.fold_symmetric_diff x y ~compare_key ~data_equal ~f ~init in
let add acc k v = f acc (k, `Right v) in
let remove acc k v = f acc (k, `Left v) in
let delta acc k v v' = if data_equal v v' then acc else f acc (k, `Unequal (v, v')) in
If two trees have the same structure at the root ( and the same key , if they 're
[ ) we can trivially diff each subpart in obvious ways .
[Node]s) we can trivially diff each subpart in obvious ways. *)
let rec loop t t' acc =
if phys_equal t t'
then acc
else (
match t, t' with
| Empty, new_vals ->
fold new_vals ~init:acc ~f:(fun ~key ~data acc -> add acc key data) [@nontail]
| old_vals, Empty ->
fold old_vals ~init:acc ~f:(fun ~key ~data acc -> remove acc key data) [@nontail]
| Leaf (k, v), Leaf (k', v') ->
(match compare_key k k' with
| x when x = 0 -> delta acc k v v'
| x when x < 0 ->
let acc = remove acc k v in
add acc k' v'
| _ (* when x > 0 *) ->
let acc = add acc k' v' in
remove acc k v)
| Node (l, k, v, r, _), Node (l', k', v', r', _) when compare_key k k' = 0 ->
let acc = loop l l' acc in
let acc = delta acc k v v' in
loop r r' acc
(* Our roots aren't the same key. Fallback to the slow mode. Trees with small
diffs will only do this on very small parts of the tree (hopefully - if the
overall root is rebalanced, we'll eat the whole cost, unfortunately.) *)
| Node _, Node _ | Node _, Leaf _ | Leaf _, Node _ -> slow t t' ~init:acc)
in
loop t1 t2 init [@nontail]
;;
let rec length = function
| Empty -> 0
| Leaf _ -> 1
| Node (l, _, _, r, _) -> length l + length r + 1
;;
let hash_fold_t_ignoring_structure hash_fold_key hash_fold_data state t =
fold
t
~init:(hash_fold_int state (length t))
~f:(fun ~key ~data state -> hash_fold_data (hash_fold_key state key) data)
;;
let keys t = fold_right ~f:(fun ~key ~data:_ list -> key :: list) t ~init:[]
let data t = fold_right ~f:(fun ~key:_ ~data list -> data :: list) t ~init:[]
module type Foldable = sig
val name : string
type 'a t
val fold : 'a t -> init:'acc -> f:(('acc -> 'a -> 'acc)[@local]) -> 'acc
end
let[@inline always] of_foldable' ~fold foldable ~init ~f ~compare_key =
(fold [@inlined hint])
foldable
~init:(with_length_global empty 0)
~f:(fun { tree = accum; length } (key, data) ->
let prev_data =
match find accum key ~compare_key with
| None -> init
| Some prev -> prev
in
let data = f prev_data data in
(set accum ~length ~key ~data ~compare_key |> globalize) [@nontail]) [@nontail]
;;
module Of_foldable (M : Foldable) = struct
let of_foldable_fold foldable ~init ~f ~compare_key =
of_foldable' ~fold:M.fold foldable ~init ~f ~compare_key
;;
let of_foldable_reduce foldable ~f ~compare_key =
M.fold
foldable
~init:(with_length_global empty 0)
~f:(fun { tree = accum; length } (key, data) ->
let new_data =
match find accum key ~compare_key with
| None -> data
| Some prev -> f prev data
in
(set accum ~length ~key ~data:new_data ~compare_key |> globalize) [@nontail]) [@nontail
]
;;
let of_foldable foldable ~compare_key =
with_return (fun r ->
let map =
M.fold
foldable
~init:(with_length_global empty 0)
~f:(fun { tree = t; length } (key, data) ->
let ({ tree = _; length = length' } as acc) =
set ~length ~key ~data t ~compare_key
in
if length = length'
then r.return (`Duplicate_key key)
else globalize acc [@nontail])
in
`Ok map)
;;
let of_foldable_or_error foldable ~comparator =
match of_foldable foldable ~compare_key:comparator.Comparator.compare with
| `Ok x -> Result.Ok x
| `Duplicate_key key ->
Or_error.error
("Map.of_" ^ M.name ^ "_or_error: duplicate key")
key
comparator.sexp_of_t
;;
let of_foldable_exn foldable ~comparator =
match of_foldable foldable ~compare_key:comparator.Comparator.compare with
| `Ok x -> x
| `Duplicate_key key ->
Error.create ("Map.of_" ^ M.name ^ "_exn: duplicate key") key comparator.sexp_of_t
|> Error.raise
;;
Reverse the input , then fold from left to right . The resulting map uses the first
instance of each key from the input list . The relative ordering of elements in each
output list is the same as in the input list .
instance of each key from the input list. The relative ordering of elements in each
output list is the same as in the input list. *)
let of_foldable_multi foldable ~compare_key =
let alist = M.fold foldable ~init:[] ~f:(fun l x -> x :: l) in
of_foldable' alist ~fold:List.fold ~init:[] ~f:(fun l x -> x :: l) ~compare_key
;;
end
module Of_alist = Of_foldable (struct
let name = "alist"
type 'a t = 'a list
let fold = List.fold
end)
let of_alist_fold = Of_alist.of_foldable_fold
let of_alist_reduce = Of_alist.of_foldable_reduce
let of_alist = Of_alist.of_foldable
let of_alist_or_error = Of_alist.of_foldable_or_error
let of_alist_exn = Of_alist.of_foldable_exn
let of_alist_multi = Of_alist.of_foldable_multi
module Of_sequence = Of_foldable (struct
let name = "sequence"
type 'a t = 'a Sequence.t
let fold = Sequence.fold
end)
let of_sequence_fold = Of_sequence.of_foldable_fold
let of_sequence_reduce = Of_sequence.of_foldable_reduce
let of_sequence = Of_sequence.of_foldable
let of_sequence_or_error = Of_sequence.of_foldable_or_error
let of_sequence_exn = Of_sequence.of_foldable_exn
let of_sequence_multi = Of_sequence.of_foldable_multi
let of_list_with_key list ~get_key ~compare_key =
with_return (fun r ->
let map =
List.fold
list
~init:(with_length_global empty 0)
~f:(fun { tree = t; length } data ->
let key = get_key data in
let ({ tree = _; length = new_length } as acc) =
set ~length ~key ~data t ~compare_key
in
if length = new_length
then r.return (`Duplicate_key key)
else globalize acc [@nontail])
in
`Ok map) [@nontail]
;;
let of_list_with_key_or_error list ~get_key ~comparator =
match of_list_with_key list ~get_key ~compare_key:comparator.Comparator.compare with
| `Ok x -> Result.Ok x
| `Duplicate_key key ->
Or_error.error
"Map.of_list_with_key_or_error: duplicate key"
key
comparator.sexp_of_t
;;
let of_list_with_key_exn list ~get_key ~comparator =
match of_list_with_key list ~get_key ~compare_key:comparator.Comparator.compare with
| `Ok x -> x
| `Duplicate_key key ->
Error.create "Map.of_list_with_key_exn: duplicate key" key comparator.sexp_of_t
|> Error.raise
;;
let of_list_with_key_multi list ~get_key ~compare_key =
let list = List.rev list in
List.fold list ~init:(with_length_global empty 0) ~f:(fun { tree = t; length } data ->
let key = get_key data in
(update t key ~length ~compare_key ~f:(fun option ->
let list = Option.value option ~default:[] in
data :: list)
|> globalize) [@nontail]) [@nontail]
;;
let for_all t ~f =
with_return (fun r ->
iter t ~f:(fun data -> if not (f data) then r.return false);
true) [@nontail]
;;
let for_alli t ~f =
with_return (fun r ->
iteri t ~f:(fun ~key ~data -> if not (f ~key ~data) then r.return false);
true) [@nontail]
;;
let exists t ~f =
with_return (fun r ->
iter t ~f:(fun data -> if f data then r.return true);
false) [@nontail]
;;
let existsi t ~f =
with_return (fun r ->
iteri t ~f:(fun ~key ~data -> if f ~key ~data then r.return true);
false) [@nontail]
;;
let count t ~f =
fold t ~init:0 ~f:(fun ~key:_ ~data acc -> if f data then acc + 1 else acc) [@nontail]
;;
let counti t ~f =
fold t ~init:0 ~f:(fun ~key ~data acc -> if f ~key ~data then acc + 1 else acc) [@nontail
]
;;
let to_alist ?(key_order = `Increasing) t =
match key_order with
| `Increasing -> fold_right t ~init:[] ~f:(fun ~key ~data x -> (key, data) :: x)
| `Decreasing -> fold t ~init:[] ~f:(fun ~key ~data x -> (key, data) :: x)
;;
let merge t1 t2 ~f ~compare_key =
let elts = Uniform_array.unsafe_create_uninitialized ~len:(length t1 + length t2) in
let i = ref 0 in
iter2 t1 t2 ~compare_key ~f:(fun ~key ~data:values ->
match f ~key values with
| Some value ->
Uniform_array.set elts !i (key, value);
incr i
| None -> ());
let len = !i in
let get i = Uniform_array.get elts i in
let tree = of_increasing_iterator_unchecked ~len ~f:get in
(with_length tree len)
;;
let merge_skewed =
let merge_large_first length_large t_large t_small ~call ~combine ~compare_key =
fold
t_small
~init:(with_length_global t_large length_large)
~f:(fun ~key ~data:data' { tree = t; length } ->
(update t key ~length ~compare_key ~f:(function
| None -> data'
| Some data -> call combine ~key data data')
|> globalize) [@nontail]) [@nontail]
in
let call f ~key x y = f ~key x y in
let swap f ~key x y = f ~key y x in
fun t1 t2 ~length1 ~length2 ~combine ~compare_key ->
if length2 <= length1
then merge_large_first length1 t1 t2 ~call ~combine ~compare_key
else merge_large_first length2 t2 t1 ~call:swap ~combine ~compare_key
;;
module Closest_key_impl = struct
(* [marker] and [repackage] allow us to create "logical" options without actually
allocating any options. Passing [Found key value] to a function is equivalent to
passing [Some (key, value)]; passing [Missing () ()] is equivalent to passing
[None]. *)
type ('k, 'v, 'k_opt, 'v_opt) marker =
| Missing : ('k, 'v, unit, unit) marker
| Found : ('k, 'v, 'k, 'v) marker
let repackage
(type k v k_opt v_opt)
(marker : (k, v, k_opt, v_opt) marker)
(k : k_opt)
(v : v_opt)
: (k * v) option
=
match marker with
| Missing -> None
| Found -> Some (k, v)
;;
(* The type signature is explicit here to allow polymorphic recursion. *)
let rec loop :
'k 'v 'k_opt 'v_opt.
('k, 'v) tree
-> [ `Greater_or_equal_to | `Greater_than | `Less_or_equal_to | `Less_than ]
-> 'k
-> compare_key:('k -> 'k -> int)
-> ('k, 'v, 'k_opt, 'v_opt) marker
-> 'k_opt
-> 'v_opt
-> ('k * 'v) option
=
fun t dir k ~compare_key found_marker found_key found_value ->
match t with
| Empty -> repackage found_marker found_key found_value
| Leaf (k', v') ->
let c = compare_key k' k in
if match dir with
| `Greater_or_equal_to -> c >= 0
| `Greater_than -> c > 0
| `Less_or_equal_to -> c <= 0
| `Less_than -> c < 0
then Some (k', v')
else repackage found_marker found_key found_value
| Node (l, k', v', r, _) ->
let c = compare_key k' k in
if c = 0
then (
(* This is a base case (no recursive call). *)
match dir with
| `Greater_or_equal_to | `Less_or_equal_to -> Some (k', v')
| `Greater_than ->
if is_empty r then repackage found_marker found_key found_value else min_elt r
| `Less_than ->
if is_empty l then repackage found_marker found_key found_value else max_elt l)
else (
(* We are guaranteed here that k' <> k. *)
(* This is the only recursive case. *)
match dir with
| `Greater_or_equal_to | `Greater_than ->
if c > 0
then loop l dir k ~compare_key Found k' v'
else loop r dir k ~compare_key found_marker found_key found_value
| `Less_or_equal_to | `Less_than ->
if c < 0
then loop r dir k ~compare_key Found k' v'
else loop l dir k ~compare_key found_marker found_key found_value)
;;
let closest_key t dir k ~compare_key = loop t dir k ~compare_key Missing () ()
end
let closest_key = Closest_key_impl.closest_key
let rec rank t k ~compare_key =
match t with
| Empty -> None
| Leaf (k', _) -> if compare_key k' k = 0 then Some 0 else None
| Node (l, k', _, r, _) ->
let c = compare_key k' k in
if c = 0
then Some (length l)
else if c > 0
then rank l k ~compare_key
else Option.map (rank r k ~compare_key) ~f:(fun rank -> rank + 1 + length l)
;;
this could be implemented using [ Sequence ] interface but the following implementation
allocates only 2 words and does n't require write - barrier
allocates only 2 words and doesn't require write-barrier *)
let rec nth' num_to_search = function
| Empty -> None
| Leaf (k, v) ->
if !num_to_search = 0
then Some (k, v)
else (
decr num_to_search;
None)
| Node (l, k, v, r, _) ->
(match nth' num_to_search l with
| Some _ as some -> some
| None ->
if !num_to_search = 0
then Some (k, v)
else (
decr num_to_search;
nth' num_to_search r))
;;
let nth t n = nth' (ref n) t
let rec find_first_satisfying t ~f =
match t with
| Empty -> None
| Leaf (k, v) -> if f ~key:k ~data:v then Some (k, v) else None
| Node (l, k, v, r, _) ->
if f ~key:k ~data:v
then (
match find_first_satisfying l ~f with
| None -> Some (k, v)
| Some _ as x -> x)
else find_first_satisfying r ~f
;;
let rec find_last_satisfying t ~f =
match t with
| Empty -> None
| Leaf (k, v) -> if f ~key:k ~data:v then Some (k, v) else None
| Node (l, k, v, r, _) ->
if f ~key:k ~data:v
then (
match find_last_satisfying r ~f with
| None -> Some (k, v)
| Some _ as x -> x)
else find_last_satisfying l ~f
;;
let binary_search t ~compare how v =
match how with
| `Last_strictly_less_than ->
find_last_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v < 0) [@nontail]
| `Last_less_than_or_equal_to ->
find_last_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v <= 0) [@nontail]
| `First_equal_to ->
(match find_first_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v >= 0) with
| Some (key, data) as pair when compare ~key ~data v = 0 -> pair
| None | Some _ -> None)
| `Last_equal_to ->
(match find_last_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v <= 0) with
| Some (key, data) as pair when compare ~key ~data v = 0 -> pair
| None | Some _ -> None)
| `First_greater_than_or_equal_to ->
find_first_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v >= 0) [@nontail]
| `First_strictly_greater_than ->
find_first_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v > 0) [@nontail]
;;
let binary_search_segmented t ~segment_of how =
let is_left ~key ~data =
match segment_of ~key ~data with
| `Left -> true
| `Right -> false
in
let is_right ~key ~data = not (is_left ~key ~data) in
match how with
| `Last_on_left -> find_last_satisfying t ~f:is_left [@nontail]
| `First_on_right -> find_first_satisfying t ~f:is_right [@nontail]
;;
[ binary_search_one_sided_bound ] finds the key in [ t ] which satisfies [ maybe_bound ]
and the relevant one of [ if_exclusive ] or [ if_inclusive ] , as judged by [ compare ] .
and the relevant one of [if_exclusive] or [if_inclusive], as judged by [compare]. *)
let binary_search_one_sided_bound t maybe_bound ~compare ~if_exclusive ~if_inclusive =
let find_bound t how bound ~compare : _ Maybe_bound.t option =
match binary_search t how bound ~compare with
| Some (bound, _) -> Some (Incl bound)
| None -> None
in
match (maybe_bound : _ Maybe_bound.t) with
| Excl bound -> find_bound t if_exclusive bound ~compare
| Incl bound -> find_bound t if_inclusive bound ~compare
| Unbounded -> Some Unbounded
;;
(* [binary_search_two_sided_bounds] finds the (not necessarily distinct) keys in [t]
which most closely approach (but do not cross) [lower_bound] and [upper_bound], as
judged by [compare]. It returns [None] if no keys in [t] are within that range. *)
let binary_search_two_sided_bounds t ~compare ~lower_bound ~upper_bound =
let find_lower_bound t maybe_bound ~compare =
binary_search_one_sided_bound
t
maybe_bound
~compare
~if_exclusive:`First_strictly_greater_than
~if_inclusive:`First_greater_than_or_equal_to
in
let find_upper_bound t maybe_bound ~compare =
binary_search_one_sided_bound
t
maybe_bound
~compare
~if_exclusive:`Last_strictly_less_than
~if_inclusive:`Last_less_than_or_equal_to
in
match find_lower_bound t lower_bound ~compare with
| None -> None
| Some lower_bound ->
(match find_upper_bound t upper_bound ~compare with
| None -> None
| Some upper_bound -> Some (lower_bound, upper_bound))
;;
type ('k, 'v) acc =
{ mutable bad_key : 'k option
; mutable map_length : ('k, 'v) t With_length.t
}
let of_iteri ~iteri ~compare_key =
let acc = { bad_key = None; map_length = with_length_global empty 0 } in
iteri ~f:(fun ~key ~data ->
let { tree = map; length } = acc.map_length in
let ({ tree = _; length = length' } as pair) =
set ~length ~key ~data map ~compare_key
in
if length = length' && Option.is_none acc.bad_key
then acc.bad_key <- Some key
else acc.map_length <- globalize pair);
match acc.bad_key with
| None -> `Ok acc.map_length
| Some key -> `Duplicate_key key
;;
let of_iteri_exn ~iteri ~(comparator : _ Comparator.t) =
match of_iteri ~iteri ~compare_key:comparator.compare with
| `Ok v -> v
| `Duplicate_key key ->
Error.create "Map.of_iteri_exn: duplicate key" key comparator.sexp_of_t
|> Error.raise
;;
let t_of_sexp_direct key_of_sexp value_of_sexp sexp ~(comparator : _ Comparator.t) =
let alist = list_of_sexp (pair_of_sexp key_of_sexp value_of_sexp) sexp in
let compare_key = comparator.compare in
match of_alist alist ~compare_key with
| `Ok v -> v
| `Duplicate_key k ->
(* find the sexp of a duplicate key, so the error is narrowed to a key and not
the whole map *)
let alist_sexps = list_of_sexp (pair_of_sexp Fn.id Fn.id) sexp in
let found_first_k = ref false in
List.iter2_ok alist alist_sexps ~f:(fun (k2, _) (k2_sexp, _) ->
if compare_key k k2 = 0
then
if !found_first_k
then of_sexp_error "Map.t_of_sexp_direct: duplicate key" k2_sexp
else found_first_k := true);
assert false
;;
let sexp_of_t sexp_of_key sexp_of_value t =
let f ~key ~data acc = Sexp.List [ sexp_of_key key; sexp_of_value data ] :: acc in
Sexp.List (fold_right ~f t ~init:[])
;;
let combine_errors t ~sexp_of_key =
let oks, errors = partition_map t ~f:Result.to_either in
if is_empty errors
then Ok oks
else Or_error.error_s (sexp_of_t sexp_of_key Error.sexp_of_t errors)
;;
let map_keys
t1
~f
~comparator:({ compare = compare_key; sexp_of_t = sexp_of_key } : _ Comparator.t)
=
with_return (fun { return } ->
`Ok
(fold
t1
~init:(with_length_global empty 0)
~f:(fun ~key ~data { tree = t2; length } ->
let key = f key in
try
add_exn_internal t2 ~length ~key ~data ~compare_key ~sexp_of_key
|> globalize
with
| Duplicate -> return (`Duplicate_key key)))) [@nontail]
;;
let map_keys_exn t ~f ~comparator =
match map_keys t ~f ~comparator with
| `Ok result -> result
| `Duplicate_key key ->
let sexp_of_key = comparator.Comparator.sexp_of_t in
Error.raise_s
(Sexp.message "Map.map_keys_exn: duplicate key" [ "key", key |> sexp_of_key ])
;;
let transpose_keys ~outer_comparator ~inner_comparator outer_t =
fold
outer_t
~init:(with_length_global empty 0)
~f:(fun ~key:outer_key ~data:inner_t acc ->
fold
inner_t
~init:acc
~f:(fun ~key:inner_key ~data { tree = acc; length = acc_len } ->
(update
acc
inner_key
~length:acc_len
~compare_key:inner_comparator.Comparator.compare
~f:(function
| None -> with_length_global (singleton outer_key data) 1
| Some { tree = elt; length = elt_len } ->
(set
elt
~key:outer_key
~data
~length:elt_len
~compare_key:outer_comparator.Comparator.compare
|> globalize) [@nontail])
|> globalize) [@nontail]))
;;
module Make_applicative_traversals (A : Applicative.Lazy_applicative) = struct
let rec mapi t ~f =
match t with
| Empty -> A.return Empty
| Leaf (v, d) -> A.map (f ~key:v ~data:d) ~f:(fun new_data -> Leaf (v, new_data))
| Node (l, v, d, r, h) ->
let l' = A.of_thunk (fun () -> mapi ~f l) in
let d' = f ~key:v ~data:d in
let r' = A.of_thunk (fun () -> mapi ~f r) in
A.map3 l' d' r' ~f:(fun l' d' r' -> Node (l', v, d', r', h))
;;
(* In theory the computation of length on-the-fly is not necessary here because it can
be done by wrapping the applicative [A] with length-computing logic. However,
introducing an applicative transformer like that makes the map benchmarks in
async_kernel/bench/src/bench_deferred_map.ml noticeably slower. *)
let filter_mapi t ~f =
let rec tree_filter_mapi t ~f =
match t with
| Empty -> A.return (with_length_global Empty 0)
| Leaf (v, d) ->
A.map (f ~key:v ~data:d) ~f:(function
| Some new_data -> with_length_global (Leaf (v, new_data)) 1
| None -> with_length_global Empty 0)
| Node (l, v, d, r, _) ->
A.map3
(A.of_thunk (fun () -> tree_filter_mapi l ~f))
(f ~key:v ~data:d)
(A.of_thunk (fun () -> tree_filter_mapi r ~f))
~f:
(fun { tree = l'; length = l_len } new_data { tree = r'; length = r_len } ->
match new_data with
| Some new_data ->
with_length_global (join l' v new_data r') (l_len + r_len + 1)
| None ->
with_length_global (concat_and_balance_unchecked l' r') (l_len + r_len))
in
tree_filter_mapi t ~f
;;
end
end
type ('k, 'v, 'comparator) t =
[ comparator ] is the first field so that polymorphic equality fails on a map due
to the functional value in the comparator .
Note that this does not affect polymorphic [ compare ] : that still produces
nonsense .
to the functional value in the comparator.
Note that this does not affect polymorphic [compare]: that still produces
nonsense. *)
comparator : ('k, 'comparator) Comparator.t
; tree : ('k, 'v) Tree0.t
; length : int
}
type ('k, 'v, 'comparator) tree = ('k, 'v) Tree0.t
let compare_key t = t.comparator.Comparator.compare
let like { tree = _; length = _; comparator } ({ tree; length } : _ With_length.t) =
{ tree; length; comparator }
;;
let like_maybe_no_op
({ tree = old_tree; length = _; comparator } as old_t)
({ tree; length } : _ With_length.t)
=
if phys_equal old_tree tree then old_t else { tree; length; comparator }
;;
let with_same_length { tree = _; comparator; length } tree = { tree; comparator; length }
let of_like_tree t tree = { tree; comparator = t.comparator; length = Tree0.length tree }
let of_like_tree_maybe_no_op t tree =
if phys_equal t.tree tree
then t
else { tree; comparator = t.comparator; length = Tree0.length tree }
;;
let of_tree ~comparator tree = { tree; comparator; length = Tree0.length tree }
(* Exposing this function would make it very easy for the invariants
of this module to be broken. *)
let of_tree_unsafe ~comparator ~length tree = { tree; comparator; length }
module Accessors = struct
let comparator t = t.comparator
let to_tree t = t.tree
let invariants t =
Tree0.invariants t.tree ~compare_key:(compare_key t) && Tree0.length t.tree = t.length
;;
let is_empty t = Tree0.is_empty t.tree
let length t = t.length
let set t ~key ~data =
like
t
(Tree0.set t.tree ~length:t.length ~key ~data ~compare_key:(compare_key t))
[@nontail]
;;
let add_exn t ~key ~data =
like
t
(Tree0.add_exn
t.tree
~length:t.length
~key
~data
~compare_key:(compare_key t)
~sexp_of_key:t.comparator.sexp_of_t) [@nontail]
;;
let add_exn_internal t ~key ~data =
like
t
(Tree0.add_exn_internal
t.tree
~length:t.length
~key
~data
~compare_key:(compare_key t)
~sexp_of_key:t.comparator.sexp_of_t) [@nontail]
;;
let add t ~key ~data =
match add_exn_internal t ~key ~data with
| result -> `Ok result
| exception Duplicate -> `Duplicate
;;
let add_multi t ~key ~data =
like
t
(Tree0.add_multi t.tree ~length:t.length ~key ~data ~compare_key:(compare_key t))
[@nontail]
;;
let remove_multi t key =
like
t
(Tree0.remove_multi t.tree ~length:t.length key ~compare_key:(compare_key t))
[@nontail]
;;
let find_multi t key = Tree0.find_multi t.tree key ~compare_key:(compare_key t)
let change t key ~f =
like
t
(Tree0.change t.tree key ~f ~length:t.length ~compare_key:(compare_key t))
[@nontail]
;;
let update t key ~f =
like
t
(Tree0.update t.tree key ~f ~length:t.length ~compare_key:(compare_key t))
[@nontail]
;;
let find_exn t key =
Tree0.find_exn
t.tree
key
~compare_key:(compare_key t)
~sexp_of_key:t.comparator.sexp_of_t
;;
let find t key = Tree0.find t.tree key ~compare_key:(compare_key t)
let remove t key =
like_maybe_no_op
t
(Tree0.remove t.tree key ~length:t.length ~compare_key:(compare_key t)) [@nontail]
;;
let mem t key = Tree0.mem t.tree key ~compare_key:(compare_key t)
let iter_keys t ~f = Tree0.iter_keys t.tree ~f
let iter t ~f = Tree0.iter t.tree ~f
let iteri t ~f = Tree0.iteri t.tree ~f
let iteri_until t ~f = Tree0.iteri_until t.tree ~f
let iter2 t1 t2 ~f = Tree0.iter2 t1.tree t2.tree ~f ~compare_key:(compare_key t1)
let map t ~f = with_same_length t (Tree0.map t.tree ~f)
let mapi t ~f = with_same_length t (Tree0.mapi t.tree ~f)
let fold t ~init ~f = Tree0.fold t.tree ~f ~init
let fold_until t ~init ~f ~finish = Tree0.fold_until t.tree ~init ~f ~finish
let fold_right t ~init ~f = Tree0.fold_right t.tree ~f ~init
let fold2 t1 t2 ~init ~f =
Tree0.fold2 t1.tree t2.tree ~init ~f ~compare_key:(compare_key t1)
;;
let filter_keys t ~f =
let len = (ref t.length) in
let tree = Tree0.filter_keys t.tree ~f ~len in
like_maybe_no_op t (with_length tree !len) [@nontail]
;;
let filter t ~f =
let len = (ref t.length) in
let tree = Tree0.filter t.tree ~f ~len in
like_maybe_no_op t (with_length tree !len) [@nontail]
;;
let filteri t ~f =
let len = (ref t.length) in
let tree = Tree0.filteri t.tree ~f ~len in
like_maybe_no_op t (with_length tree !len) [@nontail]
;;
let filter_map t ~f =
let len = (ref t.length) in
let tree = Tree0.filter_map t.tree ~f ~len in
like t (with_length tree !len) [@nontail]
;;
let filter_mapi t ~f =
let len = (ref t.length) in
let tree = Tree0.filter_mapi t.tree ~f ~len in
like t (with_length tree !len) [@nontail]
;;
let of_like_tree2 t (t1, t2) = of_like_tree t t1, of_like_tree t t2
let of_like_tree2_maybe_no_op t (t1, t2) =
of_like_tree_maybe_no_op t t1, of_like_tree_maybe_no_op t t2
;;
let partition_mapi t ~f = of_like_tree2 t (Tree0.partition_mapi t.tree ~f)
let partition_map t ~f = of_like_tree2 t (Tree0.partition_map t.tree ~f)
let partitioni_tf t ~f = of_like_tree2_maybe_no_op t (Tree0.partitioni_tf t.tree ~f)
let partition_tf t ~f = of_like_tree2_maybe_no_op t (Tree0.partition_tf t.tree ~f)
let combine_errors t =
Or_error.map
~f:(of_like_tree t)
(Tree0.combine_errors t.tree ~sexp_of_key:t.comparator.sexp_of_t)
;;
let compare_direct compare_data t1 t2 =
Tree0.compare (compare_key t1) compare_data t1.tree t2.tree
;;
let equal compare_data t1 t2 = Tree0.equal (compare_key t1) compare_data t1.tree t2.tree
let keys t = Tree0.keys t.tree
let data t = Tree0.data t.tree
let to_alist ?key_order t = Tree0.to_alist ?key_order t.tree
let symmetric_diff t1 t2 ~data_equal =
Tree0.symmetric_diff t1.tree t2.tree ~compare_key:(compare_key t1) ~data_equal
;;
let fold_symmetric_diff t1 t2 ~data_equal ~init ~f =
Tree0.fold_symmetric_diff
t1.tree
t2.tree
~compare_key:(compare_key t1)
~data_equal
~init
~f
;;
let merge t1 t2 ~f =
like t1 (Tree0.merge t1.tree t2.tree ~f ~compare_key:(compare_key t1)) [@nontail]
;;
let merge_skewed t1 t2 ~combine =
This is only a no - op in the case where at least one of the maps is empty .
like_maybe_no_op
(if t2.length <= t1.length then t1 else t2)
(Tree0.merge_skewed
t1.tree
t2.tree
~length1:t1.length
~length2:t2.length
~combine
~compare_key:(compare_key t1))
;;
let min_elt t = Tree0.min_elt t.tree
let min_elt_exn t = Tree0.min_elt_exn t.tree
let max_elt t = Tree0.max_elt t.tree
let max_elt_exn t = Tree0.max_elt_exn t.tree
let for_all t ~f = Tree0.for_all t.tree ~f
let for_alli t ~f = Tree0.for_alli t.tree ~f
let exists t ~f = Tree0.exists t.tree ~f
let existsi t ~f = Tree0.existsi t.tree ~f
let count t ~f = Tree0.count t.tree ~f
let counti t ~f = Tree0.counti t.tree ~f
let split t k =
let l, maybe, r = Tree0.split t.tree k ~compare_key:(compare_key t) in
let comparator = comparator t in
(* Try to traverse the least amount possible to calculate the length,
using height as a heuristic. *)
let both_len = if Option.is_some maybe then t.length - 1 else t.length in
if Tree0.height l < Tree0.height r
then (
let l = of_tree l ~comparator in
l, maybe, of_tree_unsafe r ~comparator ~length:(both_len - length l))
else (
let r = of_tree r ~comparator in
of_tree_unsafe l ~comparator ~length:(both_len - length r), maybe, r)
;;
let split_and_reinsert_boundary t ~into k =
let l, r =
Tree0.split_and_reinsert_boundary t.tree ~into k ~compare_key:(compare_key t)
in
let comparator = comparator t in
(* Try to traverse the least amount possible to calculate the length,
using height as a heuristic. *)
if Tree0.height l < Tree0.height r
then (
let l = of_tree l ~comparator in
l, of_tree_unsafe r ~comparator ~length:(t.length - length l))
else (
let r = of_tree r ~comparator in
of_tree_unsafe l ~comparator ~length:(t.length - length r), r)
;;
let split_le_gt t k = split_and_reinsert_boundary t ~into:`Left k
let split_lt_ge t k = split_and_reinsert_boundary t ~into:`Right k
let subrange t ~lower_bound ~upper_bound =
let left, mid, right =
Tree0.split_range t.tree ~lower_bound ~upper_bound ~compare_key:(compare_key t)
in
(* Try to traverse the least amount possible to calculate the length,
using height as a heuristic. *)
let outer_joined_height =
let h_l = Tree0.height left
and h_r = Tree0.height right in
if h_l = h_r then h_l + 1 else max h_l h_r
in
if outer_joined_height < Tree0.height mid
then (
let mid_length = t.length - (Tree0.length left + Tree0.length right) in
of_tree_unsafe mid ~comparator:(comparator t) ~length:mid_length)
else of_tree mid ~comparator:(comparator t)
;;
let append ~lower_part ~upper_part =
match
Tree0.append
~compare_key:(compare_key lower_part)
~lower_part:lower_part.tree
~upper_part:upper_part.tree
with
| `Ok tree ->
`Ok
(of_tree_unsafe
tree
~comparator:(comparator lower_part)
~length:(lower_part.length + upper_part.length))
| `Overlapping_key_ranges -> `Overlapping_key_ranges
;;
let fold_range_inclusive t ~min ~max ~init ~f =
Tree0.fold_range_inclusive t.tree ~min ~max ~init ~f ~compare_key:(compare_key t)
;;
let range_to_alist t ~min ~max =
Tree0.range_to_alist t.tree ~min ~max ~compare_key:(compare_key t)
;;
let closest_key t dir key =
Tree0.closest_key t.tree dir key ~compare_key:(compare_key t)
;;
let nth t n = Tree0.nth t.tree n
let nth_exn t n = Option.value_exn (nth t n)
let rank t key = Tree0.rank t.tree key ~compare_key:(compare_key t)
let sexp_of_t sexp_of_k sexp_of_v _ t = Tree0.sexp_of_t sexp_of_k sexp_of_v t.tree
let to_sequence ?order ?keys_greater_or_equal_to ?keys_less_or_equal_to t =
Tree0.to_sequence
t.comparator
?order
?keys_greater_or_equal_to
?keys_less_or_equal_to
t.tree
;;
let binary_search t ~compare how v = Tree0.binary_search t.tree ~compare how v
let binary_search_segmented t ~segment_of how =
Tree0.binary_search_segmented t.tree ~segment_of how
;;
let hash_fold_direct hash_fold_key hash_fold_data state t =
Tree0.hash_fold_t_ignoring_structure hash_fold_key hash_fold_data state t.tree
;;
let binary_search_subrange t ~compare ~lower_bound ~upper_bound =
match
Tree0.binary_search_two_sided_bounds t.tree ~compare ~lower_bound ~upper_bound
with
| Some (lower_bound, upper_bound) -> subrange t ~lower_bound ~upper_bound
| None -> like_maybe_no_op t (with_length Tree0.Empty 0) [@nontail]
;;
module Make_applicative_traversals (A : Applicative.Lazy_applicative) = struct
module Tree_traversals = Tree0.Make_applicative_traversals (A)
let mapi t ~f =
A.map (Tree_traversals.mapi t.tree ~f) ~f:(fun new_tree ->
with_same_length t new_tree)
;;
let filter_mapi t ~f =
A.map (Tree_traversals.filter_mapi t.tree ~f) ~f:(fun new_tree_with_length ->
like t new_tree_with_length)
;;
end
end
(* [0] is used as the [length] argument everywhere in this module, since trees do not
have their lengths stored at the root, unlike maps. The values are discarded always. *)
module Tree = struct
type ('k, 'v, 'comparator) t = ('k, 'v, 'comparator) tree
let empty_without_value_restriction = Tree0.empty
let empty ~comparator:_ = empty_without_value_restriction
let of_tree ~comparator:_ tree = tree
let singleton ~comparator:_ k v = Tree0.singleton k v
let of_sorted_array_unchecked ~comparator array =
(Tree0.of_sorted_array_unchecked array ~compare_key:comparator.Comparator.compare)
.tree
;;
let of_sorted_array ~comparator array =
Tree0.of_sorted_array array ~compare_key:comparator.Comparator.compare
|> Or_error.map ~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
let of_alist ~comparator alist =
match Tree0.of_alist alist ~compare_key:comparator.Comparator.compare with
| `Duplicate_key _ as d -> d
| `Ok { tree; length = _ } -> `Ok tree
;;
let of_alist_or_error ~comparator alist =
Tree0.of_alist_or_error alist ~comparator
|> Or_error.map ~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
let of_alist_exn ~comparator alist = (Tree0.of_alist_exn alist ~comparator).tree
let of_alist_multi ~comparator alist =
(Tree0.of_alist_multi alist ~compare_key:comparator.Comparator.compare).tree
;;
let of_alist_fold ~comparator alist ~init ~f =
(Tree0.of_alist_fold alist ~init ~f ~compare_key:comparator.Comparator.compare).tree
;;
let of_alist_reduce ~comparator alist ~f =
(Tree0.of_alist_reduce alist ~f ~compare_key:comparator.Comparator.compare).tree
;;
let of_iteri ~comparator ~iteri =
match Tree0.of_iteri ~iteri ~compare_key:comparator.Comparator.compare with
| `Ok { tree; length = _ } -> `Ok tree
| `Duplicate_key _ as d -> d
;;
let of_iteri_exn ~comparator ~iteri = (Tree0.of_iteri_exn ~iteri ~comparator).tree
let of_increasing_iterator_unchecked ~comparator:_required_by_intf ~len ~f =
Tree0.of_increasing_iterator_unchecked ~len ~f
;;
let of_increasing_sequence ~comparator seq =
Or_error.map
~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
(Tree0.of_increasing_sequence seq ~compare_key:comparator.Comparator.compare)
;;
let of_sequence ~comparator seq =
match Tree0.of_sequence seq ~compare_key:comparator.Comparator.compare with
| `Duplicate_key _ as d -> d
| `Ok { tree; length = _ } -> `Ok tree
;;
let of_sequence_or_error ~comparator seq =
Tree0.of_sequence_or_error seq ~comparator
|> Or_error.map ~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
let of_sequence_exn ~comparator seq = (Tree0.of_sequence_exn seq ~comparator).tree
let of_sequence_multi ~comparator seq =
(Tree0.of_sequence_multi seq ~compare_key:comparator.Comparator.compare).tree
;;
let of_sequence_fold ~comparator seq ~init ~f =
(Tree0.of_sequence_fold seq ~init ~f ~compare_key:comparator.Comparator.compare).tree
;;
let of_sequence_reduce ~comparator seq ~f =
(Tree0.of_sequence_reduce seq ~f ~compare_key:comparator.Comparator.compare).tree
;;
let of_list_with_key ~comparator list ~get_key =
match
Tree0.of_list_with_key list ~get_key ~compare_key:comparator.Comparator.compare
with
| `Duplicate_key _ as d -> d
| `Ok { tree; length = _ } -> `Ok tree
;;
let of_list_with_key_or_error ~comparator list ~get_key =
Tree0.of_list_with_key_or_error list ~get_key ~comparator
|> Or_error.map ~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
let of_list_with_key_exn ~comparator list ~get_key =
(Tree0.of_list_with_key_exn list ~get_key ~comparator).tree
;;
let of_list_with_key_multi ~comparator list ~get_key =
(Tree0.of_list_with_key_multi
list
~get_key
~compare_key:comparator.Comparator.compare)
.tree
;;
let to_tree t = t
let invariants ~comparator t =
Tree0.invariants t ~compare_key:comparator.Comparator.compare
;;
let is_empty t = Tree0.is_empty t
let length t = Tree0.length t
let set ~comparator t ~key ~data =
(Tree0.set t ~key ~data ~length:0 ~compare_key:comparator.Comparator.compare).tree
;;
let add_exn ~comparator t ~key ~data =
(Tree0.add_exn
t
~key
~data
~length:0
~compare_key:comparator.Comparator.compare
~sexp_of_key:comparator.sexp_of_t)
.tree
;;
let add_exn_internal ~comparator t ~key ~data =
(Tree0.add_exn_internal
t
~key
~data
~length:0
~compare_key:comparator.Comparator.compare
~sexp_of_key:comparator.sexp_of_t)
.tree
;;
let add ~comparator t ~key ~data =
try `Ok (add_exn_internal t ~comparator ~key ~data) with
| _ -> `Duplicate
;;
let add_multi ~comparator t ~key ~data =
(Tree0.add_multi t ~key ~data ~length:0 ~compare_key:comparator.Comparator.compare)
.tree
;;
let remove_multi ~comparator t key =
(Tree0.remove_multi t key ~length:0 ~compare_key:comparator.Comparator.compare).tree
;;
let find_multi ~comparator t key =
Tree0.find_multi t key ~compare_key:comparator.Comparator.compare
;;
let change ~comparator t key ~f =
(Tree0.change t key ~f ~length:0 ~compare_key:comparator.Comparator.compare).tree
;;
let update ~comparator t key ~f =
change ~comparator t key ~f:(fun data -> Some (f data)) [@nontail]
;;
let find_exn ~comparator t key =
Tree0.find_exn
t
key
~compare_key:comparator.Comparator.compare
~sexp_of_key:comparator.Comparator.sexp_of_t
;;
let find ~comparator t key = Tree0.find t key ~compare_key:comparator.Comparator.compare
let remove ~comparator t key =
(Tree0.remove t key ~length:0 ~compare_key:comparator.Comparator.compare).tree
;;
let mem ~comparator t key = Tree0.mem t key ~compare_key:comparator.Comparator.compare
let iter_keys t ~f = Tree0.iter_keys t ~f
let iter t ~f = Tree0.iter t ~f
let iteri t ~f = Tree0.iteri t ~f
let iteri_until t ~f = Tree0.iteri_until t ~f
let iter2 ~comparator t1 t2 ~f =
Tree0.iter2 t1 t2 ~f ~compare_key:comparator.Comparator.compare
;;
let map t ~f = Tree0.map t ~f
let mapi t ~f = Tree0.mapi t ~f
let fold t ~init ~f = Tree0.fold t ~f ~init
let fold_until t ~init ~f ~finish = Tree0.fold_until t ~f ~init ~finish
let fold_right t ~init ~f = Tree0.fold_right t ~f ~init
let fold2 ~comparator t1 t2 ~init ~f =
Tree0.fold2 t1 t2 ~init ~f ~compare_key:comparator.Comparator.compare
;;
let filter_keys t ~f = Tree0.filter_keys t ~f ~len:( (ref 0)) [@nontail]
let filter t ~f = Tree0.filter t ~f ~len:( (ref 0)) [@nontail]
let filteri t ~f = Tree0.filteri t ~f ~len:( (ref 0)) [@nontail]
let filter_map t ~f = Tree0.filter_map t ~f ~len:( (ref 0)) [@nontail]
let filter_mapi t ~f = Tree0.filter_mapi t ~f ~len:( (ref 0)) [@nontail]
let partition_mapi t ~f = Tree0.partition_mapi t ~f
let partition_map t ~f = Tree0.partition_map t ~f
let partitioni_tf t ~f = Tree0.partitioni_tf t ~f
let partition_tf t ~f = Tree0.partition_tf t ~f
let combine_errors ~comparator t =
Tree0.combine_errors t ~sexp_of_key:comparator.Comparator.sexp_of_t
;;
let compare_direct ~comparator compare_data t1 t2 =
Tree0.compare comparator.Comparator.compare compare_data t1 t2
;;
let equal ~comparator compare_data t1 t2 =
Tree0.equal comparator.Comparator.compare compare_data t1 t2
;;
let keys t = Tree0.keys t
let data t = Tree0.data t
let to_alist ?key_order t = Tree0.to_alist ?key_order t
let symmetric_diff ~comparator t1 t2 ~data_equal =
Tree0.symmetric_diff t1 t2 ~compare_key:comparator.Comparator.compare ~data_equal
;;
let fold_symmetric_diff ~comparator t1 t2 ~data_equal ~init ~f =
Tree0.fold_symmetric_diff
t1
t2
~compare_key:comparator.Comparator.compare
~data_equal
~init
~f
;;
let merge ~comparator t1 t2 ~f =
(Tree0.merge t1 t2 ~f ~compare_key:comparator.Comparator.compare).tree
;;
let merge_skewed ~comparator t1 t2 ~combine =
(* Length computation makes this significantly slower than [merge_skewed] on a map
with a [length] field, but does preserve amount of allocation. *)
(Tree0.merge_skewed
t1
t2
~length1:(length t1)
~length2:(length t2)
~combine
~compare_key:comparator.Comparator.compare)
.tree
;;
let min_elt t = Tree0.min_elt t
let min_elt_exn t = Tree0.min_elt_exn t
let max_elt t = Tree0.max_elt t
let max_elt_exn t = Tree0.max_elt_exn t
let for_all t ~f = Tree0.for_all t ~f
let for_alli t ~f = Tree0.for_alli t ~f
let exists t ~f = Tree0.exists t ~f
let existsi t ~f = Tree0.existsi t ~f
let count t ~f = Tree0.count t ~f
let counti t ~f = Tree0.counti t ~f
let split ~comparator t k = Tree0.split t k ~compare_key:comparator.Comparator.compare
let split_le_gt ~comparator t k =
Tree0.split_and_reinsert_boundary
t
~into:`Left
k
~compare_key:comparator.Comparator.compare
;;
let split_lt_ge ~comparator t k =
Tree0.split_and_reinsert_boundary
t
~into:`Right
k
~compare_key:comparator.Comparator.compare
;;
let append ~comparator ~lower_part ~upper_part =
Tree0.append ~lower_part ~upper_part ~compare_key:comparator.Comparator.compare
;;
let subrange ~comparator t ~lower_bound ~upper_bound =
let _, ret, _ =
Tree0.split_range
t
~lower_bound
~upper_bound
~compare_key:comparator.Comparator.compare
in
ret
;;
let fold_range_inclusive ~comparator t ~min ~max ~init ~f =
Tree0.fold_range_inclusive
t
~min
~max
~init
~f
~compare_key:comparator.Comparator.compare
;;
let range_to_alist ~comparator t ~min ~max =
Tree0.range_to_alist t ~min ~max ~compare_key:comparator.Comparator.compare
;;
let closest_key ~comparator t dir key =
Tree0.closest_key t dir key ~compare_key:comparator.Comparator.compare
;;
let nth t n = Tree0.nth t n
let nth_exn t n = Option.value_exn (nth t n)
let rank ~comparator t key = Tree0.rank t key ~compare_key:comparator.Comparator.compare
let sexp_of_t sexp_of_k sexp_of_v _ t = Tree0.sexp_of_t sexp_of_k sexp_of_v t
let t_of_sexp_direct ~comparator k_of_sexp v_of_sexp sexp =
(Tree0.t_of_sexp_direct k_of_sexp v_of_sexp sexp ~comparator).tree
;;
let to_sequence ~comparator ?order ?keys_greater_or_equal_to ?keys_less_or_equal_to t =
Tree0.to_sequence comparator ?order ?keys_greater_or_equal_to ?keys_less_or_equal_to t
;;
let binary_search ~comparator:_ t ~compare how v = Tree0.binary_search t ~compare how v
let binary_search_segmented ~comparator:_ t ~segment_of how =
Tree0.binary_search_segmented t ~segment_of how
;;
let binary_search_subrange ~comparator t ~compare ~lower_bound ~upper_bound =
match Tree0.binary_search_two_sided_bounds t ~compare ~lower_bound ~upper_bound with
| Some (lower_bound, upper_bound) -> subrange ~comparator t ~lower_bound ~upper_bound
| None -> Empty
;;
module Make_applicative_traversals (A : Applicative.Lazy_applicative) = struct
module Tree0_traversals = Tree0.Make_applicative_traversals (A)
let mapi t ~f = Tree0_traversals.mapi t ~f
let filter_mapi t ~f =
A.map
(Tree0_traversals.filter_mapi t ~f)
~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
end
let map_keys ~comparator t ~f =
match Tree0.map_keys ~comparator t ~f with
| `Ok { tree = t; length = _ } -> `Ok t
| `Duplicate_key _ as dup -> dup
;;
let map_keys_exn ~comparator t ~f = (Tree0.map_keys_exn ~comparator t ~f).tree
(* This calling convention of [~comparator ~comparator] is confusing. It is required
because [access_options] and [create_options] both demand a [~comparator] argument in
[Map.Using_comparator.Tree].
Making it less confusing would require some unnecessary complexity in signatures.
Better to just live with an undesirable interface in a function that will probably
never be called directly. *)
let transpose_keys ~comparator:outer_comparator ~comparator:inner_comparator t =
(Tree0.transpose_keys ~outer_comparator ~inner_comparator t).tree
|> map ~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
module Build_increasing = struct
type ('k, 'v, 'w) t = ('k, 'v) Tree0.Build_increasing.t
let empty = Tree0.Build_increasing.empty
let add_exn t ~comparator ~key ~data =
match Tree0.Build_increasing.max_key t with
| Some prev_key when comparator.Comparator.compare prev_key key >= 0 ->
Error.raise_s (Sexp.Atom "Map.Build_increasing.add: non-increasing key")
| _ -> Tree0.Build_increasing.add_unchecked t ~key ~data
;;
let to_tree t = Tree0.Build_increasing.to_tree_unchecked t
end
end
module Using_comparator = struct
type nonrec ('k, 'v, 'cmp) t = ('k, 'v, 'cmp) t
include Accessors
let empty ~comparator = { tree = Tree0.empty; comparator; length = 0 }
let singleton ~comparator k v = { comparator; tree = Tree0.singleton k v; length = 1 }
let of_tree0 ~comparator ({ tree; length } : _ With_length.t) =
{ comparator; tree; length }
;;
let of_tree ~comparator tree =
of_tree0 ~comparator (with_length tree (Tree0.length tree)) [@nontail]
;;
let to_tree = to_tree
let of_sorted_array_unchecked ~comparator array =
of_tree0
~comparator
(Tree0.of_sorted_array_unchecked array ~compare_key:comparator.Comparator.compare)
[@nontail]
;;
let of_sorted_array ~comparator array =
Or_error.map
(Tree0.of_sorted_array array ~compare_key:comparator.Comparator.compare)
~f:(fun tree -> of_tree0 ~comparator tree)
;;
let of_alist ~comparator alist =
match Tree0.of_alist alist ~compare_key:comparator.Comparator.compare with
| `Ok { tree; length } -> `Ok { comparator; tree; length }
| `Duplicate_key _ as z -> z
;;
let of_alist_or_error ~comparator alist =
Result.map (Tree0.of_alist_or_error alist ~comparator) ~f:(fun tree ->
of_tree0 ~comparator tree)
;;
let of_alist_exn ~comparator alist =
of_tree0 ~comparator (Tree0.of_alist_exn alist ~comparator)
;;
let of_alist_multi ~comparator alist =
of_tree0
~comparator
(Tree0.of_alist_multi alist ~compare_key:comparator.Comparator.compare)
;;
let of_alist_fold ~comparator alist ~init ~f =
of_tree0
~comparator
(Tree0.of_alist_fold alist ~init ~f ~compare_key:comparator.Comparator.compare)
;;
let of_alist_reduce ~comparator alist ~f =
of_tree0
~comparator
(Tree0.of_alist_reduce alist ~f ~compare_key:comparator.Comparator.compare)
;;
let of_iteri ~comparator ~iteri =
match Tree0.of_iteri ~compare_key:comparator.Comparator.compare ~iteri with
| `Ok tree_length -> `Ok (of_tree0 ~comparator tree_length)
| `Duplicate_key _ as z -> z
;;
let of_iteri_exn ~comparator ~iteri =
of_tree0 ~comparator (Tree0.of_iteri_exn ~comparator ~iteri)
;;
let of_increasing_iterator_unchecked ~comparator ~len ~f =
of_tree0
~comparator
(with_length (Tree0.of_increasing_iterator_unchecked ~len ~f) len) [@nontail]
;;
let of_increasing_sequence ~comparator seq =
Or_error.map
~f:(fun x -> of_tree0 ~comparator x)
(Tree0.of_increasing_sequence seq ~compare_key:comparator.Comparator.compare)
;;
let of_sequence ~comparator seq =
match Tree0.of_sequence seq ~compare_key:comparator.Comparator.compare with
| `Ok { tree; length } -> `Ok { comparator; tree; length }
| `Duplicate_key _ as z -> z
;;
let of_sequence_or_error ~comparator seq =
Result.map (Tree0.of_sequence_or_error seq ~comparator) ~f:(fun tree ->
of_tree0 ~comparator tree)
;;
let of_sequence_exn ~comparator seq =
of_tree0 ~comparator (Tree0.of_sequence_exn seq ~comparator)
;;
let of_sequence_multi ~comparator seq =
of_tree0
~comparator
(Tree0.of_sequence_multi seq ~compare_key:comparator.Comparator.compare)
;;
let of_sequence_fold ~comparator seq ~init ~f =
of_tree0
~comparator
(Tree0.of_sequence_fold seq ~init ~f ~compare_key:comparator.Comparator.compare)
;;
let of_sequence_reduce ~comparator seq ~f =
of_tree0
~comparator
(Tree0.of_sequence_reduce seq ~f ~compare_key:comparator.Comparator.compare)
;;
let of_list_with_key ~comparator list ~get_key =
match
Tree0.of_list_with_key list ~get_key ~compare_key:comparator.Comparator.compare
with
| `Ok { tree; length } -> `Ok { comparator; tree; length }
| `Duplicate_key _ as z -> z
;;
let of_list_with_key_or_error ~comparator list ~get_key =
Result.map (Tree0.of_list_with_key_or_error list ~get_key ~comparator) ~f:(fun tree ->
of_tree0 ~comparator tree)
;;
let of_list_with_key_exn ~comparator list ~get_key =
of_tree0 ~comparator (Tree0.of_list_with_key_exn list ~get_key ~comparator)
;;
let of_list_with_key_multi ~comparator list ~get_key =
Tree0.of_list_with_key_multi list ~get_key ~compare_key:comparator.Comparator.compare
|> of_tree0 ~comparator
;;
let t_of_sexp_direct ~comparator k_of_sexp v_of_sexp sexp =
of_tree0 ~comparator (Tree0.t_of_sexp_direct k_of_sexp v_of_sexp sexp ~comparator)
;;
let map_keys ~comparator t ~f =
match Tree0.map_keys t.tree ~f ~comparator with
| `Ok pair -> `Ok (of_tree0 ~comparator pair)
| `Duplicate_key _ as dup -> dup
;;
let map_keys_exn ~comparator t ~f =
of_tree0 ~comparator (Tree0.map_keys_exn t.tree ~f ~comparator)
;;
let transpose_keys ~comparator:inner_comparator t =
let outer_comparator = t.comparator in
Tree0.transpose_keys ~outer_comparator ~inner_comparator (Tree0.map t.tree ~f:to_tree)
|> of_tree0 ~comparator:inner_comparator
|> map ~f:(fun x -> of_tree0 ~comparator:outer_comparator x)
;;
module Empty_without_value_restriction (K : Comparator.S1) = struct
let empty = { tree = Tree0.empty; comparator = K.comparator; length = 0 }
end
module Tree = Tree
end
include Accessors
type ('k, 'cmp) comparator =
(module Comparator.S with type t = 'k and type comparator_witness = 'cmp)
let comparator_s (type k cmp) t : (k, cmp) comparator =
(module struct
type t = k
type comparator_witness = cmp
let comparator = t.comparator
end)
;;
let to_comparator (type k cmp) ((module M) : (k, cmp) comparator) = M.comparator
let of_tree (type k cmp) ((module M) : (k, cmp) comparator) tree =
of_tree ~comparator:M.comparator tree
;;
let empty m = Using_comparator.empty ~comparator:(to_comparator m)
let singleton m a = Using_comparator.singleton ~comparator:(to_comparator m) a
let of_alist m a = Using_comparator.of_alist ~comparator:(to_comparator m) a
let of_alist_or_error m a =
Using_comparator.of_alist_or_error ~comparator:(to_comparator m) a
;;
let of_alist_exn m a = Using_comparator.of_alist_exn ~comparator:(to_comparator m) a
let of_alist_multi m a = Using_comparator.of_alist_multi ~comparator:(to_comparator m) a
let of_alist_fold m a ~init ~f =
Using_comparator.of_alist_fold ~comparator:(to_comparator m) a ~init ~f
;;
let of_alist_reduce m a ~f =
Using_comparator.of_alist_reduce ~comparator:(to_comparator m) a ~f
;;
let of_sorted_array_unchecked m a =
Using_comparator.of_sorted_array_unchecked ~comparator:(to_comparator m) a
;;
let of_sorted_array m a = Using_comparator.of_sorted_array ~comparator:(to_comparator m) a
let of_iteri m ~iteri = Using_comparator.of_iteri ~iteri ~comparator:(to_comparator m)
let of_iteri_exn m ~iteri =
Using_comparator.of_iteri_exn ~iteri ~comparator:(to_comparator m)
;;
let of_increasing_iterator_unchecked m ~len ~f =
Using_comparator.of_increasing_iterator_unchecked ~len ~f ~comparator:(to_comparator m)
;;
let of_increasing_sequence m seq =
Using_comparator.of_increasing_sequence ~comparator:(to_comparator m) seq
;;
let of_sequence m s = Using_comparator.of_sequence ~comparator:(to_comparator m) s
let of_sequence_or_error m s =
Using_comparator.of_sequence_or_error ~comparator:(to_comparator m) s
;;
let of_sequence_exn m s = Using_comparator.of_sequence_exn ~comparator:(to_comparator m) s
let of_sequence_multi m s =
Using_comparator.of_sequence_multi ~comparator:(to_comparator m) s
;;
let of_sequence_fold m s ~init ~f =
Using_comparator.of_sequence_fold ~comparator:(to_comparator m) s ~init ~f
;;
let of_sequence_reduce m s ~f =
Using_comparator.of_sequence_reduce ~comparator:(to_comparator m) s ~f
;;
let of_list_with_key m l ~get_key =
Using_comparator.of_list_with_key ~comparator:(to_comparator m) l ~get_key
;;
let of_list_with_key_or_error m l ~get_key =
Using_comparator.of_list_with_key_or_error ~comparator:(to_comparator m) l ~get_key
;;
let of_list_with_key_exn m l ~get_key =
Using_comparator.of_list_with_key_exn ~comparator:(to_comparator m) l ~get_key
;;
let of_list_with_key_multi m l ~get_key =
Using_comparator.of_list_with_key_multi ~comparator:(to_comparator m) l ~get_key
;;
let map_keys m t ~f = Using_comparator.map_keys ~comparator:(to_comparator m) t ~f
let map_keys_exn m t ~f = Using_comparator.map_keys_exn ~comparator:(to_comparator m) t ~f
let transpose_keys m t = Using_comparator.transpose_keys ~comparator:(to_comparator m) t
module M (K : sig
type t
type comparator_witness
end) =
struct
type nonrec 'v t = (K.t, 'v, K.comparator_witness) t
end
module type Sexp_of_m = sig
type t [@@deriving_inline sexp_of]
val sexp_of_t : t -> Sexplib0.Sexp.t
[@@@end]
end
module type M_of_sexp = sig
type t [@@deriving_inline of_sexp]
val t_of_sexp : Sexplib0.Sexp.t -> t
[@@@end]
include Comparator.S with type t := t
end
module type M_sexp_grammar = sig
type t [@@deriving_inline sexp_grammar]
val t_sexp_grammar : t Sexplib0.Sexp_grammar.t
[@@@end]
end
module type Compare_m = sig end
module type Equal_m = sig end
module type Hash_fold_m = Hasher.S
let sexp_of_m__t (type k) (module K : Sexp_of_m with type t = k) sexp_of_v t =
sexp_of_t K.sexp_of_t sexp_of_v (fun _ -> Sexp.Atom "_") t
;;
let m__t_of_sexp
(type k cmp)
(module K : M_of_sexp with type t = k and type comparator_witness = cmp)
v_of_sexp
sexp
=
Using_comparator.t_of_sexp_direct ~comparator:K.comparator K.t_of_sexp v_of_sexp sexp
;;
let m__t_sexp_grammar
(type k)
(module K : M_sexp_grammar with type t = k)
(v_grammar : _ Sexplib0.Sexp_grammar.t)
: _ Sexplib0.Sexp_grammar.t
=
{ untyped =
Tagged
{ key = Sexplib0.Sexp_grammar.assoc_tag
; value = List []
; grammar =
List
(Many
(List
(Cons
( Tagged
{ key = Sexplib0.Sexp_grammar.assoc_key_tag
; value = List []
; grammar = K.t_sexp_grammar.untyped
}
, Cons
( Tagged
{ key = Sexplib0.Sexp_grammar.assoc_value_tag
; value = List []
; grammar = v_grammar.untyped
}
, Empty ) ))))
}
}
;;
let compare_m__t (module _ : Compare_m) compare_v t1 t2 = compare_direct compare_v t1 t2
let equal_m__t (module _ : Equal_m) equal_v t1 t2 = equal equal_v t1 t2
let hash_fold_m__t (type k) (module K : Hash_fold_m with type t = k) hash_fold_v state =
hash_fold_direct K.hash_fold_t hash_fold_v state
;;
module Poly = struct
type nonrec ('k, 'v) t = ('k, 'v, Comparator.Poly.comparator_witness) t
type nonrec ('k, 'v) tree = ('k, 'v) Tree0.t
type comparator_witness = Comparator.Poly.comparator_witness
include Accessors
let comparator = Comparator.Poly.comparator
let of_tree tree = { tree; comparator; length = Tree0.length tree }
include Using_comparator.Empty_without_value_restriction (Comparator.Poly)
let singleton a = Using_comparator.singleton ~comparator a
let of_alist a = Using_comparator.of_alist ~comparator a
let of_alist_or_error a = Using_comparator.of_alist_or_error ~comparator a
let of_alist_exn a = Using_comparator.of_alist_exn ~comparator a
let of_alist_multi a = Using_comparator.of_alist_multi ~comparator a
let of_alist_fold a ~init ~f = Using_comparator.of_alist_fold ~comparator a ~init ~f
let of_alist_reduce a ~f = Using_comparator.of_alist_reduce ~comparator a ~f
let of_sorted_array_unchecked a =
Using_comparator.of_sorted_array_unchecked ~comparator a
;;
let of_sorted_array a = Using_comparator.of_sorted_array ~comparator a
let of_iteri ~iteri = Using_comparator.of_iteri ~iteri ~comparator
let of_iteri_exn ~iteri = Using_comparator.of_iteri_exn ~iteri ~comparator
let of_increasing_iterator_unchecked ~len ~f =
Using_comparator.of_increasing_iterator_unchecked ~len ~f ~comparator
;;
let of_increasing_sequence seq = Using_comparator.of_increasing_sequence ~comparator seq
let of_sequence s = Using_comparator.of_sequence ~comparator s
let of_sequence_or_error s = Using_comparator.of_sequence_or_error ~comparator s
let of_sequence_exn s = Using_comparator.of_sequence_exn ~comparator s
let of_sequence_multi s = Using_comparator.of_sequence_multi ~comparator s
let of_sequence_fold s ~init ~f =
Using_comparator.of_sequence_fold ~comparator s ~init ~f
;;
let of_sequence_reduce s ~f = Using_comparator.of_sequence_reduce ~comparator s ~f
let of_list_with_key l ~get_key =
Using_comparator.of_list_with_key ~comparator l ~get_key
;;
let of_list_with_key_or_error l ~get_key =
Using_comparator.of_list_with_key_or_error ~comparator l ~get_key
;;
let of_list_with_key_exn l ~get_key =
Using_comparator.of_list_with_key_exn ~comparator l ~get_key
;;
let of_list_with_key_multi l ~get_key =
Using_comparator.of_list_with_key_multi ~comparator l ~get_key
;;
let map_keys t ~f = Using_comparator.map_keys ~comparator t ~f
let map_keys_exn t ~f = Using_comparator.map_keys_exn ~comparator t ~f
let transpose_keys t = Using_comparator.transpose_keys ~comparator t
end
| null | https://raw.githubusercontent.com/janestreet/base/1462b7d5458e96569275a1c673df968ecbf3342f/src/map.ml | ocaml | *********************************************************************
Objective Caml
for details.
*********************************************************************
[With_length.t] allows us to store length information on the stack while
keeping the tree global. This saves up to O(log n) blocks of heap allocation.
We must call [f] with increasing indexes, because the bin_prot reader in
Core.Map needs it.
height(Leaf) = 1 && 1 is not larger than hr + 2
height(Leaf) = 1 && 1 is not larger than hl + 2
specialization of [set'] for the case when [key] is less than all the existing keys
specialization of [set'] for the case when [key] is greater than all the
existing keys
[unit] to make pattern matching faster
Like [bal] but allows any difference in height between [l] and [r].
O(|height l - height r|)
named to preserve symbol in compiled binary
This assumes that min <= max, which is checked by the outer function.
k < min || k > max
if k < min, then this node and its left branch are outside our range
if k = min, then this node's left branch is outside our range
k > min
if k > max, we're done
similar to [concat_unchecked], and balances trees of arbitrary height differences
Use exception to avoid tree-rebuild in no-op case
equivalent to returning: Empty
[Enum.fold_diffs] is a correct implementation of this function, but is considerably
slower, as we have to allocate quite a lot of state to track enumeration of a tree.
Avoid if we can.
when x > 0
Our roots aren't the same key. Fallback to the slow mode. Trees with small
diffs will only do this on very small parts of the tree (hopefully - if the
overall root is rebalanced, we'll eat the whole cost, unfortunately.)
[marker] and [repackage] allow us to create "logical" options without actually
allocating any options. Passing [Found key value] to a function is equivalent to
passing [Some (key, value)]; passing [Missing () ()] is equivalent to passing
[None].
The type signature is explicit here to allow polymorphic recursion.
This is a base case (no recursive call).
We are guaranteed here that k' <> k.
This is the only recursive case.
[binary_search_two_sided_bounds] finds the (not necessarily distinct) keys in [t]
which most closely approach (but do not cross) [lower_bound] and [upper_bound], as
judged by [compare]. It returns [None] if no keys in [t] are within that range.
find the sexp of a duplicate key, so the error is narrowed to a key and not
the whole map
In theory the computation of length on-the-fly is not necessary here because it can
be done by wrapping the applicative [A] with length-computing logic. However,
introducing an applicative transformer like that makes the map benchmarks in
async_kernel/bench/src/bench_deferred_map.ml noticeably slower.
Exposing this function would make it very easy for the invariants
of this module to be broken.
Try to traverse the least amount possible to calculate the length,
using height as a heuristic.
Try to traverse the least amount possible to calculate the length,
using height as a heuristic.
Try to traverse the least amount possible to calculate the length,
using height as a heuristic.
[0] is used as the [length] argument everywhere in this module, since trees do not
have their lengths stored at the root, unlike maps. The values are discarded always.
Length computation makes this significantly slower than [merge_skewed] on a map
with a [length] field, but does preserve amount of allocation.
This calling convention of [~comparator ~comparator] is confusing. It is required
because [access_options] and [create_options] both demand a [~comparator] argument in
[Map.Using_comparator.Tree].
Making it less confusing would require some unnecessary complexity in signatures.
Better to just live with an undesirable interface in a function that will probably
never be called directly. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Apache 2.0 license . See .. /THIRD - PARTY.txt
open! Import
module List = List0
include Map_intf
module Finished_or_unfinished = struct
include Map_intf.Finished_or_unfinished
These two functions are tested in [ test_map.ml ] to make sure our use of
[ Stdlib.Obj.magic ] is correct and safe .
[Stdlib.Obj.magic] is correct and safe. *)
let of_continue_or_stop : Continue_or_stop.t -> t = Stdlib.Obj.magic
let to_continue_or_stop : t -> Continue_or_stop.t = Stdlib.Obj.magic
end
module Merge_element = struct
include Map_intf.Merge_element
let left = function
| `Right _ -> None
| `Left left | `Both (left, _) -> Some left
;;
let right = function
| `Left _ -> None
| `Right right | `Both (_, right) -> Some right
;;
let left_value t ~default =
match t with
| `Right _ -> default
| `Left left | `Both (left, _) -> left
;;
let right_value t ~default =
match t with
| `Left _ -> default
| `Right right | `Both (_, right) -> right
;;
let values t ~left_default ~right_default =
match t with
| `Left left -> left, right_default
| `Right right -> left_default, right
| `Both (left, right) -> left, right
;;
end
let with_return = With_return.with_return
exception Duplicate [@@deriving_inline sexp]
let () =
Sexplib0.Sexp_conv.Exn_converter.add [%extension_constructor Duplicate] (function
| Duplicate -> Sexplib0.Sexp.Atom "map.ml.Duplicate"
| _ -> assert false)
;;
[@@@end]
module With_length : sig
type 'a t = private
{ tree : 'a
[@global]
; length : int [@global]
}
val with_length : 'a -> int -> ('a t[@local])
val with_length_global : 'a -> int -> 'a t
val globalize : ('a t[@local]) -> 'a t
end = struct
type 'a t =
{ tree : 'a [@global]
; length : int [@global]
}
let with_length tree length = { tree; length }
let with_length_global tree length = { tree; length }
let globalize ({ tree; length } [@local]) = { tree; length }
end
open With_length
module Tree0 = struct
type ('k, 'v) t =
| Empty
| Leaf of 'k * 'v
| Node of ('k, 'v) t * 'k * 'v * ('k, 'v) t * int
type ('k, 'v) tree = ('k, 'v) t
let height = function
| Empty -> 0
| Leaf _ -> 1
| Node (_, _, _, _, h) -> h
;;
let invariants =
let in_range lower upper compare_key k =
(match lower with
| None -> true
| Some lower -> compare_key lower k < 0)
&&
match upper with
| None -> true
| Some upper -> compare_key k upper < 0
in
let rec loop lower upper compare_key t =
match t with
| Empty -> true
| Leaf (k, _) -> in_range lower upper compare_key k
| Node (l, k, _, r, h) ->
let hl = height l
and hr = height r in
abs (hl - hr) <= 2
&& h = max hl hr + 1
&& in_range lower upper compare_key k
&& loop lower (Some k) compare_key l
&& loop (Some k) upper compare_key r
in
fun t ~compare_key -> loop None None compare_key t
;;
precondition : |height(l ) - height(r)| < = 2
let create l x d r =
let hl = height l
and hr = height r in
if hl = 0 && hr = 0
then Leaf (x, d)
else Node (l, x, d, r, if hl >= hr then hl + 1 else hr + 1)
;;
let singleton key data = Leaf (key, data)
let of_increasing_iterator_unchecked ~len ~f =
let rec loop n ~f i : (_, _) t =
match n with
| 0 -> Empty
| 1 ->
let k, v = f i in
Leaf (k, v)
| 2 ->
let kl, vl = f i in
let k, v = f (i + 1) in
Node (Leaf (kl, vl), k, v, Empty, 2)
| 3 ->
let kl, vl = f i in
let k, v = f (i + 1) in
let kr, vr = f (i + 2) in
Node (Leaf (kl, vl), k, v, Leaf (kr, vr), 2)
| n ->
let left_length = n lsr 1 in
let right_length = n - left_length - 1 in
let left = loop left_length ~f i in
let k, v = f (i + left_length) in
let right = loop right_length ~f (i + left_length + 1) in
create left k v right
in
loop len ~f 0
;;
let of_sorted_array_unchecked array ~compare_key =
let array_length = Array.length array in
let next =
if array_length < 2
||
let k0, _ = array.(0) in
let k1, _ = array.(1) in
compare_key k0 k1 < 0
then fun i -> array.(i)
else fun i -> array.(array_length - 1 - i)
in
(with_length
(of_increasing_iterator_unchecked ~len:array_length ~f:next)
array_length)
;;
let of_sorted_array array ~compare_key =
match array with
| [||] | [| _ |] ->
Result.Ok (of_sorted_array_unchecked array ~compare_key |> globalize)
| _ ->
with_return (fun r ->
let increasing =
match compare_key (fst array.(0)) (fst array.(1)) with
| 0 -> r.return (Or_error.error_string "of_sorted_array: duplicated elements")
| i -> i < 0
in
for i = 1 to Array.length array - 2 do
match compare_key (fst array.(i)) (fst array.(i + 1)) with
| 0 -> r.return (Or_error.error_string "of_sorted_array: duplicated elements")
| i ->
if Poly.( <> ) (i < 0) increasing
then
r.return
(Or_error.error_string "of_sorted_array: elements are not ordered")
done;
Result.Ok (of_sorted_array_unchecked array ~compare_key |> globalize))
;;
precondition : |height(l ) - height(r)| < = 3
let bal l x d r =
let hl = height l in
let hr = height r in
if hl > hr + 2
then (
match l with
| Empty -> invalid_arg "Map.bal"
| Node (ll, lv, ld, lr, _) ->
if height ll >= height lr
then create ll lv ld (create lr x d r)
else (
match lr with
| Empty -> invalid_arg "Map.bal"
| Leaf (lrv, lrd) -> create (create ll lv ld Empty) lrv lrd (create Empty x d r)
| Node (lrl, lrv, lrd, lrr, _) ->
create (create ll lv ld lrl) lrv lrd (create lrr x d r)))
else if hr > hl + 2
then (
match r with
| Empty -> invalid_arg "Map.bal"
| Node (rl, rv, rd, rr, _) ->
if height rr >= height rl
then create (create l x d rl) rv rd rr
else (
match rl with
| Empty -> invalid_arg "Map.bal"
| Leaf (rlv, rld) -> create (create l x d Empty) rlv rld (create Empty rv rd rr)
| Node (rll, rlv, rld, rlr, _) ->
create (create l x d rll) rlv rld (create rlr rv rd rr)))
else create l x d r
;;
let empty = Empty
let is_empty = function
| Empty -> true
| _ -> false
;;
let raise_key_already_present ~key ~sexp_of_key =
Error.raise_s
(Sexp.message "[Map.add_exn] got key already present" [ "key", key |> sexp_of_key ])
;;
module Add_or_set = struct
type t =
| Add_exn_internal
| Add_exn
| Set
end
let rec find_and_add_or_set
t
~length
~key:x
~data
~compare_key
~sexp_of_key
~(add_or_set : Add_or_set.t)
=
match t with
| Empty -> (with_length (Leaf (x, data)) (length + 1))
| Leaf (v, d) ->
let c = compare_key x v in
if c = 0
then (
match add_or_set with
| Add_exn_internal -> (Exn.raise_without_backtrace Duplicate)
| Add_exn -> (raise_key_already_present ~key:x ~sexp_of_key)
| Set -> (with_length (Leaf (x, data)) length))
else if c < 0
then (with_length (Node (Leaf (x, data), v, d, Empty, 2)) (length + 1))
else (with_length (Node (Empty, v, d, Leaf (x, data), 2)) (length + 1))
| Node (l, v, d, r, h) ->
let c = compare_key x v in
if c = 0
then (
match add_or_set with
| Add_exn_internal -> (Exn.raise_without_backtrace Duplicate)
| Add_exn -> (raise_key_already_present ~key:x ~sexp_of_key)
| Set -> (with_length (Node (l, x, data, r, h)) length))
else if c < 0
then (
let { tree = l; length } =
find_and_add_or_set ~length ~key:x ~data l ~compare_key ~sexp_of_key ~add_or_set
in
(with_length (bal l v d r) length))
else (
let { tree = r; length } =
find_and_add_or_set ~length ~key:x ~data r ~compare_key ~sexp_of_key ~add_or_set
in
(with_length (bal l v d r) length))
;;
let rec set_min key data t =
match t with
| Empty -> Leaf (key, data)
| Leaf (v, d) -> Node (Leaf (key, data), v, d, Empty, 2)
| Node (l, v, d, r, _) ->
let l = set_min key data l in
bal l v d r
;;
let rec set_max t key data =
match t with
| Empty -> Leaf (key, data)
| Leaf (v, d) -> Node (Empty, v, d, Leaf (key, data), 2)
| Node (l, v, d, r, _) ->
let r = set_max r key data in
bal l v d r
;;
let add_exn t ~length ~key ~data ~compare_key ~sexp_of_key =
(find_and_add_or_set
t
~length
~key
~data
~compare_key
~sexp_of_key
~add_or_set:Add_exn)
;;
let add_exn_internal t ~length ~key ~data ~compare_key ~sexp_of_key =
(find_and_add_or_set
t
~length
~key
~data
~compare_key
~sexp_of_key
~add_or_set:Add_exn_internal)
;;
let set t ~length ~key ~data ~compare_key =
(find_and_add_or_set
t
~length
~key
~data
~compare_key
~sexp_of_key:(fun _ -> List [])
~add_or_set:Set)
;;
let set' t key data ~compare_key = (set t ~length:0 ~key ~data ~compare_key).tree
module Build_increasing = struct
module Fragment = struct
type nonrec ('k, 'v) t =
{ left_subtree : ('k, 'v) t
; key : 'k
; data : 'v
}
let singleton_to_tree_exn = function
| { left_subtree = Empty; key; data } -> singleton key data
| _ -> failwith "Map.singleton_to_tree_exn: not a singleton"
;;
let singleton ~key ~data = { left_subtree = Empty; key; data }
precondition : |height(l.left_subtree ) - height(r)| < = 2 ,
max_key(l ) < min_key(r )
max_key(l) < min_key(r)
*)
let collapse l r = create l.left_subtree l.key l.data r
precondition : |height(l.left_subtree ) - height(r.left_subtree)| < = 2 ,
max_key(l ) < min_key(r )
max_key(l) < min_key(r)
*)
let join l r = { r with left_subtree = collapse l r.left_subtree }
let max_key t = t.key
end
* Build trees from singletons in a balanced way by using skew binary encoding .
Each level contains trees of the same height , consecutive levels have consecutive
heights . There are no gaps . The first level are single keys .
Each level contains trees of the same height, consecutive levels have consecutive
heights. There are no gaps. The first level are single keys.
*)
type ('k, 'v) t =
| Zero of unit
| One of ('k, 'v) t * ('k, 'v) Fragment.t
| Two of ('k, 'v) t * ('k, 'v) Fragment.t * ('k, 'v) Fragment.t
let empty = Zero ()
let add_unchecked =
let rec go t x =
match t with
| Zero () -> One (t, x)
| One (t, y) -> Two (t, y, x)
| Two (t, z, y) -> One (go t (Fragment.join z y), x)
in
fun t ~key ~data -> go t (Fragment.singleton ~key ~data)
;;
let to_tree_unchecked =
let rec go t r =
match t with
| Zero () -> r
| One (t, l) -> go t (Fragment.collapse l r)
| Two (t, ll, l) -> go t (Fragment.collapse (Fragment.join ll l) r)
in
function
| Zero () -> Empty
| One (t, r) -> go t (Fragment.singleton_to_tree_exn r)
| Two (t, l, r) -> go (One (t, l)) (Fragment.singleton_to_tree_exn r)
;;
let max_key = function
| Zero () -> None
| One (_, r) | Two (_, _, r) -> Some (Fragment.max_key r)
;;
end
let of_increasing_sequence seq ~compare_key =
with_return (fun { return } ->
let { tree = builder; length } =
Sequence.fold
seq
~init:(with_length_global Build_increasing.empty 0)
~f:(fun { tree = builder; length } (key, data) ->
match Build_increasing.max_key builder with
| Some prev_key when compare_key prev_key key >= 0 ->
return
(Or_error.error_string "of_increasing_sequence: non-increasing key")
| _ ->
with_length_global
(Build_increasing.add_unchecked builder ~key ~data)
(length + 1))
in
Ok (with_length_global (Build_increasing.to_tree_unchecked builder) length))
;;
let rec join l k d r =
match l, r with
| Empty, _ -> set_min k d r
| _, Empty -> set_max l k d
| Leaf (lk, ld), _ -> set_min lk ld (set_min k d r)
| _, Leaf (rk, rd) -> set_max (set_max l k d) rk rd
| Node (ll, lk, ld, lr, lh), Node (rl, rk, rd, rr, rh) ->
[ bal ] requires height difference < = 3 .
if lh > rh + 3
[ height lr > = height r ] ,
therefore [ height ( join lr k d r ... ) ] is [ height rl + 1 ] or [ height rl ]
therefore the height difference with [ ll ] will be < = 3
therefore [height (join lr k d r ...)] is [height rl + 1] or [height rl]
therefore the height difference with [ll] will be <= 3 *)
then bal ll lk ld (join lr k d r)
else if rh > lh + 3
then bal (join l k d rl) rk rd rr
else bal l k d r
;;
let[@inline] rec split_gen t x ~compare_key =
match t with
| Empty -> Empty, None, Empty
| Leaf (k, d) ->
let cmp = compare_key k in
if cmp = 0
then Empty, Some (k, d), Empty
else if cmp < 0
then Empty, None, t
else t, None, Empty
| Node (l, k, d, r, _) ->
let cmp = compare_key k in
if cmp = 0
then l, Some (k, d), r
else if cmp < 0
then (
let ll, maybe, lr = split_gen l x ~compare_key in
ll, maybe, join lr k d r)
else (
let rl, maybe, rr = split_gen r x ~compare_key in
join l k d rl, maybe, rr)
;;
let split t x ~compare_key = split_gen t x ~compare_key:(fun y -> compare_key x y)
This function does not really reinsert [ x ] , but just arranges so that [ split ]
produces the equivalent tree in the first place .
produces the equivalent tree in the first place. *)
let split_and_reinsert_boundary t ~into x ~compare_key =
let left, boundary_opt, right =
split_gen
t
x
~compare_key:
(match into with
| `Left ->
fun y ->
(match compare_key x y with
| 0 -> 1
| res -> res)
| `Right ->
fun y ->
(match compare_key x y with
| 0 -> -1
| res -> res))
in
assert (Option.is_none boundary_opt);
left, right
;;
let split_range
t
~(lower_bound : 'a Maybe_bound.t)
~(upper_bound : 'a Maybe_bound.t)
~compare_key
=
if Maybe_bound.bounds_crossed
~compare:compare_key
~lower:lower_bound
~upper:upper_bound
then empty, empty, empty
else (
let left, mid_and_right =
match lower_bound with
| Unbounded -> empty, t
| Incl lb -> split_and_reinsert_boundary ~into:`Right t lb ~compare_key
| Excl lb -> split_and_reinsert_boundary ~into:`Left t lb ~compare_key
in
let mid, right =
match upper_bound with
| Unbounded -> mid_and_right, empty
| Incl lb -> split_and_reinsert_boundary ~into:`Left mid_and_right lb ~compare_key
| Excl lb ->
split_and_reinsert_boundary ~into:`Right mid_and_right lb ~compare_key
in
left, mid, right)
;;
let rec find t x ~compare_key =
match t with
| Empty -> None
| Leaf (v, d) -> if compare_key x v = 0 then Some d else None
| Node (l, v, d, r, _) ->
let c = compare_key x v in
if c = 0 then Some d else find (if c < 0 then l else r) x ~compare_key
;;
let add_multi t ~length ~key ~data ~compare_key =
let data = data :: Option.value (find t key ~compare_key) ~default:[] in
(set ~length ~key ~data t ~compare_key)
;;
let find_multi t x ~compare_key =
match find t x ~compare_key with
| None -> []
| Some l -> l
;;
let find_exn =
let if_not_found key ~sexp_of_key =
raise (Not_found_s (List [ Atom "Map.find_exn: not found"; sexp_of_key key ]))
in
let rec find_exn t x ~compare_key ~sexp_of_key =
match t with
| Empty -> if_not_found x ~sexp_of_key
| Leaf (v, d) -> if compare_key x v = 0 then d else if_not_found x ~sexp_of_key
| Node (l, v, d, r, _) ->
let c = compare_key x v in
if c = 0 then d else find_exn (if c < 0 then l else r) x ~compare_key ~sexp_of_key
in
find_exn
;;
let mem t x ~compare_key = Option.is_some (find t x ~compare_key)
let rec min_elt = function
| Empty -> None
| Leaf (k, d) -> Some (k, d)
| Node (Empty, k, d, _, _) -> Some (k, d)
| Node (l, _, _, _, _) -> min_elt l
;;
exception Map_min_elt_exn_of_empty_map [@@deriving_inline sexp]
let () =
Sexplib0.Sexp_conv.Exn_converter.add
[%extension_constructor Map_min_elt_exn_of_empty_map]
(function
| Map_min_elt_exn_of_empty_map ->
Sexplib0.Sexp.Atom "map.ml.Tree0.Map_min_elt_exn_of_empty_map"
| _ -> assert false)
;;
[@@@end]
exception Map_max_elt_exn_of_empty_map [@@deriving_inline sexp]
let () =
Sexplib0.Sexp_conv.Exn_converter.add
[%extension_constructor Map_max_elt_exn_of_empty_map]
(function
| Map_max_elt_exn_of_empty_map ->
Sexplib0.Sexp.Atom "map.ml.Tree0.Map_max_elt_exn_of_empty_map"
| _ -> assert false)
;;
[@@@end]
let min_elt_exn t =
match min_elt t with
| None -> raise Map_min_elt_exn_of_empty_map
| Some v -> v
;;
let rec max_elt = function
| Empty -> None
| Leaf (k, d) -> Some (k, d)
| Node (_, k, d, Empty, _) -> Some (k, d)
| Node (_, _, _, r, _) -> max_elt r
;;
let max_elt_exn t =
match max_elt t with
| None -> raise Map_max_elt_exn_of_empty_map
| Some v -> v
;;
let rec remove_min_elt t =
match t with
| Empty -> invalid_arg "Map.remove_min_elt"
| Leaf _ -> Empty
| Node (Empty, _, _, r, _) -> r
| Node (l, x, d, r, _) -> bal (remove_min_elt l) x d r
;;
let append ~lower_part ~upper_part ~compare_key =
match max_elt lower_part, min_elt upper_part with
| None, _ -> `Ok upper_part
| _, None -> `Ok lower_part
| Some (max_lower, _), Some (min_upper, v) when compare_key max_lower min_upper < 0 ->
let upper_part_without_min = remove_min_elt upper_part in
`Ok (join lower_part min_upper v upper_part_without_min)
| _ -> `Overlapping_key_ranges
;;
let fold_range_inclusive =
let rec go t ~min ~max ~init ~f ~compare_key =
match t with
| Empty -> init
| Leaf (k, d) ->
if compare_key k min < 0 || compare_key k max > 0
init
else f ~key:k ~data:d init
| Node (l, k, d, r, _) ->
let c_min = compare_key k min in
if c_min < 0
then
go r ~min ~max ~init ~f ~compare_key
else if c_min = 0
then
go r ~min ~max ~init:(f ~key:k ~data:d init) ~f ~compare_key
else (
let z = go l ~min ~max ~init ~f ~compare_key in
let c_max = compare_key k max in
if c_max > 0
then z
else (
let z = f ~key:k ~data:d z in
if k = max , then we fold in this one last value and we 're done
if c_max = 0 then z else go r ~min ~max ~init:z ~f ~compare_key))
in
fun t ~min ~max ~init ~f ~compare_key ->
if compare_key min max <= 0 then go t ~min ~max ~init ~f ~compare_key else init
;;
let range_to_alist t ~min ~max ~compare_key =
List.rev
(fold_range_inclusive
t
~min
~max
~init:[]
~f:(fun ~key ~data l -> (key, data) :: l)
~compare_key)
;;
preconditions :
- all elements in t1 are less than elements in t2
- |height(t1 ) - height(t2)| < = 2
- all elements in t1 are less than elements in t2
- |height(t1) - height(t2)| <= 2 *)
let concat_unchecked t1 t2 =
match t1, t2 with
| Empty, t -> t
| t, Empty -> t
| _, _ ->
let x, d = min_elt_exn t2 in
bal t1 x d (remove_min_elt t2)
;;
let concat_and_balance_unchecked t1 t2 =
match t1, t2 with
| Empty, t -> t
| t, Empty -> t
| _, _ ->
let x, d = min_elt_exn t2 in
join t1 x d (remove_min_elt t2)
;;
exception Remove_no_op
let remove t x ~length ~compare_key =
let rec remove_loop t x ~length ~compare_key =
match t with
| Empty -> (Exn.raise_without_backtrace Remove_no_op)
| Leaf (v, _) ->
if compare_key x v = 0
then (with_length Empty (length - 1))
else (Exn.raise_without_backtrace Remove_no_op)
| Node (l, v, d, r, _) ->
let c = compare_key x v in
if c = 0
then (with_length (concat_unchecked l r) (length - 1))
else if c < 0
then (
let { tree = l; length } = remove_loop l x ~length ~compare_key in
(with_length (bal l v d r) length))
else (
let { tree = r; length } = remove_loop r x ~length ~compare_key in
(with_length (bal l v d r) length))
in
try (remove_loop t x ~length ~compare_key) with
| Remove_no_op -> (with_length t length)
;;
exception Change_no_op
let change t key ~f ~length ~compare_key =
let rec change_core t key f =
match t with
| Empty ->
(match f None with
| None ->
(Exn.raise_without_backtrace Change_no_op)
| Some data -> (with_length (Leaf (key, data)) (length + 1)))
| Leaf (v, d) ->
let c = compare_key key v in
if c = 0
then (
match f (Some d) with
| None -> (with_length Empty (length - 1))
| Some d' -> (with_length (Leaf (v, d')) length))
else if c < 0
then (
let { tree = l; length } = change_core Empty key f in
(with_length (bal l v d Empty) length))
else (
let { tree = r; length } = change_core Empty key f in
(with_length (bal Empty v d r) length))
| Node (l, v, d, r, h) ->
let c = compare_key key v in
if c = 0
then (
match f (Some d) with
| None -> (with_length (concat_unchecked l r) (length - 1))
| Some data -> (with_length (Node (l, key, data, r, h)) length))
else if c < 0
then (
let { tree = l; length } = change_core l key f in
(with_length (bal l v d r) length))
else (
let { tree = r; length } = change_core r key f in
(with_length (bal l v d r) length))
in
try (change_core t key f) with
| Change_no_op -> (with_length t length)
;;
let update t key ~f ~length ~compare_key =
let rec update_core t key f =
match t with
| Empty ->
let data = f None in
(with_length (Leaf (key, data)) (length + 1))
| Leaf (v, d) ->
let c = compare_key key v in
if c = 0
then (
let d' = f (Some d) in
(with_length (Leaf (v, d')) length))
else if c < 0
then (
let { tree = l; length } = update_core Empty key f in
(with_length (bal l v d Empty) length))
else (
let { tree = r; length } = update_core Empty key f in
(with_length (bal Empty v d r) length))
| Node (l, v, d, r, h) ->
let c = compare_key key v in
if c = 0
then (
let data = f (Some d) in
(with_length (Node (l, key, data, r, h)) length))
else if c < 0
then (
let { tree = l; length } = update_core l key f in
(with_length (bal l v d r) length))
else (
let { tree = r; length } = update_core r key f in
(with_length (bal l v d r) length))
in
(update_core t key f)
;;
let remove_multi t key ~length ~compare_key =
(change t key ~length ~compare_key ~f:(function
| None | Some ([] | [ _ ]) -> None
| Some (_ :: (_ :: _ as non_empty_tail)) -> Some non_empty_tail))
;;
let rec iter_keys t ~f =
match t with
| Empty -> ()
| Leaf (v, _) -> f v
| Node (l, v, _, r, _) ->
iter_keys ~f l;
f v;
iter_keys ~f r
;;
let rec iter t ~f =
match t with
| Empty -> ()
| Leaf (_, d) -> f d
| Node (l, _, d, r, _) ->
iter ~f l;
f d;
iter ~f r
;;
let rec iteri t ~f =
match t with
| Empty -> ()
| Leaf (v, d) -> f ~key:v ~data:d
| Node (l, v, d, r, _) ->
iteri ~f l;
f ~key:v ~data:d;
iteri ~f r
;;
let iteri_until =
let rec iteri_until_loop t ~f : Continue_or_stop.t =
match t with
| Empty -> Continue
| Leaf (v, d) -> f ~key:v ~data:d
| Node (l, v, d, r, _) ->
(match iteri_until_loop ~f l with
| Stop -> Stop
| Continue ->
(match f ~key:v ~data:d with
| Stop -> Stop
| Continue -> iteri_until_loop ~f r))
in
fun t ~f -> Finished_or_unfinished.of_continue_or_stop (iteri_until_loop t ~f)
;;
let rec map t ~f =
match t with
| Empty -> Empty
| Leaf (v, d) -> Leaf (v, f d)
| Node (l, v, d, r, h) ->
let l' = map ~f l in
let d' = f d in
let r' = map ~f r in
Node (l', v, d', r', h)
;;
let rec mapi t ~f =
match t with
| Empty -> Empty
| Leaf (v, d) -> Leaf (v, f ~key:v ~data:d)
| Node (l, v, d, r, h) ->
let l' = mapi ~f l in
let d' = f ~key:v ~data:d in
let r' = mapi ~f r in
Node (l', v, d', r', h)
;;
let rec fold t ~init:accu ~f =
match t with
| Empty -> accu
| Leaf (v, d) -> f ~key:v ~data:d accu
| Node (l, v, d, r, _) -> fold ~f r ~init:(f ~key:v ~data:d (fold ~f l ~init:accu))
;;
let fold_until t ~init ~f ~finish =
let rec fold_until_loop t ~acc ~f : (_, _) Container.Continue_or_stop.t =
match t with
| Empty -> Continue acc
| Leaf (v, d) -> f ~key:v ~data:d acc
| Node (l, v, d, r, _) ->
(match fold_until_loop l ~acc ~f with
| Stop final -> Stop final
| Continue acc ->
(match f ~key:v ~data:d acc with
| Stop final -> Stop final
| Continue acc -> fold_until_loop r ~acc ~f))
in
match fold_until_loop t ~acc:init ~f with
| Continue acc -> finish acc [@nontail]
| Stop stop -> stop
;;
let rec fold_right t ~init:accu ~f =
match t with
| Empty -> accu
| Leaf (v, d) -> f ~key:v ~data:d accu
| Node (l, v, d, r, _) ->
fold_right ~f l ~init:(f ~key:v ~data:d (fold_right ~f r ~init:accu))
;;
let rec filter_mapi t ~f ~len =
match t with
| Empty -> Empty
| Leaf (v, d) ->
(match f ~key:v ~data:d with
| Some new_data -> Leaf (v, new_data)
| None ->
decr len;
Empty)
| Node (l, v, d, r, _) ->
let l' = filter_mapi l ~f ~len in
let new_data = f ~key:v ~data:d in
let r' = filter_mapi r ~f ~len in
(match new_data with
| Some new_data -> join l' v new_data r'
| None ->
decr len;
concat_and_balance_unchecked l' r')
;;
let rec filteri t ~f ~len =
match t with
| Empty -> Empty
| Leaf (v, d) ->
(match f ~key:v ~data:d with
| true -> t
| false ->
decr len;
Empty)
| Node (l, v, d, r, _) ->
let l' = filteri l ~f ~len in
let keep_data = f ~key:v ~data:d in
let r' = filteri r ~f ~len in
if phys_equal l l' && keep_data && phys_equal r r'
then t
else (
match keep_data with
| true -> join l' v d r'
| false ->
decr len;
concat_and_balance_unchecked l' r')
;;
let filter t ~f ~len = filteri t ~len ~f:(fun ~key:_ ~data -> f data) [@nontail]
let filter_keys t ~f ~len = filteri t ~len ~f:(fun ~key ~data:_ -> f key) [@nontail]
let filter_map t ~f ~len = filter_mapi t ~len ~f:(fun ~key:_ ~data -> f data) [@nontail]
let partition_mapi t ~f =
let t1, t2 =
fold
t
~init:(Build_increasing.empty, Build_increasing.empty)
~f:(fun ~key ~data (t1, t2) ->
match (f ~key ~data : _ Either.t) with
| First x -> Build_increasing.add_unchecked t1 ~key ~data:x, t2
| Second y -> t1, Build_increasing.add_unchecked t2 ~key ~data:y)
in
Build_increasing.to_tree_unchecked t1, Build_increasing.to_tree_unchecked t2
;;
let partition_map t ~f = partition_mapi t ~f:(fun ~key:_ ~data -> f data) [@nontail]
let partitioni_tf t ~f =
let rec loop t ~f =
match t with
| Empty -> Empty, Empty
| Leaf (v, d) ->
(match f ~key:v ~data:d with
| true -> t, Empty
| false -> Empty, t)
| Node (l, v, d, r, _) ->
let l't, l'f = loop l ~f in
let keep_data_t = f ~key:v ~data:d in
let r't, r'f = loop r ~f in
let mk l' keep_data r' =
if phys_equal l l' && keep_data && phys_equal r r'
then t
else (
match keep_data with
| true -> join l' v d r'
| false -> concat_and_balance_unchecked l' r')
in
mk l't keep_data_t r't, mk l'f (not keep_data_t) r'f
in
loop t ~f
;;
let partition_tf t ~f = partitioni_tf t ~f:(fun ~key:_ ~data -> f data) [@nontail]
module Enum = struct
type increasing
type decreasing
type ('k, 'v, 'direction) t =
| End
| More of 'k * 'v * ('k, 'v) tree * ('k, 'v, 'direction) t
let rec cons t (e : (_, _, increasing) t) : (_, _, increasing) t =
match t with
| Empty -> e
| Leaf (v, d) -> More (v, d, Empty, e)
| Node (l, v, d, r, _) -> cons l (More (v, d, r, e))
;;
let rec cons_right t (e : (_, _, decreasing) t) : (_, _, decreasing) t =
match t with
| Empty -> e
| Leaf (v, d) -> More (v, d, Empty, e)
| Node (l, v, d, r, _) -> cons_right r (More (v, d, l, e))
;;
let of_tree tree : (_, _, increasing) t = cons tree End
let of_tree_right tree : (_, _, decreasing) t = cons_right tree End
let starting_at_increasing t key compare : (_, _, increasing) t =
let rec loop t e =
match t with
| Empty -> e
| Leaf (v, d) -> loop (Node (Empty, v, d, Empty, 1)) e
| Node (_, v, _, r, _) when compare v key < 0 -> loop r e
| Node (l, v, d, r, _) -> loop l (More (v, d, r, e))
in
loop t End
;;
let starting_at_decreasing t key compare : (_, _, decreasing) t =
let rec loop t e =
match t with
| Empty -> e
| Leaf (v, d) -> loop (Node (Empty, v, d, Empty, 1)) e
| Node (l, v, _, _, _) when compare v key > 0 -> loop l e
| Node (l, v, d, r, _) -> loop r (More (v, d, l, e))
in
loop t End
;;
let step_deeper_exn tree e =
match tree with
| Empty -> assert false
| Leaf (v, d) -> Empty, More (v, d, Empty, e)
| Node (l, v, d, r, _) -> l, More (v, d, r, e)
;;
[ drop_phys_equal_prefix tree1 acc1 tree2 acc2 ] drops the largest physically - equal
prefix of and tree2 that they share , and then prepends the remaining data
into acc1 and acc2 , respectively .
This can be asymptotically faster than [ cons ] even if it skips a small proportion
of the tree because [ cons ] is always O(log(n ) ) in the size of the tree , while
this function is O(log(n / m ) ) where [ m ] is the size of the part of the tree that
is skipped .
prefix of tree1 and tree2 that they share, and then prepends the remaining data
into acc1 and acc2, respectively.
This can be asymptotically faster than [cons] even if it skips a small proportion
of the tree because [cons] is always O(log(n)) in the size of the tree, while
this function is O(log(n/m)) where [m] is the size of the part of the tree that
is skipped. *)
let rec drop_phys_equal_prefix tree1 acc1 tree2 acc2 =
if phys_equal tree1 tree2
then acc1, acc2
else (
let h2 = height tree2 in
let h1 = height tree1 in
if h2 = h1
then (
let tree1, acc1 = step_deeper_exn tree1 acc1 in
let tree2, acc2 = step_deeper_exn tree2 acc2 in
drop_phys_equal_prefix tree1 acc1 tree2 acc2)
else if h2 > h1
then (
let tree2, acc2 = step_deeper_exn tree2 acc2 in
drop_phys_equal_prefix tree1 acc1 tree2 acc2)
else (
let tree1, acc1 = step_deeper_exn tree1 acc1 in
drop_phys_equal_prefix tree1 acc1 tree2 acc2))
;;
let compare compare_key compare_data t1 t2 =
let rec loop t1 t2 =
match t1, t2 with
| End, End -> 0
| End, _ -> -1
| _, End -> 1
| More (v1, d1, r1, e1), More (v2, d2, r2, e2) ->
let c = compare_key v1 v2 in
if c <> 0
then c
else (
let c = compare_data d1 d2 in
if c <> 0
then c
else (
let e1, e2 = drop_phys_equal_prefix r1 e1 r2 e2 in
loop e1 e2))
in
loop t1 t2
;;
let equal compare_key data_equal t1 t2 =
let rec loop t1 t2 =
match t1, t2 with
| End, End -> true
| End, _ | _, End -> false
| More (v1, d1, r1, e1), More (v2, d2, r2, e2) ->
compare_key v1 v2 = 0
&& data_equal d1 d2
&&
let e1, e2 = drop_phys_equal_prefix r1 e1 r2 e2 in
loop e1 e2
in
loop t1 t2
;;
let rec fold ~init ~f = function
| End -> init
| More (key, data, tree, enum) ->
let next = f ~key ~data init in
fold (cons tree enum) ~init:next ~f
;;
let fold2 compare_key t1 t2 ~init ~f =
let rec loop t1 t2 curr =
match t1, t2 with
| End, End -> curr
| End, _ ->
fold t2 ~init:curr ~f:(fun ~key ~data acc -> f ~key ~data:(`Right data) acc) [@nontail
]
| _, End ->
fold t1 ~init:curr ~f:(fun ~key ~data acc -> f ~key ~data:(`Left data) acc) [@nontail
]
| More (k1, v1, tree1, enum1), More (k2, v2, tree2, enum2) ->
let compare_result = compare_key k1 k2 in
if compare_result = 0
then (
let next = f ~key:k1 ~data:(`Both (v1, v2)) curr in
loop (cons tree1 enum1) (cons tree2 enum2) next)
else if compare_result < 0
then (
let next = f ~key:k1 ~data:(`Left v1) curr in
loop (cons tree1 enum1) t2 next)
else (
let next = f ~key:k2 ~data:(`Right v2) curr in
loop t1 (cons tree2 enum2) next)
in
loop t1 t2 init [@nontail]
;;
let symmetric_diff t1 t2 ~compare_key ~data_equal =
let step state =
match state with
| End, End -> Sequence.Step.Done
| End, More (key, data, tree, enum) ->
Sequence.Step.Yield { value = key, `Right data; state = End, cons tree enum }
| More (key, data, tree, enum), End ->
Sequence.Step.Yield { value = key, `Left data; state = cons tree enum, End }
| (More (k1, v1, tree1, enum1) as left), (More (k2, v2, tree2, enum2) as right) ->
let compare_result = compare_key k1 k2 in
if compare_result = 0
then (
let next_state = drop_phys_equal_prefix tree1 enum1 tree2 enum2 in
if data_equal v1 v2
then Sequence.Step.Skip { state = next_state }
else Sequence.Step.Yield { value = k1, `Unequal (v1, v2); state = next_state })
else if compare_result < 0
then
Sequence.Step.Yield { value = k1, `Left v1; state = cons tree1 enum1, right }
else
Sequence.Step.Yield { value = k2, `Right v2; state = left, cons tree2 enum2 }
in
Sequence.unfold_step ~init:(drop_phys_equal_prefix t1 End t2 End) ~f:step
;;
let fold_symmetric_diff t1 t2 ~compare_key ~data_equal ~init ~f =
let add acc k v = f acc (k, `Right v) in
let remove acc k v = f acc (k, `Left v) in
let rec loop left right acc =
match left, right with
| End, enum ->
fold enum ~init:acc ~f:(fun ~key ~data acc -> add acc key data) [@nontail]
| enum, End ->
fold enum ~init:acc ~f:(fun ~key ~data acc -> remove acc key data) [@nontail]
| (More (k1, v1, tree1, enum1) as left), (More (k2, v2, tree2, enum2) as right) ->
let compare_result = compare_key k1 k2 in
if compare_result = 0
then (
let acc = if data_equal v1 v2 then acc else f acc (k1, `Unequal (v1, v2)) in
let enum1, enum2 = drop_phys_equal_prefix tree1 enum1 tree2 enum2 in
loop enum1 enum2 acc)
else if compare_result < 0
then (
let acc = remove acc k1 v1 in
loop (cons tree1 enum1) right acc)
else (
let acc = add acc k2 v2 in
loop left (cons tree2 enum2) acc)
in
let left, right = drop_phys_equal_prefix t1 End t2 End in
loop left right init [@nontail]
;;
end
let to_sequence_increasing comparator ~from_key t =
let next enum =
match enum with
| Enum.End -> Sequence.Step.Done
| Enum.More (k, v, t, e) ->
Sequence.Step.Yield { value = k, v; state = Enum.cons t e }
in
let init =
match from_key with
| None -> Enum.of_tree t
| Some key -> Enum.starting_at_increasing t key comparator.Comparator.compare
in
Sequence.unfold_step ~init ~f:next
;;
let to_sequence_decreasing comparator ~from_key t =
let next enum =
match enum with
| Enum.End -> Sequence.Step.Done
| Enum.More (k, v, t, e) ->
Sequence.Step.Yield { value = k, v; state = Enum.cons_right t e }
in
let init =
match from_key with
| None -> Enum.of_tree_right t
| Some key -> Enum.starting_at_decreasing t key comparator.Comparator.compare
in
Sequence.unfold_step ~init ~f:next
;;
let to_sequence
comparator
?(order = `Increasing_key)
?keys_greater_or_equal_to
?keys_less_or_equal_to
t
=
let inclusive_bound side t bound =
let compare_key = comparator.Comparator.compare in
let l, maybe, r = split t bound ~compare_key in
let t = side (l, r) in
match maybe with
| None -> t
| Some (key, data) -> set' t key data ~compare_key
in
match order with
| `Increasing_key ->
let t = Option.fold keys_less_or_equal_to ~init:t ~f:(inclusive_bound fst) in
to_sequence_increasing comparator ~from_key:keys_greater_or_equal_to t
| `Decreasing_key ->
let t = Option.fold keys_greater_or_equal_to ~init:t ~f:(inclusive_bound snd) in
to_sequence_decreasing comparator ~from_key:keys_less_or_equal_to t
;;
let compare compare_key compare_data t1 t2 =
let e1, e2 = Enum.drop_phys_equal_prefix t1 End t2 End in
Enum.compare compare_key compare_data e1 e2
;;
let equal compare_key compare_data t1 t2 =
let e1, e2 = Enum.drop_phys_equal_prefix t1 End t2 End in
Enum.equal compare_key compare_data e1 e2
;;
let iter2 t1 t2 ~f ~compare_key =
Enum.fold2
compare_key
(Enum.of_tree t1)
(Enum.of_tree t2)
~init:()
~f:(fun ~key ~data () -> f ~key ~data) [@nontail]
;;
let fold2 t1 t2 ~init ~f ~compare_key =
Enum.fold2 compare_key (Enum.of_tree t1) (Enum.of_tree t2) ~f ~init
;;
let symmetric_diff = Enum.symmetric_diff
let fold_symmetric_diff t1 t2 ~compare_key ~data_equal ~init ~f =
let slow x y ~init = Enum.fold_symmetric_diff x y ~compare_key ~data_equal ~f ~init in
let add acc k v = f acc (k, `Right v) in
let remove acc k v = f acc (k, `Left v) in
let delta acc k v v' = if data_equal v v' then acc else f acc (k, `Unequal (v, v')) in
If two trees have the same structure at the root ( and the same key , if they 're
[ ) we can trivially diff each subpart in obvious ways .
[Node]s) we can trivially diff each subpart in obvious ways. *)
let rec loop t t' acc =
if phys_equal t t'
then acc
else (
match t, t' with
| Empty, new_vals ->
fold new_vals ~init:acc ~f:(fun ~key ~data acc -> add acc key data) [@nontail]
| old_vals, Empty ->
fold old_vals ~init:acc ~f:(fun ~key ~data acc -> remove acc key data) [@nontail]
| Leaf (k, v), Leaf (k', v') ->
(match compare_key k k' with
| x when x = 0 -> delta acc k v v'
| x when x < 0 ->
let acc = remove acc k v in
add acc k' v'
let acc = add acc k' v' in
remove acc k v)
| Node (l, k, v, r, _), Node (l', k', v', r', _) when compare_key k k' = 0 ->
let acc = loop l l' acc in
let acc = delta acc k v v' in
loop r r' acc
| Node _, Node _ | Node _, Leaf _ | Leaf _, Node _ -> slow t t' ~init:acc)
in
loop t1 t2 init [@nontail]
;;
let rec length = function
| Empty -> 0
| Leaf _ -> 1
| Node (l, _, _, r, _) -> length l + length r + 1
;;
let hash_fold_t_ignoring_structure hash_fold_key hash_fold_data state t =
fold
t
~init:(hash_fold_int state (length t))
~f:(fun ~key ~data state -> hash_fold_data (hash_fold_key state key) data)
;;
let keys t = fold_right ~f:(fun ~key ~data:_ list -> key :: list) t ~init:[]
let data t = fold_right ~f:(fun ~key:_ ~data list -> data :: list) t ~init:[]
module type Foldable = sig
val name : string
type 'a t
val fold : 'a t -> init:'acc -> f:(('acc -> 'a -> 'acc)[@local]) -> 'acc
end
let[@inline always] of_foldable' ~fold foldable ~init ~f ~compare_key =
(fold [@inlined hint])
foldable
~init:(with_length_global empty 0)
~f:(fun { tree = accum; length } (key, data) ->
let prev_data =
match find accum key ~compare_key with
| None -> init
| Some prev -> prev
in
let data = f prev_data data in
(set accum ~length ~key ~data ~compare_key |> globalize) [@nontail]) [@nontail]
;;
module Of_foldable (M : Foldable) = struct
let of_foldable_fold foldable ~init ~f ~compare_key =
of_foldable' ~fold:M.fold foldable ~init ~f ~compare_key
;;
let of_foldable_reduce foldable ~f ~compare_key =
M.fold
foldable
~init:(with_length_global empty 0)
~f:(fun { tree = accum; length } (key, data) ->
let new_data =
match find accum key ~compare_key with
| None -> data
| Some prev -> f prev data
in
(set accum ~length ~key ~data:new_data ~compare_key |> globalize) [@nontail]) [@nontail
]
;;
let of_foldable foldable ~compare_key =
with_return (fun r ->
let map =
M.fold
foldable
~init:(with_length_global empty 0)
~f:(fun { tree = t; length } (key, data) ->
let ({ tree = _; length = length' } as acc) =
set ~length ~key ~data t ~compare_key
in
if length = length'
then r.return (`Duplicate_key key)
else globalize acc [@nontail])
in
`Ok map)
;;
let of_foldable_or_error foldable ~comparator =
match of_foldable foldable ~compare_key:comparator.Comparator.compare with
| `Ok x -> Result.Ok x
| `Duplicate_key key ->
Or_error.error
("Map.of_" ^ M.name ^ "_or_error: duplicate key")
key
comparator.sexp_of_t
;;
let of_foldable_exn foldable ~comparator =
match of_foldable foldable ~compare_key:comparator.Comparator.compare with
| `Ok x -> x
| `Duplicate_key key ->
Error.create ("Map.of_" ^ M.name ^ "_exn: duplicate key") key comparator.sexp_of_t
|> Error.raise
;;
Reverse the input , then fold from left to right . The resulting map uses the first
instance of each key from the input list . The relative ordering of elements in each
output list is the same as in the input list .
instance of each key from the input list. The relative ordering of elements in each
output list is the same as in the input list. *)
let of_foldable_multi foldable ~compare_key =
let alist = M.fold foldable ~init:[] ~f:(fun l x -> x :: l) in
of_foldable' alist ~fold:List.fold ~init:[] ~f:(fun l x -> x :: l) ~compare_key
;;
end
module Of_alist = Of_foldable (struct
let name = "alist"
type 'a t = 'a list
let fold = List.fold
end)
let of_alist_fold = Of_alist.of_foldable_fold
let of_alist_reduce = Of_alist.of_foldable_reduce
let of_alist = Of_alist.of_foldable
let of_alist_or_error = Of_alist.of_foldable_or_error
let of_alist_exn = Of_alist.of_foldable_exn
let of_alist_multi = Of_alist.of_foldable_multi
module Of_sequence = Of_foldable (struct
let name = "sequence"
type 'a t = 'a Sequence.t
let fold = Sequence.fold
end)
let of_sequence_fold = Of_sequence.of_foldable_fold
let of_sequence_reduce = Of_sequence.of_foldable_reduce
let of_sequence = Of_sequence.of_foldable
let of_sequence_or_error = Of_sequence.of_foldable_or_error
let of_sequence_exn = Of_sequence.of_foldable_exn
let of_sequence_multi = Of_sequence.of_foldable_multi
let of_list_with_key list ~get_key ~compare_key =
with_return (fun r ->
let map =
List.fold
list
~init:(with_length_global empty 0)
~f:(fun { tree = t; length } data ->
let key = get_key data in
let ({ tree = _; length = new_length } as acc) =
set ~length ~key ~data t ~compare_key
in
if length = new_length
then r.return (`Duplicate_key key)
else globalize acc [@nontail])
in
`Ok map) [@nontail]
;;
let of_list_with_key_or_error list ~get_key ~comparator =
match of_list_with_key list ~get_key ~compare_key:comparator.Comparator.compare with
| `Ok x -> Result.Ok x
| `Duplicate_key key ->
Or_error.error
"Map.of_list_with_key_or_error: duplicate key"
key
comparator.sexp_of_t
;;
let of_list_with_key_exn list ~get_key ~comparator =
match of_list_with_key list ~get_key ~compare_key:comparator.Comparator.compare with
| `Ok x -> x
| `Duplicate_key key ->
Error.create "Map.of_list_with_key_exn: duplicate key" key comparator.sexp_of_t
|> Error.raise
;;
let of_list_with_key_multi list ~get_key ~compare_key =
let list = List.rev list in
List.fold list ~init:(with_length_global empty 0) ~f:(fun { tree = t; length } data ->
let key = get_key data in
(update t key ~length ~compare_key ~f:(fun option ->
let list = Option.value option ~default:[] in
data :: list)
|> globalize) [@nontail]) [@nontail]
;;
let for_all t ~f =
with_return (fun r ->
iter t ~f:(fun data -> if not (f data) then r.return false);
true) [@nontail]
;;
let for_alli t ~f =
with_return (fun r ->
iteri t ~f:(fun ~key ~data -> if not (f ~key ~data) then r.return false);
true) [@nontail]
;;
let exists t ~f =
with_return (fun r ->
iter t ~f:(fun data -> if f data then r.return true);
false) [@nontail]
;;
let existsi t ~f =
with_return (fun r ->
iteri t ~f:(fun ~key ~data -> if f ~key ~data then r.return true);
false) [@nontail]
;;
let count t ~f =
fold t ~init:0 ~f:(fun ~key:_ ~data acc -> if f data then acc + 1 else acc) [@nontail]
;;
let counti t ~f =
fold t ~init:0 ~f:(fun ~key ~data acc -> if f ~key ~data then acc + 1 else acc) [@nontail
]
;;
let to_alist ?(key_order = `Increasing) t =
match key_order with
| `Increasing -> fold_right t ~init:[] ~f:(fun ~key ~data x -> (key, data) :: x)
| `Decreasing -> fold t ~init:[] ~f:(fun ~key ~data x -> (key, data) :: x)
;;
let merge t1 t2 ~f ~compare_key =
let elts = Uniform_array.unsafe_create_uninitialized ~len:(length t1 + length t2) in
let i = ref 0 in
iter2 t1 t2 ~compare_key ~f:(fun ~key ~data:values ->
match f ~key values with
| Some value ->
Uniform_array.set elts !i (key, value);
incr i
| None -> ());
let len = !i in
let get i = Uniform_array.get elts i in
let tree = of_increasing_iterator_unchecked ~len ~f:get in
(with_length tree len)
;;
let merge_skewed =
let merge_large_first length_large t_large t_small ~call ~combine ~compare_key =
fold
t_small
~init:(with_length_global t_large length_large)
~f:(fun ~key ~data:data' { tree = t; length } ->
(update t key ~length ~compare_key ~f:(function
| None -> data'
| Some data -> call combine ~key data data')
|> globalize) [@nontail]) [@nontail]
in
let call f ~key x y = f ~key x y in
let swap f ~key x y = f ~key y x in
fun t1 t2 ~length1 ~length2 ~combine ~compare_key ->
if length2 <= length1
then merge_large_first length1 t1 t2 ~call ~combine ~compare_key
else merge_large_first length2 t2 t1 ~call:swap ~combine ~compare_key
;;
module Closest_key_impl = struct
type ('k, 'v, 'k_opt, 'v_opt) marker =
| Missing : ('k, 'v, unit, unit) marker
| Found : ('k, 'v, 'k, 'v) marker
let repackage
(type k v k_opt v_opt)
(marker : (k, v, k_opt, v_opt) marker)
(k : k_opt)
(v : v_opt)
: (k * v) option
=
match marker with
| Missing -> None
| Found -> Some (k, v)
;;
let rec loop :
'k 'v 'k_opt 'v_opt.
('k, 'v) tree
-> [ `Greater_or_equal_to | `Greater_than | `Less_or_equal_to | `Less_than ]
-> 'k
-> compare_key:('k -> 'k -> int)
-> ('k, 'v, 'k_opt, 'v_opt) marker
-> 'k_opt
-> 'v_opt
-> ('k * 'v) option
=
fun t dir k ~compare_key found_marker found_key found_value ->
match t with
| Empty -> repackage found_marker found_key found_value
| Leaf (k', v') ->
let c = compare_key k' k in
if match dir with
| `Greater_or_equal_to -> c >= 0
| `Greater_than -> c > 0
| `Less_or_equal_to -> c <= 0
| `Less_than -> c < 0
then Some (k', v')
else repackage found_marker found_key found_value
| Node (l, k', v', r, _) ->
let c = compare_key k' k in
if c = 0
then (
match dir with
| `Greater_or_equal_to | `Less_or_equal_to -> Some (k', v')
| `Greater_than ->
if is_empty r then repackage found_marker found_key found_value else min_elt r
| `Less_than ->
if is_empty l then repackage found_marker found_key found_value else max_elt l)
else (
match dir with
| `Greater_or_equal_to | `Greater_than ->
if c > 0
then loop l dir k ~compare_key Found k' v'
else loop r dir k ~compare_key found_marker found_key found_value
| `Less_or_equal_to | `Less_than ->
if c < 0
then loop r dir k ~compare_key Found k' v'
else loop l dir k ~compare_key found_marker found_key found_value)
;;
let closest_key t dir k ~compare_key = loop t dir k ~compare_key Missing () ()
end
let closest_key = Closest_key_impl.closest_key
let rec rank t k ~compare_key =
match t with
| Empty -> None
| Leaf (k', _) -> if compare_key k' k = 0 then Some 0 else None
| Node (l, k', _, r, _) ->
let c = compare_key k' k in
if c = 0
then Some (length l)
else if c > 0
then rank l k ~compare_key
else Option.map (rank r k ~compare_key) ~f:(fun rank -> rank + 1 + length l)
;;
this could be implemented using [ Sequence ] interface but the following implementation
allocates only 2 words and does n't require write - barrier
allocates only 2 words and doesn't require write-barrier *)
let rec nth' num_to_search = function
| Empty -> None
| Leaf (k, v) ->
if !num_to_search = 0
then Some (k, v)
else (
decr num_to_search;
None)
| Node (l, k, v, r, _) ->
(match nth' num_to_search l with
| Some _ as some -> some
| None ->
if !num_to_search = 0
then Some (k, v)
else (
decr num_to_search;
nth' num_to_search r))
;;
let nth t n = nth' (ref n) t
let rec find_first_satisfying t ~f =
match t with
| Empty -> None
| Leaf (k, v) -> if f ~key:k ~data:v then Some (k, v) else None
| Node (l, k, v, r, _) ->
if f ~key:k ~data:v
then (
match find_first_satisfying l ~f with
| None -> Some (k, v)
| Some _ as x -> x)
else find_first_satisfying r ~f
;;
let rec find_last_satisfying t ~f =
match t with
| Empty -> None
| Leaf (k, v) -> if f ~key:k ~data:v then Some (k, v) else None
| Node (l, k, v, r, _) ->
if f ~key:k ~data:v
then (
match find_last_satisfying r ~f with
| None -> Some (k, v)
| Some _ as x -> x)
else find_last_satisfying l ~f
;;
let binary_search t ~compare how v =
match how with
| `Last_strictly_less_than ->
find_last_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v < 0) [@nontail]
| `Last_less_than_or_equal_to ->
find_last_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v <= 0) [@nontail]
| `First_equal_to ->
(match find_first_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v >= 0) with
| Some (key, data) as pair when compare ~key ~data v = 0 -> pair
| None | Some _ -> None)
| `Last_equal_to ->
(match find_last_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v <= 0) with
| Some (key, data) as pair when compare ~key ~data v = 0 -> pair
| None | Some _ -> None)
| `First_greater_than_or_equal_to ->
find_first_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v >= 0) [@nontail]
| `First_strictly_greater_than ->
find_first_satisfying t ~f:(fun ~key ~data -> compare ~key ~data v > 0) [@nontail]
;;
let binary_search_segmented t ~segment_of how =
let is_left ~key ~data =
match segment_of ~key ~data with
| `Left -> true
| `Right -> false
in
let is_right ~key ~data = not (is_left ~key ~data) in
match how with
| `Last_on_left -> find_last_satisfying t ~f:is_left [@nontail]
| `First_on_right -> find_first_satisfying t ~f:is_right [@nontail]
;;
[ binary_search_one_sided_bound ] finds the key in [ t ] which satisfies [ maybe_bound ]
and the relevant one of [ if_exclusive ] or [ if_inclusive ] , as judged by [ compare ] .
and the relevant one of [if_exclusive] or [if_inclusive], as judged by [compare]. *)
let binary_search_one_sided_bound t maybe_bound ~compare ~if_exclusive ~if_inclusive =
let find_bound t how bound ~compare : _ Maybe_bound.t option =
match binary_search t how bound ~compare with
| Some (bound, _) -> Some (Incl bound)
| None -> None
in
match (maybe_bound : _ Maybe_bound.t) with
| Excl bound -> find_bound t if_exclusive bound ~compare
| Incl bound -> find_bound t if_inclusive bound ~compare
| Unbounded -> Some Unbounded
;;
let binary_search_two_sided_bounds t ~compare ~lower_bound ~upper_bound =
let find_lower_bound t maybe_bound ~compare =
binary_search_one_sided_bound
t
maybe_bound
~compare
~if_exclusive:`First_strictly_greater_than
~if_inclusive:`First_greater_than_or_equal_to
in
let find_upper_bound t maybe_bound ~compare =
binary_search_one_sided_bound
t
maybe_bound
~compare
~if_exclusive:`Last_strictly_less_than
~if_inclusive:`Last_less_than_or_equal_to
in
match find_lower_bound t lower_bound ~compare with
| None -> None
| Some lower_bound ->
(match find_upper_bound t upper_bound ~compare with
| None -> None
| Some upper_bound -> Some (lower_bound, upper_bound))
;;
type ('k, 'v) acc =
{ mutable bad_key : 'k option
; mutable map_length : ('k, 'v) t With_length.t
}
let of_iteri ~iteri ~compare_key =
let acc = { bad_key = None; map_length = with_length_global empty 0 } in
iteri ~f:(fun ~key ~data ->
let { tree = map; length } = acc.map_length in
let ({ tree = _; length = length' } as pair) =
set ~length ~key ~data map ~compare_key
in
if length = length' && Option.is_none acc.bad_key
then acc.bad_key <- Some key
else acc.map_length <- globalize pair);
match acc.bad_key with
| None -> `Ok acc.map_length
| Some key -> `Duplicate_key key
;;
let of_iteri_exn ~iteri ~(comparator : _ Comparator.t) =
match of_iteri ~iteri ~compare_key:comparator.compare with
| `Ok v -> v
| `Duplicate_key key ->
Error.create "Map.of_iteri_exn: duplicate key" key comparator.sexp_of_t
|> Error.raise
;;
let t_of_sexp_direct key_of_sexp value_of_sexp sexp ~(comparator : _ Comparator.t) =
let alist = list_of_sexp (pair_of_sexp key_of_sexp value_of_sexp) sexp in
let compare_key = comparator.compare in
match of_alist alist ~compare_key with
| `Ok v -> v
| `Duplicate_key k ->
let alist_sexps = list_of_sexp (pair_of_sexp Fn.id Fn.id) sexp in
let found_first_k = ref false in
List.iter2_ok alist alist_sexps ~f:(fun (k2, _) (k2_sexp, _) ->
if compare_key k k2 = 0
then
if !found_first_k
then of_sexp_error "Map.t_of_sexp_direct: duplicate key" k2_sexp
else found_first_k := true);
assert false
;;
let sexp_of_t sexp_of_key sexp_of_value t =
let f ~key ~data acc = Sexp.List [ sexp_of_key key; sexp_of_value data ] :: acc in
Sexp.List (fold_right ~f t ~init:[])
;;
let combine_errors t ~sexp_of_key =
let oks, errors = partition_map t ~f:Result.to_either in
if is_empty errors
then Ok oks
else Or_error.error_s (sexp_of_t sexp_of_key Error.sexp_of_t errors)
;;
let map_keys
t1
~f
~comparator:({ compare = compare_key; sexp_of_t = sexp_of_key } : _ Comparator.t)
=
with_return (fun { return } ->
`Ok
(fold
t1
~init:(with_length_global empty 0)
~f:(fun ~key ~data { tree = t2; length } ->
let key = f key in
try
add_exn_internal t2 ~length ~key ~data ~compare_key ~sexp_of_key
|> globalize
with
| Duplicate -> return (`Duplicate_key key)))) [@nontail]
;;
let map_keys_exn t ~f ~comparator =
match map_keys t ~f ~comparator with
| `Ok result -> result
| `Duplicate_key key ->
let sexp_of_key = comparator.Comparator.sexp_of_t in
Error.raise_s
(Sexp.message "Map.map_keys_exn: duplicate key" [ "key", key |> sexp_of_key ])
;;
let transpose_keys ~outer_comparator ~inner_comparator outer_t =
fold
outer_t
~init:(with_length_global empty 0)
~f:(fun ~key:outer_key ~data:inner_t acc ->
fold
inner_t
~init:acc
~f:(fun ~key:inner_key ~data { tree = acc; length = acc_len } ->
(update
acc
inner_key
~length:acc_len
~compare_key:inner_comparator.Comparator.compare
~f:(function
| None -> with_length_global (singleton outer_key data) 1
| Some { tree = elt; length = elt_len } ->
(set
elt
~key:outer_key
~data
~length:elt_len
~compare_key:outer_comparator.Comparator.compare
|> globalize) [@nontail])
|> globalize) [@nontail]))
;;
module Make_applicative_traversals (A : Applicative.Lazy_applicative) = struct
let rec mapi t ~f =
match t with
| Empty -> A.return Empty
| Leaf (v, d) -> A.map (f ~key:v ~data:d) ~f:(fun new_data -> Leaf (v, new_data))
| Node (l, v, d, r, h) ->
let l' = A.of_thunk (fun () -> mapi ~f l) in
let d' = f ~key:v ~data:d in
let r' = A.of_thunk (fun () -> mapi ~f r) in
A.map3 l' d' r' ~f:(fun l' d' r' -> Node (l', v, d', r', h))
;;
let filter_mapi t ~f =
let rec tree_filter_mapi t ~f =
match t with
| Empty -> A.return (with_length_global Empty 0)
| Leaf (v, d) ->
A.map (f ~key:v ~data:d) ~f:(function
| Some new_data -> with_length_global (Leaf (v, new_data)) 1
| None -> with_length_global Empty 0)
| Node (l, v, d, r, _) ->
A.map3
(A.of_thunk (fun () -> tree_filter_mapi l ~f))
(f ~key:v ~data:d)
(A.of_thunk (fun () -> tree_filter_mapi r ~f))
~f:
(fun { tree = l'; length = l_len } new_data { tree = r'; length = r_len } ->
match new_data with
| Some new_data ->
with_length_global (join l' v new_data r') (l_len + r_len + 1)
| None ->
with_length_global (concat_and_balance_unchecked l' r') (l_len + r_len))
in
tree_filter_mapi t ~f
;;
end
end
type ('k, 'v, 'comparator) t =
[ comparator ] is the first field so that polymorphic equality fails on a map due
to the functional value in the comparator .
Note that this does not affect polymorphic [ compare ] : that still produces
nonsense .
to the functional value in the comparator.
Note that this does not affect polymorphic [compare]: that still produces
nonsense. *)
comparator : ('k, 'comparator) Comparator.t
; tree : ('k, 'v) Tree0.t
; length : int
}
type ('k, 'v, 'comparator) tree = ('k, 'v) Tree0.t
let compare_key t = t.comparator.Comparator.compare
let like { tree = _; length = _; comparator } ({ tree; length } : _ With_length.t) =
{ tree; length; comparator }
;;
let like_maybe_no_op
({ tree = old_tree; length = _; comparator } as old_t)
({ tree; length } : _ With_length.t)
=
if phys_equal old_tree tree then old_t else { tree; length; comparator }
;;
let with_same_length { tree = _; comparator; length } tree = { tree; comparator; length }
let of_like_tree t tree = { tree; comparator = t.comparator; length = Tree0.length tree }
let of_like_tree_maybe_no_op t tree =
if phys_equal t.tree tree
then t
else { tree; comparator = t.comparator; length = Tree0.length tree }
;;
let of_tree ~comparator tree = { tree; comparator; length = Tree0.length tree }
let of_tree_unsafe ~comparator ~length tree = { tree; comparator; length }
module Accessors = struct
let comparator t = t.comparator
let to_tree t = t.tree
let invariants t =
Tree0.invariants t.tree ~compare_key:(compare_key t) && Tree0.length t.tree = t.length
;;
let is_empty t = Tree0.is_empty t.tree
let length t = t.length
let set t ~key ~data =
like
t
(Tree0.set t.tree ~length:t.length ~key ~data ~compare_key:(compare_key t))
[@nontail]
;;
let add_exn t ~key ~data =
like
t
(Tree0.add_exn
t.tree
~length:t.length
~key
~data
~compare_key:(compare_key t)
~sexp_of_key:t.comparator.sexp_of_t) [@nontail]
;;
let add_exn_internal t ~key ~data =
like
t
(Tree0.add_exn_internal
t.tree
~length:t.length
~key
~data
~compare_key:(compare_key t)
~sexp_of_key:t.comparator.sexp_of_t) [@nontail]
;;
let add t ~key ~data =
match add_exn_internal t ~key ~data with
| result -> `Ok result
| exception Duplicate -> `Duplicate
;;
let add_multi t ~key ~data =
like
t
(Tree0.add_multi t.tree ~length:t.length ~key ~data ~compare_key:(compare_key t))
[@nontail]
;;
let remove_multi t key =
like
t
(Tree0.remove_multi t.tree ~length:t.length key ~compare_key:(compare_key t))
[@nontail]
;;
let find_multi t key = Tree0.find_multi t.tree key ~compare_key:(compare_key t)
let change t key ~f =
like
t
(Tree0.change t.tree key ~f ~length:t.length ~compare_key:(compare_key t))
[@nontail]
;;
let update t key ~f =
like
t
(Tree0.update t.tree key ~f ~length:t.length ~compare_key:(compare_key t))
[@nontail]
;;
let find_exn t key =
Tree0.find_exn
t.tree
key
~compare_key:(compare_key t)
~sexp_of_key:t.comparator.sexp_of_t
;;
let find t key = Tree0.find t.tree key ~compare_key:(compare_key t)
let remove t key =
like_maybe_no_op
t
(Tree0.remove t.tree key ~length:t.length ~compare_key:(compare_key t)) [@nontail]
;;
let mem t key = Tree0.mem t.tree key ~compare_key:(compare_key t)
let iter_keys t ~f = Tree0.iter_keys t.tree ~f
let iter t ~f = Tree0.iter t.tree ~f
let iteri t ~f = Tree0.iteri t.tree ~f
let iteri_until t ~f = Tree0.iteri_until t.tree ~f
let iter2 t1 t2 ~f = Tree0.iter2 t1.tree t2.tree ~f ~compare_key:(compare_key t1)
let map t ~f = with_same_length t (Tree0.map t.tree ~f)
let mapi t ~f = with_same_length t (Tree0.mapi t.tree ~f)
let fold t ~init ~f = Tree0.fold t.tree ~f ~init
let fold_until t ~init ~f ~finish = Tree0.fold_until t.tree ~init ~f ~finish
let fold_right t ~init ~f = Tree0.fold_right t.tree ~f ~init
let fold2 t1 t2 ~init ~f =
Tree0.fold2 t1.tree t2.tree ~init ~f ~compare_key:(compare_key t1)
;;
let filter_keys t ~f =
let len = (ref t.length) in
let tree = Tree0.filter_keys t.tree ~f ~len in
like_maybe_no_op t (with_length tree !len) [@nontail]
;;
let filter t ~f =
let len = (ref t.length) in
let tree = Tree0.filter t.tree ~f ~len in
like_maybe_no_op t (with_length tree !len) [@nontail]
;;
let filteri t ~f =
let len = (ref t.length) in
let tree = Tree0.filteri t.tree ~f ~len in
like_maybe_no_op t (with_length tree !len) [@nontail]
;;
let filter_map t ~f =
let len = (ref t.length) in
let tree = Tree0.filter_map t.tree ~f ~len in
like t (with_length tree !len) [@nontail]
;;
let filter_mapi t ~f =
let len = (ref t.length) in
let tree = Tree0.filter_mapi t.tree ~f ~len in
like t (with_length tree !len) [@nontail]
;;
let of_like_tree2 t (t1, t2) = of_like_tree t t1, of_like_tree t t2
let of_like_tree2_maybe_no_op t (t1, t2) =
of_like_tree_maybe_no_op t t1, of_like_tree_maybe_no_op t t2
;;
let partition_mapi t ~f = of_like_tree2 t (Tree0.partition_mapi t.tree ~f)
let partition_map t ~f = of_like_tree2 t (Tree0.partition_map t.tree ~f)
let partitioni_tf t ~f = of_like_tree2_maybe_no_op t (Tree0.partitioni_tf t.tree ~f)
let partition_tf t ~f = of_like_tree2_maybe_no_op t (Tree0.partition_tf t.tree ~f)
let combine_errors t =
Or_error.map
~f:(of_like_tree t)
(Tree0.combine_errors t.tree ~sexp_of_key:t.comparator.sexp_of_t)
;;
let compare_direct compare_data t1 t2 =
Tree0.compare (compare_key t1) compare_data t1.tree t2.tree
;;
let equal compare_data t1 t2 = Tree0.equal (compare_key t1) compare_data t1.tree t2.tree
let keys t = Tree0.keys t.tree
let data t = Tree0.data t.tree
let to_alist ?key_order t = Tree0.to_alist ?key_order t.tree
let symmetric_diff t1 t2 ~data_equal =
Tree0.symmetric_diff t1.tree t2.tree ~compare_key:(compare_key t1) ~data_equal
;;
let fold_symmetric_diff t1 t2 ~data_equal ~init ~f =
Tree0.fold_symmetric_diff
t1.tree
t2.tree
~compare_key:(compare_key t1)
~data_equal
~init
~f
;;
let merge t1 t2 ~f =
like t1 (Tree0.merge t1.tree t2.tree ~f ~compare_key:(compare_key t1)) [@nontail]
;;
let merge_skewed t1 t2 ~combine =
This is only a no - op in the case where at least one of the maps is empty .
like_maybe_no_op
(if t2.length <= t1.length then t1 else t2)
(Tree0.merge_skewed
t1.tree
t2.tree
~length1:t1.length
~length2:t2.length
~combine
~compare_key:(compare_key t1))
;;
let min_elt t = Tree0.min_elt t.tree
let min_elt_exn t = Tree0.min_elt_exn t.tree
let max_elt t = Tree0.max_elt t.tree
let max_elt_exn t = Tree0.max_elt_exn t.tree
let for_all t ~f = Tree0.for_all t.tree ~f
let for_alli t ~f = Tree0.for_alli t.tree ~f
let exists t ~f = Tree0.exists t.tree ~f
let existsi t ~f = Tree0.existsi t.tree ~f
let count t ~f = Tree0.count t.tree ~f
let counti t ~f = Tree0.counti t.tree ~f
let split t k =
let l, maybe, r = Tree0.split t.tree k ~compare_key:(compare_key t) in
let comparator = comparator t in
let both_len = if Option.is_some maybe then t.length - 1 else t.length in
if Tree0.height l < Tree0.height r
then (
let l = of_tree l ~comparator in
l, maybe, of_tree_unsafe r ~comparator ~length:(both_len - length l))
else (
let r = of_tree r ~comparator in
of_tree_unsafe l ~comparator ~length:(both_len - length r), maybe, r)
;;
let split_and_reinsert_boundary t ~into k =
let l, r =
Tree0.split_and_reinsert_boundary t.tree ~into k ~compare_key:(compare_key t)
in
let comparator = comparator t in
if Tree0.height l < Tree0.height r
then (
let l = of_tree l ~comparator in
l, of_tree_unsafe r ~comparator ~length:(t.length - length l))
else (
let r = of_tree r ~comparator in
of_tree_unsafe l ~comparator ~length:(t.length - length r), r)
;;
let split_le_gt t k = split_and_reinsert_boundary t ~into:`Left k
let split_lt_ge t k = split_and_reinsert_boundary t ~into:`Right k
let subrange t ~lower_bound ~upper_bound =
let left, mid, right =
Tree0.split_range t.tree ~lower_bound ~upper_bound ~compare_key:(compare_key t)
in
let outer_joined_height =
let h_l = Tree0.height left
and h_r = Tree0.height right in
if h_l = h_r then h_l + 1 else max h_l h_r
in
if outer_joined_height < Tree0.height mid
then (
let mid_length = t.length - (Tree0.length left + Tree0.length right) in
of_tree_unsafe mid ~comparator:(comparator t) ~length:mid_length)
else of_tree mid ~comparator:(comparator t)
;;
let append ~lower_part ~upper_part =
match
Tree0.append
~compare_key:(compare_key lower_part)
~lower_part:lower_part.tree
~upper_part:upper_part.tree
with
| `Ok tree ->
`Ok
(of_tree_unsafe
tree
~comparator:(comparator lower_part)
~length:(lower_part.length + upper_part.length))
| `Overlapping_key_ranges -> `Overlapping_key_ranges
;;
let fold_range_inclusive t ~min ~max ~init ~f =
Tree0.fold_range_inclusive t.tree ~min ~max ~init ~f ~compare_key:(compare_key t)
;;
let range_to_alist t ~min ~max =
Tree0.range_to_alist t.tree ~min ~max ~compare_key:(compare_key t)
;;
let closest_key t dir key =
Tree0.closest_key t.tree dir key ~compare_key:(compare_key t)
;;
let nth t n = Tree0.nth t.tree n
let nth_exn t n = Option.value_exn (nth t n)
let rank t key = Tree0.rank t.tree key ~compare_key:(compare_key t)
let sexp_of_t sexp_of_k sexp_of_v _ t = Tree0.sexp_of_t sexp_of_k sexp_of_v t.tree
let to_sequence ?order ?keys_greater_or_equal_to ?keys_less_or_equal_to t =
Tree0.to_sequence
t.comparator
?order
?keys_greater_or_equal_to
?keys_less_or_equal_to
t.tree
;;
let binary_search t ~compare how v = Tree0.binary_search t.tree ~compare how v
let binary_search_segmented t ~segment_of how =
Tree0.binary_search_segmented t.tree ~segment_of how
;;
let hash_fold_direct hash_fold_key hash_fold_data state t =
Tree0.hash_fold_t_ignoring_structure hash_fold_key hash_fold_data state t.tree
;;
let binary_search_subrange t ~compare ~lower_bound ~upper_bound =
match
Tree0.binary_search_two_sided_bounds t.tree ~compare ~lower_bound ~upper_bound
with
| Some (lower_bound, upper_bound) -> subrange t ~lower_bound ~upper_bound
| None -> like_maybe_no_op t (with_length Tree0.Empty 0) [@nontail]
;;
module Make_applicative_traversals (A : Applicative.Lazy_applicative) = struct
module Tree_traversals = Tree0.Make_applicative_traversals (A)
let mapi t ~f =
A.map (Tree_traversals.mapi t.tree ~f) ~f:(fun new_tree ->
with_same_length t new_tree)
;;
let filter_mapi t ~f =
A.map (Tree_traversals.filter_mapi t.tree ~f) ~f:(fun new_tree_with_length ->
like t new_tree_with_length)
;;
end
end
module Tree = struct
type ('k, 'v, 'comparator) t = ('k, 'v, 'comparator) tree
let empty_without_value_restriction = Tree0.empty
let empty ~comparator:_ = empty_without_value_restriction
let of_tree ~comparator:_ tree = tree
let singleton ~comparator:_ k v = Tree0.singleton k v
let of_sorted_array_unchecked ~comparator array =
(Tree0.of_sorted_array_unchecked array ~compare_key:comparator.Comparator.compare)
.tree
;;
let of_sorted_array ~comparator array =
Tree0.of_sorted_array array ~compare_key:comparator.Comparator.compare
|> Or_error.map ~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
let of_alist ~comparator alist =
match Tree0.of_alist alist ~compare_key:comparator.Comparator.compare with
| `Duplicate_key _ as d -> d
| `Ok { tree; length = _ } -> `Ok tree
;;
let of_alist_or_error ~comparator alist =
Tree0.of_alist_or_error alist ~comparator
|> Or_error.map ~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
let of_alist_exn ~comparator alist = (Tree0.of_alist_exn alist ~comparator).tree
let of_alist_multi ~comparator alist =
(Tree0.of_alist_multi alist ~compare_key:comparator.Comparator.compare).tree
;;
let of_alist_fold ~comparator alist ~init ~f =
(Tree0.of_alist_fold alist ~init ~f ~compare_key:comparator.Comparator.compare).tree
;;
let of_alist_reduce ~comparator alist ~f =
(Tree0.of_alist_reduce alist ~f ~compare_key:comparator.Comparator.compare).tree
;;
let of_iteri ~comparator ~iteri =
match Tree0.of_iteri ~iteri ~compare_key:comparator.Comparator.compare with
| `Ok { tree; length = _ } -> `Ok tree
| `Duplicate_key _ as d -> d
;;
let of_iteri_exn ~comparator ~iteri = (Tree0.of_iteri_exn ~iteri ~comparator).tree
let of_increasing_iterator_unchecked ~comparator:_required_by_intf ~len ~f =
Tree0.of_increasing_iterator_unchecked ~len ~f
;;
let of_increasing_sequence ~comparator seq =
Or_error.map
~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
(Tree0.of_increasing_sequence seq ~compare_key:comparator.Comparator.compare)
;;
let of_sequence ~comparator seq =
match Tree0.of_sequence seq ~compare_key:comparator.Comparator.compare with
| `Duplicate_key _ as d -> d
| `Ok { tree; length = _ } -> `Ok tree
;;
let of_sequence_or_error ~comparator seq =
Tree0.of_sequence_or_error seq ~comparator
|> Or_error.map ~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
let of_sequence_exn ~comparator seq = (Tree0.of_sequence_exn seq ~comparator).tree
let of_sequence_multi ~comparator seq =
(Tree0.of_sequence_multi seq ~compare_key:comparator.Comparator.compare).tree
;;
let of_sequence_fold ~comparator seq ~init ~f =
(Tree0.of_sequence_fold seq ~init ~f ~compare_key:comparator.Comparator.compare).tree
;;
let of_sequence_reduce ~comparator seq ~f =
(Tree0.of_sequence_reduce seq ~f ~compare_key:comparator.Comparator.compare).tree
;;
let of_list_with_key ~comparator list ~get_key =
match
Tree0.of_list_with_key list ~get_key ~compare_key:comparator.Comparator.compare
with
| `Duplicate_key _ as d -> d
| `Ok { tree; length = _ } -> `Ok tree
;;
let of_list_with_key_or_error ~comparator list ~get_key =
Tree0.of_list_with_key_or_error list ~get_key ~comparator
|> Or_error.map ~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
let of_list_with_key_exn ~comparator list ~get_key =
(Tree0.of_list_with_key_exn list ~get_key ~comparator).tree
;;
let of_list_with_key_multi ~comparator list ~get_key =
(Tree0.of_list_with_key_multi
list
~get_key
~compare_key:comparator.Comparator.compare)
.tree
;;
let to_tree t = t
let invariants ~comparator t =
Tree0.invariants t ~compare_key:comparator.Comparator.compare
;;
let is_empty t = Tree0.is_empty t
let length t = Tree0.length t
let set ~comparator t ~key ~data =
(Tree0.set t ~key ~data ~length:0 ~compare_key:comparator.Comparator.compare).tree
;;
let add_exn ~comparator t ~key ~data =
(Tree0.add_exn
t
~key
~data
~length:0
~compare_key:comparator.Comparator.compare
~sexp_of_key:comparator.sexp_of_t)
.tree
;;
let add_exn_internal ~comparator t ~key ~data =
(Tree0.add_exn_internal
t
~key
~data
~length:0
~compare_key:comparator.Comparator.compare
~sexp_of_key:comparator.sexp_of_t)
.tree
;;
let add ~comparator t ~key ~data =
try `Ok (add_exn_internal t ~comparator ~key ~data) with
| _ -> `Duplicate
;;
let add_multi ~comparator t ~key ~data =
(Tree0.add_multi t ~key ~data ~length:0 ~compare_key:comparator.Comparator.compare)
.tree
;;
let remove_multi ~comparator t key =
(Tree0.remove_multi t key ~length:0 ~compare_key:comparator.Comparator.compare).tree
;;
let find_multi ~comparator t key =
Tree0.find_multi t key ~compare_key:comparator.Comparator.compare
;;
let change ~comparator t key ~f =
(Tree0.change t key ~f ~length:0 ~compare_key:comparator.Comparator.compare).tree
;;
let update ~comparator t key ~f =
change ~comparator t key ~f:(fun data -> Some (f data)) [@nontail]
;;
let find_exn ~comparator t key =
Tree0.find_exn
t
key
~compare_key:comparator.Comparator.compare
~sexp_of_key:comparator.Comparator.sexp_of_t
;;
let find ~comparator t key = Tree0.find t key ~compare_key:comparator.Comparator.compare
let remove ~comparator t key =
(Tree0.remove t key ~length:0 ~compare_key:comparator.Comparator.compare).tree
;;
let mem ~comparator t key = Tree0.mem t key ~compare_key:comparator.Comparator.compare
let iter_keys t ~f = Tree0.iter_keys t ~f
let iter t ~f = Tree0.iter t ~f
let iteri t ~f = Tree0.iteri t ~f
let iteri_until t ~f = Tree0.iteri_until t ~f
let iter2 ~comparator t1 t2 ~f =
Tree0.iter2 t1 t2 ~f ~compare_key:comparator.Comparator.compare
;;
let map t ~f = Tree0.map t ~f
let mapi t ~f = Tree0.mapi t ~f
let fold t ~init ~f = Tree0.fold t ~f ~init
let fold_until t ~init ~f ~finish = Tree0.fold_until t ~f ~init ~finish
let fold_right t ~init ~f = Tree0.fold_right t ~f ~init
let fold2 ~comparator t1 t2 ~init ~f =
Tree0.fold2 t1 t2 ~init ~f ~compare_key:comparator.Comparator.compare
;;
let filter_keys t ~f = Tree0.filter_keys t ~f ~len:( (ref 0)) [@nontail]
let filter t ~f = Tree0.filter t ~f ~len:( (ref 0)) [@nontail]
let filteri t ~f = Tree0.filteri t ~f ~len:( (ref 0)) [@nontail]
let filter_map t ~f = Tree0.filter_map t ~f ~len:( (ref 0)) [@nontail]
let filter_mapi t ~f = Tree0.filter_mapi t ~f ~len:( (ref 0)) [@nontail]
let partition_mapi t ~f = Tree0.partition_mapi t ~f
let partition_map t ~f = Tree0.partition_map t ~f
let partitioni_tf t ~f = Tree0.partitioni_tf t ~f
let partition_tf t ~f = Tree0.partition_tf t ~f
let combine_errors ~comparator t =
Tree0.combine_errors t ~sexp_of_key:comparator.Comparator.sexp_of_t
;;
let compare_direct ~comparator compare_data t1 t2 =
Tree0.compare comparator.Comparator.compare compare_data t1 t2
;;
let equal ~comparator compare_data t1 t2 =
Tree0.equal comparator.Comparator.compare compare_data t1 t2
;;
let keys t = Tree0.keys t
let data t = Tree0.data t
let to_alist ?key_order t = Tree0.to_alist ?key_order t
let symmetric_diff ~comparator t1 t2 ~data_equal =
Tree0.symmetric_diff t1 t2 ~compare_key:comparator.Comparator.compare ~data_equal
;;
let fold_symmetric_diff ~comparator t1 t2 ~data_equal ~init ~f =
Tree0.fold_symmetric_diff
t1
t2
~compare_key:comparator.Comparator.compare
~data_equal
~init
~f
;;
let merge ~comparator t1 t2 ~f =
(Tree0.merge t1 t2 ~f ~compare_key:comparator.Comparator.compare).tree
;;
let merge_skewed ~comparator t1 t2 ~combine =
(Tree0.merge_skewed
t1
t2
~length1:(length t1)
~length2:(length t2)
~combine
~compare_key:comparator.Comparator.compare)
.tree
;;
let min_elt t = Tree0.min_elt t
let min_elt_exn t = Tree0.min_elt_exn t
let max_elt t = Tree0.max_elt t
let max_elt_exn t = Tree0.max_elt_exn t
let for_all t ~f = Tree0.for_all t ~f
let for_alli t ~f = Tree0.for_alli t ~f
let exists t ~f = Tree0.exists t ~f
let existsi t ~f = Tree0.existsi t ~f
let count t ~f = Tree0.count t ~f
let counti t ~f = Tree0.counti t ~f
let split ~comparator t k = Tree0.split t k ~compare_key:comparator.Comparator.compare
let split_le_gt ~comparator t k =
Tree0.split_and_reinsert_boundary
t
~into:`Left
k
~compare_key:comparator.Comparator.compare
;;
let split_lt_ge ~comparator t k =
Tree0.split_and_reinsert_boundary
t
~into:`Right
k
~compare_key:comparator.Comparator.compare
;;
let append ~comparator ~lower_part ~upper_part =
Tree0.append ~lower_part ~upper_part ~compare_key:comparator.Comparator.compare
;;
let subrange ~comparator t ~lower_bound ~upper_bound =
let _, ret, _ =
Tree0.split_range
t
~lower_bound
~upper_bound
~compare_key:comparator.Comparator.compare
in
ret
;;
let fold_range_inclusive ~comparator t ~min ~max ~init ~f =
Tree0.fold_range_inclusive
t
~min
~max
~init
~f
~compare_key:comparator.Comparator.compare
;;
let range_to_alist ~comparator t ~min ~max =
Tree0.range_to_alist t ~min ~max ~compare_key:comparator.Comparator.compare
;;
let closest_key ~comparator t dir key =
Tree0.closest_key t dir key ~compare_key:comparator.Comparator.compare
;;
let nth t n = Tree0.nth t n
let nth_exn t n = Option.value_exn (nth t n)
let rank ~comparator t key = Tree0.rank t key ~compare_key:comparator.Comparator.compare
let sexp_of_t sexp_of_k sexp_of_v _ t = Tree0.sexp_of_t sexp_of_k sexp_of_v t
let t_of_sexp_direct ~comparator k_of_sexp v_of_sexp sexp =
(Tree0.t_of_sexp_direct k_of_sexp v_of_sexp sexp ~comparator).tree
;;
let to_sequence ~comparator ?order ?keys_greater_or_equal_to ?keys_less_or_equal_to t =
Tree0.to_sequence comparator ?order ?keys_greater_or_equal_to ?keys_less_or_equal_to t
;;
let binary_search ~comparator:_ t ~compare how v = Tree0.binary_search t ~compare how v
let binary_search_segmented ~comparator:_ t ~segment_of how =
Tree0.binary_search_segmented t ~segment_of how
;;
let binary_search_subrange ~comparator t ~compare ~lower_bound ~upper_bound =
match Tree0.binary_search_two_sided_bounds t ~compare ~lower_bound ~upper_bound with
| Some (lower_bound, upper_bound) -> subrange ~comparator t ~lower_bound ~upper_bound
| None -> Empty
;;
module Make_applicative_traversals (A : Applicative.Lazy_applicative) = struct
module Tree0_traversals = Tree0.Make_applicative_traversals (A)
let mapi t ~f = Tree0_traversals.mapi t ~f
let filter_mapi t ~f =
A.map
(Tree0_traversals.filter_mapi t ~f)
~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
end
let map_keys ~comparator t ~f =
match Tree0.map_keys ~comparator t ~f with
| `Ok { tree = t; length = _ } -> `Ok t
| `Duplicate_key _ as dup -> dup
;;
let map_keys_exn ~comparator t ~f = (Tree0.map_keys_exn ~comparator t ~f).tree
let transpose_keys ~comparator:outer_comparator ~comparator:inner_comparator t =
(Tree0.transpose_keys ~outer_comparator ~inner_comparator t).tree
|> map ~f:(fun (x : ('k, 'v) Tree0.t With_length.t) -> x.tree)
;;
module Build_increasing = struct
type ('k, 'v, 'w) t = ('k, 'v) Tree0.Build_increasing.t
let empty = Tree0.Build_increasing.empty
let add_exn t ~comparator ~key ~data =
match Tree0.Build_increasing.max_key t with
| Some prev_key when comparator.Comparator.compare prev_key key >= 0 ->
Error.raise_s (Sexp.Atom "Map.Build_increasing.add: non-increasing key")
| _ -> Tree0.Build_increasing.add_unchecked t ~key ~data
;;
let to_tree t = Tree0.Build_increasing.to_tree_unchecked t
end
end
module Using_comparator = struct
type nonrec ('k, 'v, 'cmp) t = ('k, 'v, 'cmp) t
include Accessors
let empty ~comparator = { tree = Tree0.empty; comparator; length = 0 }
let singleton ~comparator k v = { comparator; tree = Tree0.singleton k v; length = 1 }
let of_tree0 ~comparator ({ tree; length } : _ With_length.t) =
{ comparator; tree; length }
;;
let of_tree ~comparator tree =
of_tree0 ~comparator (with_length tree (Tree0.length tree)) [@nontail]
;;
let to_tree = to_tree
let of_sorted_array_unchecked ~comparator array =
of_tree0
~comparator
(Tree0.of_sorted_array_unchecked array ~compare_key:comparator.Comparator.compare)
[@nontail]
;;
let of_sorted_array ~comparator array =
Or_error.map
(Tree0.of_sorted_array array ~compare_key:comparator.Comparator.compare)
~f:(fun tree -> of_tree0 ~comparator tree)
;;
let of_alist ~comparator alist =
match Tree0.of_alist alist ~compare_key:comparator.Comparator.compare with
| `Ok { tree; length } -> `Ok { comparator; tree; length }
| `Duplicate_key _ as z -> z
;;
let of_alist_or_error ~comparator alist =
Result.map (Tree0.of_alist_or_error alist ~comparator) ~f:(fun tree ->
of_tree0 ~comparator tree)
;;
let of_alist_exn ~comparator alist =
of_tree0 ~comparator (Tree0.of_alist_exn alist ~comparator)
;;
let of_alist_multi ~comparator alist =
of_tree0
~comparator
(Tree0.of_alist_multi alist ~compare_key:comparator.Comparator.compare)
;;
let of_alist_fold ~comparator alist ~init ~f =
of_tree0
~comparator
(Tree0.of_alist_fold alist ~init ~f ~compare_key:comparator.Comparator.compare)
;;
let of_alist_reduce ~comparator alist ~f =
of_tree0
~comparator
(Tree0.of_alist_reduce alist ~f ~compare_key:comparator.Comparator.compare)
;;
let of_iteri ~comparator ~iteri =
match Tree0.of_iteri ~compare_key:comparator.Comparator.compare ~iteri with
| `Ok tree_length -> `Ok (of_tree0 ~comparator tree_length)
| `Duplicate_key _ as z -> z
;;
let of_iteri_exn ~comparator ~iteri =
of_tree0 ~comparator (Tree0.of_iteri_exn ~comparator ~iteri)
;;
let of_increasing_iterator_unchecked ~comparator ~len ~f =
of_tree0
~comparator
(with_length (Tree0.of_increasing_iterator_unchecked ~len ~f) len) [@nontail]
;;
let of_increasing_sequence ~comparator seq =
Or_error.map
~f:(fun x -> of_tree0 ~comparator x)
(Tree0.of_increasing_sequence seq ~compare_key:comparator.Comparator.compare)
;;
let of_sequence ~comparator seq =
match Tree0.of_sequence seq ~compare_key:comparator.Comparator.compare with
| `Ok { tree; length } -> `Ok { comparator; tree; length }
| `Duplicate_key _ as z -> z
;;
let of_sequence_or_error ~comparator seq =
Result.map (Tree0.of_sequence_or_error seq ~comparator) ~f:(fun tree ->
of_tree0 ~comparator tree)
;;
let of_sequence_exn ~comparator seq =
of_tree0 ~comparator (Tree0.of_sequence_exn seq ~comparator)
;;
let of_sequence_multi ~comparator seq =
of_tree0
~comparator
(Tree0.of_sequence_multi seq ~compare_key:comparator.Comparator.compare)
;;
let of_sequence_fold ~comparator seq ~init ~f =
of_tree0
~comparator
(Tree0.of_sequence_fold seq ~init ~f ~compare_key:comparator.Comparator.compare)
;;
let of_sequence_reduce ~comparator seq ~f =
of_tree0
~comparator
(Tree0.of_sequence_reduce seq ~f ~compare_key:comparator.Comparator.compare)
;;
let of_list_with_key ~comparator list ~get_key =
match
Tree0.of_list_with_key list ~get_key ~compare_key:comparator.Comparator.compare
with
| `Ok { tree; length } -> `Ok { comparator; tree; length }
| `Duplicate_key _ as z -> z
;;
let of_list_with_key_or_error ~comparator list ~get_key =
Result.map (Tree0.of_list_with_key_or_error list ~get_key ~comparator) ~f:(fun tree ->
of_tree0 ~comparator tree)
;;
let of_list_with_key_exn ~comparator list ~get_key =
of_tree0 ~comparator (Tree0.of_list_with_key_exn list ~get_key ~comparator)
;;
let of_list_with_key_multi ~comparator list ~get_key =
Tree0.of_list_with_key_multi list ~get_key ~compare_key:comparator.Comparator.compare
|> of_tree0 ~comparator
;;
let t_of_sexp_direct ~comparator k_of_sexp v_of_sexp sexp =
of_tree0 ~comparator (Tree0.t_of_sexp_direct k_of_sexp v_of_sexp sexp ~comparator)
;;
let map_keys ~comparator t ~f =
match Tree0.map_keys t.tree ~f ~comparator with
| `Ok pair -> `Ok (of_tree0 ~comparator pair)
| `Duplicate_key _ as dup -> dup
;;
let map_keys_exn ~comparator t ~f =
of_tree0 ~comparator (Tree0.map_keys_exn t.tree ~f ~comparator)
;;
let transpose_keys ~comparator:inner_comparator t =
let outer_comparator = t.comparator in
Tree0.transpose_keys ~outer_comparator ~inner_comparator (Tree0.map t.tree ~f:to_tree)
|> of_tree0 ~comparator:inner_comparator
|> map ~f:(fun x -> of_tree0 ~comparator:outer_comparator x)
;;
module Empty_without_value_restriction (K : Comparator.S1) = struct
let empty = { tree = Tree0.empty; comparator = K.comparator; length = 0 }
end
module Tree = Tree
end
include Accessors
type ('k, 'cmp) comparator =
(module Comparator.S with type t = 'k and type comparator_witness = 'cmp)
let comparator_s (type k cmp) t : (k, cmp) comparator =
(module struct
type t = k
type comparator_witness = cmp
let comparator = t.comparator
end)
;;
let to_comparator (type k cmp) ((module M) : (k, cmp) comparator) = M.comparator
let of_tree (type k cmp) ((module M) : (k, cmp) comparator) tree =
of_tree ~comparator:M.comparator tree
;;
let empty m = Using_comparator.empty ~comparator:(to_comparator m)
let singleton m a = Using_comparator.singleton ~comparator:(to_comparator m) a
let of_alist m a = Using_comparator.of_alist ~comparator:(to_comparator m) a
let of_alist_or_error m a =
Using_comparator.of_alist_or_error ~comparator:(to_comparator m) a
;;
let of_alist_exn m a = Using_comparator.of_alist_exn ~comparator:(to_comparator m) a
let of_alist_multi m a = Using_comparator.of_alist_multi ~comparator:(to_comparator m) a
let of_alist_fold m a ~init ~f =
Using_comparator.of_alist_fold ~comparator:(to_comparator m) a ~init ~f
;;
let of_alist_reduce m a ~f =
Using_comparator.of_alist_reduce ~comparator:(to_comparator m) a ~f
;;
let of_sorted_array_unchecked m a =
Using_comparator.of_sorted_array_unchecked ~comparator:(to_comparator m) a
;;
let of_sorted_array m a = Using_comparator.of_sorted_array ~comparator:(to_comparator m) a
let of_iteri m ~iteri = Using_comparator.of_iteri ~iteri ~comparator:(to_comparator m)
let of_iteri_exn m ~iteri =
Using_comparator.of_iteri_exn ~iteri ~comparator:(to_comparator m)
;;
let of_increasing_iterator_unchecked m ~len ~f =
Using_comparator.of_increasing_iterator_unchecked ~len ~f ~comparator:(to_comparator m)
;;
let of_increasing_sequence m seq =
Using_comparator.of_increasing_sequence ~comparator:(to_comparator m) seq
;;
let of_sequence m s = Using_comparator.of_sequence ~comparator:(to_comparator m) s
let of_sequence_or_error m s =
Using_comparator.of_sequence_or_error ~comparator:(to_comparator m) s
;;
let of_sequence_exn m s = Using_comparator.of_sequence_exn ~comparator:(to_comparator m) s
let of_sequence_multi m s =
Using_comparator.of_sequence_multi ~comparator:(to_comparator m) s
;;
let of_sequence_fold m s ~init ~f =
Using_comparator.of_sequence_fold ~comparator:(to_comparator m) s ~init ~f
;;
let of_sequence_reduce m s ~f =
Using_comparator.of_sequence_reduce ~comparator:(to_comparator m) s ~f
;;
let of_list_with_key m l ~get_key =
Using_comparator.of_list_with_key ~comparator:(to_comparator m) l ~get_key
;;
let of_list_with_key_or_error m l ~get_key =
Using_comparator.of_list_with_key_or_error ~comparator:(to_comparator m) l ~get_key
;;
let of_list_with_key_exn m l ~get_key =
Using_comparator.of_list_with_key_exn ~comparator:(to_comparator m) l ~get_key
;;
let of_list_with_key_multi m l ~get_key =
Using_comparator.of_list_with_key_multi ~comparator:(to_comparator m) l ~get_key
;;
let map_keys m t ~f = Using_comparator.map_keys ~comparator:(to_comparator m) t ~f
let map_keys_exn m t ~f = Using_comparator.map_keys_exn ~comparator:(to_comparator m) t ~f
let transpose_keys m t = Using_comparator.transpose_keys ~comparator:(to_comparator m) t
module M (K : sig
type t
type comparator_witness
end) =
struct
type nonrec 'v t = (K.t, 'v, K.comparator_witness) t
end
module type Sexp_of_m = sig
type t [@@deriving_inline sexp_of]
val sexp_of_t : t -> Sexplib0.Sexp.t
[@@@end]
end
module type M_of_sexp = sig
type t [@@deriving_inline of_sexp]
val t_of_sexp : Sexplib0.Sexp.t -> t
[@@@end]
include Comparator.S with type t := t
end
module type M_sexp_grammar = sig
type t [@@deriving_inline sexp_grammar]
val t_sexp_grammar : t Sexplib0.Sexp_grammar.t
[@@@end]
end
module type Compare_m = sig end
module type Equal_m = sig end
module type Hash_fold_m = Hasher.S
let sexp_of_m__t (type k) (module K : Sexp_of_m with type t = k) sexp_of_v t =
sexp_of_t K.sexp_of_t sexp_of_v (fun _ -> Sexp.Atom "_") t
;;
let m__t_of_sexp
(type k cmp)
(module K : M_of_sexp with type t = k and type comparator_witness = cmp)
v_of_sexp
sexp
=
Using_comparator.t_of_sexp_direct ~comparator:K.comparator K.t_of_sexp v_of_sexp sexp
;;
let m__t_sexp_grammar
(type k)
(module K : M_sexp_grammar with type t = k)
(v_grammar : _ Sexplib0.Sexp_grammar.t)
: _ Sexplib0.Sexp_grammar.t
=
{ untyped =
Tagged
{ key = Sexplib0.Sexp_grammar.assoc_tag
; value = List []
; grammar =
List
(Many
(List
(Cons
( Tagged
{ key = Sexplib0.Sexp_grammar.assoc_key_tag
; value = List []
; grammar = K.t_sexp_grammar.untyped
}
, Cons
( Tagged
{ key = Sexplib0.Sexp_grammar.assoc_value_tag
; value = List []
; grammar = v_grammar.untyped
}
, Empty ) ))))
}
}
;;
let compare_m__t (module _ : Compare_m) compare_v t1 t2 = compare_direct compare_v t1 t2
let equal_m__t (module _ : Equal_m) equal_v t1 t2 = equal equal_v t1 t2
let hash_fold_m__t (type k) (module K : Hash_fold_m with type t = k) hash_fold_v state =
hash_fold_direct K.hash_fold_t hash_fold_v state
;;
module Poly = struct
type nonrec ('k, 'v) t = ('k, 'v, Comparator.Poly.comparator_witness) t
type nonrec ('k, 'v) tree = ('k, 'v) Tree0.t
type comparator_witness = Comparator.Poly.comparator_witness
include Accessors
let comparator = Comparator.Poly.comparator
let of_tree tree = { tree; comparator; length = Tree0.length tree }
include Using_comparator.Empty_without_value_restriction (Comparator.Poly)
let singleton a = Using_comparator.singleton ~comparator a
let of_alist a = Using_comparator.of_alist ~comparator a
let of_alist_or_error a = Using_comparator.of_alist_or_error ~comparator a
let of_alist_exn a = Using_comparator.of_alist_exn ~comparator a
let of_alist_multi a = Using_comparator.of_alist_multi ~comparator a
let of_alist_fold a ~init ~f = Using_comparator.of_alist_fold ~comparator a ~init ~f
let of_alist_reduce a ~f = Using_comparator.of_alist_reduce ~comparator a ~f
let of_sorted_array_unchecked a =
Using_comparator.of_sorted_array_unchecked ~comparator a
;;
let of_sorted_array a = Using_comparator.of_sorted_array ~comparator a
let of_iteri ~iteri = Using_comparator.of_iteri ~iteri ~comparator
let of_iteri_exn ~iteri = Using_comparator.of_iteri_exn ~iteri ~comparator
let of_increasing_iterator_unchecked ~len ~f =
Using_comparator.of_increasing_iterator_unchecked ~len ~f ~comparator
;;
let of_increasing_sequence seq = Using_comparator.of_increasing_sequence ~comparator seq
let of_sequence s = Using_comparator.of_sequence ~comparator s
let of_sequence_or_error s = Using_comparator.of_sequence_or_error ~comparator s
let of_sequence_exn s = Using_comparator.of_sequence_exn ~comparator s
let of_sequence_multi s = Using_comparator.of_sequence_multi ~comparator s
let of_sequence_fold s ~init ~f =
Using_comparator.of_sequence_fold ~comparator s ~init ~f
;;
let of_sequence_reduce s ~f = Using_comparator.of_sequence_reduce ~comparator s ~f
let of_list_with_key l ~get_key =
Using_comparator.of_list_with_key ~comparator l ~get_key
;;
let of_list_with_key_or_error l ~get_key =
Using_comparator.of_list_with_key_or_error ~comparator l ~get_key
;;
let of_list_with_key_exn l ~get_key =
Using_comparator.of_list_with_key_exn ~comparator l ~get_key
;;
let of_list_with_key_multi l ~get_key =
Using_comparator.of_list_with_key_multi ~comparator l ~get_key
;;
let map_keys t ~f = Using_comparator.map_keys ~comparator t ~f
let map_keys_exn t ~f = Using_comparator.map_keys_exn ~comparator t ~f
let transpose_keys t = Using_comparator.transpose_keys ~comparator t
end
|
fc7f48513d9c09cbdc804af3549a1227d900ffafd3c4dbbbefe1b2e4ba7340b6 | reanimate/reanimate | doc_chainT.hs | #!/usr/bin/env stack
-- stack runghc --package reanimate
module Main(main) where
import Reanimate
import Reanimate.Transition
import Reanimate.Builtin.Documentation
main :: IO ()
main = reanimate $ docEnv $ chainT (overlapT 0.5 fadeT) [drawBox, drawCircle, drawProgress]
| null | https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/examples/doc_chainT.hs | haskell | stack runghc --package reanimate | #!/usr/bin/env stack
module Main(main) where
import Reanimate
import Reanimate.Transition
import Reanimate.Builtin.Documentation
main :: IO ()
main = reanimate $ docEnv $ chainT (overlapT 0.5 fadeT) [drawBox, drawCircle, drawProgress]
|
1a6f737322bb4b3b2e25bb8b0b8c02e18c7596f3084b504fd368bc01e36c64e3 | mflatt/shrubbery-rhombus-0 | dot.rkt | #lang racket/base
(require (for-syntax racket/base
syntax/parse
enforest/property
enforest/syntax-local
"operator-parse.rkt")
"definition.rkt"
"expression.rkt"
"static-info.rkt"
"dot-provider-key.rkt")
(provide |.|
use_static_dot
use_dynamic_dot)
(module+ for-dot-provider
(begin-for-syntax
(provide (property-out dot-provider)
in-dot-provider-space
wrap-dot-provider))
(provide define-dot-provider-syntax
#%dot-provider
prop:field-name->accessor))
(begin-for-syntax
(property dot-provider (handler))
(define in-dot-provider-space (make-interned-syntax-introducer 'rhombus/dot-provider))
(define (wrap-dot-provider expr provider-stx)
(quasisyntax/loc expr
(begin (quote-syntax (#%dot-provider #,provider-stx))
#,expr)))
(define-syntax-class :dot-provider
#:literals (begin quote-syntax #%dot-provider)
(pattern id:identifier
#:when (syntax-local-value* (in-dot-provider-space #'id) dot-provider-ref))
(pattern (~var ref-id (:static-info #'#%dot-provider))
#:attr id #'ref-id.val)))
(define-for-syntax (make-|.| strict?)
(expression-infix-operator
(quote-syntax |.|)
'((default . stronger))
'macro
(lambda (form1 tail)
(syntax-parse tail
[(dot::operator field:identifier . tail)
(define (generic)
(if strict?
(raise-syntax-error #f
"strict operator not supported for left-hand side"
#'dot.name
#f
(list form1))
(values #`(dot-lookup-by-name #,form1 'field)
#'tail)))
(syntax-parse form1
[dp::dot-provider
(define p (syntax-local-value* (in-dot-provider-space #'dp.id) dot-provider-ref))
(define e ((dot-provider-handler p) form1 #'dot #'field))
(if e
(values e #'tail)
(generic))]
[_ (generic)])]
[(dot::operator other . tail)
(raise-syntax-error #f
"expected an identifier for a field name, but found something else"
#'dot.name
#f
(list #'other))]))
'left))
(define-syntax |.| (make-|.| #f))
(define-syntaxes (use_static_dot use_dynamic_dot)
(let ([mk (lambda (strict?)
(definition-transformer
(lambda (stx)
(syntax-parse stx
[(form-id)
#`((define-syntax #,(datum->syntax #'form-id '|.|) (make-|.| #,strict?)))]))))])
(values (mk #t)
(mk #f))))
(define-syntax (define-dot-provider-syntax stx)
(syntax-parse stx
[(_ id:identifier rhs)
#`(define-syntax #,(in-dot-provider-space #'id)
rhs)]))
(define-values (prop:field-name->accessor field-name->accessor? field-name->accessor-ref)
(make-struct-type-property 'field-name->accessor
(lambda (field-names info)
(define gen-acc (list-ref info 3))
(for/hasheq ([name (in-list field-names)]
[i (in-naturals)])
(values name
(make-struct-field-accessor gen-acc i name))))))
(define (dot-lookup-by-name v field)
(define ht (field-name->accessor-ref v #f))
(define (fail)
(raise-arguments-error field
"no such field"
"in value" v))
(cond
[(not ht) (fail)]
[(hash-ref ht field #f) => (lambda (acc) (acc v))]
[else (fail)]))
| null | https://raw.githubusercontent.com/mflatt/shrubbery-rhombus-0/0ced6cdba7c5f9ec7a9cb65922e386375f3162e0/rhombus/private/dot.rkt | racket | #lang racket/base
(require (for-syntax racket/base
syntax/parse
enforest/property
enforest/syntax-local
"operator-parse.rkt")
"definition.rkt"
"expression.rkt"
"static-info.rkt"
"dot-provider-key.rkt")
(provide |.|
use_static_dot
use_dynamic_dot)
(module+ for-dot-provider
(begin-for-syntax
(provide (property-out dot-provider)
in-dot-provider-space
wrap-dot-provider))
(provide define-dot-provider-syntax
#%dot-provider
prop:field-name->accessor))
(begin-for-syntax
(property dot-provider (handler))
(define in-dot-provider-space (make-interned-syntax-introducer 'rhombus/dot-provider))
(define (wrap-dot-provider expr provider-stx)
(quasisyntax/loc expr
(begin (quote-syntax (#%dot-provider #,provider-stx))
#,expr)))
(define-syntax-class :dot-provider
#:literals (begin quote-syntax #%dot-provider)
(pattern id:identifier
#:when (syntax-local-value* (in-dot-provider-space #'id) dot-provider-ref))
(pattern (~var ref-id (:static-info #'#%dot-provider))
#:attr id #'ref-id.val)))
(define-for-syntax (make-|.| strict?)
(expression-infix-operator
(quote-syntax |.|)
'((default . stronger))
'macro
(lambda (form1 tail)
(syntax-parse tail
[(dot::operator field:identifier . tail)
(define (generic)
(if strict?
(raise-syntax-error #f
"strict operator not supported for left-hand side"
#'dot.name
#f
(list form1))
(values #`(dot-lookup-by-name #,form1 'field)
#'tail)))
(syntax-parse form1
[dp::dot-provider
(define p (syntax-local-value* (in-dot-provider-space #'dp.id) dot-provider-ref))
(define e ((dot-provider-handler p) form1 #'dot #'field))
(if e
(values e #'tail)
(generic))]
[_ (generic)])]
[(dot::operator other . tail)
(raise-syntax-error #f
"expected an identifier for a field name, but found something else"
#'dot.name
#f
(list #'other))]))
'left))
(define-syntax |.| (make-|.| #f))
(define-syntaxes (use_static_dot use_dynamic_dot)
(let ([mk (lambda (strict?)
(definition-transformer
(lambda (stx)
(syntax-parse stx
[(form-id)
#`((define-syntax #,(datum->syntax #'form-id '|.|) (make-|.| #,strict?)))]))))])
(values (mk #t)
(mk #f))))
(define-syntax (define-dot-provider-syntax stx)
(syntax-parse stx
[(_ id:identifier rhs)
#`(define-syntax #,(in-dot-provider-space #'id)
rhs)]))
(define-values (prop:field-name->accessor field-name->accessor? field-name->accessor-ref)
(make-struct-type-property 'field-name->accessor
(lambda (field-names info)
(define gen-acc (list-ref info 3))
(for/hasheq ([name (in-list field-names)]
[i (in-naturals)])
(values name
(make-struct-field-accessor gen-acc i name))))))
(define (dot-lookup-by-name v field)
(define ht (field-name->accessor-ref v #f))
(define (fail)
(raise-arguments-error field
"no such field"
"in value" v))
(cond
[(not ht) (fail)]
[(hash-ref ht field #f) => (lambda (acc) (acc v))]
[else (fail)]))
| |
d364a3a33972c8c313b4f2791093dd9ea12fec7da49f85691b9091a99cc5b77d | jasonstolaruk/CurryMUD | EffectFuns.hs | {-# LANGUAGE OverloadedStrings #-}
module Mud.Misc.EffectFuns ( effectFuns
, instaEffectFuns ) where
import Mud.Data.Misc
import Mud.Data.State.MudData
import Mud.Data.State.Util.Get
import Mud.Data.State.Util.Misc
import Mud.Data.State.Util.Output
import Mud.Data.State.Util.Random
import qualified Mud.Misc.Logging as L (logPla)
import Mud.TheWorld.Liqs
import Mud.Util.Misc
import Control.Monad (when)
import Data.Monoid ((<>))
import Data.Text (Text)
logPla :: Text -> Id -> Text -> MudStack ()
logPla = L.logPla "Mud.Misc.EffectFuns"
-- ==================================================
-- Effect functions are run on a new thread every second.
effectFuns :: [(FunName, EffectFun)]
effectFuns = [ (oilTag, oilEffectFun )
, (potTinnitusTag, tinnitusEffectFun) ]
-- Instantaneous effect functions are run once.
instaEffectFuns :: [(FunName, InstaEffectFun)]
instaEffectFuns = pure (potTinnitusTag, tinnitusInstaEffectFun)
-----
oilEffectFun :: EffectFun
oilEffectFun i secs = let f = getState >>= \ms -> when (isLoggedIn . getPla i $ ms) . rndmDo_ 25 . helper $ ms
in when (isZero $ secs `mod` 10) f
where
helper ms = let (mq, cols) = getMsgQueueColumns i ms
d = mkStdDesig i ms DoCap
bs = pure (serialize d <> "'s stomach rumbles loudly.", desigOtherIds d)
in do logPla "oilEffectFun" i "stomach rumbling."
wrapSend mq cols "Your stomach rumbles loudly."
bcastIfNotIncogNl i bs
tinnitusEffectFun :: EffectFun -- Potion of instant tinnitus.
tinnitusEffectFun i secs = when (isZero $ secs `mod` 5) $ getState >>= \ms ->
let (mq, cols) = getMsgQueueColumns i ms
in when (isLoggedIn . getPla i $ ms) . rndmDo_ 25 . wrapSend mq cols $ "There is an awful ringing in your ears."
tinnitusInstaEffectFun :: InstaEffectFun -- Potion of tinnitus.
tinnitusInstaEffectFun i = getMsgQueueColumns i <$> getState >>= \(mq, cols) ->
wrapSend mq cols "There is a terrible ringing in your ears."
| null | https://raw.githubusercontent.com/jasonstolaruk/CurryMUD/f9775fb3ede08610f33f27bb1fb5fc0565e98266/lib/Mud/Misc/EffectFuns.hs | haskell | # LANGUAGE OverloadedStrings #
==================================================
Effect functions are run on a new thread every second.
Instantaneous effect functions are run once.
---
Potion of instant tinnitus.
Potion of tinnitus. |
module Mud.Misc.EffectFuns ( effectFuns
, instaEffectFuns ) where
import Mud.Data.Misc
import Mud.Data.State.MudData
import Mud.Data.State.Util.Get
import Mud.Data.State.Util.Misc
import Mud.Data.State.Util.Output
import Mud.Data.State.Util.Random
import qualified Mud.Misc.Logging as L (logPla)
import Mud.TheWorld.Liqs
import Mud.Util.Misc
import Control.Monad (when)
import Data.Monoid ((<>))
import Data.Text (Text)
logPla :: Text -> Id -> Text -> MudStack ()
logPla = L.logPla "Mud.Misc.EffectFuns"
effectFuns :: [(FunName, EffectFun)]
effectFuns = [ (oilTag, oilEffectFun )
, (potTinnitusTag, tinnitusEffectFun) ]
instaEffectFuns :: [(FunName, InstaEffectFun)]
instaEffectFuns = pure (potTinnitusTag, tinnitusInstaEffectFun)
oilEffectFun :: EffectFun
oilEffectFun i secs = let f = getState >>= \ms -> when (isLoggedIn . getPla i $ ms) . rndmDo_ 25 . helper $ ms
in when (isZero $ secs `mod` 10) f
where
helper ms = let (mq, cols) = getMsgQueueColumns i ms
d = mkStdDesig i ms DoCap
bs = pure (serialize d <> "'s stomach rumbles loudly.", desigOtherIds d)
in do logPla "oilEffectFun" i "stomach rumbling."
wrapSend mq cols "Your stomach rumbles loudly."
bcastIfNotIncogNl i bs
tinnitusEffectFun i secs = when (isZero $ secs `mod` 5) $ getState >>= \ms ->
let (mq, cols) = getMsgQueueColumns i ms
in when (isLoggedIn . getPla i $ ms) . rndmDo_ 25 . wrapSend mq cols $ "There is an awful ringing in your ears."
tinnitusInstaEffectFun i = getMsgQueueColumns i <$> getState >>= \(mq, cols) ->
wrapSend mq cols "There is a terrible ringing in your ears."
|
bca04c511f89313ed263b02d09671bad529d2f9c0470b543401b380cc6d47ef9 | jimweirich/sicp-study | ex1_36.scm | SICP 1.36
Exercise 1.36 . Modify fixed - point so that it prints the sequence
;; of approximations it generates, using the newline and display
primitives shown in exercise 1.22 . Then find a solution to xx =
1000 by finding a fixed point of x - > log(1000)/log(x ) . ( Use
;; Scheme's primitive log procedure, which computes natural
;; logarithms.) Compare the number of steps this takes with and
;; without average damping. (Note that you cannot start fixed-point
with a guess of 1 , as this would cause division by log(1 ) = 0 . )
;; ANSWER ------------------------------------------------------------
(define tolerance 0.00001)
(define (fixed-point f first-guess)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess)
(display guess)
(newline)
(let ((next (f guess)))
(if (close-enough? guess next)
next
(try next))))
(try first-guess))
(define (average a b) (/ (+ a b) 2.0))
(define (damped-fixed-point f first-guess)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess)
(display guess)
(newline)
(let ((next (average guess (f guess))))
(if (close-enough? guess next)
next
(try next))))
(try first-guess))
(fixed-point (lambda (x) (/ (log 10000) (log x))) 2.0)
Takes 28 steps to converge on 5.438579853089483
(damped-fixed-point (lambda (x) (/ (log 10000) (log x))) 2.0)
Takes 10 steps to converge on 5.438585155442469
| null | https://raw.githubusercontent.com/jimweirich/sicp-study/bc5190e04ed6ae321107ed6149241f26efc1b8c8/scheme/chapter1/ex1_36.scm | scheme | of approximations it generates, using the newline and display
Scheme's primitive log procedure, which computes natural
logarithms.) Compare the number of steps this takes with and
without average damping. (Note that you cannot start fixed-point
ANSWER ------------------------------------------------------------ | SICP 1.36
Exercise 1.36 . Modify fixed - point so that it prints the sequence
primitives shown in exercise 1.22 . Then find a solution to xx =
1000 by finding a fixed point of x - > log(1000)/log(x ) . ( Use
with a guess of 1 , as this would cause division by log(1 ) = 0 . )
(define tolerance 0.00001)
(define (fixed-point f first-guess)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess)
(display guess)
(newline)
(let ((next (f guess)))
(if (close-enough? guess next)
next
(try next))))
(try first-guess))
(define (average a b) (/ (+ a b) 2.0))
(define (damped-fixed-point f first-guess)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess)
(display guess)
(newline)
(let ((next (average guess (f guess))))
(if (close-enough? guess next)
next
(try next))))
(try first-guess))
(fixed-point (lambda (x) (/ (log 10000) (log x))) 2.0)
Takes 28 steps to converge on 5.438579853089483
(damped-fixed-point (lambda (x) (/ (log 10000) (log x))) 2.0)
Takes 10 steps to converge on 5.438585155442469
|
28928f2ba5d8fc1739f1ad9a852f22d8f289ddad8d633bd9e4612faa56005117 | konn/smooth | higher-diff-speed.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
# OPTIONS_GHC -Wno - type - defaults #
# OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver #
{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}
module Main where
import Algebra.Prelude.Core (IsOrderedPolynomial (coeff, leadingMonomial), Polynomial, toNatural, toSomeSNat, vars)
import qualified AlgebraicPrelude as AP
import Data.Data
import Data.List (inits)
import qualified Data.Map.Strict as Map
import Data.Reflection
import Data.Type.Natural (SNat (Succ, Zero), SomeSNat (SomeSNat), withKnownNat)
import Data.Type.Ordinal (enumOrdinal)
import GHC.TypeNats (KnownNat, type (^))
import Gauge
import Numeric.Algebra.Smooth.Weil
main :: IO ()
main =
defaultMain
[ bgroup
lab
[ case toSomeSNat n of
SomeSNat sn ->
bgroup
(show n)
[ bench "tensors" $ nf (diffUpToTensor sn input) 1.0
, bench "Dn" $ nf (diffUpToDn sn input) 1.0
]
| n <- [1 .. iter]
]
| (lab, MkSmooth input, iter) <-
[ ("identity", MkSmooth id, 10)
, ("exp x", MkSmooth exp, 10)
,
( "x * exp (-x * x + x)"
, MkSmooth $ \x ->
x * exp (- x * x + x)
, 9
)
]
]
data SomeDuals n where
MkSomeDuals :: (KnownNat n, KnownNat (2 ^ n), Reifies w (WeilSettings (2 ^ n) n)) => Proxy w -> SomeDuals n
deriving instance Show (SomeDuals n)
someDuals :: SNat n -> SomeDuals n
someDuals Zero = error "error: SomeDuals 0"
someDuals (Succ Zero) = MkSomeDuals $ Proxy @D1
someDuals sn@(Succ n) = withKnownNat sn $
case someDuals n of
MkSomeDuals (_ :: Proxy w) ->
MkSomeDuals $ Proxy @(w |*| D1)
diffUpToTensor :: forall n. SNat n -> (forall x. Floating x => x -> x) -> Double -> [Double]
diffUpToTensor Zero f x = [f x]
diffUpToTensor sn f x = case someDuals sn of
MkSomeDuals (_ :: Proxy w) ->
let ords = map (di @Double @w) $ enumOrdinal sn
input = injCoeWeil x + sum ords
terms = weilToPoly $ f input
in [ AP.unwrapFractional $ coeff mon terms
| vs <- inits $ vars @(Polynomial AP.Rational n)
, let mon = leadingMonomial $ product vs
]
diffUpToDn ::
(Floating a, Eq a) =>
SNat n ->
(forall x. Floating x => x -> x) ->
Double ->
[Double]
diffUpToDn sn f =
map snd . Map.toAscList . diffUpTo (toNatural sn) f
newtype Smooth where
MkSmooth :: (forall x. Floating x => x -> x) -> Smooth
| null | https://raw.githubusercontent.com/konn/smooth/bdbbd7e627177c6358d024803d339a9b15decb43/bench/higher-diff-speed.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise # | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
# OPTIONS_GHC -Wno - type - defaults #
# OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver #
module Main where
import Algebra.Prelude.Core (IsOrderedPolynomial (coeff, leadingMonomial), Polynomial, toNatural, toSomeSNat, vars)
import qualified AlgebraicPrelude as AP
import Data.Data
import Data.List (inits)
import qualified Data.Map.Strict as Map
import Data.Reflection
import Data.Type.Natural (SNat (Succ, Zero), SomeSNat (SomeSNat), withKnownNat)
import Data.Type.Ordinal (enumOrdinal)
import GHC.TypeNats (KnownNat, type (^))
import Gauge
import Numeric.Algebra.Smooth.Weil
main :: IO ()
main =
defaultMain
[ bgroup
lab
[ case toSomeSNat n of
SomeSNat sn ->
bgroup
(show n)
[ bench "tensors" $ nf (diffUpToTensor sn input) 1.0
, bench "Dn" $ nf (diffUpToDn sn input) 1.0
]
| n <- [1 .. iter]
]
| (lab, MkSmooth input, iter) <-
[ ("identity", MkSmooth id, 10)
, ("exp x", MkSmooth exp, 10)
,
( "x * exp (-x * x + x)"
, MkSmooth $ \x ->
x * exp (- x * x + x)
, 9
)
]
]
data SomeDuals n where
MkSomeDuals :: (KnownNat n, KnownNat (2 ^ n), Reifies w (WeilSettings (2 ^ n) n)) => Proxy w -> SomeDuals n
deriving instance Show (SomeDuals n)
someDuals :: SNat n -> SomeDuals n
someDuals Zero = error "error: SomeDuals 0"
someDuals (Succ Zero) = MkSomeDuals $ Proxy @D1
someDuals sn@(Succ n) = withKnownNat sn $
case someDuals n of
MkSomeDuals (_ :: Proxy w) ->
MkSomeDuals $ Proxy @(w |*| D1)
diffUpToTensor :: forall n. SNat n -> (forall x. Floating x => x -> x) -> Double -> [Double]
diffUpToTensor Zero f x = [f x]
diffUpToTensor sn f x = case someDuals sn of
MkSomeDuals (_ :: Proxy w) ->
let ords = map (di @Double @w) $ enumOrdinal sn
input = injCoeWeil x + sum ords
terms = weilToPoly $ f input
in [ AP.unwrapFractional $ coeff mon terms
| vs <- inits $ vars @(Polynomial AP.Rational n)
, let mon = leadingMonomial $ product vs
]
diffUpToDn ::
(Floating a, Eq a) =>
SNat n ->
(forall x. Floating x => x -> x) ->
Double ->
[Double]
diffUpToDn sn f =
map snd . Map.toAscList . diffUpTo (toNatural sn) f
newtype Smooth where
MkSmooth :: (forall x. Floating x => x -> x) -> Smooth
|
d25d004b53d29ef7176a00b6200940f8cc5be71c30204a0aa4eb558e2b3f3850 | fission-codes/fission | Error.hs | module Network.IPFS.Add.Error (Error (..)) where
import qualified Network.IPFS.Get.Error as Get
import Network.IPFS.Prelude
data Error
= InvalidFile
| UnexpectedOutput Text
| RecursiveAddErr Get.Error
| IPFSDaemonErr Text
| UnknownAddErr Text
deriving ( Exception
, Eq
, Generic
, Show
)
instance Display Error where
display = \case
InvalidFile -> "Invalid file"
UnexpectedOutput txt -> "Unexpected IPFS output: " <> display txt
RecursiveAddErr err -> "Error while adding directory" <> display err
IPFSDaemonErr txt -> "IPFS Daemon error: " <> display txt
UnknownAddErr txt -> "Unknown IPFS add error: " <> display txt
| null | https://raw.githubusercontent.com/fission-codes/fission/fb76d255f06ea73187c9b787bd207c3778e1b559/ipfs/library/Network/IPFS/Add/Error.hs | haskell | module Network.IPFS.Add.Error (Error (..)) where
import qualified Network.IPFS.Get.Error as Get
import Network.IPFS.Prelude
data Error
= InvalidFile
| UnexpectedOutput Text
| RecursiveAddErr Get.Error
| IPFSDaemonErr Text
| UnknownAddErr Text
deriving ( Exception
, Eq
, Generic
, Show
)
instance Display Error where
display = \case
InvalidFile -> "Invalid file"
UnexpectedOutput txt -> "Unexpected IPFS output: " <> display txt
RecursiveAddErr err -> "Error while adding directory" <> display err
IPFSDaemonErr txt -> "IPFS Daemon error: " <> display txt
UnknownAddErr txt -> "Unknown IPFS add error: " <> display txt
| |
e63e9d61e924060992c47ee8ca5af6049af1f2c9d48f212ecfe6a9e8ba5775ed | mkcp/raft-consensus | project.clj | (defproject raft "0.1.0"
:description "Toy raft implementation for use with jepsen-io/maelstrom"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:main raft.core
:dependencies [[org.clojure/clojure "1.9.0-alpha14"]
[org.clojure/core.async "0.2.374"]
[cheshire "5.7.0"]
[mount "0.1.11"]])
| null | https://raw.githubusercontent.com/mkcp/raft-consensus/575cc831d3861ae415e372bd6c15ab067b683471/project.clj | clojure | (defproject raft "0.1.0"
:description "Toy raft implementation for use with jepsen-io/maelstrom"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:main raft.core
:dependencies [[org.clojure/clojure "1.9.0-alpha14"]
[org.clojure/core.async "0.2.374"]
[cheshire "5.7.0"]
[mount "0.1.11"]])
| |
f235e406a9bb555d9a957b32fb0564588d8ef8607e91f6842059d20338d8fb6e | haskell-lisp/blaise | Expression.hs |
module Expression where
import Text.ParserCombinators.Parsec
import qualified Data.Map as Map
import Control.Monad.State
import Control.Monad.Error
-- Our Lisp expression
data Expr = BlaiseInt Integer |
BlaiseSymbol String |
BlaiseFn BlaiseFunction FunctionSignature |
BlaiseSpecial BlaiseFunction FunctionSignature |
BlaiseList [Expr]
-- The function type
type FunctionSignature = [String]
type BlaiseFunction = BlaiseResult
-- Context in which expressions will be evaluated
type SymbolTable = Map.Map String Expr
data Context = Ctx SymbolTable (Maybe Context)
-- Helper context functions
updateSymbol s eval_e = modify (\(Ctx sym_table parentCtx)->(Ctx (Map.insert s eval_e sym_table)) parentCtx)
updateSymbolInParent s eval_e = modify (\(Ctx sym_table parent_ctx)->(Ctx sym_table (updatedCtx parent_ctx)))
where updatedCtx (Just (Ctx sym_table ctx)) = (Just (Ctx (Map.insert s eval_e sym_table) ctx))
pushContext ctx = Ctx Map.empty (Just ctx)
popContext ctx@(Ctx _ Nothing) = ctx
popContext (Ctx _ (Just parentCtx)) = parentCtx
-- A state monad that holds a context and an evaluation result
type BlaiseError = ErrorT String IO
type BlaiseResult = StateT Context BlaiseError Expr
-- Printing the expression
instance Show Expr where
show (BlaiseInt x) = show x
show (BlaiseSymbol x) = x
show (BlaiseFn _ _) = "<function>"
show (BlaiseSpecial _ _) = "<special-form>"
show (BlaiseList x) = "(" ++ unwords (map show x) ++ ")"
-- Parsing the expression
parseInteger = do sign <- option "" (string "-")
number <- many1 digit
return $ BlaiseInt (read (sign++number))
parseSymbol = do f <- firstAllowed
r <- many (firstAllowed <|> digit)
return $ BlaiseSymbol (f:r)
where firstAllowed = oneOf "+-*/" <|> letter
parseExprAux = (try parseInteger) <|> (try parseSymbol) <|> (try parseList)
parseList = do char '(' ; skipMany space
x <- parseExprAux `sepEndBy` (many1 space)
char ')'
return $ BlaiseList x
parseExpr = do skipMany space
x <- parseExprAux
skipMany space ; eof
return x
parse :: String -> BlaiseResult
parse source = case (Text.ParserCombinators.Parsec.parse parseExpr "" source) of
Right x -> return x
Left e -> throwError $ show e
| null | https://raw.githubusercontent.com/haskell-lisp/blaise/17c75be05b6f6d2b2fff4774229ca733b2c5f0e3/src/Expression.hs | haskell | Our Lisp expression
The function type
Context in which expressions will be evaluated
Helper context functions
A state monad that holds a context and an evaluation result
Printing the expression
Parsing the expression
|
module Expression where
import Text.ParserCombinators.Parsec
import qualified Data.Map as Map
import Control.Monad.State
import Control.Monad.Error
data Expr = BlaiseInt Integer |
BlaiseSymbol String |
BlaiseFn BlaiseFunction FunctionSignature |
BlaiseSpecial BlaiseFunction FunctionSignature |
BlaiseList [Expr]
type FunctionSignature = [String]
type BlaiseFunction = BlaiseResult
type SymbolTable = Map.Map String Expr
data Context = Ctx SymbolTable (Maybe Context)
updateSymbol s eval_e = modify (\(Ctx sym_table parentCtx)->(Ctx (Map.insert s eval_e sym_table)) parentCtx)
updateSymbolInParent s eval_e = modify (\(Ctx sym_table parent_ctx)->(Ctx sym_table (updatedCtx parent_ctx)))
where updatedCtx (Just (Ctx sym_table ctx)) = (Just (Ctx (Map.insert s eval_e sym_table) ctx))
pushContext ctx = Ctx Map.empty (Just ctx)
popContext ctx@(Ctx _ Nothing) = ctx
popContext (Ctx _ (Just parentCtx)) = parentCtx
type BlaiseError = ErrorT String IO
type BlaiseResult = StateT Context BlaiseError Expr
instance Show Expr where
show (BlaiseInt x) = show x
show (BlaiseSymbol x) = x
show (BlaiseFn _ _) = "<function>"
show (BlaiseSpecial _ _) = "<special-form>"
show (BlaiseList x) = "(" ++ unwords (map show x) ++ ")"
parseInteger = do sign <- option "" (string "-")
number <- many1 digit
return $ BlaiseInt (read (sign++number))
parseSymbol = do f <- firstAllowed
r <- many (firstAllowed <|> digit)
return $ BlaiseSymbol (f:r)
where firstAllowed = oneOf "+-*/" <|> letter
parseExprAux = (try parseInteger) <|> (try parseSymbol) <|> (try parseList)
parseList = do char '(' ; skipMany space
x <- parseExprAux `sepEndBy` (many1 space)
char ')'
return $ BlaiseList x
parseExpr = do skipMany space
x <- parseExprAux
skipMany space ; eof
return x
parse :: String -> BlaiseResult
parse source = case (Text.ParserCombinators.Parsec.parse parseExpr "" source) of
Right x -> return x
Left e -> throwError $ show e
|
e325890eda55c3300b39fccccfa101c1954e79d2ed3d1fd89fc7b063a9d6d612 | NoRedInk/jetpack | Text.hs | module Utils.Text where
import Data.Text as T
{-| Check if a text starts with a given prefix.
>>> startsWith "--" "-- foo"
True
>>> startsWith "--" "-/ foo"
False
-}
startsWith :: T.Text -> T.Text -> Bool
startsWith start text = start == textStart
where
len = T.length start
(textStart, _) = T.splitAt len text
| null | https://raw.githubusercontent.com/NoRedInk/jetpack/721d12226b593c117cba26ceb7c463c7c3334b8b/src/Utils/Text.hs | haskell | | Check if a text starts with a given prefix.
>>> startsWith "--" "-- foo"
True
>>> startsWith "--" "-/ foo"
False
| module Utils.Text where
import Data.Text as T
startsWith :: T.Text -> T.Text -> Bool
startsWith start text = start == textStart
where
len = T.length start
(textStart, _) = T.splitAt len text
|
ce60effb3899c99b39ed80512d973efc2e13412787d4d0a3e245ef7c8099d385 | tonyg/racket-something | sh.rkt | #lang something/shell
// Simple demos
ls -la $HOME | grep "^d" | fgrep -v "."
ls -la | wc -l | read-line |> string-split |> car |> string->number |> \
printf "There are ~a lines here." | sed -e "s: are : seem to be :"
(newline)
def ps-output
pipeline
ps -wwwax
preserve-header 1 {: grep "racket" }
space-separated-columns [string->number]
|> csv-expr->table
print ps-output
def message-box text:
whiptail --title "Testing" --ok-button "OK" --msgbox text 8 50
message-box "This is pretty cool."
| null | https://raw.githubusercontent.com/tonyg/racket-something/4a00a9a6d37777f5aab4f28b03c53555b87e21d7/examples/sh.rkt | racket | #lang something/shell
// Simple demos
ls -la $HOME | grep "^d" | fgrep -v "."
ls -la | wc -l | read-line |> string-split |> car |> string->number |> \
printf "There are ~a lines here." | sed -e "s: are : seem to be :"
(newline)
def ps-output
pipeline
ps -wwwax
preserve-header 1 {: grep "racket" }
space-separated-columns [string->number]
|> csv-expr->table
print ps-output
def message-box text:
whiptail --title "Testing" --ok-button "OK" --msgbox text 8 50
message-box "This is pretty cool."
| |
6f91a894b0ac6203abd52da96a45a6d70334486bf3c777bcd096845c5921620e | ghc/ghc | Echo.hs | module Echo (plugin) where
import GHC.Plugins
import GHC.Tc.Plugin
import GHC.Tc.Utils.Monad
import qualified GHC.Tc.Utils.Monad as Utils
import GHC.Types.Unique.FM ( emptyUFM )
import System.IO
plugin :: Plugin
plugin = mkPureOptTcPlugin optCallCount
mkPureOptTcPlugin :: ([CommandLineOption] -> Maybe Utils.TcPlugin) -> Plugin
mkPureOptTcPlugin p =
defaultPlugin
{ tcPlugin = p
, pluginRecompile = impurePlugin
}
newtype State = State{callref :: IORef Int}
optCallCount :: [CommandLineOption] -> Maybe Utils.TcPlugin
optCallCount opts = Just $
Utils.TcPlugin
{ tcPluginInit = return . State =<< (unsafeTcPluginTcM $ newMutVar 1)
, tcPluginSolve = \State{callref = c} _ _ _ -> do
n <- unsafeTcPluginTcM $ readMutVar c
let msg = if null opts then "" else mconcat opts
tcPluginIO . putStrLn $ "Echo TcPlugin " ++ msg ++ "#" ++ show n
TODO : Remove # 20791
tcPluginIO $ hFlush stdout
unsafeTcPluginTcM $ writeMutVar c (n + 1)
return $ TcPluginOk [] []
, tcPluginRewrite = \ _ -> emptyUFM
, tcPluginStop = const $ return ()
}
| null | https://raw.githubusercontent.com/ghc/ghc/0196cc2ba8f848187be47b5fc53bab89e5026bf6/testsuite/tests/plugins/echo-plugin/Echo.hs | haskell | module Echo (plugin) where
import GHC.Plugins
import GHC.Tc.Plugin
import GHC.Tc.Utils.Monad
import qualified GHC.Tc.Utils.Monad as Utils
import GHC.Types.Unique.FM ( emptyUFM )
import System.IO
plugin :: Plugin
plugin = mkPureOptTcPlugin optCallCount
mkPureOptTcPlugin :: ([CommandLineOption] -> Maybe Utils.TcPlugin) -> Plugin
mkPureOptTcPlugin p =
defaultPlugin
{ tcPlugin = p
, pluginRecompile = impurePlugin
}
newtype State = State{callref :: IORef Int}
optCallCount :: [CommandLineOption] -> Maybe Utils.TcPlugin
optCallCount opts = Just $
Utils.TcPlugin
{ tcPluginInit = return . State =<< (unsafeTcPluginTcM $ newMutVar 1)
, tcPluginSolve = \State{callref = c} _ _ _ -> do
n <- unsafeTcPluginTcM $ readMutVar c
let msg = if null opts then "" else mconcat opts
tcPluginIO . putStrLn $ "Echo TcPlugin " ++ msg ++ "#" ++ show n
TODO : Remove # 20791
tcPluginIO $ hFlush stdout
unsafeTcPluginTcM $ writeMutVar c (n + 1)
return $ TcPluginOk [] []
, tcPluginRewrite = \ _ -> emptyUFM
, tcPluginStop = const $ return ()
}
| |
01dab906ba3793a25d5e8d49acea2f045b5dd9b3a81bcb1b04aa609fdc3ee7f3 | dmp1ce/DMSS | DaemonTest.hs | module DaemonTest (tests) where
import Test.Tasty
import Test.Tasty.HUnit
import Control.Concurrent
import DMSS.Config ( localDirectory )
import DMSS.Daemon ( daemonMain )
import DMSS.CLI ( runCommand, cliMain )
import DMSS.Daemon.Command ( Command (Status) )
import Common ( withTemporaryTestDirectory )
import System.Environment (withArgs)
import Data.List (isPrefixOf)
import DMSS.Daemon.Common ( cliPort )
import System.Directory (doesPathExist, doesFileExist)
tests :: [TestTree]
tests =
[ testCase "Daemon creates data directory" homedirCreated
, testCase "Daemon startup" daemonStartUp
, testCase "Two daemon startup" twoDaemonStartUp
]
tempDir :: FilePath
tempDir = "daemonTest"
-- NOTICE: Tests are run with different ports to prevent threads cleanup
-- from effecting ports on another test.
--
-- Using the same port from test to test will cause tests to not be able to
-- connect.
homedirCreated :: Assertion
homedirCreated = withTemporaryTestDirectory tempDir
( \homedir -> do
-- Start daemon silently
let newDatadir = homedir ++ "/test"
t <- forkIO $ withArgs [ "-s"
, "--homedir=" ++ newDatadir
, "--cli-port=8006"
, "--peer-port=8007"
] daemonMain
Allow Daemon to start . 1 second delay
threadDelay (1000 * 1000)
-- Verify data directory was created
pathExists <- doesPathExist newDatadir
assertBool (newDatadir ++ " directory has been created.") pathExists
-- Verify database was created
let sqlFile = newDatadir ++ "/.local/share/dmss/dmss.sqlite"
dataExists <- doesFileExist sqlFile
assertBool (sqlFile ++ " database has been created.") dataExists
-- Stop Daemon
killThread t
)
daemonStartUp :: Assertion
daemonStartUp = withTemporaryTestDirectory tempDir ( \homedir -> do
-- Start daemon silently
t <- forkIO $ withArgs ["-s"] daemonMain
Allow Daemon to start . 1 second delay
threadDelay (1000 * 1000)
-- Verify it is running with status command
r <- runCommand cliPort Status
-- Stop Daemon
killThread t
-- Make sure home directory is correct
l <- localDirectory
assertBool
(homedir ++ " is not the prefix of actual home directory " ++ l)
(homedir `isPrefixOf` l)
Just "Daemon is running!" @=? r
)
Test that can be run side by side without colliding in any way
twoDaemonStartUp :: Assertion
twoDaemonStartUp = withTemporaryTestDirectory tempDir $ \h1-> do
-- Start daemon silently
t1 <- forkIO $ withArgs
[ "--homedir=" ++ h1
, "--cli-port=7006"
, "--peer-port=7007"
, "-s"
] daemonMain
Allow Daemon to start . 1 second delay
threadDelay (1000 * 1000)
-- Make sure home directory is correct
l1 <- localDirectory
assertBool
(h1 ++ " is not the prefix of actual home directory " ++ l1)
(h1 `isPrefixOf` l1)
Start daemon two silently with different home directory
let h2 = h1 ++ "daemon2"
t2 <- forkIO $ withArgs
[ "--homedir=" ++ h2
, "--cli-port=6006"
, "--peer-port=6007"
, "-s"
] daemonMain
Allow Daemon to start . 1 second delay
threadDelay (1000 * 1000)
-- Verify both daemons are running with status command
r1 < - withArgs [ ] ( cliPort Status )
_ <- withArgs ["--silent", "--homedir=" ++ h1, "--port=7006", "status"] cliMain
killThread t1
threadDelay (1000 * 1000)
_ <- withArgs ["--silent", "--homedir=" ++ h2, "--port=6006", "status"] cliMain
killThread t2
-- Make sure home directory is correct
l2 <- localDirectory
assertBool
(h2 ++ " is not the prefix of actual home directory " ++ l1)
(h2 `isPrefixOf` l2)
| null | https://raw.githubusercontent.com/dmp1ce/DMSS/fd88690d97ed267e76f8345e6a76cd3727ef4efb/src-test/DaemonTest.hs | haskell | NOTICE: Tests are run with different ports to prevent threads cleanup
from effecting ports on another test.
Using the same port from test to test will cause tests to not be able to
connect.
Start daemon silently
Verify data directory was created
Verify database was created
Stop Daemon
Start daemon silently
Verify it is running with status command
Stop Daemon
Make sure home directory is correct
Start daemon silently
Make sure home directory is correct
Verify both daemons are running with status command
Make sure home directory is correct | module DaemonTest (tests) where
import Test.Tasty
import Test.Tasty.HUnit
import Control.Concurrent
import DMSS.Config ( localDirectory )
import DMSS.Daemon ( daemonMain )
import DMSS.CLI ( runCommand, cliMain )
import DMSS.Daemon.Command ( Command (Status) )
import Common ( withTemporaryTestDirectory )
import System.Environment (withArgs)
import Data.List (isPrefixOf)
import DMSS.Daemon.Common ( cliPort )
import System.Directory (doesPathExist, doesFileExist)
tests :: [TestTree]
tests =
[ testCase "Daemon creates data directory" homedirCreated
, testCase "Daemon startup" daemonStartUp
, testCase "Two daemon startup" twoDaemonStartUp
]
tempDir :: FilePath
tempDir = "daemonTest"
homedirCreated :: Assertion
homedirCreated = withTemporaryTestDirectory tempDir
( \homedir -> do
let newDatadir = homedir ++ "/test"
t <- forkIO $ withArgs [ "-s"
, "--homedir=" ++ newDatadir
, "--cli-port=8006"
, "--peer-port=8007"
] daemonMain
Allow Daemon to start . 1 second delay
threadDelay (1000 * 1000)
pathExists <- doesPathExist newDatadir
assertBool (newDatadir ++ " directory has been created.") pathExists
let sqlFile = newDatadir ++ "/.local/share/dmss/dmss.sqlite"
dataExists <- doesFileExist sqlFile
assertBool (sqlFile ++ " database has been created.") dataExists
killThread t
)
daemonStartUp :: Assertion
daemonStartUp = withTemporaryTestDirectory tempDir ( \homedir -> do
t <- forkIO $ withArgs ["-s"] daemonMain
Allow Daemon to start . 1 second delay
threadDelay (1000 * 1000)
r <- runCommand cliPort Status
killThread t
l <- localDirectory
assertBool
(homedir ++ " is not the prefix of actual home directory " ++ l)
(homedir `isPrefixOf` l)
Just "Daemon is running!" @=? r
)
Test that can be run side by side without colliding in any way
twoDaemonStartUp :: Assertion
twoDaemonStartUp = withTemporaryTestDirectory tempDir $ \h1-> do
t1 <- forkIO $ withArgs
[ "--homedir=" ++ h1
, "--cli-port=7006"
, "--peer-port=7007"
, "-s"
] daemonMain
Allow Daemon to start . 1 second delay
threadDelay (1000 * 1000)
l1 <- localDirectory
assertBool
(h1 ++ " is not the prefix of actual home directory " ++ l1)
(h1 `isPrefixOf` l1)
Start daemon two silently with different home directory
let h2 = h1 ++ "daemon2"
t2 <- forkIO $ withArgs
[ "--homedir=" ++ h2
, "--cli-port=6006"
, "--peer-port=6007"
, "-s"
] daemonMain
Allow Daemon to start . 1 second delay
threadDelay (1000 * 1000)
r1 < - withArgs [ ] ( cliPort Status )
_ <- withArgs ["--silent", "--homedir=" ++ h1, "--port=7006", "status"] cliMain
killThread t1
threadDelay (1000 * 1000)
_ <- withArgs ["--silent", "--homedir=" ++ h2, "--port=6006", "status"] cliMain
killThread t2
l2 <- localDirectory
assertBool
(h2 ++ " is not the prefix of actual home directory " ++ l1)
(h2 `isPrefixOf` l2)
|
c2fb301eb3e18e49941aaac0238149b5621ff5e510357453996f486df1d53399 | ClockworksIO/rum-natal | config.cljs | (ns env.config)
(def figwheel-urls {:ios "ws:3449/figwheel-ws"
:android "ws:3449/figwheel-ws"})
| null | https://raw.githubusercontent.com/ClockworksIO/rum-natal/fee021a360a085d4e8b67d44ac2c998e2fcdc571/resources/leiningen/new/rum_natal/env/dev/env/config.cljs | clojure | (ns env.config)
(def figwheel-urls {:ios "ws:3449/figwheel-ws"
:android "ws:3449/figwheel-ws"})
| |
810954e5cc119c88eeb1c85c634038add32dff85bb683010666e37b5999e5fcf | xvw/preface | traversable.mli | * A [ ] is a data structure that can be traversed from left to
right , performing an action on each element .
right, performing an action on each element. *)
* A common usage of [ ] is to turn any [ ] of
{ ! module : Applicative } into a { ! module : Applicative } of [ ] .
For example , going to [ ' a option list ] to [ ' a list option ] .
{!module:Applicative} into a {!module:Applicative} of [Traversable].
For example, going to ['a option list] to ['a list option]. *)
* { 1 Minimal definition }
(** Minimal definition using [traverse] over a ['a iter].*)
module type WITH_TRAVERSE = sig
type 'a t
* The type held by the [ ] .
type 'a iter
* The iterable type held by the [ ] .
val traverse : ('a -> 'b t) -> 'a iter -> 'b iter t
(** Map each element of a structure to an action, evaluate these actions from
left to right, and collect the results. **)
end
(** {1 Structure anatomy} *)
module type CORE = WITH_TRAVERSE
(** Basis operations. *)
(** Additional operations. *)
module type OPERATION = sig
type 'a t
* The type held by the [ ] .
type 'a iter
* The iterable type held by the [ ] .
val sequence : 'a t iter -> 'a iter t
(** Evaluate each action in the structure from left to right, and collect the
results *)
end
(** {1 Complete API} *)
* The complete interface of a [ ]
module type API = sig
(** {1 Types} *)
type 'a t
* The type held by the [ ] .
type 'a iter
* The iterable type held by the [ ] .
* { 1 Functions }
* @inline
include CORE with type 'a t := 'a t and type 'a iter := 'a iter
* @inline
include OPERATION with type 'a t := 'a t and type 'a iter := 'a iter
end
* The complete interface of a [ ] over a { ! module : Monad }
module type API_OVER_MONAD = sig
include Monad.API
* @inline
* { 1 using Monad form }
module Traversable (M : Monad.API) :
API with type 'a iter = 'a t and type 'a t = 'a M.t
end
* The complete interface of a [ ] over an { ! module : Applicative }
module type API_OVER_APPLICATIVE = sig
include Applicative.API
* @inline
* { 1 using Applicative form }
module Traversable (A : Applicative.API) :
API with type 'a iter = 'a t and type 'a t = 'a A.t
end
* { 1 Additional references }
- { { : /~ross/papers/Applicative.html } Applicative
Programming with Effects }
- { { : /#iterator }
The Essence of the Iterator Pattern }
- { { : } An Investigation of the Laws of
}
- {{:/~ross/papers/Applicative.html} Applicative
Programming with Effects}
- {{:/#iterator}
The Essence of the Iterator Pattern}
- {{:} An Investigation of the Laws of
Traversals} *)
| null | https://raw.githubusercontent.com/xvw/preface/b54d6ef98957bb3e00eaa4bf36b3d79b8da859fe/lib/preface_specs/traversable.mli | ocaml | * Minimal definition using [traverse] over a ['a iter].
* Map each element of a structure to an action, evaluate these actions from
left to right, and collect the results. *
* {1 Structure anatomy}
* Basis operations.
* Additional operations.
* Evaluate each action in the structure from left to right, and collect the
results
* {1 Complete API}
* {1 Types} | * A [ ] is a data structure that can be traversed from left to
right , performing an action on each element .
right, performing an action on each element. *)
* A common usage of [ ] is to turn any [ ] of
{ ! module : Applicative } into a { ! module : Applicative } of [ ] .
For example , going to [ ' a option list ] to [ ' a list option ] .
{!module:Applicative} into a {!module:Applicative} of [Traversable].
For example, going to ['a option list] to ['a list option]. *)
* { 1 Minimal definition }
module type WITH_TRAVERSE = sig
type 'a t
* The type held by the [ ] .
type 'a iter
* The iterable type held by the [ ] .
val traverse : ('a -> 'b t) -> 'a iter -> 'b iter t
end
module type CORE = WITH_TRAVERSE
module type OPERATION = sig
type 'a t
* The type held by the [ ] .
type 'a iter
* The iterable type held by the [ ] .
val sequence : 'a t iter -> 'a iter t
end
* The complete interface of a [ ]
module type API = sig
type 'a t
* The type held by the [ ] .
type 'a iter
* The iterable type held by the [ ] .
* { 1 Functions }
* @inline
include CORE with type 'a t := 'a t and type 'a iter := 'a iter
* @inline
include OPERATION with type 'a t := 'a t and type 'a iter := 'a iter
end
* The complete interface of a [ ] over a { ! module : Monad }
module type API_OVER_MONAD = sig
include Monad.API
* @inline
* { 1 using Monad form }
module Traversable (M : Monad.API) :
API with type 'a iter = 'a t and type 'a t = 'a M.t
end
* The complete interface of a [ ] over an { ! module : Applicative }
module type API_OVER_APPLICATIVE = sig
include Applicative.API
* @inline
* { 1 using Applicative form }
module Traversable (A : Applicative.API) :
API with type 'a iter = 'a t and type 'a t = 'a A.t
end
* { 1 Additional references }
- { { : /~ross/papers/Applicative.html } Applicative
Programming with Effects }
- { { : /#iterator }
The Essence of the Iterator Pattern }
- { { : } An Investigation of the Laws of
}
- {{:/~ross/papers/Applicative.html} Applicative
Programming with Effects}
- {{:/#iterator}
The Essence of the Iterator Pattern}
- {{:} An Investigation of the Laws of
Traversals} *)
|
6535114500cbeecea96f73704585af82fe63d7c97db40754bc0393f18ebdb9c5 | elaforge/karya | Postproc_test.hs | Copyright 2014
-- This program is distributed under the terms of the GNU General Public
-- License 3.0, see COPYING or -3.0.txt
module Derive.C.Post.Postproc_test where
import qualified Util.Seq as Seq
import Util.Test
import qualified Ui.UiTest as UiTest
import qualified Derive.C.Post.Postproc as Postproc
import qualified Derive.C.Prelude.Note as Note
import qualified Derive.DeriveTest as DeriveTest
import qualified Derive.Score as Score
import Global
-- * cancel
test_cancel :: Test
test_cancel = do
let run = DeriveTest.extract DeriveTest.e_note
. DeriveTest.derive_tracks "cancel" . UiTest.note_track
notes n1 n2 = [(0, 2, n1 <> "d 2 | -- 4c"), (2, 3, n2 <> "-- 4d")]
-- No flags, no cancel.
equal (run (notes "" ""))
([(2, 2, "4c"), (2, 3, "4d")], [])
equal (run (notes "" "add-flag weak | "))
([(2, 2, "4c")], [])
equal (run (notes "add-flag weak | " ""))
([(2, 3, "4d")], [])
equal (run (notes "add-flag strong | " ""))
([(2, 2, "4c")], [])
-- Multiple weaks and strongs together are ok.
equal (run (notes "add-flag weak | " "add-flag weak | "))
([(2, 2, "4c"), (2, 3, "4d")], [])
equal (run (notes "add-flag strong | " "add-flag strong | "))
([(2, 2, "4c"), (2, 3, "4d")], [])
test_infer_duration_block :: Test
test_infer_duration_block = do
-- The note deriver automatically adds flags so that a note at the end of
-- a block can cancel the next event and get an inferred duration.
let run = DeriveTest.extract DeriveTest.e_note . DeriveTest.derive_blocks
top = ("top -- cancel 2",
[(">", [(0, 2, "sub")]), (">", [(2, 2, "sub")])])
sub notes = ("sub=ruler", UiTest.note_track notes)
equal (run [top, sub [(1, 1, "4c"), (2, 0, "4d")]])
([(1, 1, "4c"), (2, 1, "4d"), (3, 1, "4c"), (4, 2, "4d")], [])
First note is cancelled out .
equal (run [top, sub [(0, 1, "4c"), (1, 1, "4d"), (2, 0, "4e")]])
([(0, 1, "4c"), (1, 1, "4d"), (2, 1, "4e"), (3, 1, "4d"), (4, 2, "4e")],
[])
-- The inferred note takes the duration of the replaced one.
equal (run [top, sub [(0, 1.5, "4c"), (2, 0, "4d")]])
([(0, 1.5, "4c"), (2, 1.5, "4d"), (4, 2, "4d")], [])
A zero duration block does n't have its duration changed , since otherwise
-- I can't write single note calls for e.g. percussion.
equal (run [top, sub [(0, 0, "4c")]]) ([(0, 0, "4c"), (2, 0, "4c")], [])
test_infer_duration :: Test
test_infer_duration = do
let run extract = DeriveTest.extract extract
. DeriveTest.derive_tracks "cancel" . UiTest.note_track
-- Infer duration to fill the gap.
equal (run DeriveTest.e_note
[(0, 1, "add-flag infer-duration | -- 4c"), (4, 1, "4d")])
([(0, 4, "4c"), (4, 1, "4d")], [])
-- Also the flag is removed to avoid inferring twice.
equal (run Score.event_flags
[(0, 0, "add-flag infer-duration | -- 4c"), (4, 1, "4d")])
([mempty, mempty], [])
test_suppress_until :: Test
test_suppress_until = do
let run = DeriveTest.extract Score.event_start
. DeriveTest.derive_tracks "cancel 1"
. map (second (map (\(d, t) -> (d, 1, t))))
suppress t = "suppress-until = " <> t <> " | --"
equal (run [(">", [(0, ""), (1, "")])]) ([0, 1], [])
equal (run [(">", [(0, ""), (1, suppress "2s"), (2, ""), (3, "")])])
([0, 1, 3], [])
-- Suppression works even with a coincident note coming later.
equal (run
[ (">", [(0, ""), (1, ""), (2, ""), (3, "")])
, (">", [(1, suppress "2s")])
])
([0, 1, 3], [])
test_randomize_start :: Test
test_randomize_start = do
let run title = DeriveTest.extract Score.event_start
. DeriveTest.derive_tracks title
let notes = [(">", [(0, 1, ""), (1, 1, "")])]
let (starts, logs) = run "randomize-start 5" notes
equal logs []
not_equal starts [0, 1]
-- * other
test_apply_start_offset :: Test
test_apply_start_offset = do
let run = DeriveTest.extract DeriveTest.e_note . DeriveTest.derive_blocks
top = "top -- apply-start-offset .25"
min_dur = 0.25
equal (run [(top, UiTest.note_track [(1, 1, "%start-s=1 | -- 4c")])])
([(2, min_dur, "4c")], [])
equal (run
[ (top, UiTest.note_track [(2, 2, "%start-s = -1 | sub -- 4c")])
, ("sub=ruler", [(">", [(0, 1, "")])])
])
([(1, 3, "4c")], [])
equal (run [(top, ("tempo", [(0, 0, "2")])
: UiTest.note_track [(2, 2, "%start-t=1 | -- 4c")])])
([(1.5, 0.5, "4c")], [])
0 1 2 3
4c--4d--4e--|
let start offset = "%start-s = " <> offset
let neighbors offset = UiTest.note_track
[(0, 1, "4c"), (1, 1, start offset <> " | -- 4d") , (2, 1, "4e")]
equal (run [(top, neighbors "-.5")])
([(0, 0.5, "4c"), (0.5, 1.5, "4d"), (2, 1, "4e")], [])
-- It's already overlapping, so don't change the duration.
equal (run [(top, UiTest.note_track
[ (0, 1, "%sus=1.5 | -- 4c"), (1, 1, start "-.5" <> " | -- 4d")
, (2, 1, "4e")
])])
([(0, 1.5, "4c"), (0.5, 1.5, "4d"), (2, 1, "4e")], [])
-- Not overlapping, but will shorten.
equal (run [(top, UiTest.note_track
[ (0, 1, "%sus=.75 | -- 4c"), (1, 1, start "-.5" <> " | -- 4d")
, (2, 1, "4e")
])])
([(0, 0.5, "4c"), (0.5, 1.5, "4d"), (2, 1, "4e")], [])
-- Bounded by previous or next notes.
equal (run [(top, neighbors "-2")])
([(0, min_dur, "4c"), (min_dur, 2 - min_dur, "4d"), (2, 1, "4e")], [])
test_apply_start_offset_sorted :: Test
test_apply_start_offset_sorted = do
-- The output is still sorted after applying start offset.
let run = DeriveTest.extract DeriveTest.e_note
. DeriveTest.derive_tracks "apply-start-offset"
. UiTest.note_track
equal (run [(0, 1, "%start-s = 2 | -- 4c"), (1, 1, "4d")])
([(1, 1, "4d"), (2, Note.min_duration, "4c")], [])
test_adjust_offset :: Test
test_adjust_offset = do
let f (s1, o1) (s2, o2) =
( s1 + Postproc.adjust_offset d Nothing (Just (o2, s2)) o1 s1
, s2 + Postproc.adjust_offset d (Just (o1, s1)) Nothing o2 s2
)
d = 0.25
range s e = Seq.range s e (if e >= s then 1 else -1)
There are two variations : they can move in the same direction , or in
-- opposite directions. And then, the directions can be positive or
-- negative.
0 1 2 3 4 5
-- |---> - - - - - >
>
equal [[f (0, o1) (2, o2) | o1 <- range 0 4] | o2 <- range 0 3]
[ [(0, 2), (1, 2), (2-d, 2), (2-d, 2), (2-d, 2)]
, [(0, 3), (1, 3), (2, 3), (3-d, 3), (3-d, 3)]
, [(0, 4), (1, 4), (2, 4), (3, 4), (4-d, 4)]
, [(0, 5), (1, 5), (2, 5), (3, 5), (4, 5)]
]
0 1 2 3 4 5
-- |---> - - - - - >
-- < - - - - - <---|
equal [[f (1, o1) (4, o2) | o1 <- range 0 4] | o2 <- range 0 (-3)]
[ [(1, 4), (2, 4), (3, 4), (4-d, 4), (4-d, 4)]
, [(1, 3), (2, 3), (3-d, 3), (3.5-d, 3.5), (3.5-d, 3.5)]
, [(1, 2), (2-d, 2), (2.5-d, 2.5), (3-d, 3), (3-d, 3)]
, [(1, 1+d), (1.5-d, 1.5), (2-d, 2), (2.5-d, 2.5), (2.5-d, 2.5)]
]
0 1 2 3 4 5
-- < - - - <---|
-- < - - - - - <---|
equal [[f (3, o1) (5, o2) | o1 <- range 0 (-3)] | o2 <- range 0 (-4)]
[ [(3, 5), (2, 5), (1, 5), (0, 5)]
, [(3, 4), (2, 4), (1, 4), (0, 4)]
, [(3, 3+d), (2, 3), (1, 3), (0, 3)]
, [(3, 3+d), (2, 2+d), (1, 2), (0, 2)]
, [(3, 3+d), (2, 2+d), (1, 1+d), (0, 1)]
]
| null | https://raw.githubusercontent.com/elaforge/karya/8ea15e6a5fb57e2f15f8c19836751e315f9c09f2/Derive/C/Post/Postproc_test.hs | haskell | This program is distributed under the terms of the GNU General Public
License 3.0, see COPYING or -3.0.txt
* cancel
No flags, no cancel.
Multiple weaks and strongs together are ok.
The note deriver automatically adds flags so that a note at the end of
a block can cancel the next event and get an inferred duration.
The inferred note takes the duration of the replaced one.
I can't write single note calls for e.g. percussion.
Infer duration to fill the gap.
Also the flag is removed to avoid inferring twice.
Suppression works even with a coincident note coming later.
* other
4d--4e--|
It's already overlapping, so don't change the duration.
Not overlapping, but will shorten.
Bounded by previous or next notes.
The output is still sorted after applying start offset.
opposite directions. And then, the directions can be positive or
negative.
|---> - - - - - >
|---> - - - - - >
< - - - - - <---|
< - - - <---|
< - - - - - <---| | Copyright 2014
module Derive.C.Post.Postproc_test where
import qualified Util.Seq as Seq
import Util.Test
import qualified Ui.UiTest as UiTest
import qualified Derive.C.Post.Postproc as Postproc
import qualified Derive.C.Prelude.Note as Note
import qualified Derive.DeriveTest as DeriveTest
import qualified Derive.Score as Score
import Global
test_cancel :: Test
test_cancel = do
let run = DeriveTest.extract DeriveTest.e_note
. DeriveTest.derive_tracks "cancel" . UiTest.note_track
notes n1 n2 = [(0, 2, n1 <> "d 2 | -- 4c"), (2, 3, n2 <> "-- 4d")]
equal (run (notes "" ""))
([(2, 2, "4c"), (2, 3, "4d")], [])
equal (run (notes "" "add-flag weak | "))
([(2, 2, "4c")], [])
equal (run (notes "add-flag weak | " ""))
([(2, 3, "4d")], [])
equal (run (notes "add-flag strong | " ""))
([(2, 2, "4c")], [])
equal (run (notes "add-flag weak | " "add-flag weak | "))
([(2, 2, "4c"), (2, 3, "4d")], [])
equal (run (notes "add-flag strong | " "add-flag strong | "))
([(2, 2, "4c"), (2, 3, "4d")], [])
test_infer_duration_block :: Test
test_infer_duration_block = do
let run = DeriveTest.extract DeriveTest.e_note . DeriveTest.derive_blocks
top = ("top -- cancel 2",
[(">", [(0, 2, "sub")]), (">", [(2, 2, "sub")])])
sub notes = ("sub=ruler", UiTest.note_track notes)
equal (run [top, sub [(1, 1, "4c"), (2, 0, "4d")]])
([(1, 1, "4c"), (2, 1, "4d"), (3, 1, "4c"), (4, 2, "4d")], [])
First note is cancelled out .
equal (run [top, sub [(0, 1, "4c"), (1, 1, "4d"), (2, 0, "4e")]])
([(0, 1, "4c"), (1, 1, "4d"), (2, 1, "4e"), (3, 1, "4d"), (4, 2, "4e")],
[])
equal (run [top, sub [(0, 1.5, "4c"), (2, 0, "4d")]])
([(0, 1.5, "4c"), (2, 1.5, "4d"), (4, 2, "4d")], [])
A zero duration block does n't have its duration changed , since otherwise
equal (run [top, sub [(0, 0, "4c")]]) ([(0, 0, "4c"), (2, 0, "4c")], [])
test_infer_duration :: Test
test_infer_duration = do
let run extract = DeriveTest.extract extract
. DeriveTest.derive_tracks "cancel" . UiTest.note_track
equal (run DeriveTest.e_note
[(0, 1, "add-flag infer-duration | -- 4c"), (4, 1, "4d")])
([(0, 4, "4c"), (4, 1, "4d")], [])
equal (run Score.event_flags
[(0, 0, "add-flag infer-duration | -- 4c"), (4, 1, "4d")])
([mempty, mempty], [])
test_suppress_until :: Test
test_suppress_until = do
let run = DeriveTest.extract Score.event_start
. DeriveTest.derive_tracks "cancel 1"
. map (second (map (\(d, t) -> (d, 1, t))))
suppress t = "suppress-until = " <> t <> " | --"
equal (run [(">", [(0, ""), (1, "")])]) ([0, 1], [])
equal (run [(">", [(0, ""), (1, suppress "2s"), (2, ""), (3, "")])])
([0, 1, 3], [])
equal (run
[ (">", [(0, ""), (1, ""), (2, ""), (3, "")])
, (">", [(1, suppress "2s")])
])
([0, 1, 3], [])
test_randomize_start :: Test
test_randomize_start = do
let run title = DeriveTest.extract Score.event_start
. DeriveTest.derive_tracks title
let notes = [(">", [(0, 1, ""), (1, 1, "")])]
let (starts, logs) = run "randomize-start 5" notes
equal logs []
not_equal starts [0, 1]
test_apply_start_offset :: Test
test_apply_start_offset = do
let run = DeriveTest.extract DeriveTest.e_note . DeriveTest.derive_blocks
top = "top -- apply-start-offset .25"
min_dur = 0.25
equal (run [(top, UiTest.note_track [(1, 1, "%start-s=1 | -- 4c")])])
([(2, min_dur, "4c")], [])
equal (run
[ (top, UiTest.note_track [(2, 2, "%start-s = -1 | sub -- 4c")])
, ("sub=ruler", [(">", [(0, 1, "")])])
])
([(1, 3, "4c")], [])
equal (run [(top, ("tempo", [(0, 0, "2")])
: UiTest.note_track [(2, 2, "%start-t=1 | -- 4c")])])
([(1.5, 0.5, "4c")], [])
0 1 2 3
let start offset = "%start-s = " <> offset
let neighbors offset = UiTest.note_track
[(0, 1, "4c"), (1, 1, start offset <> " | -- 4d") , (2, 1, "4e")]
equal (run [(top, neighbors "-.5")])
([(0, 0.5, "4c"), (0.5, 1.5, "4d"), (2, 1, "4e")], [])
equal (run [(top, UiTest.note_track
[ (0, 1, "%sus=1.5 | -- 4c"), (1, 1, start "-.5" <> " | -- 4d")
, (2, 1, "4e")
])])
([(0, 1.5, "4c"), (0.5, 1.5, "4d"), (2, 1, "4e")], [])
equal (run [(top, UiTest.note_track
[ (0, 1, "%sus=.75 | -- 4c"), (1, 1, start "-.5" <> " | -- 4d")
, (2, 1, "4e")
])])
([(0, 0.5, "4c"), (0.5, 1.5, "4d"), (2, 1, "4e")], [])
equal (run [(top, neighbors "-2")])
([(0, min_dur, "4c"), (min_dur, 2 - min_dur, "4d"), (2, 1, "4e")], [])
test_apply_start_offset_sorted :: Test
test_apply_start_offset_sorted = do
let run = DeriveTest.extract DeriveTest.e_note
. DeriveTest.derive_tracks "apply-start-offset"
. UiTest.note_track
equal (run [(0, 1, "%start-s = 2 | -- 4c"), (1, 1, "4d")])
([(1, 1, "4d"), (2, Note.min_duration, "4c")], [])
test_adjust_offset :: Test
test_adjust_offset = do
let f (s1, o1) (s2, o2) =
( s1 + Postproc.adjust_offset d Nothing (Just (o2, s2)) o1 s1
, s2 + Postproc.adjust_offset d (Just (o1, s1)) Nothing o2 s2
)
d = 0.25
range s e = Seq.range s e (if e >= s then 1 else -1)
There are two variations : they can move in the same direction , or in
0 1 2 3 4 5
>
equal [[f (0, o1) (2, o2) | o1 <- range 0 4] | o2 <- range 0 3]
[ [(0, 2), (1, 2), (2-d, 2), (2-d, 2), (2-d, 2)]
, [(0, 3), (1, 3), (2, 3), (3-d, 3), (3-d, 3)]
, [(0, 4), (1, 4), (2, 4), (3, 4), (4-d, 4)]
, [(0, 5), (1, 5), (2, 5), (3, 5), (4, 5)]
]
0 1 2 3 4 5
equal [[f (1, o1) (4, o2) | o1 <- range 0 4] | o2 <- range 0 (-3)]
[ [(1, 4), (2, 4), (3, 4), (4-d, 4), (4-d, 4)]
, [(1, 3), (2, 3), (3-d, 3), (3.5-d, 3.5), (3.5-d, 3.5)]
, [(1, 2), (2-d, 2), (2.5-d, 2.5), (3-d, 3), (3-d, 3)]
, [(1, 1+d), (1.5-d, 1.5), (2-d, 2), (2.5-d, 2.5), (2.5-d, 2.5)]
]
0 1 2 3 4 5
equal [[f (3, o1) (5, o2) | o1 <- range 0 (-3)] | o2 <- range 0 (-4)]
[ [(3, 5), (2, 5), (1, 5), (0, 5)]
, [(3, 4), (2, 4), (1, 4), (0, 4)]
, [(3, 3+d), (2, 3), (1, 3), (0, 3)]
, [(3, 3+d), (2, 2+d), (1, 2), (0, 2)]
, [(3, 3+d), (2, 2+d), (1, 1+d), (0, 1)]
]
|
255f3ea62d3a626ea305f87bd78628d7b937c70015b15c8c65415e986daa4418 | xh4/web-toolkit | packages.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
$ Header : /usr / local / cvsrep / cl - unicode / test / packages.lisp , v 1.3 2012 - 05 - 04 21:17:48 edi Exp $
Copyright ( c ) 2008 - 2012 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
(defpackage :cl-unicode-test
(:use :cl :cl-unicode)
(:export :run-all-tests))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/cl-unicode-20190521-git/test/packages.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | $ Header : /usr / local / cvsrep / cl - unicode / test / packages.lisp , v 1.3 2012 - 05 - 04 21:17:48 edi Exp $
Copyright ( c ) 2008 - 2012 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :cl-user)
(defpackage :cl-unicode-test
(:use :cl :cl-unicode)
(:export :run-all-tests))
|
fc9032606fc2b5b2ca1d75cd3b7e41f270f0002b170917e5229ad4e064f2c131 | KestrelInstitute/Specware | swank-asdf.lisp | ;;; swank-asdf.lisp -- ASDF support
;;
Authors : < >
< >
< >
< >
;; and others
;; License: Public Domain
;;
(in-package :swank)
(eval-when (:compile-toplevel :load-toplevel :execute)
;;; The best way to load ASDF is from an init file of an
;;; implementation. If ASDF is not loaded at the time swank-asdf is
loaded , it will be tried first with ( require " asdf " ) , if that
;;; doesn't help and *asdf-path* is set, it will be loaded from that
;;; file.
;;; To set *asdf-path* put the following into ~/.swank.lisp:
( * # p"/path / to / asdf / asdf.lisp " )
(defvar *asdf-path* nil
"Path to asdf.lisp file, to be loaded in case (require \"asdf\") fails."))
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (member :asdf *features*)
(ignore-errors (let ((saved-fasl-type sb-fasl:*fasl-file-type*)) ; sjw
(setq sb-fasl:*fasl-file-type* "fasl")
(funcall 'require "asdf")
(setq sb-fasl:*fasl-file-type* saved-fasl-type)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (member :asdf *features*)
(handler-bind ((warning #'muffle-warning))
(when *asdf-path*
(load *asdf-path* :if-does-not-exist nil)))))
;; If still not found, error out.
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (member :asdf *features*)
(error "Could not load ASDF.
Please update your implementation or
install a recent release of ASDF and in your ~~/.swank.lisp specify:
(defparameter swank::*asdf-path* #p\"/path/containing/asdf/asdf.lisp\")")))
;;; If ASDF is too old, punt.
As of January 2014 , Quicklisp has been providing 2.26 for a year
( and previously had 2.014.6 for over a year ) , whereas
all SLIME - supported implementations provide ASDF3 ( i.e. 2.27 or later )
except LispWorks ( stuck with 2.019 ) and SCL ( which has n't been released
in years and does n't provide ASDF at all , but is fully supported by ASDF ) .
;; If your implementation doesn't provide ASDF, or provides an old one,
;; install an upgrade yourself and configure *asdf-path*.
;; It's just not worth the hassle supporting something
;; that doesn't even have COERCE-PATHNAME.
;;
NB : this version check is duplicated in swank-loader.lisp so that we do n't
try to load this contrib when ASDF is too old since that will abort the SLIME
;; connection.
#-asdf3
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (and #+asdf2 (asdf:version-satisfies (asdf:asdf-version) "2.14.6"))
(error "Your ASDF is too old. ~
The oldest version supported by swank-asdf is 2.014.6.")))
;;; Import functionality from ASDF that isn't available in all ASDF versions.
;;; Please do NOT depend on any of the below as reference:
;;; they are sometimes stripped down versions, for compatibility only.
Indeed , they are supposed to work on * OLDER * , not * NEWER * versions of ASDF .
;;;
;;; The way I got these is usually by looking at the current definition,
using git blame in one screen to locate which commit last modified it ,
;;; and git log in another to determine which release that made it in.
;;; It is OK for some of the below definitions to be or become obsolete,
;;; as long as it will make do with versions older than the tagged version:
;;; if ASDF is more recent, its more recent version will win.
;;;
;;; If your software is hacking ASDF, use its internals.
;;; If you want ASDF utilities in user software, please use ASDF-UTILS.
(defun asdf-at-least (version)
(asdf:version-satisfies (asdf:asdf-version) version))
(defmacro asdefs (version &rest defs)
(flet ((defun* (version name aname rest)
`(progn
(defun ,name ,@rest)
(declaim (notinline ,name))
(when (asdf-at-least ,version)
(setf (fdefinition ',name) (fdefinition ',aname)))))
(defmethod* (version aname rest)
`(unless (asdf-at-least ,version)
(defmethod ,aname ,@rest)))
(defvar* (name aname rest)
`(progn
(define-symbol-macro ,name ,aname)
(defvar ,aname ,@rest))))
`(progn
,@(loop :for (def name . args) :in defs
:for aname = (intern (string name) :asdf)
:collect
(ecase def
((defun) (defun* version name aname args))
((defmethod) (defmethod* version aname args))
((defvar) (defvar* name aname args)))))))
(asdefs "2.15"
(defvar *wild* #-cormanlisp :wild #+cormanlisp "*")
(defun collect-asds-in-directory (directory collect)
(map () collect (directory-asd-files directory)))
(defun register-asd-directory (directory &key recurse exclude collect)
(if (not recurse)
(collect-asds-in-directory directory collect)
(collect-sub*directories-asd-files
directory :exclude exclude :collect collect))))
(asdefs "2.16"
(defun load-sysdef (name pathname)
(declare (ignore name))
(let ((package (asdf::make-temporary-package)))
(unwind-protect
(let ((*package* package)
(*default-pathname-defaults*
(asdf::pathname-directory-pathname
(translate-logical-pathname pathname))))
(asdf::asdf-message
"~&; Loading system definition from ~A into ~A~%" ;
pathname package)
(load pathname))
(delete-package package))))
(defun directory* (pathname-spec &rest keys &key &allow-other-keys)
(apply 'directory pathname-spec
(append keys
'#.(or #+allegro
'(:directories-are-files nil
:follow-symbolic-links nil)
#+clozure
'(:follow-links nil)
#+clisp
'(:circle t :if-does-not-exist :ignore)
#+(or cmu scl)
'(:follow-links nil :truenamep nil)
#+sbcl
(when (find-symbol "RESOLVE-SYMLINKS" '#:sb-impl)
'(:resolve-symlinks nil)))))))
(asdefs "2.17"
(defun collect-sub*directories-asd-files
(directory &key
(exclude asdf::*default-source-registry-exclusions*)
collect)
(asdf::collect-sub*directories
directory
(constantly t)
(lambda (x) (not (member (car (last (pathname-directory x)))
exclude :test #'equal)))
(lambda (dir) (collect-asds-in-directory dir collect))))
(defun system-source-directory (system-designator)
(asdf::pathname-directory-pathname
(asdf::system-source-file system-designator)))
(defun filter-logical-directory-results (directory entries merger)
(if (typep directory 'logical-pathname)
(loop for f in entries
when
(if (typep f 'logical-pathname)
f
(let ((u (ignore-errors (funcall merger f))))
(and u
(equal (ignore-errors (truename u))
(truename f))
u)))
collect it)
entries))
(defun directory-asd-files (directory)
(directory-files directory asdf::*wild-asd*)))
(asdefs "2.19"
(defun subdirectories (directory)
(let* ((directory (asdf::ensure-directory-pathname directory))
#-(or abcl cormanlisp xcl)
(wild (asdf::merge-pathnames*
#-(or abcl allegro cmu lispworks sbcl scl xcl)
asdf::*wild-directory*
#+(or abcl allegro cmu lispworks sbcl scl xcl) "*.*"
directory))
(dirs
#-(or abcl cormanlisp xcl)
(ignore-errors
(directory* wild . #.(or #+clozure '(:directories t :files nil)
#+mcl '(:directories t))))
#+(or abcl xcl) (system:list-directory directory)
#+cormanlisp (cl::directory-subdirs directory))
#+(or abcl allegro cmu lispworks sbcl scl xcl)
(dirs (loop for x in dirs
for d = #+(or abcl xcl) (extensions:probe-directory x)
#+allegro (excl:probe-directory x)
#+(or cmu sbcl scl) (asdf::directory-pathname-p x)
#+lispworks (lw:file-directory-p x)
when d collect #+(or abcl allegro xcl) d
#+(or cmu lispworks sbcl scl) x)))
(filter-logical-directory-results
directory dirs
(let ((prefix (or (normalize-pathname-directory-component
(pathname-directory directory))
because allegro 8.x returns NIL for # p"FOO : "
'(:absolute))))
(lambda (d)
(let ((dir (normalize-pathname-directory-component
(pathname-directory d))))
(and (consp dir) (consp (cdr dir))
(make-pathname
:defaults directory :name nil :type nil :version nil
:directory
(append prefix
(make-pathname-component-logical
(last dir))))))))))))
(asdefs "2.21"
(defun component-loaded-p (c)
(and (gethash 'load-op (asdf::component-operation-times
(asdf::find-component c nil))) t))
(defun normalize-pathname-directory-component (directory)
(cond
#-(or cmu sbcl scl)
((stringp directory) `(:absolute ,directory) directory)
((or (null directory)
(and (consp directory)
(member (first directory) '(:absolute :relative))))
directory)
(t
(error "Unrecognized pathname directory component ~S" directory))))
(defun make-pathname-component-logical (x)
(typecase x
((eql :unspecific) nil)
#+clisp (string (string-upcase x))
#+clisp (cons (mapcar 'make-pathname-component-logical x))
(t x)))
(defun make-pathname-logical (pathname host)
(make-pathname
:host host
:directory (make-pathname-component-logical (pathname-directory pathname))
:name (make-pathname-component-logical (pathname-name pathname))
:type (make-pathname-component-logical (pathname-type pathname))
:version (make-pathname-component-logical (pathname-version pathname)))))
(asdefs "2.22"
(defun directory-files (directory &optional (pattern asdf::*wild-file*))
(let ((dir (pathname directory)))
(when (typep dir 'logical-pathname)
(when (wild-pathname-p dir)
(error "Invalid wild pattern in logical directory ~S" directory))
(unless (member (pathname-directory pattern)
'(() (:relative)) :test 'equal)
(error "Invalid file pattern ~S for logical directory ~S"
pattern directory))
(setf pattern (make-pathname-logical pattern (pathname-host dir))))
(let ((entries (ignore-errors
(directory* (asdf::merge-pathnames* pattern dir)))))
(filter-logical-directory-results
directory entries
(lambda (f)
(make-pathname :defaults dir
:name (make-pathname-component-logical
(pathname-name f))
:type (make-pathname-component-logical
(pathname-type f))
:version (make-pathname-component-logical
(pathname-version f)))))))))
(asdefs "2.26.149"
(defmethod component-relative-pathname ((system asdf:system))
(asdf::coerce-pathname
(and (slot-boundp system 'asdf::relative-pathname)
(slot-value system 'asdf::relative-pathname))
:type :directory
:defaults (system-source-directory system)))
(defun load-asd (pathname &key name &allow-other-keys)
(asdf::load-sysdef (or name (string-downcase (pathname-name pathname)))
pathname)))
Taken from ASDF 1.628
(defmacro while-collecting ((&rest collectors) &body body)
`(asdf::while-collecting ,collectors ,@body))
;;; Now for SLIME-specific stuff
(defun asdf-operation (operation)
(or (asdf::find-symbol* operation :asdf)
(error "Couldn't find ASDF operation ~S" operation)))
(defun map-system-components (fn system)
(map-component-subcomponents fn (asdf:find-system system)))
(defun map-component-subcomponents (fn component)
(when component
(funcall fn component)
(when (typep component 'asdf:module)
(dolist (c (asdf:module-components component))
(map-component-subcomponents fn c)))))
;;; Maintaining a pathname to component table
(defvar *pathname-component* (make-hash-table :test 'equal))
(defun clear-pathname-component-table ()
(clrhash *pathname-component*))
(defun register-system-pathnames (system)
(map-system-components 'register-component-pathname system))
(defun recompute-pathname-component-table ()
(clear-pathname-component-table)
(asdf::map-systems 'register-system-pathnames))
(defun pathname-component (x)
(gethash (pathname x) *pathname-component*))
(defmethod asdf:component-pathname :around ((component asdf:component))
(let ((p (call-next-method)))
(when (pathnamep p)
(setf (gethash p *pathname-component*) component))
p))
(defun register-component-pathname (component)
(asdf:component-pathname component))
(recompute-pathname-component-table)
This is a crude hack , see ASDF 's LP # 481187 .
(defslimefun who-depends-on (system)
(flet ((system-dependencies (op system)
(mapcar (lambda (dep)
(asdf::coerce-name (if (consp dep) (second dep) dep)))
(cdr (assoc op (asdf:component-depends-on op system))))))
(let ((system-name (asdf::coerce-name system))
(result))
(asdf::map-systems
(lambda (system)
(when (member system-name
(system-dependencies 'asdf:load-op system)
:test #'string=)
(push (asdf:component-name system) result))))
result)))
(defmethod xref-doit ((type (eql :depends-on)) thing)
(when (typep thing '(or string symbol))
(loop for dependency in (who-depends-on thing)
for asd-file = (asdf:system-definition-pathname dependency)
when asd-file
collect (list dependency
(swank/backend:make-location
`(:file ,(namestring asd-file))
`(:position 1)
`(:snippet ,(format nil "(defsystem :~A" dependency)
:align t))))))
(defslimefun operate-on-system-for-emacs (system-name operation &rest keywords)
"Compile and load SYSTEM using ASDF.
Record compiler notes signalled as `compiler-condition's."
(collect-notes
(lambda ()
(apply #'operate-on-system system-name operation keywords))))
(defun operate-on-system (system-name operation-name &rest keyword-args)
"Perform OPERATION-NAME on SYSTEM-NAME using ASDF.
The KEYWORD-ARGS are passed on to the operation.
Example:
\(operate-on-system \"cl-ppcre\" 'compile-op :force t)"
(handler-case
(with-compilation-hooks ()
(apply #'asdf:operate (asdf-operation operation-name)
system-name keyword-args)
t)
((or asdf:compile-error #+asdf3 asdf/lisp-build:compile-file-error)
() nil)))
(defun unique-string-list (&rest lists)
(sort (delete-duplicates (apply #'append lists) :test #'string=) #'string<))
(defslimefun list-all-systems-in-central-registry ()
"Returns a list of all systems in ASDF's central registry
AND in its source-registry. (legacy name)"
(unique-string-list
(mapcar
#'pathname-name
(while-collecting (c)
(loop for dir in asdf:*central-registry*
for defaults = (eval dir)
when defaults
do (collect-asds-in-directory defaults #'c))
(asdf:ensure-source-registry)
(if (or #+asdf3 t
#-asdf3 (asdf:version-satisfies (asdf:asdf-version) "2.15"))
(loop :for k :being :the :hash-keys :of asdf::*source-registry*
:do (c k))
#-asdf3
(dolist (entry (asdf::flatten-source-registry))
(destructuring-bind (directory &key recurse exclude) entry
(register-asd-directory
directory
:recurse recurse :exclude exclude :collect #'c))))))))
(defslimefun list-all-systems-known-to-asdf ()
"Returns a list of all systems ASDF knows already."
(while-collecting (c)
(asdf::map-systems (lambda (system) (c (asdf:component-name system))))))
(defslimefun list-asdf-systems ()
"Returns the systems in ASDF's central registry and those which ASDF
already knows."
(unique-string-list
(list-all-systems-known-to-asdf)
(list-all-systems-in-central-registry)))
(defun asdf-component-source-files (component)
(while-collecting (c)
(labels ((f (x)
(typecase x
(asdf:source-file (c (asdf:component-pathname x)))
(asdf:module (map () #'f (asdf:module-components x))))))
(f component))))
(defun make-operation (x)
#+#.(swank/backend:with-symbol 'make-operation 'asdf)
(asdf:make-operation x)
#-#.(swank/backend:with-symbol 'make-operation 'asdf)
(make-instance x))
(defun asdf-component-output-files (component)
(while-collecting (c)
(labels ((f (x)
(typecase x
(asdf:source-file
(map () #'c
(asdf:output-files (make-operation 'asdf:compile-op) x)))
(asdf:module (map () #'f (asdf:module-components x))))))
(f component))))
(defslimefun asdf-system-files (name)
(let* ((system (asdf:find-system name))
(files (mapcar #'namestring
(cons
(asdf:system-definition-pathname system)
(asdf-component-source-files system))))
(main-file (find name files
:test #'equalp :key #'pathname-name :start 1)))
(if main-file
(cons main-file (remove main-file files
:test #'equal :count 1))
files)))
(defslimefun asdf-system-loaded-p (name)
(component-loaded-p name))
(defslimefun asdf-system-directory (name)
(namestring (translate-logical-pathname (asdf:system-source-directory name))))
(defun pathname-system (pathname)
(let ((component (pathname-component pathname)))
(when component
(asdf:component-name (asdf:component-system component)))))
(defslimefun asdf-determine-system (file buffer-package-name)
(or
(and file
(pathname-system file))
(and file
(progn
If not found , let 's rebuild the table first
(recompute-pathname-component-table)
(pathname-system file)))
;; If we couldn't find an already defined system,
;; try finding a system that's named like BUFFER-PACKAGE-NAME.
(loop with package = (guess-buffer-package buffer-package-name)
for name in (package-names package)
for system = (asdf:find-system (asdf::coerce-name name) nil)
when (and system
(or (not file)
(pathname-system file)))
return (asdf:component-name system))))
(defslimefun delete-system-fasls (name)
(let ((removed-count
(loop for file in (asdf-component-output-files
(asdf:find-system name))
when (probe-file file)
count it
and
do (delete-file file))))
(format nil "~d file~:p ~:*~[were~;was~:;were~] removed" removed-count)))
(defvar *recompile-system* nil)
(defmethod asdf:operation-done-p :around
((operation asdf:compile-op)
component)
(unless (eql *recompile-system*
(asdf:component-system component))
(call-next-method)))
(defslimefun reload-system (name)
(let ((*recompile-system* (asdf:find-system name)))
(operate-on-system-for-emacs name 'asdf:load-op)))
;;; Hook for compile-file-for-emacs
(defun try-compile-file-with-asdf (pathname load-p &rest options)
(declare (ignore options))
(let ((component (pathname-component pathname)))
(when component
;;(format t "~&Compiling ASDF component ~S~%" component)
(let ((op (make-operation 'asdf:compile-op)))
(with-compilation-hooks ()
(asdf:perform op component))
(when load-p
(asdf:perform (make-operation 'asdf:load-op) component))
(values t t nil (first (asdf:output-files op component)))))))
(defun try-compile-asd-file (pathname load-p &rest options)
(declare (ignore load-p options))
(when (equalp (pathname-type pathname) "asd")
(load-asd pathname)
(values t t nil pathname)))
(pushnew 'try-compile-asd-file *compile-file-for-emacs-hook*)
( pushnew ' try - compile - file - with - asdf * compile - file - for - emacs - hook * )
(provide :swank-asdf)
| null | https://raw.githubusercontent.com/KestrelInstitute/Specware/edc5f7755b9edd67b5d52362df97e8230d346942/Library/IO/Emacs/slime/contrib/swank-asdf.lisp | lisp | swank-asdf.lisp -- ASDF support
and others
License: Public Domain
The best way to load ASDF is from an init file of an
implementation. If ASDF is not loaded at the time swank-asdf is
doesn't help and *asdf-path* is set, it will be loaded from that
file.
To set *asdf-path* put the following into ~/.swank.lisp:
sjw
If still not found, error out.
If ASDF is too old, punt.
If your implementation doesn't provide ASDF, or provides an old one,
install an upgrade yourself and configure *asdf-path*.
It's just not worth the hassle supporting something
that doesn't even have COERCE-PATHNAME.
connection.
Import functionality from ASDF that isn't available in all ASDF versions.
Please do NOT depend on any of the below as reference:
they are sometimes stripped down versions, for compatibility only.
The way I got these is usually by looking at the current definition,
and git log in another to determine which release that made it in.
It is OK for some of the below definitions to be or become obsolete,
as long as it will make do with versions older than the tagged version:
if ASDF is more recent, its more recent version will win.
If your software is hacking ASDF, use its internals.
If you want ASDF utilities in user software, please use ASDF-UTILS.
Now for SLIME-specific stuff
Maintaining a pathname to component table
If we couldn't find an already defined system,
try finding a system that's named like BUFFER-PACKAGE-NAME.
Hook for compile-file-for-emacs
(format t "~&Compiling ASDF component ~S~%" component) | Authors : < >
< >
< >
< >
(in-package :swank)
(eval-when (:compile-toplevel :load-toplevel :execute)
loaded , it will be tried first with ( require " asdf " ) , if that
( * # p"/path / to / asdf / asdf.lisp " )
(defvar *asdf-path* nil
"Path to asdf.lisp file, to be loaded in case (require \"asdf\") fails."))
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (member :asdf *features*)
(setq sb-fasl:*fasl-file-type* "fasl")
(funcall 'require "asdf")
(setq sb-fasl:*fasl-file-type* saved-fasl-type)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (member :asdf *features*)
(handler-bind ((warning #'muffle-warning))
(when *asdf-path*
(load *asdf-path* :if-does-not-exist nil)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (member :asdf *features*)
(error "Could not load ASDF.
Please update your implementation or
install a recent release of ASDF and in your ~~/.swank.lisp specify:
(defparameter swank::*asdf-path* #p\"/path/containing/asdf/asdf.lisp\")")))
As of January 2014 , Quicklisp has been providing 2.26 for a year
( and previously had 2.014.6 for over a year ) , whereas
all SLIME - supported implementations provide ASDF3 ( i.e. 2.27 or later )
except LispWorks ( stuck with 2.019 ) and SCL ( which has n't been released
in years and does n't provide ASDF at all , but is fully supported by ASDF ) .
NB : this version check is duplicated in swank-loader.lisp so that we do n't
try to load this contrib when ASDF is too old since that will abort the SLIME
#-asdf3
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (and #+asdf2 (asdf:version-satisfies (asdf:asdf-version) "2.14.6"))
(error "Your ASDF is too old. ~
The oldest version supported by swank-asdf is 2.014.6.")))
Indeed , they are supposed to work on * OLDER * , not * NEWER * versions of ASDF .
using git blame in one screen to locate which commit last modified it ,
(defun asdf-at-least (version)
(asdf:version-satisfies (asdf:asdf-version) version))
(defmacro asdefs (version &rest defs)
(flet ((defun* (version name aname rest)
`(progn
(defun ,name ,@rest)
(declaim (notinline ,name))
(when (asdf-at-least ,version)
(setf (fdefinition ',name) (fdefinition ',aname)))))
(defmethod* (version aname rest)
`(unless (asdf-at-least ,version)
(defmethod ,aname ,@rest)))
(defvar* (name aname rest)
`(progn
(define-symbol-macro ,name ,aname)
(defvar ,aname ,@rest))))
`(progn
,@(loop :for (def name . args) :in defs
:for aname = (intern (string name) :asdf)
:collect
(ecase def
((defun) (defun* version name aname args))
((defmethod) (defmethod* version aname args))
((defvar) (defvar* name aname args)))))))
(asdefs "2.15"
(defvar *wild* #-cormanlisp :wild #+cormanlisp "*")
(defun collect-asds-in-directory (directory collect)
(map () collect (directory-asd-files directory)))
(defun register-asd-directory (directory &key recurse exclude collect)
(if (not recurse)
(collect-asds-in-directory directory collect)
(collect-sub*directories-asd-files
directory :exclude exclude :collect collect))))
(asdefs "2.16"
(defun load-sysdef (name pathname)
(declare (ignore name))
(let ((package (asdf::make-temporary-package)))
(unwind-protect
(let ((*package* package)
(*default-pathname-defaults*
(asdf::pathname-directory-pathname
(translate-logical-pathname pathname))))
(asdf::asdf-message
pathname package)
(load pathname))
(delete-package package))))
(defun directory* (pathname-spec &rest keys &key &allow-other-keys)
(apply 'directory pathname-spec
(append keys
'#.(or #+allegro
'(:directories-are-files nil
:follow-symbolic-links nil)
#+clozure
'(:follow-links nil)
#+clisp
'(:circle t :if-does-not-exist :ignore)
#+(or cmu scl)
'(:follow-links nil :truenamep nil)
#+sbcl
(when (find-symbol "RESOLVE-SYMLINKS" '#:sb-impl)
'(:resolve-symlinks nil)))))))
(asdefs "2.17"
(defun collect-sub*directories-asd-files
(directory &key
(exclude asdf::*default-source-registry-exclusions*)
collect)
(asdf::collect-sub*directories
directory
(constantly t)
(lambda (x) (not (member (car (last (pathname-directory x)))
exclude :test #'equal)))
(lambda (dir) (collect-asds-in-directory dir collect))))
(defun system-source-directory (system-designator)
(asdf::pathname-directory-pathname
(asdf::system-source-file system-designator)))
(defun filter-logical-directory-results (directory entries merger)
(if (typep directory 'logical-pathname)
(loop for f in entries
when
(if (typep f 'logical-pathname)
f
(let ((u (ignore-errors (funcall merger f))))
(and u
(equal (ignore-errors (truename u))
(truename f))
u)))
collect it)
entries))
(defun directory-asd-files (directory)
(directory-files directory asdf::*wild-asd*)))
(asdefs "2.19"
(defun subdirectories (directory)
(let* ((directory (asdf::ensure-directory-pathname directory))
#-(or abcl cormanlisp xcl)
(wild (asdf::merge-pathnames*
#-(or abcl allegro cmu lispworks sbcl scl xcl)
asdf::*wild-directory*
#+(or abcl allegro cmu lispworks sbcl scl xcl) "*.*"
directory))
(dirs
#-(or abcl cormanlisp xcl)
(ignore-errors
(directory* wild . #.(or #+clozure '(:directories t :files nil)
#+mcl '(:directories t))))
#+(or abcl xcl) (system:list-directory directory)
#+cormanlisp (cl::directory-subdirs directory))
#+(or abcl allegro cmu lispworks sbcl scl xcl)
(dirs (loop for x in dirs
for d = #+(or abcl xcl) (extensions:probe-directory x)
#+allegro (excl:probe-directory x)
#+(or cmu sbcl scl) (asdf::directory-pathname-p x)
#+lispworks (lw:file-directory-p x)
when d collect #+(or abcl allegro xcl) d
#+(or cmu lispworks sbcl scl) x)))
(filter-logical-directory-results
directory dirs
(let ((prefix (or (normalize-pathname-directory-component
(pathname-directory directory))
because allegro 8.x returns NIL for # p"FOO : "
'(:absolute))))
(lambda (d)
(let ((dir (normalize-pathname-directory-component
(pathname-directory d))))
(and (consp dir) (consp (cdr dir))
(make-pathname
:defaults directory :name nil :type nil :version nil
:directory
(append prefix
(make-pathname-component-logical
(last dir))))))))))))
(asdefs "2.21"
(defun component-loaded-p (c)
(and (gethash 'load-op (asdf::component-operation-times
(asdf::find-component c nil))) t))
(defun normalize-pathname-directory-component (directory)
(cond
#-(or cmu sbcl scl)
((stringp directory) `(:absolute ,directory) directory)
((or (null directory)
(and (consp directory)
(member (first directory) '(:absolute :relative))))
directory)
(t
(error "Unrecognized pathname directory component ~S" directory))))
(defun make-pathname-component-logical (x)
(typecase x
((eql :unspecific) nil)
#+clisp (string (string-upcase x))
#+clisp (cons (mapcar 'make-pathname-component-logical x))
(t x)))
(defun make-pathname-logical (pathname host)
(make-pathname
:host host
:directory (make-pathname-component-logical (pathname-directory pathname))
:name (make-pathname-component-logical (pathname-name pathname))
:type (make-pathname-component-logical (pathname-type pathname))
:version (make-pathname-component-logical (pathname-version pathname)))))
(asdefs "2.22"
(defun directory-files (directory &optional (pattern asdf::*wild-file*))
(let ((dir (pathname directory)))
(when (typep dir 'logical-pathname)
(when (wild-pathname-p dir)
(error "Invalid wild pattern in logical directory ~S" directory))
(unless (member (pathname-directory pattern)
'(() (:relative)) :test 'equal)
(error "Invalid file pattern ~S for logical directory ~S"
pattern directory))
(setf pattern (make-pathname-logical pattern (pathname-host dir))))
(let ((entries (ignore-errors
(directory* (asdf::merge-pathnames* pattern dir)))))
(filter-logical-directory-results
directory entries
(lambda (f)
(make-pathname :defaults dir
:name (make-pathname-component-logical
(pathname-name f))
:type (make-pathname-component-logical
(pathname-type f))
:version (make-pathname-component-logical
(pathname-version f)))))))))
(asdefs "2.26.149"
(defmethod component-relative-pathname ((system asdf:system))
(asdf::coerce-pathname
(and (slot-boundp system 'asdf::relative-pathname)
(slot-value system 'asdf::relative-pathname))
:type :directory
:defaults (system-source-directory system)))
(defun load-asd (pathname &key name &allow-other-keys)
(asdf::load-sysdef (or name (string-downcase (pathname-name pathname)))
pathname)))
Taken from ASDF 1.628
(defmacro while-collecting ((&rest collectors) &body body)
`(asdf::while-collecting ,collectors ,@body))
(defun asdf-operation (operation)
(or (asdf::find-symbol* operation :asdf)
(error "Couldn't find ASDF operation ~S" operation)))
(defun map-system-components (fn system)
(map-component-subcomponents fn (asdf:find-system system)))
(defun map-component-subcomponents (fn component)
(when component
(funcall fn component)
(when (typep component 'asdf:module)
(dolist (c (asdf:module-components component))
(map-component-subcomponents fn c)))))
(defvar *pathname-component* (make-hash-table :test 'equal))
(defun clear-pathname-component-table ()
(clrhash *pathname-component*))
(defun register-system-pathnames (system)
(map-system-components 'register-component-pathname system))
(defun recompute-pathname-component-table ()
(clear-pathname-component-table)
(asdf::map-systems 'register-system-pathnames))
(defun pathname-component (x)
(gethash (pathname x) *pathname-component*))
(defmethod asdf:component-pathname :around ((component asdf:component))
(let ((p (call-next-method)))
(when (pathnamep p)
(setf (gethash p *pathname-component*) component))
p))
(defun register-component-pathname (component)
(asdf:component-pathname component))
(recompute-pathname-component-table)
This is a crude hack , see ASDF 's LP # 481187 .
(defslimefun who-depends-on (system)
(flet ((system-dependencies (op system)
(mapcar (lambda (dep)
(asdf::coerce-name (if (consp dep) (second dep) dep)))
(cdr (assoc op (asdf:component-depends-on op system))))))
(let ((system-name (asdf::coerce-name system))
(result))
(asdf::map-systems
(lambda (system)
(when (member system-name
(system-dependencies 'asdf:load-op system)
:test #'string=)
(push (asdf:component-name system) result))))
result)))
(defmethod xref-doit ((type (eql :depends-on)) thing)
(when (typep thing '(or string symbol))
(loop for dependency in (who-depends-on thing)
for asd-file = (asdf:system-definition-pathname dependency)
when asd-file
collect (list dependency
(swank/backend:make-location
`(:file ,(namestring asd-file))
`(:position 1)
`(:snippet ,(format nil "(defsystem :~A" dependency)
:align t))))))
(defslimefun operate-on-system-for-emacs (system-name operation &rest keywords)
"Compile and load SYSTEM using ASDF.
Record compiler notes signalled as `compiler-condition's."
(collect-notes
(lambda ()
(apply #'operate-on-system system-name operation keywords))))
(defun operate-on-system (system-name operation-name &rest keyword-args)
"Perform OPERATION-NAME on SYSTEM-NAME using ASDF.
The KEYWORD-ARGS are passed on to the operation.
Example:
\(operate-on-system \"cl-ppcre\" 'compile-op :force t)"
(handler-case
(with-compilation-hooks ()
(apply #'asdf:operate (asdf-operation operation-name)
system-name keyword-args)
t)
((or asdf:compile-error #+asdf3 asdf/lisp-build:compile-file-error)
() nil)))
(defun unique-string-list (&rest lists)
(sort (delete-duplicates (apply #'append lists) :test #'string=) #'string<))
(defslimefun list-all-systems-in-central-registry ()
"Returns a list of all systems in ASDF's central registry
AND in its source-registry. (legacy name)"
(unique-string-list
(mapcar
#'pathname-name
(while-collecting (c)
(loop for dir in asdf:*central-registry*
for defaults = (eval dir)
when defaults
do (collect-asds-in-directory defaults #'c))
(asdf:ensure-source-registry)
(if (or #+asdf3 t
#-asdf3 (asdf:version-satisfies (asdf:asdf-version) "2.15"))
(loop :for k :being :the :hash-keys :of asdf::*source-registry*
:do (c k))
#-asdf3
(dolist (entry (asdf::flatten-source-registry))
(destructuring-bind (directory &key recurse exclude) entry
(register-asd-directory
directory
:recurse recurse :exclude exclude :collect #'c))))))))
(defslimefun list-all-systems-known-to-asdf ()
"Returns a list of all systems ASDF knows already."
(while-collecting (c)
(asdf::map-systems (lambda (system) (c (asdf:component-name system))))))
(defslimefun list-asdf-systems ()
"Returns the systems in ASDF's central registry and those which ASDF
already knows."
(unique-string-list
(list-all-systems-known-to-asdf)
(list-all-systems-in-central-registry)))
(defun asdf-component-source-files (component)
(while-collecting (c)
(labels ((f (x)
(typecase x
(asdf:source-file (c (asdf:component-pathname x)))
(asdf:module (map () #'f (asdf:module-components x))))))
(f component))))
(defun make-operation (x)
#+#.(swank/backend:with-symbol 'make-operation 'asdf)
(asdf:make-operation x)
#-#.(swank/backend:with-symbol 'make-operation 'asdf)
(make-instance x))
(defun asdf-component-output-files (component)
(while-collecting (c)
(labels ((f (x)
(typecase x
(asdf:source-file
(map () #'c
(asdf:output-files (make-operation 'asdf:compile-op) x)))
(asdf:module (map () #'f (asdf:module-components x))))))
(f component))))
(defslimefun asdf-system-files (name)
(let* ((system (asdf:find-system name))
(files (mapcar #'namestring
(cons
(asdf:system-definition-pathname system)
(asdf-component-source-files system))))
(main-file (find name files
:test #'equalp :key #'pathname-name :start 1)))
(if main-file
(cons main-file (remove main-file files
:test #'equal :count 1))
files)))
(defslimefun asdf-system-loaded-p (name)
(component-loaded-p name))
(defslimefun asdf-system-directory (name)
(namestring (translate-logical-pathname (asdf:system-source-directory name))))
(defun pathname-system (pathname)
(let ((component (pathname-component pathname)))
(when component
(asdf:component-name (asdf:component-system component)))))
(defslimefun asdf-determine-system (file buffer-package-name)
(or
(and file
(pathname-system file))
(and file
(progn
If not found , let 's rebuild the table first
(recompute-pathname-component-table)
(pathname-system file)))
(loop with package = (guess-buffer-package buffer-package-name)
for name in (package-names package)
for system = (asdf:find-system (asdf::coerce-name name) nil)
when (and system
(or (not file)
(pathname-system file)))
return (asdf:component-name system))))
(defslimefun delete-system-fasls (name)
(let ((removed-count
(loop for file in (asdf-component-output-files
(asdf:find-system name))
when (probe-file file)
count it
and
do (delete-file file))))
(format nil "~d file~:p ~:*~[were~;was~:;were~] removed" removed-count)))
(defvar *recompile-system* nil)
(defmethod asdf:operation-done-p :around
((operation asdf:compile-op)
component)
(unless (eql *recompile-system*
(asdf:component-system component))
(call-next-method)))
(defslimefun reload-system (name)
(let ((*recompile-system* (asdf:find-system name)))
(operate-on-system-for-emacs name 'asdf:load-op)))
(defun try-compile-file-with-asdf (pathname load-p &rest options)
(declare (ignore options))
(let ((component (pathname-component pathname)))
(when component
(let ((op (make-operation 'asdf:compile-op)))
(with-compilation-hooks ()
(asdf:perform op component))
(when load-p
(asdf:perform (make-operation 'asdf:load-op) component))
(values t t nil (first (asdf:output-files op component)))))))
(defun try-compile-asd-file (pathname load-p &rest options)
(declare (ignore load-p options))
(when (equalp (pathname-type pathname) "asd")
(load-asd pathname)
(values t t nil pathname)))
(pushnew 'try-compile-asd-file *compile-file-for-emacs-hook*)
( pushnew ' try - compile - file - with - asdf * compile - file - for - emacs - hook * )
(provide :swank-asdf)
|
ebdfe64d2db92c578fc485ad5b0df0baacf4908b8f551158bfed8c1f25720903 | K1D77A/lisp-pay | paypal.lisp | (in-package #:lisp-pay/paypal)
;;;tracking
(defapi tracking%update-or-cancel ("/v1/shipping/trackers/:id" put-request)
())
(defapi tracking%information ("/v1/shipping/trackers/:id" get-request)
())
(defapi tracking%batch ("/v1/shipping/trackers-batch" post-request)
())
;;;billing
(defapi billing%create ("/v1/payments/billing-agreements" post-request)
())
(defapi billing%update ("/v1/payments/billing-agreements/:agreement-id" patch-request)
())
(defapi billing%information ("/v1/payments/billing-agreements/:agreement-id" get-request)
())
(defapi billing%bill-balance
("/v1/payments/billing-agreements/:agreement-id/balance" post-request)
())
(defapi billing%cancel
("/v1/payments/billing-agreements/:agreement-id/cancel" post-request)
())
(defapi billing%re-activate
("/v1/payments/billing-agreements/:agreement-id/re-activate" post-request)
())
(defapi billing%set-balance
("/v1/payments/billing-agreements/:agreement-id/set-balance" post-request)
())
(defapi billing%suspend
("/v1/payments/billing-agreements/:agreement-id/suspend" post-request)
())
(defapi billing%list-transactions
("/v1/payments/billing-agreements/:agreement-id/transactions" get-request)
((start-date
:accessor start-date
:initarg start-date
:as-string "start_date")
(end-date
:accessor end-date
:initarg :end-date
:as-string "end-date")))
(defapi billing%execute
("/v1/payments/billing-agreements/:agreement-id/agreement-execute" post-request)
())
;;;catalog products
(defapi products%list ("/v1/catalogs/products" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(total-required
:accessor total-requried
:initarg :total-required
:as-string "total_required")))
(defapi products%create ("/v1/catalogs/products" post-request)
())
;;has the extra header Prefer and Paypal-Request-Id
(defapi products%update ("/v1/catalogs/products/:product-id" patch-request)
())
(defapi products%details ("/v1/catalogs/products/:product-id" get-request)
())
;;;disputes
(defapi disputes%get ("/v1/customer/disputes" get-request)
((start-time
:accessor start-time
:initarg :start-time
:as-string "start_time")
(disputed-transaction-id
:accessor disputed-transaction_id
:initarg :disputed-transaction_id
:as-string "disputed_transaction_id")
(page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(next-page-token
:accessor next-page-token
:initarg :next-page-token
:as-string "next_page_token")
(dispute-state
:accessor dispute-state
:initarg :dispute-state
:as-string "dispute_state")
(update-time-before
:accessor update-time-before
:initarg :update-time-before
:as-string "update_time_before")
(update-time-after
:accessor update-time-after
:initarg :update-time-after
:as-string "update_time_after")))
(defapi disputes%update ("/v1/customer/disputes/:dispute-id" patch-request)
())
(defapi disputes%details ("/v1/customer/disputes/:dispute-id" get-request)
())
;;;dispute-actions
(defapi disputes-actions%accept-claim ("/v1/customer/disputes/:dispute-id/accept-claim"
post-request)
())
(defapi disputes-actions%accept-resolve ("/v1/customer/disputes/:dispute-id/accept-offer"
post-request)
())
(defapi disputes-actions%acknowledge-return
("/v1/customer/disputes/:dispute-id/acknowledge-return-item"
post-request)
())
(defapi disputes-actions%adjudicate
("/v1/customer/disputes/:dispute-id/adjudicate"
post-request)
());;for sandbox use only
(defapi disputes-actions%appeal
("/v1/customer/disputes/:dispute-id/appeal"
post-files-request)
())
(defapi disputes-actions%deny-resolve
("/v1/customer/disputes/:dispute-id/deny-offer"
post-request)
())
(defapi disputes-actions%escalate
("/v1/customer/disputes/:dispute-id/escalate"
post-request)
())
(defapi disputes-actions%offer-resolve
("/v1/customer/disputes/:dispute-id/make-offer"
post-request)
())
(defapi disputes-actions%provide-evidence
("/v1/customer/disputes/:dispute-id/provide-evidence"
post-files-request)
())
(defapi disputes-actions%provide-supporting-info
("/v1/customer/disputes/:dispute-id/provide-supporting-info"
post-files-request)
());;this wont work if you only want to upload notes.
(defapi disputes-actions%require-evidence
("/v1/customer/disputes/:dispute-id/require-evidence"
post-request)
());;sandbox only
(defapi disputes-actions%send-message
("/v1/customer/disputes/:dispute-id/send-message"
post-files-request)
())
;;;the way to make these api calls that accept either files or json would be to
;;;set the content-type to your desired then change-class into either post-files-r
;;;which will send the data as multipart-form or post-request which will send it as
;;;json
;;;identity
(defapi identity-userinfo&profile-info ("/v1/identity/oauth2/userinfo" get-request)
((schema
:accessor schema
:initarg :schema)))
(defapi identity-applications%create ("/v1/identity/applications" post-request)
())
(defapi identity-account%set-properties ("/v1/identity/account-settings" post-request)
())
(defapi identity-account%disable-properties
("/v1/identity/account-settings/deactivate" post-request)
())
;;;invoices
(defapi invoices%generate-invoice-number ("/v2/invoicing/generate-next-invoice-number"
post-request)
())
(defapi invoices%list ("/v2/invoicing/invoices" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(total-required
:accessor total-requried
:initarg :total-required
:as-string "total_required")
(fields
:accessor fields
:initarg :fields)))
(defapi invoices%create-draft ("/v2/invoicing/invoices"
post-request)
())
(defapi invoices%delete ("/v2/invoicing/invoices/:invoice-id"
delete-request)
())
(defapi invoices%update-invoice ("/v2/invoicing/invoices/:invoice-id"
put-request)
((send-to-recipient
:accessor send-to-recipient
:initarg :send-to-recipient
:as-string "send_to_recipient")
(send_to_invoicer
:accessor send-to-invoicer
:initarg :send-to-invoicer
:as-string "send_to_invoicer")))
(defapi invoices%details ("/v2/invoicing/invoices/:invoice-id"
get-request)
())
(defapi invoices%cancel ("/v2/invoicing/invoices/:invoice-id/cancel"
post-request)
())
(defapi invoices%generate-qr-code ("/v2/invoicing/invoices/:invoice-id/generate-qr-code"
post-request)
())
(defapi invoices%record-payment ("/v2/invoicing/invoices/:invoice-id/payments"
post-request)
())
(defapi invoices%delete-external-payment
("/v2/invoicing/invoices/:invoice-id/payments/:transaction-id"
delete-request)
())
(defapi invoices%record-refund
("/v2/invoicing/invoices/:invoice-id/refunds"
post-request)
())
(defapi invoices%delete-external-refund
("/v2/invoicing/invoices/:invoice-id/refunds/:transaction-id"
delete-request)
())
(defapi invoices%remind
("/v2/invoicing/invoices/:invoice-id/remind"
post-request)
())
(defapi invoices%send
("/v2/invoicing/invoices/:invoice-id/send"
post-request)
());;has the Paypal-Request-Id header
(defapi invoices%search ("/v2/invoicing/search-invoices" post-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(total_required
:accessor total-requried
:initarg :total-required
:as-string "total_required")))
(defapi invoices-templates%list ("/v2/invoicing/templates" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(fields
:accessor fields
:initarg :fields)))
(defapi invoices-templates%create ("/v2/invoicing/templates" post-request)
())
(defapi invoices-templates%delete ("/v2/invoicing/templates/:template-id" delete-request)
())
(defapi invoices-templates%update ("/v2/invoicing/templates/:template-id" put-request)
())
(defapi invoices-templates%details ("/v2/invoicing/templates/:template-id" get-request)
())
;;;orders
(defapi orders%create ("/v2/checkout/orders" post-request)
());;has the request-id partner-att client-metadata and prefer headers if wanted
(defapi orders%update ("/v2/checkout/orders/:order-id" patch-request)
())
(defapi orders%details ("/v2/checkout/orders/:order-id" get-request)
((fields
:accessor fields
:initarg :fields)))
(defapi orders%authorize ("/v2/checkout/orders/:order-id/authorize" post-request)
());;has the request-id metadata prefer auth-assertion
(defapi orders%capture ("/v2/checkout/orders/:order-id/capture" post-request)
());;has the request-id prefer metadata auth-assertion
;;;partner referrals
(defapi partner%create ("/v2/customer/partner-referrals" post-request)
())
(defapi partner%get-data ("/v2/customer/partner-referrals/:referral-id" get-request)
())
;;;payment-experience
(defapi web-profiles%list ("/v1/payment-experience/web-profiles" get-request)
())
(defapi web-profiles%create ("/v1/payment-experience/web-profiles" post-request)
());;has request-id
(defapi web-profiles%delete ("/v1/payment-experience/web-profiles/:profile-id" delete-request)
())
(defapi web-profiles%update ("/v1/payment-experience/web-profiles/:profile-id" patch-request)
())
(defapi web-profiles%partial-update
("/v1/payment-experience/web-profiles/:profile-id" patch-request)
())
(defapi web-profiles%details
("/v1/payment-experience/web-profiles/:profile-id" get-request)
())
;;;payments
(defapi payments-authorization%details
("/v2/payments/authorizations/:authorization-id" get-request)
())
(defapi payments-authorization%capture
("/v2/payments/authorizations/:authorization-id/capture" post-request)
());;has request id and prefer
(defapi payments-authorization%reauthorize
("/v2/payments/authorizations/:authorization-id/reauthorize" post-request)
());;has request id and prefer
(defapi payments-authorization%void
("/v2/payments/authorizations/:authorization-id/void" post-request)
());;has auth assertion
(defapi payments-captures%details
("/v2/payments/captures/:capture-id" get-request)
());;has auth assertion
(defapi payments-captures%refund
("/v2/payments/captures/:capture-id/refund" post-request)
());;has request-id prefer auth-assertion
(defapi payments-refunds%details
("/v2/payments/refunds/:refund-id" get-request)
())
;;;payouts
(defapi payouts-batch%create
("/v1/payments/payouts" post-request)
());has request-id
(defapi payouts-batch%details
("/v1/payments/payouts/:batch-id" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(fields
:accessor fields
:initarg :fields)
(total-required
:accessor total-required
:initarg :total-required
:as-string "total_required")))
(defapi payouts-item%details
("/v1/payments/payouts-item/:payout-id" get-request)
())
(defapi payouts-item%cancel-unclaimed
("/v1/payments/payouts-item/:payout-id/cancel" post-request)
())
;;;reference payouts
(defapi referenced-payouts-batch%create
("/v1/payments/referenced-payouts" post-request)
());has partner-attribution request-id prefer
(defapi referenced-payouts-batch%details
("/v1/payments/referenced-payouts/:batch-id" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(fields
:accessor fields
:initarg :fields)
(total-required
:accessor total-required
:initarg :total-required
:as-string "total_required")))
(defapi referenced-payouts-item%create
("/v1/payments/referenced-payouts-items" post-request)
());;partner-attribution request-id prefer
(defapi referenced-payouts-item%cancel-unclaimed
("/v1/payments/referenced-payouts-items/:payout-id" get-request)
());;has partner-attribution
;;;subscriptions
(defapi subscriptions-plans%list ("/v1/billing/plans" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(product-id
:accessor product-id
:initarg :product-id
:as-string "product_id")
(plan-ids
:accessor plan-ids
:initarg :plan-ids
:as-string "plan_ids")
(total-required
:accessor total-required
:initarg :total-required
:as-string "total_required")))
(defapi subscribtions-plans%create ("/v1/billing/plans" post-request)
());;has prefer request-id
(defapi subscribtions-plans%update ("/v1/billing/plans/:plan-id" patch-request)
())
(defapi subscribtions-plans%details ("/v1/billing/plans/:plan-id" get-request)
())
(defapi subscribtions-plans%activate ("/v1/billing/plans/:plan-id/activate" post-request)
())
(defapi subscribtions-plans%deactivate ("/v1/billing/plans/:plan-id/deactivate" post-request)
())
(defapi subscribtions-plans%update-pricing-schemas
("/v1/billing/plans/:plan-id/update-pricing-schemas" post-request)
())
(defapi subscriptions%create ("/v1/billing/subscriptions" post-request)
());has prefer
(defapi subscriptions%update ("/v1/billing/subscriptions/:sub-id" patch-request)
())
(defapi subscriptions%details ("/v1/billing/subscriptions/:sub-id" get-request)
())
(defapi subscriptions%activate ("/v1/billing/subscriptions/:sub-id/activate" post-request)
())
(defapi subscriptions%cancel ("/v1/billing/subscriptions/:sub-id/activate" post-request)
())
(defapi subscriptions%capture ("/v1/billing/subscriptions/:sub-id/capture" post-request)
())
(defapi subscriptions%revise ("/v1/billing/subscriptions/:sub-id/revise" post-request)
())
(defapi subscriptions%suspend ("/v1/billing/subscriptions/:sub-id/suspend" post-request)
())
(defapi subscriptions%transactions ("/v1/billing/subscriptions/:sub-id/transactions"
post-request)
((start-time
:accessor start-time
:initarg :start-time
:as-string "start_time")
(end-time
:accessor end-time
:initarg :end-time
:as-string "end_time")))
;;;search
(defapi search-transactions%list ("/v1/reporting/transactions" get-request)
((transaction-id
:accessor transaction-id
:initarg :transaction-id
:as-string "transaction_id")
(transaction-type
:accessor transaction-type
:initarg :transaction-type
:as-string "transaction_type")
(transaction-status
:accessor transaction-status
:initarg :transaction-status
:as-string "transaction_status")
(transaction-amount
:accessor transaction-amount
:initarg :transaction-amount
:as-string "transaction_amount")
(transaction-currency
:accessor transaction-currency
:initarg :transaction-currency
:as-string "transaction_currency")
(start-date
:accessor start-date
:initarg :start-date
:as-string "start_date")
(end-date
:accessor end-date
:initarg :end-date
:as-string "end_date")
(payment-instrument-type
:accessor payment-instrument-type
:initarg :payment-instrument-type
:as-string "payment_instrument_type")
(store-id
:accessor store-id
:initarg :store-id
:as-string "store_id")
(terminal-id
:accessor terminal-id
:initarg :terminal-id
:as-string "terminal_id")
(fields
:accessor fields
:initarg :fields)
(balance-affecting-records-only
:accessor balance-affecting-records-only
:initarg :balance-affecting-records-only
:as-string "balance_affecting_records_only")
(page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)))
(defapi search-balances%list ("/v1/reporting/balances" get-request)
((as-of-time
:accessor as-of-time
:initarg :as-of-time
:as-string "as_of_time")
(currency-code
:accessor currency-code
:initarg :currency-code
:as-string "currency_code")))
;;;webhooks
(defapi webhooks%list ("/v1/notifications/webhooks" get-request)
((anchor-time
:accessor anchor-time
:initarg :anchor-time
:as-string "anchor_time")))
(defapi webhooks%create ("/v1/notifications/webhooks" post-request)
())
(defapi webhooks%delete ("/v1/notifications/webhooks/:webhook-id" delete-request)
())
(defapi webhooks%update ("/v1/notifications/webhooks/:webhook-id" patch-request)
())
(defapi webhooks%details ("/v1/notifications/webhooks/:webhook-id" get-request)
())
(defapi webhooks%list-event-subscriptions
("/v1/notifications/webhooks/:webhook-id/event-types" get-request)
())
( defapi webhooks%verify - signature ( " /v1 / notifications / verify - webhook - signature " post - request%jojo )
;; ());;this will not work.
(defapi webhooks%list-event-types ("/v1/notifications/webhooks-event-types" get-request)
())
(defapi webhooks%list-event-notifications ("/v1/notifications/webhooks-events" get-request)
((page_size
:accessor page-size
:initarg :page-size)
(transaction_id
:accessor transaction-id
:initarg :transaction-id)
(event_type
:accessor event-type
:initarg :event-type)
(start-time
:accessor start-time
:initarg :start-time
:as-string "start_time")
(end-time
:accessor end-time
:initarg :end-time
:as-string "end_time")))
(defapi webhooks%notification-details ("/v1/notifications/webhooks-events/:event-id"
get-request)
())
(defapi webhooks%resend-event ("/v1/notifications/webhooks-events/:event-id/resend"
post-request)
())
(defapi webhooks%simulate-event ("/v1/notifications/simulate-event"
post-request)
())
| null | https://raw.githubusercontent.com/K1D77A/lisp-pay/cb3d220134bab9f09bfabc890f938ea08fddb11a/src/paypal/paypal.lisp | lisp | tracking
billing
catalog products
has the extra header Prefer and Paypal-Request-Id
disputes
dispute-actions
for sandbox use only
this wont work if you only want to upload notes.
sandbox only
the way to make these api calls that accept either files or json would be to
set the content-type to your desired then change-class into either post-files-r
which will send the data as multipart-form or post-request which will send it as
json
identity
invoices
has the Paypal-Request-Id header
orders
has the request-id partner-att client-metadata and prefer headers if wanted
has the request-id metadata prefer auth-assertion
has the request-id prefer metadata auth-assertion
partner referrals
payment-experience
has request-id
payments
has request id and prefer
has request id and prefer
has auth assertion
has auth assertion
has request-id prefer auth-assertion
payouts
has request-id
reference payouts
has partner-attribution request-id prefer
partner-attribution request-id prefer
has partner-attribution
subscriptions
has prefer request-id
has prefer
search
webhooks
());;this will not work. | (in-package #:lisp-pay/paypal)
(defapi tracking%update-or-cancel ("/v1/shipping/trackers/:id" put-request)
())
(defapi tracking%information ("/v1/shipping/trackers/:id" get-request)
())
(defapi tracking%batch ("/v1/shipping/trackers-batch" post-request)
())
(defapi billing%create ("/v1/payments/billing-agreements" post-request)
())
(defapi billing%update ("/v1/payments/billing-agreements/:agreement-id" patch-request)
())
(defapi billing%information ("/v1/payments/billing-agreements/:agreement-id" get-request)
())
(defapi billing%bill-balance
("/v1/payments/billing-agreements/:agreement-id/balance" post-request)
())
(defapi billing%cancel
("/v1/payments/billing-agreements/:agreement-id/cancel" post-request)
())
(defapi billing%re-activate
("/v1/payments/billing-agreements/:agreement-id/re-activate" post-request)
())
(defapi billing%set-balance
("/v1/payments/billing-agreements/:agreement-id/set-balance" post-request)
())
(defapi billing%suspend
("/v1/payments/billing-agreements/:agreement-id/suspend" post-request)
())
(defapi billing%list-transactions
("/v1/payments/billing-agreements/:agreement-id/transactions" get-request)
((start-date
:accessor start-date
:initarg start-date
:as-string "start_date")
(end-date
:accessor end-date
:initarg :end-date
:as-string "end-date")))
(defapi billing%execute
("/v1/payments/billing-agreements/:agreement-id/agreement-execute" post-request)
())
(defapi products%list ("/v1/catalogs/products" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(total-required
:accessor total-requried
:initarg :total-required
:as-string "total_required")))
(defapi products%create ("/v1/catalogs/products" post-request)
())
(defapi products%update ("/v1/catalogs/products/:product-id" patch-request)
())
(defapi products%details ("/v1/catalogs/products/:product-id" get-request)
())
(defapi disputes%get ("/v1/customer/disputes" get-request)
((start-time
:accessor start-time
:initarg :start-time
:as-string "start_time")
(disputed-transaction-id
:accessor disputed-transaction_id
:initarg :disputed-transaction_id
:as-string "disputed_transaction_id")
(page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(next-page-token
:accessor next-page-token
:initarg :next-page-token
:as-string "next_page_token")
(dispute-state
:accessor dispute-state
:initarg :dispute-state
:as-string "dispute_state")
(update-time-before
:accessor update-time-before
:initarg :update-time-before
:as-string "update_time_before")
(update-time-after
:accessor update-time-after
:initarg :update-time-after
:as-string "update_time_after")))
(defapi disputes%update ("/v1/customer/disputes/:dispute-id" patch-request)
())
(defapi disputes%details ("/v1/customer/disputes/:dispute-id" get-request)
())
(defapi disputes-actions%accept-claim ("/v1/customer/disputes/:dispute-id/accept-claim"
post-request)
())
(defapi disputes-actions%accept-resolve ("/v1/customer/disputes/:dispute-id/accept-offer"
post-request)
())
(defapi disputes-actions%acknowledge-return
("/v1/customer/disputes/:dispute-id/acknowledge-return-item"
post-request)
())
(defapi disputes-actions%adjudicate
("/v1/customer/disputes/:dispute-id/adjudicate"
post-request)
(defapi disputes-actions%appeal
("/v1/customer/disputes/:dispute-id/appeal"
post-files-request)
())
(defapi disputes-actions%deny-resolve
("/v1/customer/disputes/:dispute-id/deny-offer"
post-request)
())
(defapi disputes-actions%escalate
("/v1/customer/disputes/:dispute-id/escalate"
post-request)
())
(defapi disputes-actions%offer-resolve
("/v1/customer/disputes/:dispute-id/make-offer"
post-request)
())
(defapi disputes-actions%provide-evidence
("/v1/customer/disputes/:dispute-id/provide-evidence"
post-files-request)
())
(defapi disputes-actions%provide-supporting-info
("/v1/customer/disputes/:dispute-id/provide-supporting-info"
post-files-request)
(defapi disputes-actions%require-evidence
("/v1/customer/disputes/:dispute-id/require-evidence"
post-request)
(defapi disputes-actions%send-message
("/v1/customer/disputes/:dispute-id/send-message"
post-files-request)
())
(defapi identity-userinfo&profile-info ("/v1/identity/oauth2/userinfo" get-request)
((schema
:accessor schema
:initarg :schema)))
(defapi identity-applications%create ("/v1/identity/applications" post-request)
())
(defapi identity-account%set-properties ("/v1/identity/account-settings" post-request)
())
(defapi identity-account%disable-properties
("/v1/identity/account-settings/deactivate" post-request)
())
(defapi invoices%generate-invoice-number ("/v2/invoicing/generate-next-invoice-number"
post-request)
())
(defapi invoices%list ("/v2/invoicing/invoices" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(total-required
:accessor total-requried
:initarg :total-required
:as-string "total_required")
(fields
:accessor fields
:initarg :fields)))
(defapi invoices%create-draft ("/v2/invoicing/invoices"
post-request)
())
(defapi invoices%delete ("/v2/invoicing/invoices/:invoice-id"
delete-request)
())
(defapi invoices%update-invoice ("/v2/invoicing/invoices/:invoice-id"
put-request)
((send-to-recipient
:accessor send-to-recipient
:initarg :send-to-recipient
:as-string "send_to_recipient")
(send_to_invoicer
:accessor send-to-invoicer
:initarg :send-to-invoicer
:as-string "send_to_invoicer")))
(defapi invoices%details ("/v2/invoicing/invoices/:invoice-id"
get-request)
())
(defapi invoices%cancel ("/v2/invoicing/invoices/:invoice-id/cancel"
post-request)
())
(defapi invoices%generate-qr-code ("/v2/invoicing/invoices/:invoice-id/generate-qr-code"
post-request)
())
(defapi invoices%record-payment ("/v2/invoicing/invoices/:invoice-id/payments"
post-request)
())
(defapi invoices%delete-external-payment
("/v2/invoicing/invoices/:invoice-id/payments/:transaction-id"
delete-request)
())
(defapi invoices%record-refund
("/v2/invoicing/invoices/:invoice-id/refunds"
post-request)
())
(defapi invoices%delete-external-refund
("/v2/invoicing/invoices/:invoice-id/refunds/:transaction-id"
delete-request)
())
(defapi invoices%remind
("/v2/invoicing/invoices/:invoice-id/remind"
post-request)
())
(defapi invoices%send
("/v2/invoicing/invoices/:invoice-id/send"
post-request)
(defapi invoices%search ("/v2/invoicing/search-invoices" post-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(total_required
:accessor total-requried
:initarg :total-required
:as-string "total_required")))
(defapi invoices-templates%list ("/v2/invoicing/templates" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(fields
:accessor fields
:initarg :fields)))
(defapi invoices-templates%create ("/v2/invoicing/templates" post-request)
())
(defapi invoices-templates%delete ("/v2/invoicing/templates/:template-id" delete-request)
())
(defapi invoices-templates%update ("/v2/invoicing/templates/:template-id" put-request)
())
(defapi invoices-templates%details ("/v2/invoicing/templates/:template-id" get-request)
())
(defapi orders%create ("/v2/checkout/orders" post-request)
(defapi orders%update ("/v2/checkout/orders/:order-id" patch-request)
())
(defapi orders%details ("/v2/checkout/orders/:order-id" get-request)
((fields
:accessor fields
:initarg :fields)))
(defapi orders%authorize ("/v2/checkout/orders/:order-id/authorize" post-request)
(defapi orders%capture ("/v2/checkout/orders/:order-id/capture" post-request)
(defapi partner%create ("/v2/customer/partner-referrals" post-request)
())
(defapi partner%get-data ("/v2/customer/partner-referrals/:referral-id" get-request)
())
(defapi web-profiles%list ("/v1/payment-experience/web-profiles" get-request)
())
(defapi web-profiles%create ("/v1/payment-experience/web-profiles" post-request)
(defapi web-profiles%delete ("/v1/payment-experience/web-profiles/:profile-id" delete-request)
())
(defapi web-profiles%update ("/v1/payment-experience/web-profiles/:profile-id" patch-request)
())
(defapi web-profiles%partial-update
("/v1/payment-experience/web-profiles/:profile-id" patch-request)
())
(defapi web-profiles%details
("/v1/payment-experience/web-profiles/:profile-id" get-request)
())
(defapi payments-authorization%details
("/v2/payments/authorizations/:authorization-id" get-request)
())
(defapi payments-authorization%capture
("/v2/payments/authorizations/:authorization-id/capture" post-request)
(defapi payments-authorization%reauthorize
("/v2/payments/authorizations/:authorization-id/reauthorize" post-request)
(defapi payments-authorization%void
("/v2/payments/authorizations/:authorization-id/void" post-request)
(defapi payments-captures%details
("/v2/payments/captures/:capture-id" get-request)
(defapi payments-captures%refund
("/v2/payments/captures/:capture-id/refund" post-request)
(defapi payments-refunds%details
("/v2/payments/refunds/:refund-id" get-request)
())
(defapi payouts-batch%create
("/v1/payments/payouts" post-request)
(defapi payouts-batch%details
("/v1/payments/payouts/:batch-id" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(fields
:accessor fields
:initarg :fields)
(total-required
:accessor total-required
:initarg :total-required
:as-string "total_required")))
(defapi payouts-item%details
("/v1/payments/payouts-item/:payout-id" get-request)
())
(defapi payouts-item%cancel-unclaimed
("/v1/payments/payouts-item/:payout-id/cancel" post-request)
())
(defapi referenced-payouts-batch%create
("/v1/payments/referenced-payouts" post-request)
(defapi referenced-payouts-batch%details
("/v1/payments/referenced-payouts/:batch-id" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(fields
:accessor fields
:initarg :fields)
(total-required
:accessor total-required
:initarg :total-required
:as-string "total_required")))
(defapi referenced-payouts-item%create
("/v1/payments/referenced-payouts-items" post-request)
(defapi referenced-payouts-item%cancel-unclaimed
("/v1/payments/referenced-payouts-items/:payout-id" get-request)
(defapi subscriptions-plans%list ("/v1/billing/plans" get-request)
((page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)
(product-id
:accessor product-id
:initarg :product-id
:as-string "product_id")
(plan-ids
:accessor plan-ids
:initarg :plan-ids
:as-string "plan_ids")
(total-required
:accessor total-required
:initarg :total-required
:as-string "total_required")))
(defapi subscribtions-plans%create ("/v1/billing/plans" post-request)
(defapi subscribtions-plans%update ("/v1/billing/plans/:plan-id" patch-request)
())
(defapi subscribtions-plans%details ("/v1/billing/plans/:plan-id" get-request)
())
(defapi subscribtions-plans%activate ("/v1/billing/plans/:plan-id/activate" post-request)
())
(defapi subscribtions-plans%deactivate ("/v1/billing/plans/:plan-id/deactivate" post-request)
())
(defapi subscribtions-plans%update-pricing-schemas
("/v1/billing/plans/:plan-id/update-pricing-schemas" post-request)
())
(defapi subscriptions%create ("/v1/billing/subscriptions" post-request)
(defapi subscriptions%update ("/v1/billing/subscriptions/:sub-id" patch-request)
())
(defapi subscriptions%details ("/v1/billing/subscriptions/:sub-id" get-request)
())
(defapi subscriptions%activate ("/v1/billing/subscriptions/:sub-id/activate" post-request)
())
(defapi subscriptions%cancel ("/v1/billing/subscriptions/:sub-id/activate" post-request)
())
(defapi subscriptions%capture ("/v1/billing/subscriptions/:sub-id/capture" post-request)
())
(defapi subscriptions%revise ("/v1/billing/subscriptions/:sub-id/revise" post-request)
())
(defapi subscriptions%suspend ("/v1/billing/subscriptions/:sub-id/suspend" post-request)
())
(defapi subscriptions%transactions ("/v1/billing/subscriptions/:sub-id/transactions"
post-request)
((start-time
:accessor start-time
:initarg :start-time
:as-string "start_time")
(end-time
:accessor end-time
:initarg :end-time
:as-string "end_time")))
(defapi search-transactions%list ("/v1/reporting/transactions" get-request)
((transaction-id
:accessor transaction-id
:initarg :transaction-id
:as-string "transaction_id")
(transaction-type
:accessor transaction-type
:initarg :transaction-type
:as-string "transaction_type")
(transaction-status
:accessor transaction-status
:initarg :transaction-status
:as-string "transaction_status")
(transaction-amount
:accessor transaction-amount
:initarg :transaction-amount
:as-string "transaction_amount")
(transaction-currency
:accessor transaction-currency
:initarg :transaction-currency
:as-string "transaction_currency")
(start-date
:accessor start-date
:initarg :start-date
:as-string "start_date")
(end-date
:accessor end-date
:initarg :end-date
:as-string "end_date")
(payment-instrument-type
:accessor payment-instrument-type
:initarg :payment-instrument-type
:as-string "payment_instrument_type")
(store-id
:accessor store-id
:initarg :store-id
:as-string "store_id")
(terminal-id
:accessor terminal-id
:initarg :terminal-id
:as-string "terminal_id")
(fields
:accessor fields
:initarg :fields)
(balance-affecting-records-only
:accessor balance-affecting-records-only
:initarg :balance-affecting-records-only
:as-string "balance_affecting_records_only")
(page-size
:accessor page-size
:initarg :page-size
:as-string "page_size")
(page
:accessor page
:initarg :page)))
(defapi search-balances%list ("/v1/reporting/balances" get-request)
((as-of-time
:accessor as-of-time
:initarg :as-of-time
:as-string "as_of_time")
(currency-code
:accessor currency-code
:initarg :currency-code
:as-string "currency_code")))
(defapi webhooks%list ("/v1/notifications/webhooks" get-request)
((anchor-time
:accessor anchor-time
:initarg :anchor-time
:as-string "anchor_time")))
(defapi webhooks%create ("/v1/notifications/webhooks" post-request)
())
(defapi webhooks%delete ("/v1/notifications/webhooks/:webhook-id" delete-request)
())
(defapi webhooks%update ("/v1/notifications/webhooks/:webhook-id" patch-request)
())
(defapi webhooks%details ("/v1/notifications/webhooks/:webhook-id" get-request)
())
(defapi webhooks%list-event-subscriptions
("/v1/notifications/webhooks/:webhook-id/event-types" get-request)
())
( defapi webhooks%verify - signature ( " /v1 / notifications / verify - webhook - signature " post - request%jojo )
(defapi webhooks%list-event-types ("/v1/notifications/webhooks-event-types" get-request)
())
(defapi webhooks%list-event-notifications ("/v1/notifications/webhooks-events" get-request)
((page_size
:accessor page-size
:initarg :page-size)
(transaction_id
:accessor transaction-id
:initarg :transaction-id)
(event_type
:accessor event-type
:initarg :event-type)
(start-time
:accessor start-time
:initarg :start-time
:as-string "start_time")
(end-time
:accessor end-time
:initarg :end-time
:as-string "end_time")))
(defapi webhooks%notification-details ("/v1/notifications/webhooks-events/:event-id"
get-request)
())
(defapi webhooks%resend-event ("/v1/notifications/webhooks-events/:event-id/resend"
post-request)
())
(defapi webhooks%simulate-event ("/v1/notifications/simulate-event"
post-request)
())
|
fd2ad410670be21fdaca37fcdc1d9a9cadd49aaa9ad6778e1d8a513b0384f471 | zwizwa/erl_tools | pdm.erl | -module(pdm).
-export([init/2, handle/2, measure/2, measure_range/4, note/1, test/1]).
Driver for uc_tools / gdb / pdm.c
init(Pid, _PacketProto) ->
log:info("pdm:init/2~n"),
Pid ! {set_forward, fun ?MODULE:handle/2},
Pid ! {set_table,
[{32.993691763118974,0.519800711025074},
{44.99687329722091,0.5035198183532176},
{56.99146889926967,0.4866359404918295},
{69.00104275427175,0.46926520840512365},
{81.0276414746553,0.4517417130595159},
{92.99664004886864,0.43381246872559903},
{105.03970518303649,0.4151599177154455},
{116.99352651532479,0.39536910814332427}]},
ok.
%% Be careful for cycles here.
super(Msg,State) ->
gdbstub_hub:dev_handle(Msg, State).
handle({set_table, Table}, State) ->
maps:put(table, Table, State);
%% resistor
handle(calibrate1, State) ->
handle({calibrate, [0.49, 0.51], 55, 8}, State);
%% diode
handle(calibrate2, State) ->
handle({calibrate, [0.4, 0.42], 55, 8}, State);
handle({calibrate, Init, Hz, N}, State) ->
Self = self(),
spawn_link(
fun() -> Self ! {set_table, octaves(Self, Init, Hz, N)} end),
State;
handle({note, Note}, State = #{ table := Table }) ->
%% log:info("note ~p~n", [Note]),
Setpoint = interpolate(Note, Table),
handle({setpoint, 0, Setpoint}, State);
handle(stop, State) ->
maps:remove(loop, State);
handle(start, State) ->
case maps:find(loop, State) of
error ->
State;
{ok,
#{ sequence := [First|Rest],
base := Base,
time := Time} = Loop} ->
self() ! {note, Base + First},
{ok,_} = timer:send_after(Time, start),
maps:put(loop,
maps:put(sequence,
Rest ++ [First],
Loop),
State)
end;
handle({loop, Base, Sequence, Time}, State) ->
maps:put(loop,
#{ sequence => Sequence,
base => Base,
time => Time },
State);
handle(loop, State) ->
handle({loop, 37, [1,3,1,11,9,1,3,3-11], 200}, State);
handle(info, State) ->
super({send_u32,[103]}, State);
handle({setpoint, Channel, FloatVal}, State) ->
IntVal = round(FloatVal * 16#100000000),
Clipped =
if
IntVal >= 16#100000000 -> 16#FFFFFFFF;
IntVal < 0 -> 0;
true -> IntVal
end,
Reduced = Clipped band 16#FFFFFFFF,
Reduced = Clipped band 16#FF000000 ,
State1 = maps:put({setpoint, Channel}, FloatVal, State),
%% log:info("~8.16.0B~n",[Reduced]),
super({send_u32,[101,Channel,Reduced]}, State1);
handle({setpoint_rel, Channel, RelVal}, State) ->
AbsVal = RelVal + maps:get({setpoint,Channel}, State, 0.5),
State1 = maps:put({setpoint,Channel}, AbsVal, State),
super({setpoint, Channel, AbsVal}, State1);
handle({epid_send,Dst,Data}=Msg, State) ->
case Dst of
midi ->
lists:foldl(
fun(Midi,S) ->
case Midi of
{cc,0,P,V} ->
midi_cc(P,V,S);
_->
S
end
end,
State,
Data);
_ ->
log:info("pdm: unknown: ~p~n",[Msg]),
State
end;
FIXME : First I want tag_u32 with binary payload and abstract
%% continuation. Put that in the library.
handle({Pid, {measure, LogMax}}, State) ->
FIrmware places continuation in a queue to reply when the
%% measurement is done.
super({Pid, {call_u32, [102, LogMax]}}, State);
handle(Msg, State) ->
%% log:info("pdm: passing on: ~p~n",[Msg]),
gdbstub_hub:default_handle_packet(Msg, State).
midi_cc(P,V,State) ->
case P of
22 ->
Frac = 0.45 - 0.0015 * (V - 64.0),
log : info("0 : ~p ~ n",[{P , V , } ] ) ,
handle({setpoint, 0, Frac}, State);
21 ->
Frac = 0.4 - 0.0015 * (V - 64.0),
log : info("1 : ~p ~ n",[{P , V , } ] ) ,
handle({setpoint, 1, Frac}, State);
20 ->
Frac = 0.435 - 0.0045 * (V - 64.0),
log : info("1 : ~p ~ n",[{P , V , } ] ) ,
handle({setpoint, 2, Frac}, State);
_ ->
log:info("~p~n",[{P,V}]),
ok
end,
State.
%% The low level interface is a little quirky. The routine below
Specify the log of the number of CPU cycles to measure . The
%% result has the decimal point shifted by that amount. 1<<26 CPU
cycles is about a second .
measure(Pid,LogMax) ->
true = LogMax < 32,
true = LogMax >= 0,
FracBits = 32 - LogMax,
Such that Period / Div is in seconds , Div / Period is in Hz .
Div = 72000000.0 * (1 bsl FracBits),
case obj:call(Pid, {measure,LogMax}, 3000) of
<<Period:32,_Count:32>> ->
Rv = Div / Period,
Rv
end.
%% Crashes when period becomes too high, probably not triggering any
%% measurements.
pdm : measure_range(pdm , 0,5 , 0,0001 , 3 ) .
measure_range(Pid, Start, Inc, N) ->
0.25sec
lists:map(
fun(I) ->
Frac = Start + Inc * I,
Pid ! {setpoint, 0, Frac},
_ = measure(Pid, LogMax), %% Throw away transition
Rv = {Frac,measure(Pid, LogMax)},
log:info("~p\n", [Rv]),
Rv
end,
lists:seq(0,N-1)).
%% It doesn't matter much which logarithm we use for the root finder,
%% so use fractional midi notes, since that is necessary anyway. That
maps A4 , Note=69 to 440Hz , with 12 steps per octave .
note(X) ->
69.0 + 12.0 * math:log(X / 440.0) / math:log(2).
%% Find the set point that gives a particular frequency using
%% successive linear approximation of the setpoint -> log(freq) curve.
%%
pdm : find_freq(pdm , 110 , 2 ) .
Two or three iterations seems to be enough for most frequencies .
Set it to 4 for an extra step . Note that the initial two points
%% are very important: too low and the frequency measurement might
%% time out. Pick them very close to the mid range of the converter.
%% Measure, but drop transition
measure_drop(Pid, LogMax, Frac) ->
Pid ! {setpoint, 0, Frac},
%% Throw away transition
_ = measure(Pid, LogMax),
M = measure(Pid, LogMax),
Rv = {Frac, note(M), M},
log:info("~p~n", [Rv]),
Rv.
octaves(Pid, XInits, Hz, NbOctaves) ->
0.25 sec
NbIter = 4,
Measure = fun(Frac) -> measure_drop(Pid, LogMax, Frac) end,
%% Initial points are meausred once and reused to start each octave scan.
[XYA, XYB] = lists:map(Measure, XInits),
map_octaves(Pid, Measure, Hz, XYA, XYB, NbIter, NbOctaves).
%% Iterate over Octaves
map_octaves(_, _, _, _, _, _, 0) -> [];
map_octaves(Pid, Measure, Hz, XYA, XYB, NbIter, NbOctaves) ->
#{setpoint := Setpoint, note := Note} = find_freq(Pid, Measure, Hz, XYA, XYB, NbIter),
[{Note, Setpoint} | map_octaves(Pid, Measure, Hz*2, XYA, XYB, NbIter, NbOctaves-1)].
find_freq(Pid, Measure, Hz, XYA, XYB, NbIter) ->
Approx = find_freq_it(Pid, Measure, note(Hz), XYA, XYB, NbIter),
{XE,YE,EYE} = lists:last(Approx),
#{setpoint => XE,
note => YE,
hz => EYE,
approx => Approx}.
%% Iterate rootfinding.
find_freq_it(_, _, _, XYA, XYB, 0) -> [XYA, XYB];
find_freq_it(Pid, Measure, YT, {XA,YA,_}=XYA, {XB,YB,_}=XYB, NbIter) ->
XC = XA + (YT-YA) * ((XB-XA) / (YB-YA)),
XYC = Measure(XC),
[XYA | find_freq_it(Pid, Measure, YT, XYB, XYC, NbIter-1)].
interpolate(Note, {NA,SA}, {NB,SB}) ->
Setpoint = SA + (Note-NA) * ((SB-SA)/(NB-NA)),
Setpoint.
interpolate(Note, [A,{NB,_}=B|Rest]) ->
case {(Note < NB),Rest} of
{true,_} ->
interpolate(Note, A, B);
{false,[]} ->
interpolate(Note, A, B);
{false,_} ->
interpolate(Note, [B|Rest])
end.
test(table) ->
%% output of test(table_init).
%% Maps midi notes to setpoints.
[{32.993691763118974,0.519800711025074},
{44.99687329722091,0.5035198183532176},
{56.99146889926967,0.4866359404918295},
{69.00104275427175,0.46926520840512365},
{81.0276414746553,0.4517417130595159},
{92.99664004886864,0.43381246872559903},
{105.03970518303649,0.4151599177154455},
{116.99352651532479,0.39536910814332427}];
test({note_setpoint,Note}) ->
interpolate(Note, test(table));
test({note,Note}) ->
pdm ! {setpoint, 0, test({note_setpoint,Note})};
test({seq,Base,Seq,Ms}) ->
lists:foreach(
fun(N) ->
_ = test({note, Base+N}),
timer:sleep(Ms)
end,
Seq);
test({loop,Base,Seq,Ms,N}) ->
lists:foreach(
fun(_I) ->
test({seq,Base,Seq,Ms})
end,
lists:seq(1,N));
%% FIXME: Put a sequencer in the object with start/stop.
test(loop) ->
test({loop, 37, [0,7,5,11,12,1,7,9], 200, 8}).
| null | https://raw.githubusercontent.com/zwizwa/erl_tools/07645992e968c1456c9d0212f380afd1ffce4c1f/src/pdm.erl | erlang | Be careful for cycles here.
resistor
diode
log:info("note ~p~n", [Note]),
log:info("~8.16.0B~n",[Reduced]),
continuation. Put that in the library.
measurement is done.
log:info("pdm: passing on: ~p~n",[Msg]),
The low level interface is a little quirky. The routine below
result has the decimal point shifted by that amount. 1<<26 CPU
Crashes when period becomes too high, probably not triggering any
measurements.
Throw away transition
It doesn't matter much which logarithm we use for the root finder,
so use fractional midi notes, since that is necessary anyway. That
Find the set point that gives a particular frequency using
successive linear approximation of the setpoint -> log(freq) curve.
are very important: too low and the frequency measurement might
time out. Pick them very close to the mid range of the converter.
Measure, but drop transition
Throw away transition
Initial points are meausred once and reused to start each octave scan.
Iterate over Octaves
Iterate rootfinding.
output of test(table_init).
Maps midi notes to setpoints.
FIXME: Put a sequencer in the object with start/stop. | -module(pdm).
-export([init/2, handle/2, measure/2, measure_range/4, note/1, test/1]).
Driver for uc_tools / gdb / pdm.c
init(Pid, _PacketProto) ->
log:info("pdm:init/2~n"),
Pid ! {set_forward, fun ?MODULE:handle/2},
Pid ! {set_table,
[{32.993691763118974,0.519800711025074},
{44.99687329722091,0.5035198183532176},
{56.99146889926967,0.4866359404918295},
{69.00104275427175,0.46926520840512365},
{81.0276414746553,0.4517417130595159},
{92.99664004886864,0.43381246872559903},
{105.03970518303649,0.4151599177154455},
{116.99352651532479,0.39536910814332427}]},
ok.
super(Msg,State) ->
gdbstub_hub:dev_handle(Msg, State).
handle({set_table, Table}, State) ->
maps:put(table, Table, State);
handle(calibrate1, State) ->
handle({calibrate, [0.49, 0.51], 55, 8}, State);
handle(calibrate2, State) ->
handle({calibrate, [0.4, 0.42], 55, 8}, State);
handle({calibrate, Init, Hz, N}, State) ->
Self = self(),
spawn_link(
fun() -> Self ! {set_table, octaves(Self, Init, Hz, N)} end),
State;
handle({note, Note}, State = #{ table := Table }) ->
Setpoint = interpolate(Note, Table),
handle({setpoint, 0, Setpoint}, State);
handle(stop, State) ->
maps:remove(loop, State);
handle(start, State) ->
case maps:find(loop, State) of
error ->
State;
{ok,
#{ sequence := [First|Rest],
base := Base,
time := Time} = Loop} ->
self() ! {note, Base + First},
{ok,_} = timer:send_after(Time, start),
maps:put(loop,
maps:put(sequence,
Rest ++ [First],
Loop),
State)
end;
handle({loop, Base, Sequence, Time}, State) ->
maps:put(loop,
#{ sequence => Sequence,
base => Base,
time => Time },
State);
handle(loop, State) ->
handle({loop, 37, [1,3,1,11,9,1,3,3-11], 200}, State);
handle(info, State) ->
super({send_u32,[103]}, State);
handle({setpoint, Channel, FloatVal}, State) ->
IntVal = round(FloatVal * 16#100000000),
Clipped =
if
IntVal >= 16#100000000 -> 16#FFFFFFFF;
IntVal < 0 -> 0;
true -> IntVal
end,
Reduced = Clipped band 16#FFFFFFFF,
Reduced = Clipped band 16#FF000000 ,
State1 = maps:put({setpoint, Channel}, FloatVal, State),
super({send_u32,[101,Channel,Reduced]}, State1);
handle({setpoint_rel, Channel, RelVal}, State) ->
AbsVal = RelVal + maps:get({setpoint,Channel}, State, 0.5),
State1 = maps:put({setpoint,Channel}, AbsVal, State),
super({setpoint, Channel, AbsVal}, State1);
handle({epid_send,Dst,Data}=Msg, State) ->
case Dst of
midi ->
lists:foldl(
fun(Midi,S) ->
case Midi of
{cc,0,P,V} ->
midi_cc(P,V,S);
_->
S
end
end,
State,
Data);
_ ->
log:info("pdm: unknown: ~p~n",[Msg]),
State
end;
FIXME : First I want tag_u32 with binary payload and abstract
handle({Pid, {measure, LogMax}}, State) ->
FIrmware places continuation in a queue to reply when the
super({Pid, {call_u32, [102, LogMax]}}, State);
handle(Msg, State) ->
gdbstub_hub:default_handle_packet(Msg, State).
midi_cc(P,V,State) ->
case P of
22 ->
Frac = 0.45 - 0.0015 * (V - 64.0),
log : info("0 : ~p ~ n",[{P , V , } ] ) ,
handle({setpoint, 0, Frac}, State);
21 ->
Frac = 0.4 - 0.0015 * (V - 64.0),
log : info("1 : ~p ~ n",[{P , V , } ] ) ,
handle({setpoint, 1, Frac}, State);
20 ->
Frac = 0.435 - 0.0045 * (V - 64.0),
log : info("1 : ~p ~ n",[{P , V , } ] ) ,
handle({setpoint, 2, Frac}, State);
_ ->
log:info("~p~n",[{P,V}]),
ok
end,
State.
Specify the log of the number of CPU cycles to measure . The
cycles is about a second .
measure(Pid,LogMax) ->
true = LogMax < 32,
true = LogMax >= 0,
FracBits = 32 - LogMax,
Such that Period / Div is in seconds , Div / Period is in Hz .
Div = 72000000.0 * (1 bsl FracBits),
case obj:call(Pid, {measure,LogMax}, 3000) of
<<Period:32,_Count:32>> ->
Rv = Div / Period,
Rv
end.
pdm : measure_range(pdm , 0,5 , 0,0001 , 3 ) .
measure_range(Pid, Start, Inc, N) ->
0.25sec
lists:map(
fun(I) ->
Frac = Start + Inc * I,
Pid ! {setpoint, 0, Frac},
Rv = {Frac,measure(Pid, LogMax)},
log:info("~p\n", [Rv]),
Rv
end,
lists:seq(0,N-1)).
maps A4 , Note=69 to 440Hz , with 12 steps per octave .
note(X) ->
69.0 + 12.0 * math:log(X / 440.0) / math:log(2).
pdm : find_freq(pdm , 110 , 2 ) .
Two or three iterations seems to be enough for most frequencies .
Set it to 4 for an extra step . Note that the initial two points
measure_drop(Pid, LogMax, Frac) ->
Pid ! {setpoint, 0, Frac},
_ = measure(Pid, LogMax),
M = measure(Pid, LogMax),
Rv = {Frac, note(M), M},
log:info("~p~n", [Rv]),
Rv.
octaves(Pid, XInits, Hz, NbOctaves) ->
0.25 sec
NbIter = 4,
Measure = fun(Frac) -> measure_drop(Pid, LogMax, Frac) end,
[XYA, XYB] = lists:map(Measure, XInits),
map_octaves(Pid, Measure, Hz, XYA, XYB, NbIter, NbOctaves).
map_octaves(_, _, _, _, _, _, 0) -> [];
map_octaves(Pid, Measure, Hz, XYA, XYB, NbIter, NbOctaves) ->
#{setpoint := Setpoint, note := Note} = find_freq(Pid, Measure, Hz, XYA, XYB, NbIter),
[{Note, Setpoint} | map_octaves(Pid, Measure, Hz*2, XYA, XYB, NbIter, NbOctaves-1)].
find_freq(Pid, Measure, Hz, XYA, XYB, NbIter) ->
Approx = find_freq_it(Pid, Measure, note(Hz), XYA, XYB, NbIter),
{XE,YE,EYE} = lists:last(Approx),
#{setpoint => XE,
note => YE,
hz => EYE,
approx => Approx}.
find_freq_it(_, _, _, XYA, XYB, 0) -> [XYA, XYB];
find_freq_it(Pid, Measure, YT, {XA,YA,_}=XYA, {XB,YB,_}=XYB, NbIter) ->
XC = XA + (YT-YA) * ((XB-XA) / (YB-YA)),
XYC = Measure(XC),
[XYA | find_freq_it(Pid, Measure, YT, XYB, XYC, NbIter-1)].
interpolate(Note, {NA,SA}, {NB,SB}) ->
Setpoint = SA + (Note-NA) * ((SB-SA)/(NB-NA)),
Setpoint.
interpolate(Note, [A,{NB,_}=B|Rest]) ->
case {(Note < NB),Rest} of
{true,_} ->
interpolate(Note, A, B);
{false,[]} ->
interpolate(Note, A, B);
{false,_} ->
interpolate(Note, [B|Rest])
end.
test(table) ->
[{32.993691763118974,0.519800711025074},
{44.99687329722091,0.5035198183532176},
{56.99146889926967,0.4866359404918295},
{69.00104275427175,0.46926520840512365},
{81.0276414746553,0.4517417130595159},
{92.99664004886864,0.43381246872559903},
{105.03970518303649,0.4151599177154455},
{116.99352651532479,0.39536910814332427}];
test({note_setpoint,Note}) ->
interpolate(Note, test(table));
test({note,Note}) ->
pdm ! {setpoint, 0, test({note_setpoint,Note})};
test({seq,Base,Seq,Ms}) ->
lists:foreach(
fun(N) ->
_ = test({note, Base+N}),
timer:sleep(Ms)
end,
Seq);
test({loop,Base,Seq,Ms,N}) ->
lists:foreach(
fun(_I) ->
test({seq,Base,Seq,Ms})
end,
lists:seq(1,N));
test(loop) ->
test({loop, 37, [0,7,5,11,12,1,7,9], 200, 8}).
|
0b96d1b64711f34d71c28d83da79ac06b762609672bb478224ba11a2b51a53f4 | schemeorg-community/index.scheme.org | srfi.160.u32.scm | (((name . "make-u32vector")
(signature
case-lambda
(((integer? size)) u32vector?)
(((integer? size) (u32? fill)) u32vector?))
(tags pure))
((name . "u32vector")
(signature lambda ((u32? value) ...) u32vector?)
(tags pure))
((name . "u32?")
(signature lambda (obj) boolean?)
(tags pure predicate)
(supertypes integer?))
((name . "u32vector?")
(signature lambda (obj) boolean?)
(tags pure predicate))
((name . "u32vector-ref")
(signature lambda ((u32vector? vec) (integer? i)) u32?)
(tags pure))
((name . "u32vector-length")
(signature lambda ((u32vector? vec)) integer?)
(tags pure))
((name . "u32vector-set!")
(signature lambda ((u32vector? vec) (integer? i) (u32? value)) undefined))
((name . "u32vector->list")
(signature
case-lambda
(((u32vector? vec)) list?)
(((u32vector? vec) (integer? start)) list?)
(((u32vector? vec) (integer? start) (integer? end)) list?))
(tags pure))
((name . "list->u32vector")
(signature lambda ((list? proper-list)) u32vector?)
(tags pure))
((name . "u32vector-unfold")
(signature
case-lambda
(((procedure? f) (integer? length) seed) u32vector?)
(((procedure? f) (integer? length) seed) u32vector?))
(subsigs (f (lambda ((integer? index) state) (values u32? *))))
(tags pure))
((name . "u32vector-copy")
(signature
case-lambda
(((u32vector? vec)) u32vector?)
(((u32vector? vec) (integer? start)) u32vector?)
(((u32vector? vec) (integer? start) (integer? end)) u32vector?))
(tags pure))
((name . "u32vector-reverse-copy")
(signature
case-lambda
(((u32vector? vec)) u32vector?)
(((u32vector? vec) (integer? start)) u32vector?)
(((u32vector? vec) (integer? start) (integer? end)) u32vector?))
(tags pure))
((name . "u32vector-append")
(signature lambda ((u32vector? vec) ...) u32vector?)
(tags pure))
((name . "u32vector-concatenate")
(signature lambda ((list? list-of-u32vectors)) u32vector?)
(tags pure))
((name . "u32vector-append-subvectors")
(signature
lambda
((u32vector? vec1) (integer? start1) (integer? start2) ...)
u32vector?)
(tags pure))
((name . "u32vector-empty?")
(signature lambda ((u32vector? vec)) boolean?)
(tags pure))
((name . "u32vector=")
(signature lambda ((u32vector? vec) ...) boolean?)
(tags pure))
((name . "u32vector-take")
(signature lambda ((u32vector? vec) (integer? n)) u32vector?)
(tags pure))
((name . "u32vector-take-right")
(signature lambda ((u32vector? vec) (integer? n)) u32vector?)
(tags pure))
((name . "u32vector-drop")
(signature lambda ((u32vector? vec) (integer? n)) u32vector?)
(tags pure))
((name . "u32vector-drop-right")
(signature lambda ((u32vector? vec) (integer? n)) u32vector?)
(tags pure))
((name . "u32vector-segment")
(signature lambda ((u32vector? vec) (integer? n)) list?)
(tags pure))
((name . "u32vector-fold")
(signature
lambda
((procedure? kons) knil (u32vector? vec1) (u32vector? vec2) ...)
*)
(subsigs (kons (lambda (state obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-fold-right")
(signature
lambda
((procedure? kons) knil (u32vector? vec1) (u32vector? vec2) ...)
*)
(subsigs (kons (lambda (state obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-map")
(signature
lambda
((procedure? proc) (u32vector? vector1) (u32vector? vector2) ...)
vector?)
(subsigs (proc (lambda (obj ...) *)))
(tags pure))
((name . "u32vector-map!")
(signature
lambda
((procedure? proc) (u32vector? vector1) (u32vector? vector2) ...)
undefined)
(subsigs (proc (lambda (obj ...) *))))
((name . "u32vector-for-each")
(signature
lambda
((procedure? proc) (u32vector? vector1) (u32vector? vector2) ...)
undefined)
(subsigs (proc (lambda (obj ...) undefined))))
((name . "u32vector-count")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
integer?)
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-cumulate")
(signature lambda ((procedure? f) knil (u32vector? vec)) u32vector?)
(subsigs (f (lambda (obj1 obj2) *)))
(tags pure))
((name . "u32vector-take-while")
(signature lambda ((procedure? pred?) (u32vector? vec)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-take-while-right")
(signature lambda ((procedure? pred?) (u32vector? vec)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-drop-while")
(signature lambda ((procedure? pred?) (u32vector? vec)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-drop-while-right")
(signature lambda ((procedure? pred?) (u32vector? vec)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-index")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
(or integer? #f))
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-index-right")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
(or integer? #f))
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-skip")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
(or integer? #f))
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-skip-right")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
(or integer? #f))
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-any")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
*)
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-every")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
*)
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-partition")
(signature
lambda
((procedure? pred?) (u32vector? vec))
(values u32vector? integer?))
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-filter")
(signature lambda ((procedure? pred?) (u32vector? vec1)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-remove")
(signature lambda ((procedure? pred?) (u32vector? vec1)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-swap!")
(signature
lambda
((u32vector? u32vector) (integer? i) (integer? j))
undefined))
((name . "u32vector-fill!")
(signature
case-lambda
(((u32vector? u32vector) (u32? fill)) undefined)
(((u32vector? u32vector) (u32? fill) (integer? start)) undefined)
(((u32vector? u32vector) (u32? fill) (integer? start) (integer? end))
undefined)))
((name . "u32vector-reverse!")
(signature
case-lambda
(((u32vector? u32vector)) undefined)
(((u32vector? u32vector) (integer? start)) undefined)
(((u32vector? u32vector) (integer? start) (integer? end)) undefined)))
((name . "u32vector-copy!")
(signature
case-lambda
(((u32vector? to) (integer? at) (u32vector? from)) undefined)
(((u32vector? to) (integer? at) (u32vector? from) (integer? start))
undefined)
(((u32vector? to)
(integer? at)
(u32vector? from)
(integer? start)
(integer? end))
undefined)))
((name . "u32vector-reverse-copy!")
(signature
case-lambda
(((u32vector? to) (integer? at) (u32vector? from)) undefined)
(((u32vector? to) (integer? at) (u32vector? from) (integer? start))
undefined)
(((u32vector? to)
(integer? at)
(u32vector? from)
(integer? start)
(integer? end))
undefined)))
((name . "u32vector-unfold!")
(signature
lambda
((procedure? f)
(u32vector? vec)
(integer? start)
(integer? end)
initial-seed
...)
undefined)
(subsigs (f (lambda ((integer? index) seed ...) (values * * ...)))))
((name . "u32vector-unfold-right!")
(signature
lambda
((procedure? f)
(u32vector? vec)
(integer? start)
(integer? end)
initial-seed
...)
undefined)
(subsigs (f (lambda ((integer? index) seed ...) (values * * ...)))))
((name . "reverse-u32vector->list")
(signature
case-lambda
(((u32vector? vec)) list?)
(((u32vector? vec) (integer? start)) list?)
(((u32vector? vec) (integer? start) (integer? end)) list?))
(tags pure))
((name . "reverse-list->u32vector")
(signature lambda ((list? proper-list)) u32vector?)
(tags pure))
((name . "u32vector->vector")
(signature
case-lambda
(((u32vector? vec)) vector?)
(((u32vector? vec) (integer? start)) vector?)
(((u32vector? vec) (integer? start) (integer? end)) vector?))
(tags pure))
((name . "vector->u32vector")
(signature
case-lambda
(((vector? vec)) u32vector?)
(((vector? vec) (integer? start)) u32vector?)
(((vector? vec) (integer? start) (integer? end)) u32vector?))
(tags pure))
((name . "make-u32vector-generator")
(signature lambda ((u32vector? vec)) procedure?)
(subsigs (return (lambda () (or eof-object? u32?)))))
((name . "u32vector-comparator") (signature value comparator?))
((name . "write-u32vector")
(signature
case-lambda
(((u32vector vec)) undefined)
(((u32vector vec) (output-port? port)) undefined))))
| null | https://raw.githubusercontent.com/schemeorg-community/index.scheme.org/32e1afcfe423a158ac8ce014f5c0b8399d12a1ea/types/srfi.160.u32.scm | scheme | (((name . "make-u32vector")
(signature
case-lambda
(((integer? size)) u32vector?)
(((integer? size) (u32? fill)) u32vector?))
(tags pure))
((name . "u32vector")
(signature lambda ((u32? value) ...) u32vector?)
(tags pure))
((name . "u32?")
(signature lambda (obj) boolean?)
(tags pure predicate)
(supertypes integer?))
((name . "u32vector?")
(signature lambda (obj) boolean?)
(tags pure predicate))
((name . "u32vector-ref")
(signature lambda ((u32vector? vec) (integer? i)) u32?)
(tags pure))
((name . "u32vector-length")
(signature lambda ((u32vector? vec)) integer?)
(tags pure))
((name . "u32vector-set!")
(signature lambda ((u32vector? vec) (integer? i) (u32? value)) undefined))
((name . "u32vector->list")
(signature
case-lambda
(((u32vector? vec)) list?)
(((u32vector? vec) (integer? start)) list?)
(((u32vector? vec) (integer? start) (integer? end)) list?))
(tags pure))
((name . "list->u32vector")
(signature lambda ((list? proper-list)) u32vector?)
(tags pure))
((name . "u32vector-unfold")
(signature
case-lambda
(((procedure? f) (integer? length) seed) u32vector?)
(((procedure? f) (integer? length) seed) u32vector?))
(subsigs (f (lambda ((integer? index) state) (values u32? *))))
(tags pure))
((name . "u32vector-copy")
(signature
case-lambda
(((u32vector? vec)) u32vector?)
(((u32vector? vec) (integer? start)) u32vector?)
(((u32vector? vec) (integer? start) (integer? end)) u32vector?))
(tags pure))
((name . "u32vector-reverse-copy")
(signature
case-lambda
(((u32vector? vec)) u32vector?)
(((u32vector? vec) (integer? start)) u32vector?)
(((u32vector? vec) (integer? start) (integer? end)) u32vector?))
(tags pure))
((name . "u32vector-append")
(signature lambda ((u32vector? vec) ...) u32vector?)
(tags pure))
((name . "u32vector-concatenate")
(signature lambda ((list? list-of-u32vectors)) u32vector?)
(tags pure))
((name . "u32vector-append-subvectors")
(signature
lambda
((u32vector? vec1) (integer? start1) (integer? start2) ...)
u32vector?)
(tags pure))
((name . "u32vector-empty?")
(signature lambda ((u32vector? vec)) boolean?)
(tags pure))
((name . "u32vector=")
(signature lambda ((u32vector? vec) ...) boolean?)
(tags pure))
((name . "u32vector-take")
(signature lambda ((u32vector? vec) (integer? n)) u32vector?)
(tags pure))
((name . "u32vector-take-right")
(signature lambda ((u32vector? vec) (integer? n)) u32vector?)
(tags pure))
((name . "u32vector-drop")
(signature lambda ((u32vector? vec) (integer? n)) u32vector?)
(tags pure))
((name . "u32vector-drop-right")
(signature lambda ((u32vector? vec) (integer? n)) u32vector?)
(tags pure))
((name . "u32vector-segment")
(signature lambda ((u32vector? vec) (integer? n)) list?)
(tags pure))
((name . "u32vector-fold")
(signature
lambda
((procedure? kons) knil (u32vector? vec1) (u32vector? vec2) ...)
*)
(subsigs (kons (lambda (state obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-fold-right")
(signature
lambda
((procedure? kons) knil (u32vector? vec1) (u32vector? vec2) ...)
*)
(subsigs (kons (lambda (state obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-map")
(signature
lambda
((procedure? proc) (u32vector? vector1) (u32vector? vector2) ...)
vector?)
(subsigs (proc (lambda (obj ...) *)))
(tags pure))
((name . "u32vector-map!")
(signature
lambda
((procedure? proc) (u32vector? vector1) (u32vector? vector2) ...)
undefined)
(subsigs (proc (lambda (obj ...) *))))
((name . "u32vector-for-each")
(signature
lambda
((procedure? proc) (u32vector? vector1) (u32vector? vector2) ...)
undefined)
(subsigs (proc (lambda (obj ...) undefined))))
((name . "u32vector-count")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
integer?)
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-cumulate")
(signature lambda ((procedure? f) knil (u32vector? vec)) u32vector?)
(subsigs (f (lambda (obj1 obj2) *)))
(tags pure))
((name . "u32vector-take-while")
(signature lambda ((procedure? pred?) (u32vector? vec)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-take-while-right")
(signature lambda ((procedure? pred?) (u32vector? vec)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-drop-while")
(signature lambda ((procedure? pred?) (u32vector? vec)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-drop-while-right")
(signature lambda ((procedure? pred?) (u32vector? vec)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-index")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
(or integer? #f))
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-index-right")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
(or integer? #f))
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-skip")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
(or integer? #f))
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-skip-right")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
(or integer? #f))
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-any")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
*)
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-every")
(signature
lambda
((procedure? pred?) (u32vector? vec1) (u32vector? vec2) ...)
*)
(subsigs (pred? (lambda (obj1 obj2 ...) *)))
(tags pure))
((name . "u32vector-partition")
(signature
lambda
((procedure? pred?) (u32vector? vec))
(values u32vector? integer?))
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-filter")
(signature lambda ((procedure? pred?) (u32vector? vec1)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-remove")
(signature lambda ((procedure? pred?) (u32vector? vec1)) u32vector?)
(subsigs (pred? (lambda (obj) boolean?)))
(tags pure))
((name . "u32vector-swap!")
(signature
lambda
((u32vector? u32vector) (integer? i) (integer? j))
undefined))
((name . "u32vector-fill!")
(signature
case-lambda
(((u32vector? u32vector) (u32? fill)) undefined)
(((u32vector? u32vector) (u32? fill) (integer? start)) undefined)
(((u32vector? u32vector) (u32? fill) (integer? start) (integer? end))
undefined)))
((name . "u32vector-reverse!")
(signature
case-lambda
(((u32vector? u32vector)) undefined)
(((u32vector? u32vector) (integer? start)) undefined)
(((u32vector? u32vector) (integer? start) (integer? end)) undefined)))
((name . "u32vector-copy!")
(signature
case-lambda
(((u32vector? to) (integer? at) (u32vector? from)) undefined)
(((u32vector? to) (integer? at) (u32vector? from) (integer? start))
undefined)
(((u32vector? to)
(integer? at)
(u32vector? from)
(integer? start)
(integer? end))
undefined)))
((name . "u32vector-reverse-copy!")
(signature
case-lambda
(((u32vector? to) (integer? at) (u32vector? from)) undefined)
(((u32vector? to) (integer? at) (u32vector? from) (integer? start))
undefined)
(((u32vector? to)
(integer? at)
(u32vector? from)
(integer? start)
(integer? end))
undefined)))
((name . "u32vector-unfold!")
(signature
lambda
((procedure? f)
(u32vector? vec)
(integer? start)
(integer? end)
initial-seed
...)
undefined)
(subsigs (f (lambda ((integer? index) seed ...) (values * * ...)))))
((name . "u32vector-unfold-right!")
(signature
lambda
((procedure? f)
(u32vector? vec)
(integer? start)
(integer? end)
initial-seed
...)
undefined)
(subsigs (f (lambda ((integer? index) seed ...) (values * * ...)))))
((name . "reverse-u32vector->list")
(signature
case-lambda
(((u32vector? vec)) list?)
(((u32vector? vec) (integer? start)) list?)
(((u32vector? vec) (integer? start) (integer? end)) list?))
(tags pure))
((name . "reverse-list->u32vector")
(signature lambda ((list? proper-list)) u32vector?)
(tags pure))
((name . "u32vector->vector")
(signature
case-lambda
(((u32vector? vec)) vector?)
(((u32vector? vec) (integer? start)) vector?)
(((u32vector? vec) (integer? start) (integer? end)) vector?))
(tags pure))
((name . "vector->u32vector")
(signature
case-lambda
(((vector? vec)) u32vector?)
(((vector? vec) (integer? start)) u32vector?)
(((vector? vec) (integer? start) (integer? end)) u32vector?))
(tags pure))
((name . "make-u32vector-generator")
(signature lambda ((u32vector? vec)) procedure?)
(subsigs (return (lambda () (or eof-object? u32?)))))
((name . "u32vector-comparator") (signature value comparator?))
((name . "write-u32vector")
(signature
case-lambda
(((u32vector vec)) undefined)
(((u32vector vec) (output-port? port)) undefined))))
| |
0d6e120570fe04ee6c330e2ac87a712677ad6bb1b795fd1e7041805e8adca3c5 | JohannesFKnauf/parti-time | tl_test.clj | (ns parti-time.output.tl-test
(:require [parti-time.util.time :as time]
[clojure.test :as t]
[parti-time.output.tl :as sut]))
(t/deftest export-timeline
(t/testing "Printing a valid timeline"
(t/is (= (str "2019-02-03\n"
"1215 Some Project\n")
(sut/export-timeline [{:start-time (time/parse-iso-date-time "2019-02-03t12:15:00")
:project "Some Project"
:occupations []}]))
"Single entry without occupations")
(t/is (= (str "2019-02-03\n"
"1215 Some Project\n"
" Something to do\n"
" Another thing to do\n")
(sut/export-timeline [{:start-time (time/parse-iso-date-time "2019-02-03t12:15:00")
:project "Some Project"
:occupations ["Something to do"
"Another thing to do"]}]))
"Single entry")
(t/is (= (str "2019-02-03\n"
"1215 Some Project\n"
" Something to do\n"
" Another thing to do\n"
"1515 Some other Project\n"
" Something else to do\n")
(sut/export-timeline [{:start-time (time/parse-iso-date-time "2019-02-03t12:15:00")
:project "Some Project"
:occupations ["Something to do"
"Another thing to do"]}
{:start-time (time/parse-iso-date-time "2019-02-03t15:15:00")
:project "Some other Project"
:occupations ["Something else to do"]}]))
"Multiple entries")
(t/is (= (str "2019-02-03\n"
"1215 Some Project\n"
" Something to do\n"
" Another thing to do\n"
"\n"
"2019-02-04\n"
"0815 Some other Project\n"
" Something else to do\n"
"1515 Yet another Project\n"
" Yet another thing to do\n")
(sut/export-timeline [{:start-time (time/parse-iso-date-time "2019-02-03t12:15:00")
:project "Some Project"
:occupations ["Something to do"
"Another thing to do"]}
{:start-time (time/parse-iso-date-time "2019-02-04t08:15:00")
:project "Some other Project"
:occupations ["Something else to do"]}
{:start-time (time/parse-iso-date-time "2019-02-04t15:15:00")
:project "Yet another Project"
:occupations ["Yet another thing to do"]}]))
"Multiple entries, multiple days")))
| null | https://raw.githubusercontent.com/JohannesFKnauf/parti-time/ee85944e7ba201c4a46be152b09b2f7c591c0389/src/test/clj/parti_time/output/tl_test.clj | clojure | (ns parti-time.output.tl-test
(:require [parti-time.util.time :as time]
[clojure.test :as t]
[parti-time.output.tl :as sut]))
(t/deftest export-timeline
(t/testing "Printing a valid timeline"
(t/is (= (str "2019-02-03\n"
"1215 Some Project\n")
(sut/export-timeline [{:start-time (time/parse-iso-date-time "2019-02-03t12:15:00")
:project "Some Project"
:occupations []}]))
"Single entry without occupations")
(t/is (= (str "2019-02-03\n"
"1215 Some Project\n"
" Something to do\n"
" Another thing to do\n")
(sut/export-timeline [{:start-time (time/parse-iso-date-time "2019-02-03t12:15:00")
:project "Some Project"
:occupations ["Something to do"
"Another thing to do"]}]))
"Single entry")
(t/is (= (str "2019-02-03\n"
"1215 Some Project\n"
" Something to do\n"
" Another thing to do\n"
"1515 Some other Project\n"
" Something else to do\n")
(sut/export-timeline [{:start-time (time/parse-iso-date-time "2019-02-03t12:15:00")
:project "Some Project"
:occupations ["Something to do"
"Another thing to do"]}
{:start-time (time/parse-iso-date-time "2019-02-03t15:15:00")
:project "Some other Project"
:occupations ["Something else to do"]}]))
"Multiple entries")
(t/is (= (str "2019-02-03\n"
"1215 Some Project\n"
" Something to do\n"
" Another thing to do\n"
"\n"
"2019-02-04\n"
"0815 Some other Project\n"
" Something else to do\n"
"1515 Yet another Project\n"
" Yet another thing to do\n")
(sut/export-timeline [{:start-time (time/parse-iso-date-time "2019-02-03t12:15:00")
:project "Some Project"
:occupations ["Something to do"
"Another thing to do"]}
{:start-time (time/parse-iso-date-time "2019-02-04t08:15:00")
:project "Some other Project"
:occupations ["Something else to do"]}
{:start-time (time/parse-iso-date-time "2019-02-04t15:15:00")
:project "Yet another Project"
:occupations ["Yet another thing to do"]}]))
"Multiple entries, multiple days")))
| |
22320a3b6469a97a05ec18257977b7139b07fda63fcacc4c09185fedcf1d4248 | haskell-suite/haskell-src-exts | MultiLinePragma.hs | {-# OPTIONS_GHC
-a
-a
-a
-a
-a
-a
-a
-a
-a
-a
-a #-}
main :: IO ()
main = dat
| null | https://raw.githubusercontent.com/haskell-suite/haskell-src-exts/84a4930e0e5c051b7d9efd20ef7c822d5fc1c33b/tests/examples/MultiLinePragma.hs | haskell | # OPTIONS_GHC
-a
-a
-a
-a
-a
-a
-a
-a
-a
-a
-a # | main :: IO ()
main = dat
|
d506f7068db38fdd913db88b208117407d7160d2c82fdb068a14771cf3102f8d | qfpl/reflex-tutorial | Common.hs | {-# LANGUAGE OverloadedStrings #-}
module Ex06.Common (
Money
, Product (..)
, Stock (..)
, carrot
, celery
, cucumber
, Inputs(..)
, Outputs(..)
, Error(..)
, errorText
, Ex06Fn
) where
import Data.Text
import Reflex
type Money = Int
data Product =
Product {
pName :: Text
, pCost :: Money
} deriving (Eq, Ord, Show)
carrot ::
Product
carrot =
Product "Carrot" 1
celery ::
Product
celery =
Product "Celery" 2
cucumber ::
Product
cucumber =
Product "Cucumber" 3
data Stock =
Stock {
sProduct :: Product
, sQuantity :: Int
} deriving (Eq, Ord, Show)
data Inputs t =
Inputs {
ibMoney :: Dynamic t Money
, ibCarrot :: Dynamic t Stock
, ibCelery :: Dynamic t Stock
, ibCucumber :: Dynamic t Stock
, ibSelected :: Dynamic t Text
, ieBuy :: Event t ()
, ieRefund :: Event t ()
}
data Outputs t =
Outputs {
oeVend :: Event t Text
, oeSpend :: Event t Money
, oeChange :: Event t Money
, oeError :: Event t Error
, odChange :: Dynamic t Money
, odVend :: Dynamic t Text
}
data Error =
NotEnoughMoney
| ItemOutOfStock
deriving (Eq, Ord, Show)
errorText ::
Error ->
Text
errorText NotEnoughMoney =
"Insufficient funds"
errorText ItemOutOfStock =
"Item out of stock"
type Ex06Fn t m = Inputs t -> m (Outputs t)
| null | https://raw.githubusercontent.com/qfpl/reflex-tutorial/07c1e6fab387cbeedd031630ba6a5cd946cc612e/code/exercises/src/Ex06/Common.hs | haskell | # LANGUAGE OverloadedStrings # | module Ex06.Common (
Money
, Product (..)
, Stock (..)
, carrot
, celery
, cucumber
, Inputs(..)
, Outputs(..)
, Error(..)
, errorText
, Ex06Fn
) where
import Data.Text
import Reflex
type Money = Int
data Product =
Product {
pName :: Text
, pCost :: Money
} deriving (Eq, Ord, Show)
carrot ::
Product
carrot =
Product "Carrot" 1
celery ::
Product
celery =
Product "Celery" 2
cucumber ::
Product
cucumber =
Product "Cucumber" 3
data Stock =
Stock {
sProduct :: Product
, sQuantity :: Int
} deriving (Eq, Ord, Show)
data Inputs t =
Inputs {
ibMoney :: Dynamic t Money
, ibCarrot :: Dynamic t Stock
, ibCelery :: Dynamic t Stock
, ibCucumber :: Dynamic t Stock
, ibSelected :: Dynamic t Text
, ieBuy :: Event t ()
, ieRefund :: Event t ()
}
data Outputs t =
Outputs {
oeVend :: Event t Text
, oeSpend :: Event t Money
, oeChange :: Event t Money
, oeError :: Event t Error
, odChange :: Dynamic t Money
, odVend :: Dynamic t Text
}
data Error =
NotEnoughMoney
| ItemOutOfStock
deriving (Eq, Ord, Show)
errorText ::
Error ->
Text
errorText NotEnoughMoney =
"Insufficient funds"
errorText ItemOutOfStock =
"Item out of stock"
type Ex06Fn t m = Inputs t -> m (Outputs t)
|
a15d05f6c95a4f13cf87fef3e8bc7a021cfadc31c881abc0d63b54564bd910df | qkrgud55/ocamlmulti | frx_entry.mli | (***********************************************************************)
(* *)
MLTk , Tcl / Tk interface of OCaml
(* *)
, , and
projet Cristal , INRIA Rocquencourt
, Kyoto University RIMS
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
General Public License , with the special exception on linking
(* described in file LICENSE found in the OCaml source tree. *)
(* *)
(***********************************************************************)
open Camltk
val new_label_entry :
Widget.widget ->
string -> (string -> unit) -> Widget.widget * Widget.widget
(* [new_label_entry parent label action]
creates a "labelled" entry widget where [action] will be invoked
when the user types Return in the widget.
Returns (frame widget, entry widget)
*)
val new_labelm_entry :
Widget.widget ->
string -> Textvariable.textVariable -> Widget.widget * Widget.widget
(* [new_labelm_entry parent label variable]
creates a "labelled" entry widget whose contents is [variable].
Returns (frame widget, entry widget)
*)
| null | https://raw.githubusercontent.com/qkrgud55/ocamlmulti/74fe84df0ce7be5ee03fb4ac0520fb3e9f4b6d1f/otherlibs/labltk/frx/frx_entry.mli | ocaml | *********************************************************************
described in file LICENSE found in the OCaml source tree.
*********************************************************************
[new_label_entry parent label action]
creates a "labelled" entry widget where [action] will be invoked
when the user types Return in the widget.
Returns (frame widget, entry widget)
[new_labelm_entry parent label variable]
creates a "labelled" entry widget whose contents is [variable].
Returns (frame widget, entry widget)
| MLTk , Tcl / Tk interface of OCaml
, , and
projet Cristal , INRIA Rocquencourt
, Kyoto University RIMS
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
General Public License , with the special exception on linking
open Camltk
val new_label_entry :
Widget.widget ->
string -> (string -> unit) -> Widget.widget * Widget.widget
val new_labelm_entry :
Widget.widget ->
string -> Textvariable.textVariable -> Widget.widget * Widget.widget
|
20ec2f69c1500042279d75adff25b50d440003880b95e18bbccfa4b463c83cd2 | coq/coq | tags.ml | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
let make_tag (tt:GText.tag_table) ~name prop =
let new_tag = GText.tag ~name () in
new_tag#set_properties prop;
tt#add new_tag#as_tag;
new_tag
module Script =
struct
(* More recently defined tags have highest priority in case of overlapping *)
let table = GText.tag_table ()
let warning = make_tag table ~name:"warning" [`UNDERLINE `SINGLE; `FOREGROUND "blue"]
let error = make_tag table ~name:"error" [`UNDERLINE `SINGLE]
let error_bg = make_tag table ~name:"error_bg" []
let to_process = make_tag table ~name:"to_process" [`EDITABLE false]
let processed = make_tag table ~name:"processed" []
let debugging = make_tag table ~name:"debugging" []
let incomplete = make_tag table ~name:"incomplete" [`EDITABLE false]
let unjustified = make_tag table ~name:"unjustified" [`BACKGROUND "gold"]
let tooltip = make_tag table ~name:"tooltip" [] (* debug:`BACKGROUND "blue" *)
let ephemere =
[warning; error; error_bg; to_process; processed; debugging;
incomplete; unjustified; tooltip]
let comment = make_tag table ~name:"comment" []
let sentence = make_tag table ~name:"sentence" []
let breakpoint = make_tag table ~name:"breakpoint" []
let edit_zone = make_tag table ~name:"edit_zone" [`UNDERLINE `SINGLE] (* for debugging *)
let all_but_bpt = comment :: sentence :: edit_zone :: ephemere (* omit breakpoint marks *)
end
module Proof =
struct
let table = GText.tag_table ()
let highlight = make_tag table ~name:"highlight" []
let hypothesis = make_tag table ~name:"hypothesis" []
let goal = make_tag table ~name:"goal" []
end
module Message =
struct
let table = GText.tag_table ()
let error = make_tag table ~name:"error" [`FOREGROUND "red"]
let warning = make_tag table ~name:"warning" [`FOREGROUND "orange"]
let item = make_tag table ~name:"item" [`WEIGHT `BOLD]
end
| null | https://raw.githubusercontent.com/coq/coq/47ad43b361960f2bb9c5149cfb732cdf8b04e411/ide/coqide/tags.ml | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
More recently defined tags have highest priority in case of overlapping
debug:`BACKGROUND "blue"
for debugging
omit breakpoint marks | v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
let make_tag (tt:GText.tag_table) ~name prop =
let new_tag = GText.tag ~name () in
new_tag#set_properties prop;
tt#add new_tag#as_tag;
new_tag
module Script =
struct
let table = GText.tag_table ()
let warning = make_tag table ~name:"warning" [`UNDERLINE `SINGLE; `FOREGROUND "blue"]
let error = make_tag table ~name:"error" [`UNDERLINE `SINGLE]
let error_bg = make_tag table ~name:"error_bg" []
let to_process = make_tag table ~name:"to_process" [`EDITABLE false]
let processed = make_tag table ~name:"processed" []
let debugging = make_tag table ~name:"debugging" []
let incomplete = make_tag table ~name:"incomplete" [`EDITABLE false]
let unjustified = make_tag table ~name:"unjustified" [`BACKGROUND "gold"]
let ephemere =
[warning; error; error_bg; to_process; processed; debugging;
incomplete; unjustified; tooltip]
let comment = make_tag table ~name:"comment" []
let sentence = make_tag table ~name:"sentence" []
let breakpoint = make_tag table ~name:"breakpoint" []
end
module Proof =
struct
let table = GText.tag_table ()
let highlight = make_tag table ~name:"highlight" []
let hypothesis = make_tag table ~name:"hypothesis" []
let goal = make_tag table ~name:"goal" []
end
module Message =
struct
let table = GText.tag_table ()
let error = make_tag table ~name:"error" [`FOREGROUND "red"]
let warning = make_tag table ~name:"warning" [`FOREGROUND "orange"]
let item = make_tag table ~name:"item" [`WEIGHT `BOLD]
end
|
1d612c7f822b111583a9fc536069354e71eae6bebcb34622afeac1b32d3d1be1 | opencog/learn | any-merge.scm | #! /usr/bin/env guile
!#
;
Atomspace deduplication repair script
;
; Due to bugs, the SQL backend can end up with multiple copies of
; atoms. This script will find them, merge them, and sum the counts
; on the associated count truth values. Its up to you to recompute
; anything else.
;
This script focuses on accidentally having two ANY nodes .
; Viz if select * from atoms where type=89 and name='ANY';
returns more than one row :-(
(load "common.scm")
; --------------------------------------------------------------
(define (get-all-atoms query colm)
"
get-all-atoms -- Execute the query, return all colm values.
colm should be the string column name; e.g. 'uuid'
Returns a list of the 'colm' entries
"
(define alist (list))
(define word-count 0)
(define row #f)
(dbi-query conxion query)
(display "Atom search connection status: ")
(display (dbi-get_status conxion)) (newline)
; Loop over table rows
(set! row (dbi-get_row conxion))
(while (not (equal? row #f))
; Extract the column value
(let* ((valu (cdr (assoc colm row))))
(set! alist (cons valu alist))
; Maintain a count, just for the hell of it.
(set! word-count (+ word-count 1))
; (display word) (newline)
(set! row (dbi-get_row conxion))
)
)
(display "For the query: ")(display query)(newline)
(display "The num rows was: ") (display word-count) (newline)
alist
)
; --------------------------------------------------------------
(define (get-all-evals alist anyid)
"
get-all-evals -- Get all of the EvaluationLinks that contain
a ListLink and the anyid uuid.
Returns a list of the EvaluationLink entries.
"
(define word-count 0)
(define elist (list))
; Get an evaluationLink
(define (get-eval uuid)
(define euid 0)
(define row #f)
(define qry (string-concatenate (list
"SELECT uuid FROM atoms WHERE type="
EvalLinkType
" AND outgoing="
(make-outgoing-str (list anyid uuid)))))
( display qry)(newline )
(dbi-query conxion qry)
; Loop over table rows
(set! row (dbi-get_row conxion))
(while (not (equal? row #f))
; Extract the column value
(set! euid (cdr (assoc "uuid" row)))
; Maintain a count, just for the hell of it.
(set! word-count (+ word-count 1))
; (display word) (newline)
(set! row (dbi-get_row conxion))
)
euid
)
(set! elist (map get-eval alist))
(display "Number of EvaluationLinks: ") (display word-count) (newline)
elist
)
; --------------------------------------------------------------
A list of all ListLinks
(define all-list-links (get-all-atoms
"SELECT uuid FROM atoms WHERE type=8" "uuid"))
(define (count-evlinks any-uuid)
(display "Numb of ") (display any-uuid) (display " evals: ")
(display (length (get-all-evals all-list-links any-uuid)))(newline))
( display " Numb of 250 - evals : " )
( display ( length ( get - all - evals all - list - links 250)))(newline )
( display " Numb of 152 - evals : " )
( display ( length ( get - all - evals all - list - links 152)))(newline )
( map count - evlinks ( list 152 250 ) )
( map count - evlinks ( list 57 139 140 186 190 270 ) )
; --------------------------------------------------------------
(define (relabel-evals alist bad-id good-id)
"
relabel-evals -- Change the oset of all of the EvaluationLinks
that use the bad ANY uuid; make it use the good ANY id.
Returns a list of the changed EvaluationLink entries.
"
(define word-count 0)
(define elist (list))
; Change an EvaluationLink
; euid == uuid of the evaluation link
luid = = uuid of the
; any-id == uuid to change it to.
(define (set-eval euid luid any-id)
(define row #f)
(define qry (string-concatenate (list
"UPDATE atoms SET outgoing="
(make-outgoing-str (list any-id luid))
" WHERE uuid="
(number->string euid))))
( display qry)(newline )
(dbi-query conxion qry)
(flush-query)
)
; Change an EvaluationLink from the old bad ANY uuid to the new
one . The argument is the uuid of the
(define (change-eval uuid)
(define euid 0)
(define row #f)
First , get the uuid of the EvaluationLink
(define qry (string-concatenate (list
"SELECT uuid FROM atoms WHERE type="
EvalLinkType
" AND outgoing="
(make-outgoing-str (list bad-id uuid)))))
( display qry)(newline )
(dbi-query conxion qry)
; Loop over table rows
(set! row (dbi-get_row conxion))
(while (not (equal? row #f))
Extract the uuid of the EvaluationLink
(set! euid (cdr (assoc "uuid" row)))
; Maintain a count, just for the hell of it.
(set! word-count (+ word-count 1))
; Print status so we don't get bored.
(if (eq? 0 (modulo word-count 1000)) (begin
(display "Processed ")(display word-count)
(display " id-relabels")(newline))
(flush-output-port (current-output-port))
)
; (display word) (newline)
(set! row (dbi-get_row conxion))
)
euid will be zero is the does not appear with
; the bad any-id
(if (< 0 euid)
(set-eval euid uuid good-id))
)
(set! elist (map change-eval alist))
(display "Relabel ANY uuid ") (display bad-id)
(display " to ") (display good-id)(newline)
(display "Relabeled uuid count was ") (display word-count) (newline)
(flush-output-port (current-output-port))
elist
)
( relabel - evals all - list - links 250 152 )
( relabel - evals all - list - links 139 57 )
( relabel - evals all - list - links 140 57 )
( relabel - evals all - list - links 186 57 )
( relabel - evals all - list - links 190 57 )
( relabel - evals all - list - links 270 57 )
; -----------------------------------------------
(define (get-all-non-any-evals any-id)
"
get-all-non-any-evals -- look for all EvalLinks that do NOT
hold the desired ANY node. At this point in the game, there
should not be any of these. But there are. WTF. Oh, it was
a bad conversion of int8 to long long in guile-dbi.
"
(define bad-list (list))
(define euid 0)
(define luid 0)
(define oset (list))
(define row #f)
(define qry (string-concatenate (list
"SELECT uuid,outgoing FROM atoms WHERE type="
EvalLinkType)))
(display qry)(newline)
(dbi-query conxion qry)
; Loop over table rows
(set! row (dbi-get_row conxion))
(while (not (equal? row #f))
; Extract the column value
(set! euid (cdr (assoc "uuid" row)))
(set! oset (cdr (assoc "outgoing" row)))
(set! luid (cadr oset))
(if (not (eq? (car oset) any-id)) (begin
(set! bad-list (cons luid bad-list))
;(display "Its bad: ")(display euid)
;(display " any: ")(display (car oset))(newline)
;(flush-output-port (current-output-port))
))
; (display word) (newline)
(set! row (dbi-get_row conxion))
)
; Return the list of bad EvaluationLinks
bad-list
)
(define bad-list (get-all-non-any-evals 57))
(display "Number of bad evals: ") (display (length bad-list))(newline)
( relabel - evals bad - list 139 57 )
( relabel - evals bad - list 140 57 )
( relabel - evals bad - list 186 57 )
( relabel - evals bad - list 190 57 )
( relabel - evals bad - list 270 57 )
| null | https://raw.githubusercontent.com/opencog/learn/c599c856f59c1815b92520bee043c588d0d1ebf9/attic/repair/any-merge.scm | scheme |
Due to bugs, the SQL backend can end up with multiple copies of
atoms. This script will find them, merge them, and sum the counts
on the associated count truth values. Its up to you to recompute
anything else.
Viz if select * from atoms where type=89 and name='ANY';
--------------------------------------------------------------
e.g. 'uuid'
Loop over table rows
Extract the column value
Maintain a count, just for the hell of it.
(display word) (newline)
--------------------------------------------------------------
Get an evaluationLink
Loop over table rows
Extract the column value
Maintain a count, just for the hell of it.
(display word) (newline)
--------------------------------------------------------------
--------------------------------------------------------------
make it use the good ANY id.
Change an EvaluationLink
euid == uuid of the evaluation link
any-id == uuid to change it to.
Change an EvaluationLink from the old bad ANY uuid to the new
Loop over table rows
Maintain a count, just for the hell of it.
Print status so we don't get bored.
(display word) (newline)
the bad any-id
-----------------------------------------------
Loop over table rows
Extract the column value
(display "Its bad: ")(display euid)
(display " any: ")(display (car oset))(newline)
(flush-output-port (current-output-port))
(display word) (newline)
Return the list of bad EvaluationLinks | #! /usr/bin/env guile
!#
Atomspace deduplication repair script
This script focuses on accidentally having two ANY nodes .
returns more than one row :-(
(load "common.scm")
(define (get-all-atoms query colm)
"
get-all-atoms -- Execute the query, return all colm values.
Returns a list of the 'colm' entries
"
(define alist (list))
(define word-count 0)
(define row #f)
(dbi-query conxion query)
(display "Atom search connection status: ")
(display (dbi-get_status conxion)) (newline)
(set! row (dbi-get_row conxion))
(while (not (equal? row #f))
(let* ((valu (cdr (assoc colm row))))
(set! alist (cons valu alist))
(set! word-count (+ word-count 1))
(set! row (dbi-get_row conxion))
)
)
(display "For the query: ")(display query)(newline)
(display "The num rows was: ") (display word-count) (newline)
alist
)
(define (get-all-evals alist anyid)
"
get-all-evals -- Get all of the EvaluationLinks that contain
a ListLink and the anyid uuid.
Returns a list of the EvaluationLink entries.
"
(define word-count 0)
(define elist (list))
(define (get-eval uuid)
(define euid 0)
(define row #f)
(define qry (string-concatenate (list
"SELECT uuid FROM atoms WHERE type="
EvalLinkType
" AND outgoing="
(make-outgoing-str (list anyid uuid)))))
( display qry)(newline )
(dbi-query conxion qry)
(set! row (dbi-get_row conxion))
(while (not (equal? row #f))
(set! euid (cdr (assoc "uuid" row)))
(set! word-count (+ word-count 1))
(set! row (dbi-get_row conxion))
)
euid
)
(set! elist (map get-eval alist))
(display "Number of EvaluationLinks: ") (display word-count) (newline)
elist
)
A list of all ListLinks
(define all-list-links (get-all-atoms
"SELECT uuid FROM atoms WHERE type=8" "uuid"))
(define (count-evlinks any-uuid)
(display "Numb of ") (display any-uuid) (display " evals: ")
(display (length (get-all-evals all-list-links any-uuid)))(newline))
( display " Numb of 250 - evals : " )
( display ( length ( get - all - evals all - list - links 250)))(newline )
( display " Numb of 152 - evals : " )
( display ( length ( get - all - evals all - list - links 152)))(newline )
( map count - evlinks ( list 152 250 ) )
( map count - evlinks ( list 57 139 140 186 190 270 ) )
(define (relabel-evals alist bad-id good-id)
"
relabel-evals -- Change the oset of all of the EvaluationLinks
Returns a list of the changed EvaluationLink entries.
"
(define word-count 0)
(define elist (list))
luid = = uuid of the
(define (set-eval euid luid any-id)
(define row #f)
(define qry (string-concatenate (list
"UPDATE atoms SET outgoing="
(make-outgoing-str (list any-id luid))
" WHERE uuid="
(number->string euid))))
( display qry)(newline )
(dbi-query conxion qry)
(flush-query)
)
one . The argument is the uuid of the
(define (change-eval uuid)
(define euid 0)
(define row #f)
First , get the uuid of the EvaluationLink
(define qry (string-concatenate (list
"SELECT uuid FROM atoms WHERE type="
EvalLinkType
" AND outgoing="
(make-outgoing-str (list bad-id uuid)))))
( display qry)(newline )
(dbi-query conxion qry)
(set! row (dbi-get_row conxion))
(while (not (equal? row #f))
Extract the uuid of the EvaluationLink
(set! euid (cdr (assoc "uuid" row)))
(set! word-count (+ word-count 1))
(if (eq? 0 (modulo word-count 1000)) (begin
(display "Processed ")(display word-count)
(display " id-relabels")(newline))
(flush-output-port (current-output-port))
)
(set! row (dbi-get_row conxion))
)
euid will be zero is the does not appear with
(if (< 0 euid)
(set-eval euid uuid good-id))
)
(set! elist (map change-eval alist))
(display "Relabel ANY uuid ") (display bad-id)
(display " to ") (display good-id)(newline)
(display "Relabeled uuid count was ") (display word-count) (newline)
(flush-output-port (current-output-port))
elist
)
( relabel - evals all - list - links 250 152 )
( relabel - evals all - list - links 139 57 )
( relabel - evals all - list - links 140 57 )
( relabel - evals all - list - links 186 57 )
( relabel - evals all - list - links 190 57 )
( relabel - evals all - list - links 270 57 )
(define (get-all-non-any-evals any-id)
"
get-all-non-any-evals -- look for all EvalLinks that do NOT
hold the desired ANY node. At this point in the game, there
should not be any of these. But there are. WTF. Oh, it was
a bad conversion of int8 to long long in guile-dbi.
"
(define bad-list (list))
(define euid 0)
(define luid 0)
(define oset (list))
(define row #f)
(define qry (string-concatenate (list
"SELECT uuid,outgoing FROM atoms WHERE type="
EvalLinkType)))
(display qry)(newline)
(dbi-query conxion qry)
(set! row (dbi-get_row conxion))
(while (not (equal? row #f))
(set! euid (cdr (assoc "uuid" row)))
(set! oset (cdr (assoc "outgoing" row)))
(set! luid (cadr oset))
(if (not (eq? (car oset) any-id)) (begin
(set! bad-list (cons luid bad-list))
))
(set! row (dbi-get_row conxion))
)
bad-list
)
(define bad-list (get-all-non-any-evals 57))
(display "Number of bad evals: ") (display (length bad-list))(newline)
( relabel - evals bad - list 139 57 )
( relabel - evals bad - list 140 57 )
( relabel - evals bad - list 186 57 )
( relabel - evals bad - list 190 57 )
( relabel - evals bad - list 270 57 )
|
a7b169f3a0d7902470881b60d36ae35139f6b3ba5f5181d890c7bf28d187b822 | biocaml/phylogenetics | discrete_pd.ml | open Core
type t = {
n : int ;
shift : int ;
weights : float array ;
}
let is_leaf dpd i = i >= dpd.shift
let init n ~f =
let shift = Float.(to_int (2. ** round_up (log (float n) /. log 2.))) - 1 in
let m = shift + n in
let weights = Array.create ~len:m 0. in
for i = 0 to n - 1 do
weights.(shift + i) <- f (i)
done ;
for i = shift - 1 downto 0 do
if 2 * i + 1 < m then weights.(i) <- weights.(2 * i + 1) ;
if 2 * i + 2 < m then weights.(i) <- weights.(i) +. weights.(2 * i + 2)
done ;
{ n ; shift ; weights }
let draw dpd rng =
let x = dpd.weights.(0) *. Gsl.Rng.uniform rng in
let rec loop acc i =
if is_leaf dpd i then i
else if Float.( >= ) (acc +. dpd.weights.(2 * i + 1)) x then
loop acc (2 * i + 1)
else loop (acc +. dpd.weights.(2 * i + 1)) (2 * i + 2)
in
loop 0. 0 - dpd.shift
let update dpd i w_i =
let m = Array.length dpd.weights in
let j = i + dpd.shift in
dpd.weights.(j) <- w_i ;
let rec loop k =
dpd.weights.(k) <- dpd.weights.(2 * k + 1) ;
if 2 * k + 2 < m then dpd.weights.(k) <- dpd.weights.(k) +. dpd.weights.(2 * k + 2) ;
if k > 0 then loop ((k - 1) / 2)
in
loop ((j - 1) / 2)
let total_weight dpd = dpd.weights.(0)
let demo ~n ~ncat =
let rng = Gsl.Rng.(make (default ())) in
let probs = Array.init ncat ~f:(fun _ -> Gsl.Rng.uniform rng) in
let sum = Array.fold probs ~init:0. ~f:( +. ) in
let pd = init ncat ~f:(fun _ -> 0.) in
let counts = Array.create ~len:ncat 0 in
Array.iteri probs ~f:(update pd) ;
for _ = 1 to n do
let k = draw pd rng in
counts.(k) <- counts.(k) + 1
done ;
Array.map probs ~f:(fun x -> x /. sum),
Array.map counts ~f:(fun k -> float k /. float n)
| null | https://raw.githubusercontent.com/biocaml/phylogenetics/e225616a700b03c429c16f760dbe8c363fb4c79d/lib/discrete_pd.ml | ocaml | open Core
type t = {
n : int ;
shift : int ;
weights : float array ;
}
let is_leaf dpd i = i >= dpd.shift
let init n ~f =
let shift = Float.(to_int (2. ** round_up (log (float n) /. log 2.))) - 1 in
let m = shift + n in
let weights = Array.create ~len:m 0. in
for i = 0 to n - 1 do
weights.(shift + i) <- f (i)
done ;
for i = shift - 1 downto 0 do
if 2 * i + 1 < m then weights.(i) <- weights.(2 * i + 1) ;
if 2 * i + 2 < m then weights.(i) <- weights.(i) +. weights.(2 * i + 2)
done ;
{ n ; shift ; weights }
let draw dpd rng =
let x = dpd.weights.(0) *. Gsl.Rng.uniform rng in
let rec loop acc i =
if is_leaf dpd i then i
else if Float.( >= ) (acc +. dpd.weights.(2 * i + 1)) x then
loop acc (2 * i + 1)
else loop (acc +. dpd.weights.(2 * i + 1)) (2 * i + 2)
in
loop 0. 0 - dpd.shift
let update dpd i w_i =
let m = Array.length dpd.weights in
let j = i + dpd.shift in
dpd.weights.(j) <- w_i ;
let rec loop k =
dpd.weights.(k) <- dpd.weights.(2 * k + 1) ;
if 2 * k + 2 < m then dpd.weights.(k) <- dpd.weights.(k) +. dpd.weights.(2 * k + 2) ;
if k > 0 then loop ((k - 1) / 2)
in
loop ((j - 1) / 2)
let total_weight dpd = dpd.weights.(0)
let demo ~n ~ncat =
let rng = Gsl.Rng.(make (default ())) in
let probs = Array.init ncat ~f:(fun _ -> Gsl.Rng.uniform rng) in
let sum = Array.fold probs ~init:0. ~f:( +. ) in
let pd = init ncat ~f:(fun _ -> 0.) in
let counts = Array.create ~len:ncat 0 in
Array.iteri probs ~f:(update pd) ;
for _ = 1 to n do
let k = draw pd rng in
counts.(k) <- counts.(k) + 1
done ;
Array.map probs ~f:(fun x -> x /. sum),
Array.map counts ~f:(fun k -> float k /. float n)
| |
9200e62222f2db6c3a630007bfa3e33d415dbeed6dcf2d8b80d1ec1db3a8b3f7 | ivanperez-keera/Yampa | Loop.hs | -- |
Module : . Loop
Copyright : ( c ) , 2014 - 2022
( c ) , 2007 - 2012
( c ) , 2005 - 2006
( c ) and , Yale University , 2003 - 2004
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer :
-- Stability : provisional
--
-- Portability : non-portable -GHC extensions-
--
-- Well-initialised loops
module FRP.Yampa.Loop
(
-- * Loops with guaranteed well-defined feedback
loopPre
, loopIntegral
)
where
import Control.Arrow
import Data.VectorSpace
import FRP.Yampa.Delays
import FRP.Yampa.Integration
import FRP.Yampa.InternalCore (SF)
-- * Loops with guaranteed well-defined feedback
-- | Loop with an initial value for the signal being fed back.
loopPre :: c -> SF (a,c) (b,c) -> SF a b
loopPre c_init sf = loop (second (iPre c_init) >>> sf)
| Loop by integrating the second value in the pair and feeding the
result back . Because the integral at time 0 is zero , this is always
-- well defined.
loopIntegral :: (Fractional s, VectorSpace c s) => SF (a,c) (b,c) -> SF a b
loopIntegral sf = loop (second integral >>> sf)
| null | https://raw.githubusercontent.com/ivanperez-keera/Yampa/3a69b884dca0b544143a01d585119ac7c5b25455/yampa/src/FRP/Yampa/Loop.hs | haskell | |
License : BSD-style (see the LICENSE file in the distribution)
Maintainer :
Stability : provisional
Portability : non-portable -GHC extensions-
Well-initialised loops
* Loops with guaranteed well-defined feedback
* Loops with guaranteed well-defined feedback
| Loop with an initial value for the signal being fed back.
well defined. | Module : . Loop
Copyright : ( c ) , 2014 - 2022
( c ) , 2007 - 2012
( c ) , 2005 - 2006
( c ) and , Yale University , 2003 - 2004
module FRP.Yampa.Loop
(
loopPre
, loopIntegral
)
where
import Control.Arrow
import Data.VectorSpace
import FRP.Yampa.Delays
import FRP.Yampa.Integration
import FRP.Yampa.InternalCore (SF)
loopPre :: c -> SF (a,c) (b,c) -> SF a b
loopPre c_init sf = loop (second (iPre c_init) >>> sf)
| Loop by integrating the second value in the pair and feeding the
result back . Because the integral at time 0 is zero , this is always
loopIntegral :: (Fractional s, VectorSpace c s) => SF (a,c) (b,c) -> SF a b
loopIntegral sf = loop (second integral >>> sf)
|
f137fd3fdeefb404e6c7e81a626c855f80d2c3c6454a41306671345437158b94 | open-company/open-company-web | wrt.cljs | (ns oc.web.utils.wrt
(:require [cuerdas.core :as s]
[oc.lib.time :as lib-time]
[oc.lib.user :as lib-user]
[oc.web.urls :as oc-urls]
[oc.web.local-settings :as ls]
[oc.web.components.ui.alert-modal :as alert-modal]))
(def column-separator ", ")
(def row-separator "\n")
(def empty-value "-")
(def premium-download-csv-tooltip "Please upgrade to premium to download your team's Analytics data.")
(defn- csv-row [row]
(let [values (map #(if (keyword? %) (name %) %) row)]
(s/join column-separator values)))
(defn- csv-rows [rows]
(let [rows-list (map csv-row rows)]
(s/join row-separator rows-list)))
(defn- read-date [row]
(if (:read-at row)
(lib-time/csv-date-time (:read-at row))
empty-value))
(defn- clean-value [row k]
(get row k empty-value))
(defn- name-from-user [current-user-id user-map]
(let [nm (lib-user/name-for-csv user-map)]
(if nm
(str nm (when (= (:user-id user-map) current-user-id)
" (you)"))
empty-value)))
(defn- clean-user [current-user-id row]
(vec [(name-from-user current-user-id row) (clean-value row :email) (read-date row)]))
(defn- post-href [entry-data]
(str ls/web-server-domain (oc-urls/entry (:board-slug entry-data) (:uuid entry-data))))
(defn- csv-intro [org-name]
(str org-name " analytics for post generated on " (lib-time/csv-date) "\n"))
(defn encoded-csv [org-data entry-data headers data current-user-id]
(let [header (when headers (s/join ", " headers))
cleaned-data (map (partial clean-user current-user-id) data)
body (csv-rows cleaned-data)
title (str "Title: " (:headline entry-data))
published (str "Published on: " (lib-time/csv-date-time (:published-at entry-data)))
post-link (str "Link: " (post-href entry-data))
reads-count (count (filter :read-at data))
reads-percent (when (pos? reads-count)
(str (.toFixed (float (* (/ reads-count (count data)) 100)) 2) "%"))
stats (str "Reads: " (count (filter :read-at data)) " of " (count data) (when reads-percent (str " (" reads-percent ")")))
intro (csv-intro (:name org-data))
csv-content (s/join "\n" [intro title published post-link stats "-" header body])]
(str "data:text/csv;charset=utf-8," (js/encodeURIComponent csv-content))))
(defn csv-filename [entry-data]
(str "post-" (:uuid entry-data) "-" (lib-time/to-iso (lib-time/utc-now)) ".csv"))
(defn empty-analytics-alert []
(alert-modal/show-alert {:action "analytics-no-posts"
:title "No posts :("
:message (str "There have been no new posts in the past " ls/default-csv-days " days.")
:solid-button-style :red
:solid-button-title "OK, got it"
:solid-button-cb #(alert-modal/dismiss-modal)})) | null | https://raw.githubusercontent.com/open-company/open-company-web/dfce3dd9bc115df91003179bceb87cca1f84b6cf/src/main/oc/web/utils/wrt.cljs | clojure | (ns oc.web.utils.wrt
(:require [cuerdas.core :as s]
[oc.lib.time :as lib-time]
[oc.lib.user :as lib-user]
[oc.web.urls :as oc-urls]
[oc.web.local-settings :as ls]
[oc.web.components.ui.alert-modal :as alert-modal]))
(def column-separator ", ")
(def row-separator "\n")
(def empty-value "-")
(def premium-download-csv-tooltip "Please upgrade to premium to download your team's Analytics data.")
(defn- csv-row [row]
(let [values (map #(if (keyword? %) (name %) %) row)]
(s/join column-separator values)))
(defn- csv-rows [rows]
(let [rows-list (map csv-row rows)]
(s/join row-separator rows-list)))
(defn- read-date [row]
(if (:read-at row)
(lib-time/csv-date-time (:read-at row))
empty-value))
(defn- clean-value [row k]
(get row k empty-value))
(defn- name-from-user [current-user-id user-map]
(let [nm (lib-user/name-for-csv user-map)]
(if nm
(str nm (when (= (:user-id user-map) current-user-id)
" (you)"))
empty-value)))
(defn- clean-user [current-user-id row]
(vec [(name-from-user current-user-id row) (clean-value row :email) (read-date row)]))
(defn- post-href [entry-data]
(str ls/web-server-domain (oc-urls/entry (:board-slug entry-data) (:uuid entry-data))))
(defn- csv-intro [org-name]
(str org-name " analytics for post generated on " (lib-time/csv-date) "\n"))
(defn encoded-csv [org-data entry-data headers data current-user-id]
(let [header (when headers (s/join ", " headers))
cleaned-data (map (partial clean-user current-user-id) data)
body (csv-rows cleaned-data)
title (str "Title: " (:headline entry-data))
published (str "Published on: " (lib-time/csv-date-time (:published-at entry-data)))
post-link (str "Link: " (post-href entry-data))
reads-count (count (filter :read-at data))
reads-percent (when (pos? reads-count)
(str (.toFixed (float (* (/ reads-count (count data)) 100)) 2) "%"))
stats (str "Reads: " (count (filter :read-at data)) " of " (count data) (when reads-percent (str " (" reads-percent ")")))
intro (csv-intro (:name org-data))
csv-content (s/join "\n" [intro title published post-link stats "-" header body])]
(str "data:text/csv;charset=utf-8," (js/encodeURIComponent csv-content))))
(defn csv-filename [entry-data]
(str "post-" (:uuid entry-data) "-" (lib-time/to-iso (lib-time/utc-now)) ".csv"))
(defn empty-analytics-alert []
(alert-modal/show-alert {:action "analytics-no-posts"
:title "No posts :("
:message (str "There have been no new posts in the past " ls/default-csv-days " days.")
:solid-button-style :red
:solid-button-title "OK, got it"
:solid-button-cb #(alert-modal/dismiss-modal)})) | |
501fe9c5c92fe058206642661c757e6fa33c0f026fcbdf3518752e1975610ecf | oisdk/monus-weighted-search | Max.hs | --------------------------------------------------------------------------------
-- |
Module : Data . Monus .
Copyright : ( c ) Kidney 2021
-- Maintainer :
-- Stability : experimental
-- Portability : non-portable
--
-- A 'Monus' for for maximums.
--------------------------------------------------------------------------------
module Data.Monus.Max where
import Control.Applicative
import Control.Monad
import Data.Monus
import Test.QuickCheck
import Control.DeepSeq
import Data.Functor.Classes
import Text.Read
import Data.Data ( Data, Typeable )
import GHC.Generics ( Generic )
import GHC.Read (expectP)
import Data.Functor (($>))
import Control.Monad.Fix
-- | A type which adds a lower bound to some ordered type.
data Max a = Bot | In a
deriving stock (Eq, Data, Generic, Typeable, Functor, Foldable, Traversable, Show, Read)
instance Arbitrary a => Arbitrary (Max a) where
arbitrary = arbitrary1
shrink = shrink1
instance NFData a => NFData (Max a) where
rnf Bot = ()
rnf (In x) = rnf x
instance Eq1 Max where
liftEq _ Bot Bot = True
liftEq eq (In x) (In y) = eq x y
liftEq _ _ _ = False
instance Ord1 Max where
liftCompare cmp Bot Bot = EQ
liftCompare cmp Bot (In _) = LT
liftCompare cmp (In _) Bot = GT
liftCompare cmp (In x) (In y) = cmp x y
instance Show1 Max where
liftShowsPrec sp sl n Bot = showString "Bot"
liftShowsPrec sp _ d (In x) = showsUnaryWith sp "In" d x
instance Read1 Max where
liftReadPrec rp _ =
parens (expectP (Ident "Bot") $> Bot)
<|>
readData (readUnaryWith rp "In" In)
liftReadListPrec = liftReadListPrecDefault
liftReadList = liftReadListDefault
instance Arbitrary1 Max where
liftArbitrary arb = fmap (maybe Bot In) (liftArbitrary arb)
liftShrink shr Bot = []
liftShrink shr (In x) = Bot : fmap In (shr x)
instance Ord a => Ord (Max a) where
Bot <= _ = True
In _ <= Bot = False
In x <= In y = x <= y
(>=) = flip (<=)
x < y = not (x >= y)
(>) = flip (<)
max = (<>)
min = liftA2 min
compare Bot Bot = EQ
compare Bot (In _) = LT
compare (In _) Bot = GT
compare (In x) (In y) = compare x y
instance Applicative Max where
pure = In
liftA2 f (In x) (In y) = In (f x y)
liftA2 _ _ _ = Bot
In f <*> In x = In (f x)
_ <*> _ = Bot
instance Monad Max where
Bot >>= _ = Bot
In x >>= f = f x
instance Alternative Max where
empty = Bot
Bot <|> y = y
x <|> _ = x
instance MonadPlus Max
instance MonadFix Max where
mfix f = r
where
r = f (unIn r)
unIn (In x) = x
unIn Bot = errorWithoutStackTrace "mfix Max: Bot"
instance Ord a => Semigroup (Max a) where
Bot <> y = y
In x <> ys = In (case ys of
Bot -> x
In y -> max x y)
instance Ord a => Monoid (Max a) where
mempty = Bot
# INLINE mempty #
instance Ord a => Monus (Max a) where
(|-|) = (<>)
{-# INLINE (|-|) #-}
| null | https://raw.githubusercontent.com/oisdk/monus-weighted-search/05ea33553b36c2c6b2b70f23c16a6ea5f6897f2a/src/Data/Monus/Max.hs | haskell | ------------------------------------------------------------------------------
|
Maintainer :
Stability : experimental
Portability : non-portable
A 'Monus' for for maximums.
------------------------------------------------------------------------------
| A type which adds a lower bound to some ordered type.
# INLINE (|-|) # | Module : Data . Monus .
Copyright : ( c ) Kidney 2021
module Data.Monus.Max where
import Control.Applicative
import Control.Monad
import Data.Monus
import Test.QuickCheck
import Control.DeepSeq
import Data.Functor.Classes
import Text.Read
import Data.Data ( Data, Typeable )
import GHC.Generics ( Generic )
import GHC.Read (expectP)
import Data.Functor (($>))
import Control.Monad.Fix
data Max a = Bot | In a
deriving stock (Eq, Data, Generic, Typeable, Functor, Foldable, Traversable, Show, Read)
instance Arbitrary a => Arbitrary (Max a) where
arbitrary = arbitrary1
shrink = shrink1
instance NFData a => NFData (Max a) where
rnf Bot = ()
rnf (In x) = rnf x
instance Eq1 Max where
liftEq _ Bot Bot = True
liftEq eq (In x) (In y) = eq x y
liftEq _ _ _ = False
instance Ord1 Max where
liftCompare cmp Bot Bot = EQ
liftCompare cmp Bot (In _) = LT
liftCompare cmp (In _) Bot = GT
liftCompare cmp (In x) (In y) = cmp x y
instance Show1 Max where
liftShowsPrec sp sl n Bot = showString "Bot"
liftShowsPrec sp _ d (In x) = showsUnaryWith sp "In" d x
instance Read1 Max where
liftReadPrec rp _ =
parens (expectP (Ident "Bot") $> Bot)
<|>
readData (readUnaryWith rp "In" In)
liftReadListPrec = liftReadListPrecDefault
liftReadList = liftReadListDefault
instance Arbitrary1 Max where
liftArbitrary arb = fmap (maybe Bot In) (liftArbitrary arb)
liftShrink shr Bot = []
liftShrink shr (In x) = Bot : fmap In (shr x)
instance Ord a => Ord (Max a) where
Bot <= _ = True
In _ <= Bot = False
In x <= In y = x <= y
(>=) = flip (<=)
x < y = not (x >= y)
(>) = flip (<)
max = (<>)
min = liftA2 min
compare Bot Bot = EQ
compare Bot (In _) = LT
compare (In _) Bot = GT
compare (In x) (In y) = compare x y
instance Applicative Max where
pure = In
liftA2 f (In x) (In y) = In (f x y)
liftA2 _ _ _ = Bot
In f <*> In x = In (f x)
_ <*> _ = Bot
instance Monad Max where
Bot >>= _ = Bot
In x >>= f = f x
instance Alternative Max where
empty = Bot
Bot <|> y = y
x <|> _ = x
instance MonadPlus Max
instance MonadFix Max where
mfix f = r
where
r = f (unIn r)
unIn (In x) = x
unIn Bot = errorWithoutStackTrace "mfix Max: Bot"
instance Ord a => Semigroup (Max a) where
Bot <> y = y
In x <> ys = In (case ys of
Bot -> x
In y -> max x y)
instance Ord a => Monoid (Max a) where
mempty = Bot
# INLINE mempty #
instance Ord a => Monus (Max a) where
(|-|) = (<>)
|
5810ee75e23283a14d25ea5f5e67b87d76717b7eafd67afc6f772f106221bfc9 | rvirding/luerl | hello_userdata.erl | %% File : hello_userdata.erl
Purpose : Brief demonstration of Luerl userdata access .
Use $ erlc hello_userdata.erl & & erl -pa .. / .. /ebin -s hello_userdata run -s init stop -noshell
-module(hello_userdata).
-export([run/0]).
run() ->
St0 = luerl:init(),
U42 = {userdata,42}, %The original decoded data
{Uref,St1} = luerl:encode(U42, St0),
St2 = luerl:set_table1([<<"u1">>], Uref, St1),
St3 = luerl:set_table1([<<"u2">>], Uref, St2),
%% This call wraps the actual data for us.
St4 = luerl_heap:set_userdata_data(Uref, 84, St3),
U84 = {userdata,84}, %New decoded data
{U84,St5} = luerl:get_table([<<"u1">>], St4),
{U84,St6} = luerl:get_table([<<"u2">>], St5),
St6.
| null | https://raw.githubusercontent.com/rvirding/luerl/5e61c1838d08430af67fb870995b05a41d64aeee/examples/hello/hello_userdata.erl | erlang | File : hello_userdata.erl
The original decoded data
This call wraps the actual data for us.
New decoded data | Purpose : Brief demonstration of Luerl userdata access .
Use $ erlc hello_userdata.erl & & erl -pa .. / .. /ebin -s hello_userdata run -s init stop -noshell
-module(hello_userdata).
-export([run/0]).
run() ->
St0 = luerl:init(),
{Uref,St1} = luerl:encode(U42, St0),
St2 = luerl:set_table1([<<"u1">>], Uref, St1),
St3 = luerl:set_table1([<<"u2">>], Uref, St2),
St4 = luerl_heap:set_userdata_data(Uref, 84, St3),
{U84,St5} = luerl:get_table([<<"u1">>], St4),
{U84,St6} = luerl:get_table([<<"u2">>], St5),
St6.
|
2e536ffa8ee7c58c4e1f94b49e8ed71ab08780a9faced7bfd29741c311ea460e | GaloisInc/renovate | Overlap.hs | {-# LANGUAGE GADTs #-}
-- | A module defining types and utilities for computing which blocks overlap
module Renovate.Recovery.Overlap (
BlockRegions,
blockRegions,
numBlockRegions,
disjoint
) where
import Control.Lens ( (^.) )
import qualified Data.Foldable as F
import qualified Data.IntervalMap.Strict as IM
import qualified Data.Macaw.CFG as MC
import qualified Data.Macaw.Discovery as MC
import qualified Data.Map as M
import Data.Maybe ( fromMaybe )
import Data.Parameterized.Some ( Some(..) )
import Renovate.Core.Address
import Renovate.Core.BasicBlock
import Renovate.ISA
data BlockRegions arch =
BlockRegions { brIntervals :: !(IM.IntervalMap (ConcreteAddress arch) (Some (MC.ParsedBlock arch)))
}
-- | Construct a map of overlapping blocks in the binary from macaw discovery results
blockRegions :: ( w ~ MC.ArchAddrWidth arch
, MC.MemWidth w
)
=> MC.Memory (MC.ArchAddrWidth arch)
-> MC.DiscoveryState arch
-> BlockRegions arch
blockRegions mem di =
BlockRegions { brIntervals = F.foldl' (addBlock mem) IM.empty discoveredBlocks
}
where
discoveredBlocks = [ Some pb
| Some dfi <- M.elems (di ^. MC.funInfo)
, pb <- M.elems (dfi ^. MC.parsedBlocks)
]
addBlock :: ( w ~ MC.ArchAddrWidth arch
, MC.MemWidth w
)
=> MC.Memory (MC.ArchAddrWidth arch)
-> IM.IntervalMap (ConcreteAddress arch) (Some (MC.ParsedBlock arch))
-> Some (MC.ParsedBlock arch)
-> IM.IntervalMap (ConcreteAddress arch) (Some (MC.ParsedBlock arch))
addBlock mem im (Some pb) = fromMaybe im $ do
blockStart <- concreteFromSegmentOff mem (MC.pblockAddr pb)
let blockEnd = blockStart `addressAddOffset` fromIntegral (MC.blockSize pb)
let i = IM.IntervalCO blockStart blockEnd
-- Note that the interval-map insert function overwrites the existing value if
-- the key is already in the map. This can arise for us because blocks can
appear in more than one function .
--
-- NOTE: it isn't actually a problem for us, as we only really care about
-- cases where blocks overlap but are not identical.
return (IM.insert i (Some pb) im)
-- | The number of block regions
numBlockRegions :: BlockRegions arch -> Int
numBlockRegions = F.length . brIntervals
-- | Check if a block is disjoint from all other blocks in the binary
--
-- > disjoint regions b
--
returns True if does not overlap with any other discovered block in @regions@.
disjoint :: ( w ~ MC.ArchAddrWidth arch
, MC.MemWidth w
)
=> ISA arch
-> BlockRegions arch
-> ConcreteBlock arch
-> Bool
disjoint isa (BlockRegions im) cb =
case IM.size (IM.intersecting im i) of
0 -> error ("No region contains block at address " ++ show baddr)
1 -> True
_ -> False
where
sz = blockSize isa cb
baddr = concreteBlockAddress cb
i = IM.IntervalCO baddr (baddr `addressAddOffset` fromIntegral sz)
| null | https://raw.githubusercontent.com/GaloisInc/renovate/550f64c1119f6804967e3077dcf0cb7c57ddb603/renovate/src/Renovate/Recovery/Overlap.hs | haskell | # LANGUAGE GADTs #
| A module defining types and utilities for computing which blocks overlap
| Construct a map of overlapping blocks in the binary from macaw discovery results
Note that the interval-map insert function overwrites the existing value if
the key is already in the map. This can arise for us because blocks can
NOTE: it isn't actually a problem for us, as we only really care about
cases where blocks overlap but are not identical.
| The number of block regions
| Check if a block is disjoint from all other blocks in the binary
> disjoint regions b
| module Renovate.Recovery.Overlap (
BlockRegions,
blockRegions,
numBlockRegions,
disjoint
) where
import Control.Lens ( (^.) )
import qualified Data.Foldable as F
import qualified Data.IntervalMap.Strict as IM
import qualified Data.Macaw.CFG as MC
import qualified Data.Macaw.Discovery as MC
import qualified Data.Map as M
import Data.Maybe ( fromMaybe )
import Data.Parameterized.Some ( Some(..) )
import Renovate.Core.Address
import Renovate.Core.BasicBlock
import Renovate.ISA
data BlockRegions arch =
BlockRegions { brIntervals :: !(IM.IntervalMap (ConcreteAddress arch) (Some (MC.ParsedBlock arch)))
}
blockRegions :: ( w ~ MC.ArchAddrWidth arch
, MC.MemWidth w
)
=> MC.Memory (MC.ArchAddrWidth arch)
-> MC.DiscoveryState arch
-> BlockRegions arch
blockRegions mem di =
BlockRegions { brIntervals = F.foldl' (addBlock mem) IM.empty discoveredBlocks
}
where
discoveredBlocks = [ Some pb
| Some dfi <- M.elems (di ^. MC.funInfo)
, pb <- M.elems (dfi ^. MC.parsedBlocks)
]
addBlock :: ( w ~ MC.ArchAddrWidth arch
, MC.MemWidth w
)
=> MC.Memory (MC.ArchAddrWidth arch)
-> IM.IntervalMap (ConcreteAddress arch) (Some (MC.ParsedBlock arch))
-> Some (MC.ParsedBlock arch)
-> IM.IntervalMap (ConcreteAddress arch) (Some (MC.ParsedBlock arch))
addBlock mem im (Some pb) = fromMaybe im $ do
blockStart <- concreteFromSegmentOff mem (MC.pblockAddr pb)
let blockEnd = blockStart `addressAddOffset` fromIntegral (MC.blockSize pb)
let i = IM.IntervalCO blockStart blockEnd
appear in more than one function .
return (IM.insert i (Some pb) im)
numBlockRegions :: BlockRegions arch -> Int
numBlockRegions = F.length . brIntervals
returns True if does not overlap with any other discovered block in @regions@.
disjoint :: ( w ~ MC.ArchAddrWidth arch
, MC.MemWidth w
)
=> ISA arch
-> BlockRegions arch
-> ConcreteBlock arch
-> Bool
disjoint isa (BlockRegions im) cb =
case IM.size (IM.intersecting im i) of
0 -> error ("No region contains block at address " ++ show baddr)
1 -> True
_ -> False
where
sz = blockSize isa cb
baddr = concreteBlockAddress cb
i = IM.IntervalCO baddr (baddr `addressAddOffset` fromIntegral sz)
|
87daec210b416c5e6ea480feb2d9ecf7262782c93c73627b5d0878a8aabac7f6 | fourmolu/fourmolu | Preprocess.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
-- | Preprocessing for input source code.
module Ormolu.Processing.Preprocess
( preprocess,
)
where
import Control.Monad
import Data.Array as A
import Data.Bifunctor (bimap)
import Data.Char (isSpace)
import Data.Function ((&))
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import qualified Data.List as L
import Data.Maybe (isJust)
import Data.Text (Text)
import qualified Data.Text as T
import Ormolu.Config (RegionDeltas (..))
import Ormolu.Processing.Common
import Ormolu.Processing.Cpp
-- | Preprocess the specified region of the input into raw snippets
-- and subregions to be formatted.
preprocess ::
| Whether CPP is enabled
Bool ->
RegionDeltas ->
Text ->
[Either Text RegionDeltas]
preprocess cppEnabled region rawInput = rawSnippetsAndRegionsToFormat
where
(linesNotToFormat', replacementLines) = linesNotToFormat cppEnabled region rawInput
regionsToFormat =
intSetToRegions rawLineLength $
IntSet.fromAscList [1 .. rawLineLength] IntSet.\\ linesNotToFormat'
regionsNotToFormat = intSetToRegions rawLineLength linesNotToFormat'
We want to interleave the regionsToFormat and .
If the first non - formattable region starts at the first line , it is
the first interleaved region , otherwise , we start with the first
-- region to format.
interleave' = case regionsNotToFormat of
r : _ | regionPrefixLength r == 0 -> interleave
_ -> flip interleave
rawSnippets = flip linesInRegion updatedInput <$> regionsNotToFormat
where
updatedInput = T.unlines . fmap updateLine . zip [1 ..] . T.lines $ rawInput
updateLine (i, line) = IntMap.findWithDefault line i replacementLines
rawSnippetsAndRegionsToFormat =
interleave' (Left <$> rawSnippets) (Right <$> regionsToFormat)
>>= patchSeparatingBlankLines
& dropWhile isBlankRawSnippet
& L.dropWhileEnd isBlankRawSnippet
-- For every formattable region, we want to ensure that it is separated by
-- a blank line from preceding/succeeding raw snippets if it starts/ends
-- with a blank line.
-- Empty formattable regions are replaced by a blank line instead.
-- Extraneous raw snippets at the start/end are dropped afterwards.
patchSeparatingBlankLines = \case
Right r@RegionDeltas {..} ->
if T.all isSpace (linesInRegion r rawInput)
then [blankRawSnippet]
else
[blankRawSnippet | isBlankLine regionPrefixLength]
<> [Right r]
<> [blankRawSnippet | isBlankLine (rawLineLength - regionSuffixLength - 1)]
Left r -> [Left r]
where
blankRawSnippet = Left "\n"
isBlankLine i = isJust . mfilter (T.all isSpace) $ rawLines !!? i
isBlankRawSnippet = \case
Left r | T.all isSpace r -> True
_ -> False
rawLines = A.listArray (0, length rawLines' - 1) rawLines'
where
rawLines' = T.lines rawInput
rawLineLength = length rawLines
interleave [] bs = bs
interleave (a : as) bs = a : interleave bs as
xs !!? i = if A.bounds rawLines `A.inRange` i then Just $ xs A.! i else Nothing
-- | All lines we are not supposed to format, and a set of replacements
-- for specific lines.
linesNotToFormat ::
| Whether CPP is enabled
Bool ->
RegionDeltas ->
Text ->
(IntSet, IntMap Text)
linesNotToFormat cppEnabled region@RegionDeltas {..} input =
(unconsidered <> magicDisabled <> otherDisabled, lineUpdates)
where
unconsidered =
IntSet.fromAscList $
[1 .. regionPrefixLength] <> [totalLines - regionSuffixLength + 1 .. totalLines]
totalLines = length (T.lines input)
regionLines = linesInRegion region input
(magicDisabled, lineUpdates) = magicDisabledLines regionLines
otherDisabled = (mconcat allLines) regionLines
where
allLines = [shebangLines, linePragmaLines] <> [cppLines | cppEnabled]
-- | Ormolu state.
data OrmoluState
= -- | Enabled
OrmoluEnabled
| -- | Disabled
OrmoluDisabled
deriving (Eq, Show)
| All lines which are disabled by Ormolu 's magic comments ,
-- as well as normalizing replacements.
magicDisabledLines :: Text -> (IntSet, IntMap Text)
magicDisabledLines input =
bimap IntSet.fromAscList IntMap.fromAscList . mconcat $
go OrmoluEnabled (T.lines input `zip` [1 ..])
where
go _ [] = []
go state ((line, i) : ls)
| Just marker <- disablingMagicComment line,
state == OrmoluEnabled =
([i], [(i, marker)]) : go OrmoluDisabled ls
| Just marker <- enablingMagicComment line,
state == OrmoluDisabled =
([i], [(i, marker)]) : go OrmoluEnabled ls
| otherwise = iIfDisabled : go state ls
where
iIfDisabled = case state of
OrmoluDisabled -> ([i], [])
OrmoluEnabled -> ([], [])
-- | All lines which satisfy a predicate.
linesFiltered :: (Text -> Bool) -> Text -> IntSet
linesFiltered p =
IntSet.fromAscList . fmap snd . filter (p . fst) . (`zip` [1 ..]) . T.lines
-- | Lines which contain a shebang.
shebangLines :: Text -> IntSet
shebangLines = linesFiltered ("#!" `T.isPrefixOf`)
-- | Lines which contain a LINE pragma.
linePragmaLines :: Text -> IntSet
linePragmaLines = linesFiltered ("{-# LINE" `T.isPrefixOf`)
| If the given string is an enabling marker ( Ormolu or Fourmolu style ) , then
-- return 'Just' the enabling marker + rest of the string. Otherwise return 'Nothing'.
enablingMagicComment :: Text -> Maybe Text
enablingMagicComment s
| Just rest <- isMagicComment "ORMOLU_ENABLE" s = Just $ "{- ORMOLU_ENABLE -}" <> rest
| Just rest <- isMagicComment "FOURMOLU_ENABLE" s = Just $ "{- FOURMOLU_ENABLE -}" <> rest
| otherwise = Nothing
| If the given string is a disabling marker ( Ormolu or Fourmolu style ) , then
-- return 'Just' the disabling marker + rest of the string. Otherwise return 'Nothing'.
disablingMagicComment :: Text -> Maybe Text
disablingMagicComment s
| Just rest <- isMagicComment "ORMOLU_DISABLE" s = Just $ "{- ORMOLU_DISABLE -}" <> rest
| Just rest <- isMagicComment "FOURMOLU_DISABLE" s = Just $ "{- FOURMOLU_DISABLE -}" <> rest
| otherwise = Nothing
-- | Construct a function for whitespace-insensitive matching of string.
isMagicComment ::
-- | What to expect
Text ->
-- | String to test
Text ->
| If the two strings match , we return the rest of the line .
Maybe Text
isMagicComment expected s0 = do
s1 <- T.stripStart <$> T.stripPrefix "{-" (T.stripStart s0)
s2 <- T.stripStart <$> T.stripPrefix expected s1
T.stripPrefix "-}" s2
| null | https://raw.githubusercontent.com/fourmolu/fourmolu/f47860f01cb3cac3b973c5df6ecbae48bbb4c295/src/Ormolu/Processing/Preprocess.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE OverloadedStrings #
| Preprocessing for input source code.
| Preprocess the specified region of the input into raw snippets
and subregions to be formatted.
region to format.
For every formattable region, we want to ensure that it is separated by
a blank line from preceding/succeeding raw snippets if it starts/ends
with a blank line.
Empty formattable regions are replaced by a blank line instead.
Extraneous raw snippets at the start/end are dropped afterwards.
| All lines we are not supposed to format, and a set of replacements
for specific lines.
| Ormolu state.
| Enabled
| Disabled
as well as normalizing replacements.
| All lines which satisfy a predicate.
| Lines which contain a shebang.
| Lines which contain a LINE pragma.
return 'Just' the enabling marker + rest of the string. Otherwise return 'Nothing'.
return 'Just' the disabling marker + rest of the string. Otherwise return 'Nothing'.
| Construct a function for whitespace-insensitive matching of string.
| What to expect
| String to test | # LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
module Ormolu.Processing.Preprocess
( preprocess,
)
where
import Control.Monad
import Data.Array as A
import Data.Bifunctor (bimap)
import Data.Char (isSpace)
import Data.Function ((&))
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import qualified Data.List as L
import Data.Maybe (isJust)
import Data.Text (Text)
import qualified Data.Text as T
import Ormolu.Config (RegionDeltas (..))
import Ormolu.Processing.Common
import Ormolu.Processing.Cpp
preprocess ::
| Whether CPP is enabled
Bool ->
RegionDeltas ->
Text ->
[Either Text RegionDeltas]
preprocess cppEnabled region rawInput = rawSnippetsAndRegionsToFormat
where
(linesNotToFormat', replacementLines) = linesNotToFormat cppEnabled region rawInput
regionsToFormat =
intSetToRegions rawLineLength $
IntSet.fromAscList [1 .. rawLineLength] IntSet.\\ linesNotToFormat'
regionsNotToFormat = intSetToRegions rawLineLength linesNotToFormat'
We want to interleave the regionsToFormat and .
If the first non - formattable region starts at the first line , it is
the first interleaved region , otherwise , we start with the first
interleave' = case regionsNotToFormat of
r : _ | regionPrefixLength r == 0 -> interleave
_ -> flip interleave
rawSnippets = flip linesInRegion updatedInput <$> regionsNotToFormat
where
updatedInput = T.unlines . fmap updateLine . zip [1 ..] . T.lines $ rawInput
updateLine (i, line) = IntMap.findWithDefault line i replacementLines
rawSnippetsAndRegionsToFormat =
interleave' (Left <$> rawSnippets) (Right <$> regionsToFormat)
>>= patchSeparatingBlankLines
& dropWhile isBlankRawSnippet
& L.dropWhileEnd isBlankRawSnippet
patchSeparatingBlankLines = \case
Right r@RegionDeltas {..} ->
if T.all isSpace (linesInRegion r rawInput)
then [blankRawSnippet]
else
[blankRawSnippet | isBlankLine regionPrefixLength]
<> [Right r]
<> [blankRawSnippet | isBlankLine (rawLineLength - regionSuffixLength - 1)]
Left r -> [Left r]
where
blankRawSnippet = Left "\n"
isBlankLine i = isJust . mfilter (T.all isSpace) $ rawLines !!? i
isBlankRawSnippet = \case
Left r | T.all isSpace r -> True
_ -> False
rawLines = A.listArray (0, length rawLines' - 1) rawLines'
where
rawLines' = T.lines rawInput
rawLineLength = length rawLines
interleave [] bs = bs
interleave (a : as) bs = a : interleave bs as
xs !!? i = if A.bounds rawLines `A.inRange` i then Just $ xs A.! i else Nothing
linesNotToFormat ::
| Whether CPP is enabled
Bool ->
RegionDeltas ->
Text ->
(IntSet, IntMap Text)
linesNotToFormat cppEnabled region@RegionDeltas {..} input =
(unconsidered <> magicDisabled <> otherDisabled, lineUpdates)
where
unconsidered =
IntSet.fromAscList $
[1 .. regionPrefixLength] <> [totalLines - regionSuffixLength + 1 .. totalLines]
totalLines = length (T.lines input)
regionLines = linesInRegion region input
(magicDisabled, lineUpdates) = magicDisabledLines regionLines
otherDisabled = (mconcat allLines) regionLines
where
allLines = [shebangLines, linePragmaLines] <> [cppLines | cppEnabled]
data OrmoluState
OrmoluEnabled
OrmoluDisabled
deriving (Eq, Show)
| All lines which are disabled by Ormolu 's magic comments ,
magicDisabledLines :: Text -> (IntSet, IntMap Text)
magicDisabledLines input =
bimap IntSet.fromAscList IntMap.fromAscList . mconcat $
go OrmoluEnabled (T.lines input `zip` [1 ..])
where
go _ [] = []
go state ((line, i) : ls)
| Just marker <- disablingMagicComment line,
state == OrmoluEnabled =
([i], [(i, marker)]) : go OrmoluDisabled ls
| Just marker <- enablingMagicComment line,
state == OrmoluDisabled =
([i], [(i, marker)]) : go OrmoluEnabled ls
| otherwise = iIfDisabled : go state ls
where
iIfDisabled = case state of
OrmoluDisabled -> ([i], [])
OrmoluEnabled -> ([], [])
linesFiltered :: (Text -> Bool) -> Text -> IntSet
linesFiltered p =
IntSet.fromAscList . fmap snd . filter (p . fst) . (`zip` [1 ..]) . T.lines
shebangLines :: Text -> IntSet
shebangLines = linesFiltered ("#!" `T.isPrefixOf`)
linePragmaLines :: Text -> IntSet
linePragmaLines = linesFiltered ("{-# LINE" `T.isPrefixOf`)
| If the given string is an enabling marker ( Ormolu or Fourmolu style ) , then
enablingMagicComment :: Text -> Maybe Text
enablingMagicComment s
| Just rest <- isMagicComment "ORMOLU_ENABLE" s = Just $ "{- ORMOLU_ENABLE -}" <> rest
| Just rest <- isMagicComment "FOURMOLU_ENABLE" s = Just $ "{- FOURMOLU_ENABLE -}" <> rest
| otherwise = Nothing
| If the given string is a disabling marker ( Ormolu or Fourmolu style ) , then
disablingMagicComment :: Text -> Maybe Text
disablingMagicComment s
| Just rest <- isMagicComment "ORMOLU_DISABLE" s = Just $ "{- ORMOLU_DISABLE -}" <> rest
| Just rest <- isMagicComment "FOURMOLU_DISABLE" s = Just $ "{- FOURMOLU_DISABLE -}" <> rest
| otherwise = Nothing
isMagicComment ::
Text ->
Text ->
| If the two strings match , we return the rest of the line .
Maybe Text
isMagicComment expected s0 = do
s1 <- T.stripStart <$> T.stripPrefix "{-" (T.stripStart s0)
s2 <- T.stripStart <$> T.stripPrefix expected s1
T.stripPrefix "-}" s2
|
69f60b3ccc785e40007855215be7a121c92038fae5be3e319659af0dba88febc | astrada/ocaml-extjs | ext_panel_AbstractPanel.mli | * A base class which provides methods common to Pane ...
{ % < p > A base class which provides methods common to Panel classes across the Sencha product range.</p >
< p > Please refer to sub class 's documentation</p > % }
{% <p>A base class which provides methods common to Panel classes across the Sencha product range.</p>
<p>Please refer to sub class's documentation</p> %}
*)
class type t =
object('self)
inherit Ext_container_Container.t
inherit Ext_container_DockingContainer.t
method body : Ext_dom_Element.t Js.t Js.readonly_prop
* { % < p > The Panel 's body < a href="#!/api / Ext.dom . Element " rel="Ext.dom . Element " class="docClass">Element</a > which may be used to contain HTML content .
The content may be specified in the < a href="#!/api / Ext.panel . AbstractPanel - cfg - html " rel="Ext.panel . AbstractPanel - cfg - html " class="docClass">html</a > config , or it may be loaded using the
< a href="#!/api / Ext.panel . AbstractPanel - cfg - loader " rel="Ext.panel . AbstractPanel - cfg - loader " class="docClass">loader</a > config . Read - only.</p >
< p > If this is used to load visible HTML elements in either way , then
the Panel may not be used as a Layout for hosting nested Panels.</p >
< p > If this Panel is intended to be used as the host of a Layout ( See < a href="#!/api / Ext.panel . AbstractPanel - cfg - layout " rel="Ext.panel . AbstractPanel - cfg - layout " class="docClass">layout</a >
then the body Element must not be loaded or changed - it is under the control
of the Panel 's Layout.</p > % }
The content may be specified in the <a href="#!/api/Ext.panel.AbstractPanel-cfg-html" rel="Ext.panel.AbstractPanel-cfg-html" class="docClass">html</a> config, or it may be loaded using the
<a href="#!/api/Ext.panel.AbstractPanel-cfg-loader" rel="Ext.panel.AbstractPanel-cfg-loader" class="docClass">loader</a> config. Read-only.</p>
<p>If this is used to load visible HTML elements in either way, then
the Panel may not be used as a Layout for hosting nested Panels.</p>
<p>If this Panel is intended to be used as the host of a Layout (See <a href="#!/api/Ext.panel.AbstractPanel-cfg-layout" rel="Ext.panel.AbstractPanel-cfg-layout" class="docClass">layout</a>
then the body Element must not be loaded or changed - it is under the control
of the Panel's Layout.</p> %}
*)
method contentPaddingProperty : Js.js_string Js.t Js.prop
* { % < p > The name of the padding property that is used by the layout to manage
padding . See < a href="#!/api / Ext.layout.container . Auto - property - managePadding " rel="Ext.layout.container . Auto - property - managePadding " class="docClass">managePadding</a></p > % }
Defaults to : [ ' bodyPadding ' ]
padding. See <a href="#!/api/Ext.layout.container.Auto-property-managePadding" rel="Ext.layout.container.Auto-property-managePadding" class="docClass">managePadding</a></p> %}
Defaults to: ['bodyPadding']
*)
method isPanel : bool Js.t Js.prop
* { % < p><code > true</code > in this class to identify an object as an instantiated Panel , or subclass thereof.</p > % }
Defaults to : [ true ]
Defaults to: [true]
*)
method addBodyCls : Js.js_string Js.t -> 'self Js.t Js.meth
* { % < p > Adds a CSS class to the body element . If not rendered , the class will
be added when the panel is rendered.</p > % }
{ b Parameters } :
{ ul { - cls : [ Js.js_string Js.t ]
{ % < p > The class to add</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_panel_Panel.t Js.t ] { % < p > this</p > % }
}
}
be added when the panel is rendered.</p> %}
{b Parameters}:
{ul {- cls: [Js.js_string Js.t]
{% <p>The class to add</p> %}
}
}
{b Returns}:
{ul {- [#Ext_panel_Panel.t Js.t] {% <p>this</p> %}
}
}
*)
method addUIClsToElement : Js.js_string Js.t -> unit Js.meth
* { % < p > inherit docs</p >
< p > Method which adds a specified UI + < code > uiCls</code > to the components element . Can be overridden to remove the UI from more
than just the components element.</p > % }
{ b Parameters } :
{ ul { - ui : [ Js.js_string Js.t ]
{ % < p > The UI to remove from the element.</p > % }
}
}
<p>Method which adds a specified UI + <code>uiCls</code> to the components element. Can be overridden to remove the UI from more
than just the components element.</p> %}
{b Parameters}:
{ul {- ui: [Js.js_string Js.t]
{% <p>The UI to remove from the element.</p> %}
}
}
*)
method beforeDestroy : unit Js.meth
(** {% <p>Invoked before the Component is destroyed.</p> %}
*)
method getComponent : _ Js.t -> #Ext_Component.t Js.t Js.meth
* { % < p > Attempts a default component lookup ( see < a href="#!/api / Ext.container . Container - method - getComponent " rel="Ext.container . Container - method - getComponent " class="docClass">Ext.container . Container.getComponent</a > ) . If the component is not found in the normal
items , the dockedItems are searched and the matched component ( if any ) returned ( see < a href="#!/api / Ext.panel . AbstractPanel - method - getDockedComponent " rel="Ext.panel . AbstractPanel - method - getDockedComponent " class="docClass">getDockedComponent</a > ) . Note that docked
items will only be matched by component i d or itemId -- if you pass a numeric index only non - docked child components will be searched.</p > % }
{ b Parameters } :
{ ul { - comp : [ _ Js.t ]
{ % < p > The component i d , itemId or position to find</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_Component.t Js.t ] { % < p > The component ( if found)</p > % }
}
}
items, the dockedItems are searched and the matched component (if any) returned (see <a href="#!/api/Ext.panel.AbstractPanel-method-getDockedComponent" rel="Ext.panel.AbstractPanel-method-getDockedComponent" class="docClass">getDockedComponent</a>). Note that docked
items will only be matched by component id or itemId -- if you pass a numeric index only non-docked child components will be searched.</p> %}
{b Parameters}:
{ul {- comp: [_ Js.t]
{% <p>The component id, itemId or position to find</p> %}
}
}
{b Returns}:
{ul {- [#Ext_Component.t Js.t] {% <p>The component (if found)</p> %}
}
}
*)
method getRefItems : _ Js.t -> unit Js.meth
* { % < p > Used by < a href="#!/api / Ext . ComponentQuery " rel="Ext . ComponentQuery " class="docClass">ComponentQuery</a > , < a href="#!/api / Ext.panel . AbstractPanel - method - child " rel="Ext.panel . AbstractPanel - method - child " class="docClass">child</a > and < a href="#!/api / Ext.panel . AbstractPanel - method - down " rel="Ext.panel . AbstractPanel - method - down " class="docClass">down</a > to retrieve all of the items
which can potentially be considered a child of this Container.</p >
< p > This may be overriden by Components which have ownership of Components
that are not contained in the < a href="#!/api / Ext.panel . AbstractPanel - property - items " rel="Ext.panel . AbstractPanel - property - items " class="docClass">items</a > collection.</p >
< p > NOTE : IMPORTANT note for maintainers :
Items are returned in tree traversal order . Each item is appended to the result array
followed by the results of that child 's getRefItems call .
Floating child items are appended after internal child items.</p > % }
{ b Parameters } :
{ ul { - deep : [ _ Js.t ]
}
}
which can potentially be considered a child of this Container.</p>
<p>This may be overriden by Components which have ownership of Components
that are not contained in the <a href="#!/api/Ext.panel.AbstractPanel-property-items" rel="Ext.panel.AbstractPanel-property-items" class="docClass">items</a> collection.</p>
<p>NOTE: IMPORTANT note for maintainers:
Items are returned in tree traversal order. Each item is appended to the result array
followed by the results of that child's getRefItems call.
Floating child items are appended after internal child items.</p> %}
{b Parameters}:
{ul {- deep: [_ Js.t]
}
}
*)
method initComponent : unit Js.meth
* { % < p > The initComponent template method is an important initialization step for a Component . It is intended to be
implemented by each subclass of < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > to provide any needed constructor logic . The
initComponent method of the class being created is called first , with each initComponent method
up the hierarchy to < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > being called thereafter . This makes it easy to implement and ,
if needed , override the constructor logic of the Component at any step in the hierarchy.</p >
< p > The initComponent method < strong > must</strong > contain a call to < a href="#!/api / Ext . Base - method - callParent " rel="Ext . Base - method - callParent " class="docClass">callParent</a > in order
to ensure that the parent class ' initComponent method is also called.</p >
< p > All config options passed to the constructor are applied to < code > this</code > before initComponent is called ,
so you can simply access them with < code > >
< p > The following example demonstrates using a dynamic string for the text of a button at the time of
instantiation of the class.</p >
< pre><code><a href="#!/api / Ext - method - define " rel="Ext - method - define " class="docClass">Ext.define</a>('DynamicButtonText ' , \ {
extend : ' < a href="#!/api / Ext.button . Button " rel="Ext.button . Button " class="docClass">Ext.button . > ' ,
initComponent : function ( ) \ {
this.text = new Date ( ) ;
this.renderTo = < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( ) ;
this.callParent ( ) ;
\ }
\ } ) ;
< a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " class="docClass">Ext.onReady</a>(function ( ) \ {
< a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('DynamicButtonText ' ) ;
\ } ) ;
< /code></pre > % }
implemented by each subclass of <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> to provide any needed constructor logic. The
initComponent method of the class being created is called first, with each initComponent method
up the hierarchy to <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> being called thereafter. This makes it easy to implement and,
if needed, override the constructor logic of the Component at any step in the hierarchy.</p>
<p>The initComponent method <strong>must</strong> contain a call to <a href="#!/api/Ext.Base-method-callParent" rel="Ext.Base-method-callParent" class="docClass">callParent</a> in order
to ensure that the parent class' initComponent method is also called.</p>
<p>All config options passed to the constructor are applied to <code>this</code> before initComponent is called,
so you can simply access them with <code>this.someOption</code>.</p>
<p>The following example demonstrates using a dynamic string for the text of a button at the time of
instantiation of the class.</p>
<pre><code><a href="#!/api/Ext-method-define" rel="Ext-method-define" class="docClass">Ext.define</a>('DynamicButtonText', \{
extend: '<a href="#!/api/Ext.button.Button" rel="Ext.button.Button" class="docClass">Ext.button.Button</a>',
initComponent: function() \{
this.text = new Date();
this.renderTo = <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>();
this.callParent();
\}
\});
<a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>(function() \{
<a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('DynamicButtonText');
\});
</code></pre> %}
*)
method removeBodyCls : Js.js_string Js.t -> 'self Js.t Js.meth
* { % < p > Removes a CSS class from the body element.</p > % }
{ b Parameters } :
{ ul { - cls : [ Js.js_string Js.t ]
{ % < p > The class to remove</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_panel_Panel.t Js.t ] { % < p > this</p > % }
}
}
{b Parameters}:
{ul {- cls: [Js.js_string Js.t]
{% <p>The class to remove</p> %}
}
}
{b Returns}:
{ul {- [#Ext_panel_Panel.t Js.t] {% <p>this</p> %}
}
}
*)
method removeUIClsFromElement : Js.js_string Js.t -> unit Js.meth
* { % < p > inherit docs</p >
< p > Method which removes a specified UI + < code > uiCls</code > from the components element . The < code > cls</code > which is added to the element
will be : < code > this.baseCls + ' - ' + ui</code>.</p > % }
{ b Parameters } :
{ ul { - ui : [ Js.js_string Js.t ]
{ % < p > The UI to add to the element.</p > % }
}
}
<p>Method which removes a specified UI + <code>uiCls</code> from the components element. The <code>cls</code> which is added to the element
will be: <code>this.baseCls + '-' + ui</code>.</p> %}
{b Parameters}:
{ul {- ui: [Js.js_string Js.t]
{% <p>The UI to add to the element.</p> %}
}
}
*)
method setBodyStyle : _ Js.t -> Js.js_string Js.t -> 'self Js.t Js.meth
* { % < p > Sets the body style according to the passed parameters.</p > % }
{ b Parameters } :
{ ul { - style : [ _ Js.t ]
{ % < p > A full style specification string , or object , or the name of a style property to set.</p > % }
}
{ - value : [ Js.js_string Js.t ]
{ % < p > If the first param was a style property name , the style property value.</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_panel_Panel.t Js.t ] { % < p > this</p > % }
}
}
{b Parameters}:
{ul {- style: [_ Js.t]
{% <p>A full style specification string, or object, or the name of a style property to set.</p> %}
}
{- value: [Js.js_string Js.t]
{% <p>If the first param was a style property name, the style property value.</p> %}
}
}
{b Returns}:
{ul {- [#Ext_panel_Panel.t Js.t] {% <p>this</p> %}
}
}
*)
end
class type configs =
object('self)
inherit Ext_container_Container.configs
inherit Ext_container_DockingContainer.configs
method baseCls : Js.js_string Js.t Js.prop
(** {% <p>The base CSS class to apply to this panel's element.</p> %}
Defaults to: [x-panel]
*)
method bodyBorder : bool Js.t Js.prop
* { % < p > A shortcut to add or remove the border on the body of a panel . In the classic theme
this only applies to a panel which has the < a href="#!/api / Ext.panel . AbstractPanel - cfg - frame " rel="Ext.panel . AbstractPanel - cfg - frame " class="docClass">frame</a > configuration set to < code > true</code>.</p > % }
this only applies to a panel which has the <a href="#!/api/Ext.panel.AbstractPanel-cfg-frame" rel="Ext.panel.AbstractPanel-cfg-frame" class="docClass">frame</a> configuration set to <code>true</code>.</p> %}
*)
method bodyCls : _ Js.t Js.prop
* { % < p > A CSS class , space - delimited string of classes , or array of classes to be applied to the panel 's body element .
The following examples are all valid:</p >
< pre><code > bodyCls : ' foo '
bodyCls : ' foo bar '
bodyCls : [ ' foo ' , ' bar ' ]
< /code></pre > % }
The following examples are all valid:</p>
<pre><code>bodyCls: 'foo'
bodyCls: 'foo bar'
bodyCls: ['foo', 'bar']
</code></pre> %}
*)
method bodyPadding : _ Js.t Js.prop
(** {% <p>A shortcut for setting a padding style on the body element. The value can either be
a number to be applied to all sides, or a normal css string describing padding.
Defaults to <code>undefined</code>.</p> %}
*)
method bodyStyle : _ Js.t Js.prop
* { % < p > Custom CSS styles to be applied to the panel 's body element , which can be supplied as a valid CSS style string ,
an object containing style property name / value pairs or a function that returns such a string or object .
For example , these two formats are interpreted to be equivalent:</p >
< pre><code > bodyStyle : ' ; padding:10px ; '
bodyStyle : \ {
background : ' # ffc ' ,
padding : ' 10px '
\ }
< /code></pre > % }
an object containing style property name/value pairs or a function that returns such a string or object.
For example, these two formats are interpreted to be equivalent:</p>
<pre><code>bodyStyle: 'background:#ffc; padding:10px;'
bodyStyle: \{
background: '#ffc',
padding: '10px'
\}
</code></pre> %}
*)
method border : _ Js.t Js.prop
* { % < p > Specifies the border size for this component . The border can be a single numeric value to apply to all sides or it can
be a CSS style specification for each style , for example : ' 10 5 3 10 ' ( top , right , bottom , left).</p >
< p > For components that have no border by default , setting this wo n't make the border appear by itself .
You also need to specify border color and style:</p >
< pre><code > border : 5 ,
style : \ {
: ' red ' ,
borderStyle : ' solid '
\ }
< /code></pre >
< p > To turn off the border , use < code > border : false</code>.</p > % }
Defaults to : [ true ]
be a CSS style specification for each style, for example: '10 5 3 10' (top, right, bottom, left).</p>
<p>For components that have no border by default, setting this won't make the border appear by itself.
You also need to specify border color and style:</p>
<pre><code>border: 5,
style: \{
borderColor: 'red',
borderStyle: 'solid'
\}
</code></pre>
<p>To turn off the border, use <code>border: false</code>.</p> %}
Defaults to: [true]
*)
method componentLayout : _ Js.t Js.prop
* { % < p > The sizing and positioning of a Component 's internal Elements is the responsibility of the Component 's layout
manager which sizes a Component 's internal structure in response to the Component being sized.</p >
< p > Generally , developers will not use this configuration as all provided Components which need their internal
elements sizing ( Such as < a href="#!/api / Ext.form.field . Base " rel="Ext.form.field . Base " class="docClass">input fields</a > ) come with their own componentLayout managers.</p >
< p > The < a href="#!/api / Ext.layout.container . Auto " rel="Ext.layout.container . Auto " class="docClass">default layout manager</a > will be used on instances of the base < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a >
class which simply sizes the Component 's encapsulating element to the height and width specified in the
< a href="#!/api / Ext.panel . AbstractPanel - method - setSize " rel="Ext.panel . AbstractPanel - method - setSize " class="docClass">setSize</a > method.</p > % }
Defaults to : [ ' dock ' ]
manager which sizes a Component's internal structure in response to the Component being sized.</p>
<p>Generally, developers will not use this configuration as all provided Components which need their internal
elements sizing (Such as <a href="#!/api/Ext.form.field.Base" rel="Ext.form.field.Base" class="docClass">input fields</a>) come with their own componentLayout managers.</p>
<p>The <a href="#!/api/Ext.layout.container.Auto" rel="Ext.layout.container.Auto" class="docClass">default layout manager</a> will be used on instances of the base <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a>
class which simply sizes the Component's encapsulating element to the height and width specified in the
<a href="#!/api/Ext.panel.AbstractPanel-method-setSize" rel="Ext.panel.AbstractPanel-method-setSize" class="docClass">setSize</a> method.</p> %}
Defaults to: ['dock']
*)
method dockedItems : _ Js.t Js.prop
* { % < p > A component or series of components to be added as docked items to this panel .
The docked items can be docked to either the top , right , left or bottom of a panel .
This is typically used for things like toolbars or tab >
< pre><code > var panel = new < a href="#!/api / Ext.panel . Panel " rel="Ext.panel . Panel " class="docClass">Ext.panel . Panel</a>(\ {
fullscreen : true ,
dockedItems : [ \ {
: ' toolbar ' ,
dock : ' top ' ,
items : [ \ {
text : ' Docked to the top '
\ } ]
\ } ]
\});</code></pre > % }
The docked items can be docked to either the top, right, left or bottom of a panel.
This is typically used for things like toolbars or tab bars:</p>
<pre><code>var panel = new <a href="#!/api/Ext.panel.Panel" rel="Ext.panel.Panel" class="docClass">Ext.panel.Panel</a>(\{
fullscreen: true,
dockedItems: [\{
xtype: 'toolbar',
dock: 'top',
items: [\{
text: 'Docked to the top'
\}]
\}]
\});</code></pre> %}
*)
method renderTpl : _ Js.t Js.prop
* { % < p > An < a href="#!/api / Ext . XTemplate " rel="Ext . XTemplate " class="docClass">XTemplate</a > used to create the internal structure inside this Component 's encapsulating
< a href="#!/api / Ext.panel . AbstractPanel - method - getEl " rel="Ext.panel . AbstractPanel - method - getEl " class="docClass">Element</a>.</p >
< p > You do not normally need to specify this . For the base classes < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > and
< a href="#!/api / Ext.container . Container " rel="Ext.container . Container " class="docClass">Ext.container . Container</a > , this defaults to < strong><code > null</code></strong > which means that they will be initially rendered
with no internal structure ; they render their < a href="#!/api / Ext.panel . AbstractPanel - method - getEl " rel="Ext.panel . AbstractPanel - method - getEl " class="docClass">Element</a > empty . The more specialized Ext JS and Sencha Touch
classes which use a more complex DOM structure , provide their own template definitions.</p >
< p > This is intended to allow the developer to create application - specific utility Components with customized
internal structure.</p >
< p > Upon rendering , any created child elements may be automatically imported into object properties using the
< a href="#!/api / Ext.panel . AbstractPanel - cfg - renderSelectors " rel="Ext.panel . AbstractPanel - cfg - renderSelectors " class="docClass">renderSelectors</a > and < a href="#!/api / Ext.panel . AbstractPanel - cfg - childEls " rel="Ext.panel . AbstractPanel - cfg - childEls " class="docClass">childEls</a > options.</p > % }
<a href="#!/api/Ext.panel.AbstractPanel-method-getEl" rel="Ext.panel.AbstractPanel-method-getEl" class="docClass">Element</a>.</p>
<p>You do not normally need to specify this. For the base classes <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> and
<a href="#!/api/Ext.container.Container" rel="Ext.container.Container" class="docClass">Ext.container.Container</a>, this defaults to <strong><code>null</code></strong> which means that they will be initially rendered
with no internal structure; they render their <a href="#!/api/Ext.panel.AbstractPanel-method-getEl" rel="Ext.panel.AbstractPanel-method-getEl" class="docClass">Element</a> empty. The more specialized Ext JS and Sencha Touch
classes which use a more complex DOM structure, provide their own template definitions.</p>
<p>This is intended to allow the developer to create application-specific utility Components with customized
internal structure.</p>
<p>Upon rendering, any created child elements may be automatically imported into object properties using the
<a href="#!/api/Ext.panel.AbstractPanel-cfg-renderSelectors" rel="Ext.panel.AbstractPanel-cfg-renderSelectors" class="docClass">renderSelectors</a> and <a href="#!/api/Ext.panel.AbstractPanel-cfg-childEls" rel="Ext.panel.AbstractPanel-cfg-childEls" class="docClass">childEls</a> options.</p> %}
*)
method shrinkWrapDock : _ Js.t Js.prop
* { % < p > Allows for this panel to include the < a href="#!/api / Ext.panel . AbstractPanel - cfg - dockedItems " rel="Ext.panel . AbstractPanel - cfg - dockedItems " class="docClass">dockedItems</a > when trying to determine the overall
size of the panel . This option is only applicable when this panel is also shrink wrapping in the
same dimensions . See < a href="#!/api / Ext . AbstractComponent - cfg - shrinkWrap " rel="Ext . " class="docClass">Ext . > for an explanation of the configuration options.</p > % }
Defaults to : [ false ]
size of the panel. This option is only applicable when this panel is also shrink wrapping in the
same dimensions. See <a href="#!/api/Ext.AbstractComponent-cfg-shrinkWrap" rel="Ext.AbstractComponent-cfg-shrinkWrap" class="docClass">Ext.AbstractComponent.shrinkWrap</a> for an explanation of the configuration options.</p> %}
Defaults to: [false]
*)
method beforeDestroy : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
(** See method [t.beforeDestroy] *)
method initComponent : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
(** See method [t.initComponent] *)
end
class type events =
object
inherit Ext_container_Container.events
inherit Ext_container_DockingContainer.events
end
class type statics =
object
inherit Ext_container_Container.statics
inherit Ext_container_DockingContainer.statics
end
val of_configs : configs Js.t -> t Js.t
(** [of_configs c] casts a config object [c] to an instance of class [t] *)
val to_configs : t Js.t -> configs Js.t
(** [to_configs o] casts instance [o] of class [t] to a config object *)
| null | https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/lib/ext_panel_AbstractPanel.mli | ocaml | * {% <p>Invoked before the Component is destroyed.</p> %}
* {% <p>The base CSS class to apply to this panel's element.</p> %}
Defaults to: [x-panel]
* {% <p>A shortcut for setting a padding style on the body element. The value can either be
a number to be applied to all sides, or a normal css string describing padding.
Defaults to <code>undefined</code>.</p> %}
* See method [t.beforeDestroy]
* See method [t.initComponent]
* [of_configs c] casts a config object [c] to an instance of class [t]
* [to_configs o] casts instance [o] of class [t] to a config object | * A base class which provides methods common to Pane ...
{ % < p > A base class which provides methods common to Panel classes across the Sencha product range.</p >
< p > Please refer to sub class 's documentation</p > % }
{% <p>A base class which provides methods common to Panel classes across the Sencha product range.</p>
<p>Please refer to sub class's documentation</p> %}
*)
class type t =
object('self)
inherit Ext_container_Container.t
inherit Ext_container_DockingContainer.t
method body : Ext_dom_Element.t Js.t Js.readonly_prop
* { % < p > The Panel 's body < a href="#!/api / Ext.dom . Element " rel="Ext.dom . Element " class="docClass">Element</a > which may be used to contain HTML content .
The content may be specified in the < a href="#!/api / Ext.panel . AbstractPanel - cfg - html " rel="Ext.panel . AbstractPanel - cfg - html " class="docClass">html</a > config , or it may be loaded using the
< a href="#!/api / Ext.panel . AbstractPanel - cfg - loader " rel="Ext.panel . AbstractPanel - cfg - loader " class="docClass">loader</a > config . Read - only.</p >
< p > If this is used to load visible HTML elements in either way , then
the Panel may not be used as a Layout for hosting nested Panels.</p >
< p > If this Panel is intended to be used as the host of a Layout ( See < a href="#!/api / Ext.panel . AbstractPanel - cfg - layout " rel="Ext.panel . AbstractPanel - cfg - layout " class="docClass">layout</a >
then the body Element must not be loaded or changed - it is under the control
of the Panel 's Layout.</p > % }
The content may be specified in the <a href="#!/api/Ext.panel.AbstractPanel-cfg-html" rel="Ext.panel.AbstractPanel-cfg-html" class="docClass">html</a> config, or it may be loaded using the
<a href="#!/api/Ext.panel.AbstractPanel-cfg-loader" rel="Ext.panel.AbstractPanel-cfg-loader" class="docClass">loader</a> config. Read-only.</p>
<p>If this is used to load visible HTML elements in either way, then
the Panel may not be used as a Layout for hosting nested Panels.</p>
<p>If this Panel is intended to be used as the host of a Layout (See <a href="#!/api/Ext.panel.AbstractPanel-cfg-layout" rel="Ext.panel.AbstractPanel-cfg-layout" class="docClass">layout</a>
then the body Element must not be loaded or changed - it is under the control
of the Panel's Layout.</p> %}
*)
method contentPaddingProperty : Js.js_string Js.t Js.prop
* { % < p > The name of the padding property that is used by the layout to manage
padding . See < a href="#!/api / Ext.layout.container . Auto - property - managePadding " rel="Ext.layout.container . Auto - property - managePadding " class="docClass">managePadding</a></p > % }
Defaults to : [ ' bodyPadding ' ]
padding. See <a href="#!/api/Ext.layout.container.Auto-property-managePadding" rel="Ext.layout.container.Auto-property-managePadding" class="docClass">managePadding</a></p> %}
Defaults to: ['bodyPadding']
*)
method isPanel : bool Js.t Js.prop
* { % < p><code > true</code > in this class to identify an object as an instantiated Panel , or subclass thereof.</p > % }
Defaults to : [ true ]
Defaults to: [true]
*)
method addBodyCls : Js.js_string Js.t -> 'self Js.t Js.meth
* { % < p > Adds a CSS class to the body element . If not rendered , the class will
be added when the panel is rendered.</p > % }
{ b Parameters } :
{ ul { - cls : [ Js.js_string Js.t ]
{ % < p > The class to add</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_panel_Panel.t Js.t ] { % < p > this</p > % }
}
}
be added when the panel is rendered.</p> %}
{b Parameters}:
{ul {- cls: [Js.js_string Js.t]
{% <p>The class to add</p> %}
}
}
{b Returns}:
{ul {- [#Ext_panel_Panel.t Js.t] {% <p>this</p> %}
}
}
*)
method addUIClsToElement : Js.js_string Js.t -> unit Js.meth
* { % < p > inherit docs</p >
< p > Method which adds a specified UI + < code > uiCls</code > to the components element . Can be overridden to remove the UI from more
than just the components element.</p > % }
{ b Parameters } :
{ ul { - ui : [ Js.js_string Js.t ]
{ % < p > The UI to remove from the element.</p > % }
}
}
<p>Method which adds a specified UI + <code>uiCls</code> to the components element. Can be overridden to remove the UI from more
than just the components element.</p> %}
{b Parameters}:
{ul {- ui: [Js.js_string Js.t]
{% <p>The UI to remove from the element.</p> %}
}
}
*)
method beforeDestroy : unit Js.meth
method getComponent : _ Js.t -> #Ext_Component.t Js.t Js.meth
* { % < p > Attempts a default component lookup ( see < a href="#!/api / Ext.container . Container - method - getComponent " rel="Ext.container . Container - method - getComponent " class="docClass">Ext.container . Container.getComponent</a > ) . If the component is not found in the normal
items , the dockedItems are searched and the matched component ( if any ) returned ( see < a href="#!/api / Ext.panel . AbstractPanel - method - getDockedComponent " rel="Ext.panel . AbstractPanel - method - getDockedComponent " class="docClass">getDockedComponent</a > ) . Note that docked
items will only be matched by component i d or itemId -- if you pass a numeric index only non - docked child components will be searched.</p > % }
{ b Parameters } :
{ ul { - comp : [ _ Js.t ]
{ % < p > The component i d , itemId or position to find</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_Component.t Js.t ] { % < p > The component ( if found)</p > % }
}
}
items, the dockedItems are searched and the matched component (if any) returned (see <a href="#!/api/Ext.panel.AbstractPanel-method-getDockedComponent" rel="Ext.panel.AbstractPanel-method-getDockedComponent" class="docClass">getDockedComponent</a>). Note that docked
items will only be matched by component id or itemId -- if you pass a numeric index only non-docked child components will be searched.</p> %}
{b Parameters}:
{ul {- comp: [_ Js.t]
{% <p>The component id, itemId or position to find</p> %}
}
}
{b Returns}:
{ul {- [#Ext_Component.t Js.t] {% <p>The component (if found)</p> %}
}
}
*)
method getRefItems : _ Js.t -> unit Js.meth
* { % < p > Used by < a href="#!/api / Ext . ComponentQuery " rel="Ext . ComponentQuery " class="docClass">ComponentQuery</a > , < a href="#!/api / Ext.panel . AbstractPanel - method - child " rel="Ext.panel . AbstractPanel - method - child " class="docClass">child</a > and < a href="#!/api / Ext.panel . AbstractPanel - method - down " rel="Ext.panel . AbstractPanel - method - down " class="docClass">down</a > to retrieve all of the items
which can potentially be considered a child of this Container.</p >
< p > This may be overriden by Components which have ownership of Components
that are not contained in the < a href="#!/api / Ext.panel . AbstractPanel - property - items " rel="Ext.panel . AbstractPanel - property - items " class="docClass">items</a > collection.</p >
< p > NOTE : IMPORTANT note for maintainers :
Items are returned in tree traversal order . Each item is appended to the result array
followed by the results of that child 's getRefItems call .
Floating child items are appended after internal child items.</p > % }
{ b Parameters } :
{ ul { - deep : [ _ Js.t ]
}
}
which can potentially be considered a child of this Container.</p>
<p>This may be overriden by Components which have ownership of Components
that are not contained in the <a href="#!/api/Ext.panel.AbstractPanel-property-items" rel="Ext.panel.AbstractPanel-property-items" class="docClass">items</a> collection.</p>
<p>NOTE: IMPORTANT note for maintainers:
Items are returned in tree traversal order. Each item is appended to the result array
followed by the results of that child's getRefItems call.
Floating child items are appended after internal child items.</p> %}
{b Parameters}:
{ul {- deep: [_ Js.t]
}
}
*)
method initComponent : unit Js.meth
* { % < p > The initComponent template method is an important initialization step for a Component . It is intended to be
implemented by each subclass of < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > to provide any needed constructor logic . The
initComponent method of the class being created is called first , with each initComponent method
up the hierarchy to < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > being called thereafter . This makes it easy to implement and ,
if needed , override the constructor logic of the Component at any step in the hierarchy.</p >
< p > The initComponent method < strong > must</strong > contain a call to < a href="#!/api / Ext . Base - method - callParent " rel="Ext . Base - method - callParent " class="docClass">callParent</a > in order
to ensure that the parent class ' initComponent method is also called.</p >
< p > All config options passed to the constructor are applied to < code > this</code > before initComponent is called ,
so you can simply access them with < code > >
< p > The following example demonstrates using a dynamic string for the text of a button at the time of
instantiation of the class.</p >
< pre><code><a href="#!/api / Ext - method - define " rel="Ext - method - define " class="docClass">Ext.define</a>('DynamicButtonText ' , \ {
extend : ' < a href="#!/api / Ext.button . Button " rel="Ext.button . Button " class="docClass">Ext.button . > ' ,
initComponent : function ( ) \ {
this.text = new Date ( ) ;
this.renderTo = < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( ) ;
this.callParent ( ) ;
\ }
\ } ) ;
< a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " class="docClass">Ext.onReady</a>(function ( ) \ {
< a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('DynamicButtonText ' ) ;
\ } ) ;
< /code></pre > % }
implemented by each subclass of <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> to provide any needed constructor logic. The
initComponent method of the class being created is called first, with each initComponent method
up the hierarchy to <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> being called thereafter. This makes it easy to implement and,
if needed, override the constructor logic of the Component at any step in the hierarchy.</p>
<p>The initComponent method <strong>must</strong> contain a call to <a href="#!/api/Ext.Base-method-callParent" rel="Ext.Base-method-callParent" class="docClass">callParent</a> in order
to ensure that the parent class' initComponent method is also called.</p>
<p>All config options passed to the constructor are applied to <code>this</code> before initComponent is called,
so you can simply access them with <code>this.someOption</code>.</p>
<p>The following example demonstrates using a dynamic string for the text of a button at the time of
instantiation of the class.</p>
<pre><code><a href="#!/api/Ext-method-define" rel="Ext-method-define" class="docClass">Ext.define</a>('DynamicButtonText', \{
extend: '<a href="#!/api/Ext.button.Button" rel="Ext.button.Button" class="docClass">Ext.button.Button</a>',
initComponent: function() \{
this.text = new Date();
this.renderTo = <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>();
this.callParent();
\}
\});
<a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>(function() \{
<a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('DynamicButtonText');
\});
</code></pre> %}
*)
method removeBodyCls : Js.js_string Js.t -> 'self Js.t Js.meth
* { % < p > Removes a CSS class from the body element.</p > % }
{ b Parameters } :
{ ul { - cls : [ Js.js_string Js.t ]
{ % < p > The class to remove</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_panel_Panel.t Js.t ] { % < p > this</p > % }
}
}
{b Parameters}:
{ul {- cls: [Js.js_string Js.t]
{% <p>The class to remove</p> %}
}
}
{b Returns}:
{ul {- [#Ext_panel_Panel.t Js.t] {% <p>this</p> %}
}
}
*)
method removeUIClsFromElement : Js.js_string Js.t -> unit Js.meth
* { % < p > inherit docs</p >
< p > Method which removes a specified UI + < code > uiCls</code > from the components element . The < code > cls</code > which is added to the element
will be : < code > this.baseCls + ' - ' + ui</code>.</p > % }
{ b Parameters } :
{ ul { - ui : [ Js.js_string Js.t ]
{ % < p > The UI to add to the element.</p > % }
}
}
<p>Method which removes a specified UI + <code>uiCls</code> from the components element. The <code>cls</code> which is added to the element
will be: <code>this.baseCls + '-' + ui</code>.</p> %}
{b Parameters}:
{ul {- ui: [Js.js_string Js.t]
{% <p>The UI to add to the element.</p> %}
}
}
*)
method setBodyStyle : _ Js.t -> Js.js_string Js.t -> 'self Js.t Js.meth
* { % < p > Sets the body style according to the passed parameters.</p > % }
{ b Parameters } :
{ ul { - style : [ _ Js.t ]
{ % < p > A full style specification string , or object , or the name of a style property to set.</p > % }
}
{ - value : [ Js.js_string Js.t ]
{ % < p > If the first param was a style property name , the style property value.</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_panel_Panel.t Js.t ] { % < p > this</p > % }
}
}
{b Parameters}:
{ul {- style: [_ Js.t]
{% <p>A full style specification string, or object, or the name of a style property to set.</p> %}
}
{- value: [Js.js_string Js.t]
{% <p>If the first param was a style property name, the style property value.</p> %}
}
}
{b Returns}:
{ul {- [#Ext_panel_Panel.t Js.t] {% <p>this</p> %}
}
}
*)
end
class type configs =
object('self)
inherit Ext_container_Container.configs
inherit Ext_container_DockingContainer.configs
method baseCls : Js.js_string Js.t Js.prop
method bodyBorder : bool Js.t Js.prop
* { % < p > A shortcut to add or remove the border on the body of a panel . In the classic theme
this only applies to a panel which has the < a href="#!/api / Ext.panel . AbstractPanel - cfg - frame " rel="Ext.panel . AbstractPanel - cfg - frame " class="docClass">frame</a > configuration set to < code > true</code>.</p > % }
this only applies to a panel which has the <a href="#!/api/Ext.panel.AbstractPanel-cfg-frame" rel="Ext.panel.AbstractPanel-cfg-frame" class="docClass">frame</a> configuration set to <code>true</code>.</p> %}
*)
method bodyCls : _ Js.t Js.prop
* { % < p > A CSS class , space - delimited string of classes , or array of classes to be applied to the panel 's body element .
The following examples are all valid:</p >
< pre><code > bodyCls : ' foo '
bodyCls : ' foo bar '
bodyCls : [ ' foo ' , ' bar ' ]
< /code></pre > % }
The following examples are all valid:</p>
<pre><code>bodyCls: 'foo'
bodyCls: 'foo bar'
bodyCls: ['foo', 'bar']
</code></pre> %}
*)
method bodyPadding : _ Js.t Js.prop
method bodyStyle : _ Js.t Js.prop
* { % < p > Custom CSS styles to be applied to the panel 's body element , which can be supplied as a valid CSS style string ,
an object containing style property name / value pairs or a function that returns such a string or object .
For example , these two formats are interpreted to be equivalent:</p >
< pre><code > bodyStyle : ' ; padding:10px ; '
bodyStyle : \ {
background : ' # ffc ' ,
padding : ' 10px '
\ }
< /code></pre > % }
an object containing style property name/value pairs or a function that returns such a string or object.
For example, these two formats are interpreted to be equivalent:</p>
<pre><code>bodyStyle: 'background:#ffc; padding:10px;'
bodyStyle: \{
background: '#ffc',
padding: '10px'
\}
</code></pre> %}
*)
method border : _ Js.t Js.prop
* { % < p > Specifies the border size for this component . The border can be a single numeric value to apply to all sides or it can
be a CSS style specification for each style , for example : ' 10 5 3 10 ' ( top , right , bottom , left).</p >
< p > For components that have no border by default , setting this wo n't make the border appear by itself .
You also need to specify border color and style:</p >
< pre><code > border : 5 ,
style : \ {
: ' red ' ,
borderStyle : ' solid '
\ }
< /code></pre >
< p > To turn off the border , use < code > border : false</code>.</p > % }
Defaults to : [ true ]
be a CSS style specification for each style, for example: '10 5 3 10' (top, right, bottom, left).</p>
<p>For components that have no border by default, setting this won't make the border appear by itself.
You also need to specify border color and style:</p>
<pre><code>border: 5,
style: \{
borderColor: 'red',
borderStyle: 'solid'
\}
</code></pre>
<p>To turn off the border, use <code>border: false</code>.</p> %}
Defaults to: [true]
*)
method componentLayout : _ Js.t Js.prop
* { % < p > The sizing and positioning of a Component 's internal Elements is the responsibility of the Component 's layout
manager which sizes a Component 's internal structure in response to the Component being sized.</p >
< p > Generally , developers will not use this configuration as all provided Components which need their internal
elements sizing ( Such as < a href="#!/api / Ext.form.field . Base " rel="Ext.form.field . Base " class="docClass">input fields</a > ) come with their own componentLayout managers.</p >
< p > The < a href="#!/api / Ext.layout.container . Auto " rel="Ext.layout.container . Auto " class="docClass">default layout manager</a > will be used on instances of the base < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a >
class which simply sizes the Component 's encapsulating element to the height and width specified in the
< a href="#!/api / Ext.panel . AbstractPanel - method - setSize " rel="Ext.panel . AbstractPanel - method - setSize " class="docClass">setSize</a > method.</p > % }
Defaults to : [ ' dock ' ]
manager which sizes a Component's internal structure in response to the Component being sized.</p>
<p>Generally, developers will not use this configuration as all provided Components which need their internal
elements sizing (Such as <a href="#!/api/Ext.form.field.Base" rel="Ext.form.field.Base" class="docClass">input fields</a>) come with their own componentLayout managers.</p>
<p>The <a href="#!/api/Ext.layout.container.Auto" rel="Ext.layout.container.Auto" class="docClass">default layout manager</a> will be used on instances of the base <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a>
class which simply sizes the Component's encapsulating element to the height and width specified in the
<a href="#!/api/Ext.panel.AbstractPanel-method-setSize" rel="Ext.panel.AbstractPanel-method-setSize" class="docClass">setSize</a> method.</p> %}
Defaults to: ['dock']
*)
method dockedItems : _ Js.t Js.prop
* { % < p > A component or series of components to be added as docked items to this panel .
The docked items can be docked to either the top , right , left or bottom of a panel .
This is typically used for things like toolbars or tab >
< pre><code > var panel = new < a href="#!/api / Ext.panel . Panel " rel="Ext.panel . Panel " class="docClass">Ext.panel . Panel</a>(\ {
fullscreen : true ,
dockedItems : [ \ {
: ' toolbar ' ,
dock : ' top ' ,
items : [ \ {
text : ' Docked to the top '
\ } ]
\ } ]
\});</code></pre > % }
The docked items can be docked to either the top, right, left or bottom of a panel.
This is typically used for things like toolbars or tab bars:</p>
<pre><code>var panel = new <a href="#!/api/Ext.panel.Panel" rel="Ext.panel.Panel" class="docClass">Ext.panel.Panel</a>(\{
fullscreen: true,
dockedItems: [\{
xtype: 'toolbar',
dock: 'top',
items: [\{
text: 'Docked to the top'
\}]
\}]
\});</code></pre> %}
*)
method renderTpl : _ Js.t Js.prop
* { % < p > An < a href="#!/api / Ext . XTemplate " rel="Ext . XTemplate " class="docClass">XTemplate</a > used to create the internal structure inside this Component 's encapsulating
< a href="#!/api / Ext.panel . AbstractPanel - method - getEl " rel="Ext.panel . AbstractPanel - method - getEl " class="docClass">Element</a>.</p >
< p > You do not normally need to specify this . For the base classes < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > and
< a href="#!/api / Ext.container . Container " rel="Ext.container . Container " class="docClass">Ext.container . Container</a > , this defaults to < strong><code > null</code></strong > which means that they will be initially rendered
with no internal structure ; they render their < a href="#!/api / Ext.panel . AbstractPanel - method - getEl " rel="Ext.panel . AbstractPanel - method - getEl " class="docClass">Element</a > empty . The more specialized Ext JS and Sencha Touch
classes which use a more complex DOM structure , provide their own template definitions.</p >
< p > This is intended to allow the developer to create application - specific utility Components with customized
internal structure.</p >
< p > Upon rendering , any created child elements may be automatically imported into object properties using the
< a href="#!/api / Ext.panel . AbstractPanel - cfg - renderSelectors " rel="Ext.panel . AbstractPanel - cfg - renderSelectors " class="docClass">renderSelectors</a > and < a href="#!/api / Ext.panel . AbstractPanel - cfg - childEls " rel="Ext.panel . AbstractPanel - cfg - childEls " class="docClass">childEls</a > options.</p > % }
<a href="#!/api/Ext.panel.AbstractPanel-method-getEl" rel="Ext.panel.AbstractPanel-method-getEl" class="docClass">Element</a>.</p>
<p>You do not normally need to specify this. For the base classes <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> and
<a href="#!/api/Ext.container.Container" rel="Ext.container.Container" class="docClass">Ext.container.Container</a>, this defaults to <strong><code>null</code></strong> which means that they will be initially rendered
with no internal structure; they render their <a href="#!/api/Ext.panel.AbstractPanel-method-getEl" rel="Ext.panel.AbstractPanel-method-getEl" class="docClass">Element</a> empty. The more specialized Ext JS and Sencha Touch
classes which use a more complex DOM structure, provide their own template definitions.</p>
<p>This is intended to allow the developer to create application-specific utility Components with customized
internal structure.</p>
<p>Upon rendering, any created child elements may be automatically imported into object properties using the
<a href="#!/api/Ext.panel.AbstractPanel-cfg-renderSelectors" rel="Ext.panel.AbstractPanel-cfg-renderSelectors" class="docClass">renderSelectors</a> and <a href="#!/api/Ext.panel.AbstractPanel-cfg-childEls" rel="Ext.panel.AbstractPanel-cfg-childEls" class="docClass">childEls</a> options.</p> %}
*)
method shrinkWrapDock : _ Js.t Js.prop
* { % < p > Allows for this panel to include the < a href="#!/api / Ext.panel . AbstractPanel - cfg - dockedItems " rel="Ext.panel . AbstractPanel - cfg - dockedItems " class="docClass">dockedItems</a > when trying to determine the overall
size of the panel . This option is only applicable when this panel is also shrink wrapping in the
same dimensions . See < a href="#!/api / Ext . AbstractComponent - cfg - shrinkWrap " rel="Ext . " class="docClass">Ext . > for an explanation of the configuration options.</p > % }
Defaults to : [ false ]
size of the panel. This option is only applicable when this panel is also shrink wrapping in the
same dimensions. See <a href="#!/api/Ext.AbstractComponent-cfg-shrinkWrap" rel="Ext.AbstractComponent-cfg-shrinkWrap" class="docClass">Ext.AbstractComponent.shrinkWrap</a> for an explanation of the configuration options.</p> %}
Defaults to: [false]
*)
method beforeDestroy : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method initComponent : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
end
class type events =
object
inherit Ext_container_Container.events
inherit Ext_container_DockingContainer.events
end
class type statics =
object
inherit Ext_container_Container.statics
inherit Ext_container_DockingContainer.statics
end
val of_configs : configs Js.t -> t Js.t
val to_configs : t Js.t -> configs Js.t
|
8b26ff9488258a1964ace1a241b516b5ea5ccbd010037c499e45b754460247ad | CUTE-Lang/miniCUTE | Step.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE StandaloneDeriving #
-- |
Copyright : ( c ) 2018 - present
-- License: BSD 3-Clause
module Minicute.Control.GMachine.Step
( module Minicute.Data.GMachine.State
, GMachineStepMonadT
, GMachineStepMonad
, runGMachineStepT
, execGMachineStepT
) where
import Control.Monad.State ( MonadState, StateT, execStateT, runStateT )
import Control.Monad.Trans ( MonadTrans )
import Data.Data ( Typeable )
import GHC.Generics ( Generic )
import Minicute.Data.GMachine.State
type GMachineStepMonad = GMachineStepMonadT IO
newtype GMachineStepMonadT m a
= GMachineStepMonadT
{ runGMachineStepMonadT :: StateT GMachineState m a
}
deriving ( Generic
, Typeable
, Functor
, Applicative
, Monad
, MonadFail
, MonadTrans
)
deriving instance (Monad m) => MonadState GMachineState (GMachineStepMonadT m)
runGMachineStepT :: GMachineStepMonadT m a -> GMachineState -> m (a, GMachineState)
runGMachineStepT = runStateT . runGMachineStepMonadT
# INLINE runGMachineStepT #
execGMachineStepT :: (Monad m) => GMachineStepMonadT m a -> GMachineState -> m GMachineState
execGMachineStepT = execStateT . runGMachineStepMonadT
{-# INLINE execGMachineStepT #-}
| null | https://raw.githubusercontent.com/CUTE-Lang/miniCUTE/b6c8a48b10e2af0786a50175d57b5339be7be2de/main-packages/g-machine-interpreter/lib/Minicute/Control/GMachine/Step.hs | haskell | |
License: BSD 3-Clause
# INLINE execGMachineStepT # | # LANGUAGE DeriveGeneric #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE StandaloneDeriving #
Copyright : ( c ) 2018 - present
module Minicute.Control.GMachine.Step
( module Minicute.Data.GMachine.State
, GMachineStepMonadT
, GMachineStepMonad
, runGMachineStepT
, execGMachineStepT
) where
import Control.Monad.State ( MonadState, StateT, execStateT, runStateT )
import Control.Monad.Trans ( MonadTrans )
import Data.Data ( Typeable )
import GHC.Generics ( Generic )
import Minicute.Data.GMachine.State
type GMachineStepMonad = GMachineStepMonadT IO
newtype GMachineStepMonadT m a
= GMachineStepMonadT
{ runGMachineStepMonadT :: StateT GMachineState m a
}
deriving ( Generic
, Typeable
, Functor
, Applicative
, Monad
, MonadFail
, MonadTrans
)
deriving instance (Monad m) => MonadState GMachineState (GMachineStepMonadT m)
runGMachineStepT :: GMachineStepMonadT m a -> GMachineState -> m (a, GMachineState)
runGMachineStepT = runStateT . runGMachineStepMonadT
# INLINE runGMachineStepT #
execGMachineStepT :: (Monad m) => GMachineStepMonadT m a -> GMachineState -> m GMachineState
execGMachineStepT = execStateT . runGMachineStepMonadT
|
234504778ab60050aa3903b3a0056e78d5ac5722965e8122b80226ea6d749eb5 | 6502/JSLisp | spiral.lisp | (defun main ()
(let** ((canvas (create-element "canvas"))
(ctx (canvas.getContext "2d"))
(#'repaint ()
(let** ((w canvas.offsetWidth)
(h canvas.offsetHeight)
(cx (/ w 2))
(cy (/ h 2))
(colors (list "#14FFA5"
"#FF00FF"
"#FF00FF"
"#FF00FF"
"#FF9921"
"#FF9921"
"#14FFA5"
"#FF9921")))
(setf canvas.width w)
(setf canvas.height h)
(setf ctx.fillStyle "#000000")
(dotimes (y h)
(dotimes (x w)
(let** ((dx (- x cx))
(dy (- y cy))
(a (atan2 dy dx))
(r (sqrt (+ (* dx dx) (* dy dy))))
(c1 (logand 1 (floor (+ (* 32 (log r))
(* a (/ 24 2 pi))))))
(c2 (logand 3 (floor (+ (* 4 (log r))
(* a (/ -12 2 pi)))))))
(setf ctx.fillStyle (aref colors (+ (* 4 c1) c2)))
(ctx.fillRect x y 1 1)))))))
(setf canvas.style.width "1024px")
(setf canvas.style.height "1024px")
(setf document.body.innerHTML "")
(append-child document.body canvas)
(repaint)))
(main) | null | https://raw.githubusercontent.com/6502/JSLisp/9a4aa1a9116f0cfc598ec9f3f30b59d99810a728/examples/spiral.lisp | lisp | (defun main ()
(let** ((canvas (create-element "canvas"))
(ctx (canvas.getContext "2d"))
(#'repaint ()
(let** ((w canvas.offsetWidth)
(h canvas.offsetHeight)
(cx (/ w 2))
(cy (/ h 2))
(colors (list "#14FFA5"
"#FF00FF"
"#FF00FF"
"#FF00FF"
"#FF9921"
"#FF9921"
"#14FFA5"
"#FF9921")))
(setf canvas.width w)
(setf canvas.height h)
(setf ctx.fillStyle "#000000")
(dotimes (y h)
(dotimes (x w)
(let** ((dx (- x cx))
(dy (- y cy))
(a (atan2 dy dx))
(r (sqrt (+ (* dx dx) (* dy dy))))
(c1 (logand 1 (floor (+ (* 32 (log r))
(* a (/ 24 2 pi))))))
(c2 (logand 3 (floor (+ (* 4 (log r))
(* a (/ -12 2 pi)))))))
(setf ctx.fillStyle (aref colors (+ (* 4 c1) c2)))
(ctx.fillRect x y 1 1)))))))
(setf canvas.style.width "1024px")
(setf canvas.style.height "1024px")
(setf document.body.innerHTML "")
(append-child document.body canvas)
(repaint)))
(main) | |
c1d459a2526d1165b72148fb71e39ccbd226e2304c33a1e9c9b58923ec9ce509 | SimulaVR/godot-haskell | Animation.hs | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.Animation
(Godot.Core.Animation._TYPE_BEZIER,
Godot.Core.Animation._INTERPOLATION_NEAREST,
Godot.Core.Animation._UPDATE_DISCRETE,
Godot.Core.Animation._INTERPOLATION_LINEAR,
Godot.Core.Animation._TYPE_VALUE,
Godot.Core.Animation._UPDATE_CAPTURE,
Godot.Core.Animation._TYPE_METHOD,
Godot.Core.Animation._UPDATE_CONTINUOUS,
Godot.Core.Animation._INTERPOLATION_CUBIC,
Godot.Core.Animation._TYPE_TRANSFORM,
Godot.Core.Animation._UPDATE_TRIGGER,
Godot.Core.Animation._TYPE_AUDIO,
Godot.Core.Animation._TYPE_ANIMATION,
Godot.Core.Animation.sig_tracks_changed,
Godot.Core.Animation.add_track,
Godot.Core.Animation.animation_track_get_key_animation,
Godot.Core.Animation.animation_track_insert_key,
Godot.Core.Animation.animation_track_set_key_animation,
Godot.Core.Animation.audio_track_get_key_end_offset,
Godot.Core.Animation.audio_track_get_key_start_offset,
Godot.Core.Animation.audio_track_get_key_stream,
Godot.Core.Animation.audio_track_insert_key,
Godot.Core.Animation.audio_track_set_key_end_offset,
Godot.Core.Animation.audio_track_set_key_start_offset,
Godot.Core.Animation.audio_track_set_key_stream,
Godot.Core.Animation.bezier_track_get_key_in_handle,
Godot.Core.Animation.bezier_track_get_key_out_handle,
Godot.Core.Animation.bezier_track_get_key_value,
Godot.Core.Animation.bezier_track_insert_key,
Godot.Core.Animation.bezier_track_interpolate,
Godot.Core.Animation.bezier_track_set_key_in_handle,
Godot.Core.Animation.bezier_track_set_key_out_handle,
Godot.Core.Animation.bezier_track_set_key_value,
Godot.Core.Animation.clear, Godot.Core.Animation.copy_track,
Godot.Core.Animation.find_track, Godot.Core.Animation.get_length,
Godot.Core.Animation.get_step,
Godot.Core.Animation.get_track_count,
Godot.Core.Animation.has_loop,
Godot.Core.Animation.method_track_get_key_indices,
Godot.Core.Animation.method_track_get_name,
Godot.Core.Animation.method_track_get_params,
Godot.Core.Animation.remove_track, Godot.Core.Animation.set_length,
Godot.Core.Animation.set_loop, Godot.Core.Animation.set_step,
Godot.Core.Animation.track_find_key,
Godot.Core.Animation.track_get_interpolation_loop_wrap,
Godot.Core.Animation.track_get_interpolation_type,
Godot.Core.Animation.track_get_key_count,
Godot.Core.Animation.track_get_key_time,
Godot.Core.Animation.track_get_key_transition,
Godot.Core.Animation.track_get_key_value,
Godot.Core.Animation.track_get_path,
Godot.Core.Animation.track_get_type,
Godot.Core.Animation.track_insert_key,
Godot.Core.Animation.track_is_enabled,
Godot.Core.Animation.track_is_imported,
Godot.Core.Animation.track_move_down,
Godot.Core.Animation.track_move_to,
Godot.Core.Animation.track_move_up,
Godot.Core.Animation.track_remove_key,
Godot.Core.Animation.track_remove_key_at_position,
Godot.Core.Animation.track_set_enabled,
Godot.Core.Animation.track_set_imported,
Godot.Core.Animation.track_set_interpolation_loop_wrap,
Godot.Core.Animation.track_set_interpolation_type,
Godot.Core.Animation.track_set_key_time,
Godot.Core.Animation.track_set_key_transition,
Godot.Core.Animation.track_set_key_value,
Godot.Core.Animation.track_set_path,
Godot.Core.Animation.track_swap,
Godot.Core.Animation.transform_track_insert_key,
Godot.Core.Animation.transform_track_interpolate,
Godot.Core.Animation.value_track_get_key_indices,
Godot.Core.Animation.value_track_get_update_mode,
Godot.Core.Animation.value_track_set_update_mode)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Resource()
_TYPE_BEZIER :: Int
_TYPE_BEZIER = 3
_INTERPOLATION_NEAREST :: Int
_INTERPOLATION_NEAREST = 0
_UPDATE_DISCRETE :: Int
_UPDATE_DISCRETE = 1
_INTERPOLATION_LINEAR :: Int
_INTERPOLATION_LINEAR = 1
_TYPE_VALUE :: Int
_TYPE_VALUE = 0
_UPDATE_CAPTURE :: Int
_UPDATE_CAPTURE = 3
_TYPE_METHOD :: Int
_TYPE_METHOD = 2
_UPDATE_CONTINUOUS :: Int
_UPDATE_CONTINUOUS = 0
_INTERPOLATION_CUBIC :: Int
_INTERPOLATION_CUBIC = 2
_TYPE_TRANSFORM :: Int
_TYPE_TRANSFORM = 1
_UPDATE_TRIGGER :: Int
_UPDATE_TRIGGER = 2
_TYPE_AUDIO :: Int
_TYPE_AUDIO = 4
_TYPE_ANIMATION :: Int
_TYPE_ANIMATION = 5
-- | Emitted when there's a change in the list of tracks, e.g. tracks are added, moved or have changed paths.
sig_tracks_changed :: Godot.Internal.Dispatch.Signal Animation
sig_tracks_changed
= Godot.Internal.Dispatch.Signal "tracks_changed"
instance NodeSignal Animation "tracks_changed" '[]
instance NodeProperty Animation "length" Float 'False where
nodeProperty = (get_length, wrapDroppingSetter set_length, Nothing)
instance NodeProperty Animation "loop" Bool 'False where
nodeProperty = (has_loop, wrapDroppingSetter set_loop, Nothing)
instance NodeProperty Animation "step" Float 'False where
nodeProperty = (get_step, wrapDroppingSetter set_step, Nothing)
# NOINLINE bindAnimation_add_track #
| Adds a track to the Animation .
bindAnimation_add_track :: MethodBind
bindAnimation_add_track
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "add_track" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Adds a track to the Animation .
add_track ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Maybe Int -> IO Int
add_track cls arg1 arg2
= withVariantArray
[toVariant arg1, maybe (VariantInt (-1)) toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_add_track (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "add_track" '[Int, Maybe Int]
(IO Int)
where
nodeMethod = Godot.Core.Animation.add_track
# NOINLINE bindAnimation_animation_track_get_key_animation #
| Returns the animation name at the key identified by @key_idx@. The must be the index of an Animation Track .
bindAnimation_animation_track_get_key_animation :: MethodBind
bindAnimation_animation_track_get_key_animation
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "animation_track_get_key_animation" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the animation name at the key identified by @key_idx@. The must be the index of an Animation Track .
animation_track_get_key_animation ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO GodotString
animation_track_get_key_animation cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_animation_track_get_key_animation
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "animation_track_get_key_animation"
'[Int, Int]
(IO GodotString)
where
nodeMethod = Godot.Core.Animation.animation_track_get_key_animation
# NOINLINE bindAnimation_animation_track_insert_key #
| Inserts a key with value @animation@ at the given @time@ ( in seconds ) . The must be the index of an Animation Track .
bindAnimation_animation_track_insert_key :: MethodBind
bindAnimation_animation_track_insert_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "animation_track_insert_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Inserts a key with value @animation@ at the given @time@ ( in seconds ) . The must be the index of an Animation Track .
animation_track_insert_key ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> GodotString -> IO Int
animation_track_insert_key cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_animation_track_insert_key
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "animation_track_insert_key"
'[Int, Float, GodotString]
(IO Int)
where
nodeMethod = Godot.Core.Animation.animation_track_insert_key
# NOINLINE bindAnimation_animation_track_set_key_animation #
| Sets the key identified by @key_idx@ to value @animation@. The must be the index of an Animation Track .
bindAnimation_animation_track_set_key_animation :: MethodBind
bindAnimation_animation_track_set_key_animation
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "animation_track_set_key_animation" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the key identified by @key_idx@ to value @animation@. The must be the index of an Animation Track .
animation_track_set_key_animation ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> GodotString -> IO ()
animation_track_set_key_animation cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_animation_track_set_key_animation
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "animation_track_set_key_animation"
'[Int, Int, GodotString]
(IO ())
where
nodeMethod = Godot.Core.Animation.animation_track_set_key_animation
# NOINLINE bindAnimation_audio_track_get_key_end_offset #
| Returns the end offset of the key identified by @key_idx@. The must be the index of an Audio Track .
End offset is the number of seconds cut off at the ending of the audio stream .
bindAnimation_audio_track_get_key_end_offset :: MethodBind
bindAnimation_audio_track_get_key_end_offset
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_get_key_end_offset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the end offset of the key identified by @key_idx@. The must be the index of an Audio Track .
End offset is the number of seconds cut off at the ending of the audio stream .
audio_track_get_key_end_offset ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO Float
audio_track_get_key_end_offset cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_audio_track_get_key_end_offset
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_get_key_end_offset"
'[Int, Int]
(IO Float)
where
nodeMethod = Godot.Core.Animation.audio_track_get_key_end_offset
# NOINLINE bindAnimation_audio_track_get_key_start_offset #
| Returns the start offset of the key identified by @key_idx@. The must be the index of an Audio Track .
Start offset is the number of seconds cut off at the beginning of the audio stream .
bindAnimation_audio_track_get_key_start_offset :: MethodBind
bindAnimation_audio_track_get_key_start_offset
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_get_key_start_offset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the start offset of the key identified by @key_idx@. The must be the index of an Audio Track .
Start offset is the number of seconds cut off at the beginning of the audio stream .
audio_track_get_key_start_offset ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO Float
audio_track_get_key_start_offset cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_audio_track_get_key_start_offset
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_get_key_start_offset"
'[Int, Int]
(IO Float)
where
nodeMethod = Godot.Core.Animation.audio_track_get_key_start_offset
# NOINLINE bindAnimation_audio_track_get_key_stream #
| Returns the audio stream of the key identified by @key_idx@. The must be the index of an Audio Track .
bindAnimation_audio_track_get_key_stream :: MethodBind
bindAnimation_audio_track_get_key_stream
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_get_key_stream" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the audio stream of the key identified by @key_idx@. The must be the index of an Audio Track .
audio_track_get_key_stream ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO Resource
audio_track_get_key_stream cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_audio_track_get_key_stream
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_get_key_stream"
'[Int, Int]
(IO Resource)
where
nodeMethod = Godot.Core.Animation.audio_track_get_key_stream
# NOINLINE bindAnimation_audio_track_insert_key #
| Inserts an Audio Track key at the given @time@ in seconds . The must be the index of an Audio Track .
@stream@ is the @AudioStream@ resource to play . @start_offset@ is the number of seconds cut off at the beginning of the audio stream , while @end_offset@ is at the ending .
bindAnimation_audio_track_insert_key :: MethodBind
bindAnimation_audio_track_insert_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_insert_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Inserts an Audio Track key at the given @time@ in seconds . The must be the index of an Audio Track .
@stream@ is the @AudioStream@ resource to play . @start_offset@ is the number of seconds cut off at the beginning of the audio stream , while @end_offset@ is at the ending .
audio_track_insert_key ::
(Animation :< cls, Object :< cls) =>
cls ->
Int -> Float -> Resource -> Maybe Float -> Maybe Float -> IO Int
audio_track_insert_key cls arg1 arg2 arg3 arg4 arg5
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3,
maybe (VariantReal (0)) toVariant arg4,
maybe (VariantReal (0)) toVariant arg5]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_audio_track_insert_key
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_insert_key"
'[Int, Float, Resource, Maybe Float, Maybe Float]
(IO Int)
where
nodeMethod = Godot.Core.Animation.audio_track_insert_key
# NOINLINE bindAnimation_audio_track_set_key_end_offset #
| Sets the end offset of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
bindAnimation_audio_track_set_key_end_offset :: MethodBind
bindAnimation_audio_track_set_key_end_offset
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_set_key_end_offset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the end offset of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
audio_track_set_key_end_offset ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Float -> IO ()
audio_track_set_key_end_offset cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_audio_track_set_key_end_offset
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_set_key_end_offset"
'[Int, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.audio_track_set_key_end_offset
# NOINLINE bindAnimation_audio_track_set_key_start_offset #
| Sets the start offset of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
bindAnimation_audio_track_set_key_start_offset :: MethodBind
bindAnimation_audio_track_set_key_start_offset
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_set_key_start_offset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the start offset of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
audio_track_set_key_start_offset ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Float -> IO ()
audio_track_set_key_start_offset cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_audio_track_set_key_start_offset
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_set_key_start_offset"
'[Int, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.audio_track_set_key_start_offset
# NOINLINE bindAnimation_audio_track_set_key_stream #
| Sets the stream of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
bindAnimation_audio_track_set_key_stream :: MethodBind
bindAnimation_audio_track_set_key_stream
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_set_key_stream" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the stream of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
audio_track_set_key_stream ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Resource -> IO ()
audio_track_set_key_stream cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_audio_track_set_key_stream
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_set_key_stream"
'[Int, Int, Resource]
(IO ())
where
nodeMethod = Godot.Core.Animation.audio_track_set_key_stream
# NOINLINE bindAnimation_bezier_track_get_key_in_handle #
| Returns the in handle of the key identified by @key_idx@. The must be the index of a Bezier Track .
bindAnimation_bezier_track_get_key_in_handle :: MethodBind
bindAnimation_bezier_track_get_key_in_handle
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_get_key_in_handle" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the in handle of the key identified by @key_idx@. The must be the index of a Bezier Track .
bezier_track_get_key_in_handle ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO Vector2
bezier_track_get_key_in_handle cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_get_key_in_handle
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_get_key_in_handle"
'[Int, Int]
(IO Vector2)
where
nodeMethod = Godot.Core.Animation.bezier_track_get_key_in_handle
{-# NOINLINE bindAnimation_bezier_track_get_key_out_handle #-}
| Returns the out handle of the key identified by @key_idx@. The must be the index of a Bezier Track .
bindAnimation_bezier_track_get_key_out_handle :: MethodBind
bindAnimation_bezier_track_get_key_out_handle
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_get_key_out_handle" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the out handle of the key identified by @key_idx@. The must be the index of a Bezier Track .
bezier_track_get_key_out_handle ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO Vector2
bezier_track_get_key_out_handle cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_bezier_track_get_key_out_handle
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_get_key_out_handle"
'[Int, Int]
(IO Vector2)
where
nodeMethod = Godot.Core.Animation.bezier_track_get_key_out_handle
# NOINLINE bindAnimation_bezier_track_get_key_value #
| Returns the value of the key identified by @key_idx@. The must be the index of a Bezier Track .
bindAnimation_bezier_track_get_key_value :: MethodBind
bindAnimation_bezier_track_get_key_value
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_get_key_value" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the value of the key identified by @key_idx@. The must be the index of a Bezier Track .
bezier_track_get_key_value ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO Float
bezier_track_get_key_value cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_get_key_value
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_get_key_value"
'[Int, Int]
(IO Float)
where
nodeMethod = Godot.Core.Animation.bezier_track_get_key_value
# NOINLINE bindAnimation_bezier_track_insert_key #
| Inserts a Bezier Track key at the given @time@ in seconds . The must be the index of a Bezier Track .
@in_handle@ is the left - side weight of the added curve point , @out_handle@ is the right - side one , while @value@ is the actual value at this point .
bindAnimation_bezier_track_insert_key :: MethodBind
bindAnimation_bezier_track_insert_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_insert_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Inserts a Bezier Track key at the given @time@ in seconds . The must be the index of a Bezier Track .
@in_handle@ is the left - side weight of the added curve point , @out_handle@ is the right - side one , while @value@ is the actual value at this point .
bezier_track_insert_key ::
(Animation :< cls, Object :< cls) =>
cls ->
Int -> Float -> Float -> Maybe Vector2 -> Maybe Vector2 -> IO Int
bezier_track_insert_key cls arg1 arg2 arg3 arg4 arg5
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3,
defaultedVariant VariantVector2 (V2 0 0) arg4,
defaultedVariant VariantVector2 (V2 0 0) arg5]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_insert_key
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_insert_key"
'[Int, Float, Float, Maybe Vector2, Maybe Vector2]
(IO Int)
where
nodeMethod = Godot.Core.Animation.bezier_track_insert_key
# NOINLINE bindAnimation_bezier_track_interpolate #
| Returns the interpolated value at the given @time@ ( in seconds ) . The must be the index of a Bezier Track .
bindAnimation_bezier_track_interpolate :: MethodBind
bindAnimation_bezier_track_interpolate
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_interpolate" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the interpolated value at the given @time@ ( in seconds ) . The must be the index of a Bezier Track .
bezier_track_interpolate ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> IO Float
bezier_track_interpolate cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_interpolate
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_interpolate"
'[Int, Float]
(IO Float)
where
nodeMethod = Godot.Core.Animation.bezier_track_interpolate
# NOINLINE bindAnimation_bezier_track_set_key_in_handle #
| Sets the in handle of the key identified by @key_idx@ to value @in_handle@. The must be the index of a Bezier Track .
bindAnimation_bezier_track_set_key_in_handle :: MethodBind
bindAnimation_bezier_track_set_key_in_handle
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_set_key_in_handle" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the in handle of the key identified by @key_idx@ to value @in_handle@. The must be the index of a Bezier Track .
bezier_track_set_key_in_handle ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Vector2 -> IO ()
bezier_track_set_key_in_handle cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_set_key_in_handle
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_set_key_in_handle"
'[Int, Int, Vector2]
(IO ())
where
nodeMethod = Godot.Core.Animation.bezier_track_set_key_in_handle
# NOINLINE bindAnimation_bezier_track_set_key_out_handle #
| Sets the out handle of the key identified by @key_idx@ to value @out_handle@. The must be the index of a Bezier Track .
bindAnimation_bezier_track_set_key_out_handle :: MethodBind
bindAnimation_bezier_track_set_key_out_handle
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_set_key_out_handle" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the out handle of the key identified by @key_idx@ to value @out_handle@. The must be the index of a Bezier Track .
bezier_track_set_key_out_handle ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Vector2 -> IO ()
bezier_track_set_key_out_handle cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_bezier_track_set_key_out_handle
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_set_key_out_handle"
'[Int, Int, Vector2]
(IO ())
where
nodeMethod = Godot.Core.Animation.bezier_track_set_key_out_handle
# NOINLINE bindAnimation_bezier_track_set_key_value #
| Sets the value of the key identified by @key_idx@ to the given value . The must be the index of a Bezier Track .
bindAnimation_bezier_track_set_key_value :: MethodBind
bindAnimation_bezier_track_set_key_value
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_set_key_value" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the value of the key identified by @key_idx@ to the given value . The must be the index of a Bezier Track .
bezier_track_set_key_value ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Float -> IO ()
bezier_track_set_key_value cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_set_key_value
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_set_key_value"
'[Int, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.bezier_track_set_key_value
# NOINLINE bindAnimation_clear #
-- | Clear the animation (clear all tracks and reset all).
bindAnimation_clear :: MethodBind
bindAnimation_clear
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "clear" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Clear the animation (clear all tracks and reset all).
clear :: (Animation :< cls, Object :< cls) => cls -> IO ()
clear cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_clear (upcast cls) arrPtr len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "clear" '[] (IO ()) where
nodeMethod = Godot.Core.Animation.clear
# NOINLINE bindAnimation_copy_track #
-- | Adds a new track that is a copy of the given track from @to_animation@.
bindAnimation_copy_track :: MethodBind
bindAnimation_copy_track
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "copy_track" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Adds a new track that is a copy of the given track from @to_animation@.
copy_track ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Animation -> IO ()
copy_track cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_copy_track (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "copy_track" '[Int, Animation]
(IO ())
where
nodeMethod = Godot.Core.Animation.copy_track
# NOINLINE bindAnimation_find_track #
-- | Returns the index of the specified track. If the track is not found, return -1.
bindAnimation_find_track :: MethodBind
bindAnimation_find_track
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "find_track" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the index of the specified track. If the track is not found, return -1.
find_track ::
(Animation :< cls, Object :< cls) => cls -> NodePath -> IO Int
find_track cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_find_track (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "find_track" '[NodePath] (IO Int)
where
nodeMethod = Godot.Core.Animation.find_track
# NOINLINE bindAnimation_get_length #
| The total length of the animation ( in seconds ) .
-- __Note:__ Length is not delimited by the last key, as this one may be before or after the end to ensure correct interpolation and looping.
bindAnimation_get_length :: MethodBind
bindAnimation_get_length
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "get_length" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The total length of the animation ( in seconds ) .
-- __Note:__ Length is not delimited by the last key, as this one may be before or after the end to ensure correct interpolation and looping.
get_length :: (Animation :< cls, Object :< cls) => cls -> IO Float
get_length cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_get_length (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "get_length" '[] (IO Float) where
nodeMethod = Godot.Core.Animation.get_length
# NOINLINE bindAnimation_get_step #
-- | The animation step value.
bindAnimation_get_step :: MethodBind
bindAnimation_get_step
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "get_step" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The animation step value.
get_step :: (Animation :< cls, Object :< cls) => cls -> IO Float
get_step cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_get_step (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "get_step" '[] (IO Float) where
nodeMethod = Godot.Core.Animation.get_step
# NOINLINE bindAnimation_get_track_count #
-- | Returns the amount of tracks in the animation.
bindAnimation_get_track_count :: MethodBind
bindAnimation_get_track_count
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "get_track_count" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the amount of tracks in the animation.
get_track_count ::
(Animation :< cls, Object :< cls) => cls -> IO Int
get_track_count cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_get_track_count (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "get_track_count" '[] (IO Int) where
nodeMethod = Godot.Core.Animation.get_track_count
# NOINLINE bindAnimation_has_loop #
-- | A flag indicating that the animation must loop. This is uses for correct interpolation of animation cycles, and for hinting the player that it must restart the animation.
bindAnimation_has_loop :: MethodBind
bindAnimation_has_loop
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "has_loop" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | A flag indicating that the animation must loop. This is uses for correct interpolation of animation cycles, and for hinting the player that it must restart the animation.
has_loop :: (Animation :< cls, Object :< cls) => cls -> IO Bool
has_loop cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_has_loop (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "has_loop" '[] (IO Bool) where
nodeMethod = Godot.Core.Animation.has_loop
# NOINLINE bindAnimation_method_track_get_key_indices #
-- | Returns all the key indices of a method track, given a position and delta time.
bindAnimation_method_track_get_key_indices :: MethodBind
bindAnimation_method_track_get_key_indices
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "method_track_get_key_indices" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns all the key indices of a method track, given a position and delta time.
method_track_get_key_indices ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> Float -> IO PoolIntArray
method_track_get_key_indices cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_method_track_get_key_indices
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "method_track_get_key_indices"
'[Int, Float, Float]
(IO PoolIntArray)
where
nodeMethod = Godot.Core.Animation.method_track_get_key_indices
# NOINLINE bindAnimation_method_track_get_name #
-- | Returns the method name of a method track.
bindAnimation_method_track_get_name :: MethodBind
bindAnimation_method_track_get_name
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "method_track_get_name" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the method name of a method track.
method_track_get_name ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO GodotString
method_track_get_name cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_method_track_get_name
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "method_track_get_name" '[Int, Int]
(IO GodotString)
where
nodeMethod = Godot.Core.Animation.method_track_get_name
# NOINLINE bindAnimation_method_track_get_params #
-- | Returns the arguments values to be called on a method track for a given key in a given track.
bindAnimation_method_track_get_params :: MethodBind
bindAnimation_method_track_get_params
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "method_track_get_params" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the arguments values to be called on a method track for a given key in a given track.
method_track_get_params ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO Array
method_track_get_params cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_method_track_get_params
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "method_track_get_params" '[Int, Int]
(IO Array)
where
nodeMethod = Godot.Core.Animation.method_track_get_params
# NOINLINE bindAnimation_remove_track #
-- | Removes a track by specifying the track index.
bindAnimation_remove_track :: MethodBind
bindAnimation_remove_track
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "remove_track" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Removes a track by specifying the track index.
remove_track ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO ()
remove_track cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_remove_track (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "remove_track" '[Int] (IO ()) where
nodeMethod = Godot.Core.Animation.remove_track
# NOINLINE bindAnimation_set_length #
| The total length of the animation ( in seconds ) .
-- __Note:__ Length is not delimited by the last key, as this one may be before or after the end to ensure correct interpolation and looping.
bindAnimation_set_length :: MethodBind
bindAnimation_set_length
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "set_length" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The total length of the animation ( in seconds ) .
-- __Note:__ Length is not delimited by the last key, as this one may be before or after the end to ensure correct interpolation and looping.
set_length ::
(Animation :< cls, Object :< cls) => cls -> Float -> IO ()
set_length cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_set_length (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "set_length" '[Float] (IO ()) where
nodeMethod = Godot.Core.Animation.set_length
# NOINLINE bindAnimation_set_loop #
-- | A flag indicating that the animation must loop. This is uses for correct interpolation of animation cycles, and for hinting the player that it must restart the animation.
bindAnimation_set_loop :: MethodBind
bindAnimation_set_loop
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "set_loop" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | A flag indicating that the animation must loop. This is uses for correct interpolation of animation cycles, and for hinting the player that it must restart the animation.
set_loop ::
(Animation :< cls, Object :< cls) => cls -> Bool -> IO ()
set_loop cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_set_loop (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "set_loop" '[Bool] (IO ()) where
nodeMethod = Godot.Core.Animation.set_loop
# NOINLINE bindAnimation_set_step #
-- | The animation step value.
bindAnimation_set_step :: MethodBind
bindAnimation_set_step
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "set_step" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The animation step value.
set_step ::
(Animation :< cls, Object :< cls) => cls -> Float -> IO ()
set_step cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_set_step (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "set_step" '[Float] (IO ()) where
nodeMethod = Godot.Core.Animation.set_step
# NOINLINE bindAnimation_track_find_key #
-- | Finds the key index by time in a given track. Optionally, only find it if the exact time is given.
bindAnimation_track_find_key :: MethodBind
bindAnimation_track_find_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_find_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Finds the key index by time in a given track. Optionally, only find it if the exact time is given.
track_find_key ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> Maybe Bool -> IO Int
track_find_key cls arg1 arg2 arg3
= withVariantArray
[toVariant arg1, toVariant arg2,
maybe (VariantBool False) toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_find_key (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_find_key"
'[Int, Float, Maybe Bool]
(IO Int)
where
nodeMethod = Godot.Core.Animation.track_find_key
# NOINLINE bindAnimation_track_get_interpolation_loop_wrap #
| Returns @true@ if the track at @idx@ wraps the interpolation loop . New tracks wrap the interpolation loop by default .
bindAnimation_track_get_interpolation_loop_wrap :: MethodBind
bindAnimation_track_get_interpolation_loop_wrap
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_interpolation_loop_wrap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns @true@ if the track at @idx@ wraps the interpolation loop . New tracks wrap the interpolation loop by default .
track_get_interpolation_loop_wrap ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Bool
track_get_interpolation_loop_wrap cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_track_get_interpolation_loop_wrap
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_interpolation_loop_wrap"
'[Int]
(IO Bool)
where
nodeMethod = Godot.Core.Animation.track_get_interpolation_loop_wrap
# NOINLINE bindAnimation_track_get_interpolation_type #
-- | Returns the interpolation type of a given track.
bindAnimation_track_get_interpolation_type :: MethodBind
bindAnimation_track_get_interpolation_type
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_interpolation_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the interpolation type of a given track.
track_get_interpolation_type ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Int
track_get_interpolation_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_interpolation_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_interpolation_type" '[Int]
(IO Int)
where
nodeMethod = Godot.Core.Animation.track_get_interpolation_type
# NOINLINE bindAnimation_track_get_key_count #
-- | Returns the amount of keys in a given track.
bindAnimation_track_get_key_count :: MethodBind
bindAnimation_track_get_key_count
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_key_count" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the amount of keys in a given track.
track_get_key_count ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Int
track_get_key_count cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_key_count
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_key_count" '[Int] (IO Int)
where
nodeMethod = Godot.Core.Animation.track_get_key_count
# NOINLINE bindAnimation_track_get_key_time #
-- | Returns the time at which the key is located.
bindAnimation_track_get_key_time :: MethodBind
bindAnimation_track_get_key_time
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_key_time" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the time at which the key is located.
track_get_key_time ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO Float
track_get_key_time cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_key_time
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_key_time" '[Int, Int]
(IO Float)
where
nodeMethod = Godot.Core.Animation.track_get_key_time
# NOINLINE bindAnimation_track_get_key_transition #
-- | Returns the transition curve (easing) for a specific key (see the built-in math function @method @GDScript.ease@).
bindAnimation_track_get_key_transition :: MethodBind
bindAnimation_track_get_key_transition
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_key_transition" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the transition curve (easing) for a specific key (see the built-in math function @method @GDScript.ease@).
track_get_key_transition ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO Float
track_get_key_transition cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_key_transition
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_key_transition"
'[Int, Int]
(IO Float)
where
nodeMethod = Godot.Core.Animation.track_get_key_transition
# NOINLINE bindAnimation_track_get_key_value #
-- | Returns the value of a given key in a given track.
bindAnimation_track_get_key_value :: MethodBind
bindAnimation_track_get_key_value
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_key_value" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the value of a given key in a given track.
track_get_key_value ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO GodotVariant
track_get_key_value cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_key_value
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_key_value" '[Int, Int]
(IO GodotVariant)
where
nodeMethod = Godot.Core.Animation.track_get_key_value
# NOINLINE bindAnimation_track_get_path #
-- | Gets the path of a track. For more information on the path format, see @method track_set_path@.
bindAnimation_track_get_path :: MethodBind
bindAnimation_track_get_path
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_path" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Gets the path of a track. For more information on the path format, see @method track_set_path@.
track_get_path ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO NodePath
track_get_path cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_path (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_path" '[Int] (IO NodePath)
where
nodeMethod = Godot.Core.Animation.track_get_path
# NOINLINE bindAnimation_track_get_type #
-- | Gets the type of a track.
bindAnimation_track_get_type :: MethodBind
bindAnimation_track_get_type
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Gets the type of a track.
track_get_type ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Int
track_get_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_type (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_type" '[Int] (IO Int)
where
nodeMethod = Godot.Core.Animation.track_get_type
# NOINLINE bindAnimation_track_insert_key #
-- | Insert a generic key in a given track.
bindAnimation_track_insert_key :: MethodBind
bindAnimation_track_insert_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_insert_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Insert a generic key in a given track.
track_insert_key ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> GodotVariant -> Maybe Float -> IO ()
track_insert_key cls arg1 arg2 arg3 arg4
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3,
maybe (VariantReal (1)) toVariant arg4]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_insert_key (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_insert_key"
'[Int, Float, GodotVariant, Maybe Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_insert_key
# NOINLINE bindAnimation_track_is_enabled #
| Returns @true@ if the track at index @idx@ is enabled .
bindAnimation_track_is_enabled :: MethodBind
bindAnimation_track_is_enabled
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_is_enabled" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns @true@ if the track at index @idx@ is enabled .
track_is_enabled ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Bool
track_is_enabled cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_is_enabled (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_is_enabled" '[Int] (IO Bool)
where
nodeMethod = Godot.Core.Animation.track_is_enabled
# NOINLINE bindAnimation_track_is_imported #
-- | Returns @true@ if the given track is imported. Else, return @false@.
bindAnimation_track_is_imported :: MethodBind
bindAnimation_track_is_imported
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_is_imported" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns @true@ if the given track is imported. Else, return @false@.
track_is_imported ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Bool
track_is_imported cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_is_imported (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_is_imported" '[Int] (IO Bool)
where
nodeMethod = Godot.Core.Animation.track_is_imported
# NOINLINE bindAnimation_track_move_down #
-- | Moves a track down.
bindAnimation_track_move_down :: MethodBind
bindAnimation_track_move_down
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_move_down" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Moves a track down.
track_move_down ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO ()
track_move_down cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_move_down (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_move_down" '[Int] (IO ())
where
nodeMethod = Godot.Core.Animation.track_move_down
# NOINLINE bindAnimation_track_move_to #
| Changes the index position of track @idx@ to the one defined in @to_idx@.
bindAnimation_track_move_to :: MethodBind
bindAnimation_track_move_to
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_move_to" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Changes the index position of track @idx@ to the one defined in @to_idx@.
track_move_to ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
track_move_to cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_move_to (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_move_to" '[Int, Int] (IO ())
where
nodeMethod = Godot.Core.Animation.track_move_to
# NOINLINE bindAnimation_track_move_up #
-- | Moves a track up.
bindAnimation_track_move_up :: MethodBind
bindAnimation_track_move_up
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_move_up" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Moves a track up.
track_move_up ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO ()
track_move_up cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_move_up (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_move_up" '[Int] (IO ()) where
nodeMethod = Godot.Core.Animation.track_move_up
# NOINLINE bindAnimation_track_remove_key #
-- | Removes a key by index in a given track.
bindAnimation_track_remove_key :: MethodBind
bindAnimation_track_remove_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_remove_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Removes a key by index in a given track.
track_remove_key ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
track_remove_key cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_remove_key (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_remove_key" '[Int, Int]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_remove_key
# NOINLINE bindAnimation_track_remove_key_at_position #
| Removes a key by position ( seconds ) in a given track .
bindAnimation_track_remove_key_at_position :: MethodBind
bindAnimation_track_remove_key_at_position
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_remove_key_at_position" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Removes a key by position ( seconds ) in a given track .
track_remove_key_at_position ::
(Animation :< cls, Object :< cls) => cls -> Int -> Float -> IO ()
track_remove_key_at_position cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_remove_key_at_position
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_remove_key_at_position"
'[Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_remove_key_at_position
# NOINLINE bindAnimation_track_set_enabled #
-- | Enables/disables the given track. Tracks are enabled by default.
bindAnimation_track_set_enabled :: MethodBind
bindAnimation_track_set_enabled
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_enabled" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Enables/disables the given track. Tracks are enabled by default.
track_set_enabled ::
(Animation :< cls, Object :< cls) => cls -> Int -> Bool -> IO ()
track_set_enabled cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_enabled (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_enabled" '[Int, Bool]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_enabled
# NOINLINE bindAnimation_track_set_imported #
-- | Sets the given track as imported or not.
bindAnimation_track_set_imported :: MethodBind
bindAnimation_track_set_imported
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_imported" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Sets the given track as imported or not.
track_set_imported ::
(Animation :< cls, Object :< cls) => cls -> Int -> Bool -> IO ()
track_set_imported cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_imported
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_imported" '[Int, Bool]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_imported
# NOINLINE bindAnimation_track_set_interpolation_loop_wrap #
| If @true@ , the track at @idx@ wraps the interpolation loop .
bindAnimation_track_set_interpolation_loop_wrap :: MethodBind
bindAnimation_track_set_interpolation_loop_wrap
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_interpolation_loop_wrap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , the track at @idx@ wraps the interpolation loop .
track_set_interpolation_loop_wrap ::
(Animation :< cls, Object :< cls) => cls -> Int -> Bool -> IO ()
track_set_interpolation_loop_wrap cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_track_set_interpolation_loop_wrap
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_interpolation_loop_wrap"
'[Int, Bool]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_interpolation_loop_wrap
# NOINLINE bindAnimation_track_set_interpolation_type #
-- | Sets the interpolation type of a given track.
bindAnimation_track_set_interpolation_type :: MethodBind
bindAnimation_track_set_interpolation_type
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_interpolation_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Sets the interpolation type of a given track.
track_set_interpolation_type ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
track_set_interpolation_type cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_interpolation_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_interpolation_type"
'[Int, Int]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_interpolation_type
# NOINLINE bindAnimation_track_set_key_time #
-- | Sets the time of an existing key.
bindAnimation_track_set_key_time :: MethodBind
bindAnimation_track_set_key_time
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_key_time" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Sets the time of an existing key.
track_set_key_time ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Float -> IO ()
track_set_key_time cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_key_time
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_key_time"
'[Int, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_key_time
# NOINLINE bindAnimation_track_set_key_transition #
-- | Sets the transition curve (easing) for a specific key (see the built-in math function @method @GDScript.ease@).
bindAnimation_track_set_key_transition :: MethodBind
bindAnimation_track_set_key_transition
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_key_transition" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Sets the transition curve (easing) for a specific key (see the built-in math function @method @GDScript.ease@).
track_set_key_transition ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Float -> IO ()
track_set_key_transition cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_key_transition
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_key_transition"
'[Int, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_key_transition
# NOINLINE bindAnimation_track_set_key_value #
-- | Sets the value of an existing key.
bindAnimation_track_set_key_value :: MethodBind
bindAnimation_track_set_key_value
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_key_value" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Sets the value of an existing key.
track_set_key_value ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> GodotVariant -> IO ()
track_set_key_value cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_key_value
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_key_value"
'[Int, Int, GodotVariant]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_key_value
# NOINLINE bindAnimation_track_set_path #
-- | Sets the path of a track. Paths must be valid scene-tree paths to a node, and must be specified starting from the parent node of the node that will reproduce the animation. Tracks that control properties or bones must append their name after the path, separated by @":"@.
-- For example, @"character/skeleton:ankle"@ or @"character/mesh:transform/local"@.
bindAnimation_track_set_path :: MethodBind
bindAnimation_track_set_path
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_path" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Sets the path of a track. Paths must be valid scene-tree paths to a node, and must be specified starting from the parent node of the node that will reproduce the animation. Tracks that control properties or bones must append their name after the path, separated by @":"@.
-- For example, @"character/skeleton:ankle"@ or @"character/mesh:transform/local"@.
track_set_path ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> NodePath -> IO ()
track_set_path cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_path (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_path" '[Int, NodePath]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_path
# NOINLINE bindAnimation_track_swap #
| Swaps the track @idx@ 's index position with the track @with_idx@.
bindAnimation_track_swap :: MethodBind
bindAnimation_track_swap
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_swap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Swaps the track @idx@ 's index position with the track @with_idx@.
track_swap ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
track_swap cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_swap (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_swap" '[Int, Int] (IO ())
where
nodeMethod = Godot.Core.Animation.track_swap
# NOINLINE bindAnimation_transform_track_insert_key #
-- | Insert a transform key for a transform track.
bindAnimation_transform_track_insert_key :: MethodBind
bindAnimation_transform_track_insert_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "transform_track_insert_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Insert a transform key for a transform track.
transform_track_insert_key ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> Vector3 -> Quat -> Vector3 -> IO Int
transform_track_insert_key cls arg1 arg2 arg3 arg4 arg5
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3, toVariant arg4,
toVariant arg5]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_transform_track_insert_key
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "transform_track_insert_key"
'[Int, Float, Vector3, Quat, Vector3]
(IO Int)
where
nodeMethod = Godot.Core.Animation.transform_track_insert_key
# NOINLINE bindAnimation_transform_track_interpolate #
| Returns the interpolated value of a transform track at a given time ( in seconds ) . An array consisting of 3 elements : position ( ) , rotation ( @Quat@ ) and scale ( ) .
bindAnimation_transform_track_interpolate :: MethodBind
bindAnimation_transform_track_interpolate
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "transform_track_interpolate" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the interpolated value of a transform track at a given time ( in seconds ) . An array consisting of 3 elements : position ( ) , rotation ( @Quat@ ) and scale ( ) .
transform_track_interpolate ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> IO Array
transform_track_interpolate cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_transform_track_interpolate
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "transform_track_interpolate"
'[Int, Float]
(IO Array)
where
nodeMethod = Godot.Core.Animation.transform_track_interpolate
# NOINLINE bindAnimation_value_track_get_key_indices #
-- | Returns all the key indices of a value track, given a position and delta time.
bindAnimation_value_track_get_key_indices :: MethodBind
bindAnimation_value_track_get_key_indices
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "value_track_get_key_indices" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns all the key indices of a value track, given a position and delta time.
value_track_get_key_indices ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> Float -> IO PoolIntArray
value_track_get_key_indices cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_value_track_get_key_indices
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "value_track_get_key_indices"
'[Int, Float, Float]
(IO PoolIntArray)
where
nodeMethod = Godot.Core.Animation.value_track_get_key_indices
{-# NOINLINE bindAnimation_value_track_get_update_mode #-}
-- | Returns the update mode of a value track.
bindAnimation_value_track_get_update_mode :: MethodBind
bindAnimation_value_track_get_update_mode
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "value_track_get_update_mode" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the update mode of a value track.
value_track_get_update_mode ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Int
value_track_get_update_mode cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_value_track_get_update_mode
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "value_track_get_update_mode" '[Int]
(IO Int)
where
nodeMethod = Godot.Core.Animation.value_track_get_update_mode
# NOINLINE bindAnimation_value_track_set_update_mode #
| Sets the update mode ( see @enum UpdateMode@ ) of a value track .
bindAnimation_value_track_set_update_mode :: MethodBind
bindAnimation_value_track_set_update_mode
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "value_track_set_update_mode" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the update mode ( see @enum UpdateMode@ ) of a value track .
value_track_set_update_mode ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
value_track_set_update_mode cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_value_track_set_update_mode
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "value_track_set_update_mode"
'[Int, Int]
(IO ())
where
nodeMethod = Godot.Core.Animation.value_track_set_update_mode | null | https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/Animation.hs | haskell | | Emitted when there's a change in the list of tracks, e.g. tracks are added, moved or have changed paths.
# NOINLINE bindAnimation_bezier_track_get_key_out_handle #
| Clear the animation (clear all tracks and reset all).
| Clear the animation (clear all tracks and reset all).
| Adds a new track that is a copy of the given track from @to_animation@.
| Adds a new track that is a copy of the given track from @to_animation@.
| Returns the index of the specified track. If the track is not found, return -1.
| Returns the index of the specified track. If the track is not found, return -1.
__Note:__ Length is not delimited by the last key, as this one may be before or after the end to ensure correct interpolation and looping.
__Note:__ Length is not delimited by the last key, as this one may be before or after the end to ensure correct interpolation and looping.
| The animation step value.
| The animation step value.
| Returns the amount of tracks in the animation.
| Returns the amount of tracks in the animation.
| A flag indicating that the animation must loop. This is uses for correct interpolation of animation cycles, and for hinting the player that it must restart the animation.
| A flag indicating that the animation must loop. This is uses for correct interpolation of animation cycles, and for hinting the player that it must restart the animation.
| Returns all the key indices of a method track, given a position and delta time.
| Returns all the key indices of a method track, given a position and delta time.
| Returns the method name of a method track.
| Returns the method name of a method track.
| Returns the arguments values to be called on a method track for a given key in a given track.
| Returns the arguments values to be called on a method track for a given key in a given track.
| Removes a track by specifying the track index.
| Removes a track by specifying the track index.
__Note:__ Length is not delimited by the last key, as this one may be before or after the end to ensure correct interpolation and looping.
__Note:__ Length is not delimited by the last key, as this one may be before or after the end to ensure correct interpolation and looping.
| A flag indicating that the animation must loop. This is uses for correct interpolation of animation cycles, and for hinting the player that it must restart the animation.
| A flag indicating that the animation must loop. This is uses for correct interpolation of animation cycles, and for hinting the player that it must restart the animation.
| The animation step value.
| The animation step value.
| Finds the key index by time in a given track. Optionally, only find it if the exact time is given.
| Finds the key index by time in a given track. Optionally, only find it if the exact time is given.
| Returns the interpolation type of a given track.
| Returns the interpolation type of a given track.
| Returns the amount of keys in a given track.
| Returns the amount of keys in a given track.
| Returns the time at which the key is located.
| Returns the time at which the key is located.
| Returns the transition curve (easing) for a specific key (see the built-in math function @method @GDScript.ease@).
| Returns the transition curve (easing) for a specific key (see the built-in math function @method @GDScript.ease@).
| Returns the value of a given key in a given track.
| Returns the value of a given key in a given track.
| Gets the path of a track. For more information on the path format, see @method track_set_path@.
| Gets the path of a track. For more information on the path format, see @method track_set_path@.
| Gets the type of a track.
| Gets the type of a track.
| Insert a generic key in a given track.
| Insert a generic key in a given track.
| Returns @true@ if the given track is imported. Else, return @false@.
| Returns @true@ if the given track is imported. Else, return @false@.
| Moves a track down.
| Moves a track down.
| Moves a track up.
| Moves a track up.
| Removes a key by index in a given track.
| Removes a key by index in a given track.
| Enables/disables the given track. Tracks are enabled by default.
| Enables/disables the given track. Tracks are enabled by default.
| Sets the given track as imported or not.
| Sets the given track as imported or not.
| Sets the interpolation type of a given track.
| Sets the interpolation type of a given track.
| Sets the time of an existing key.
| Sets the time of an existing key.
| Sets the transition curve (easing) for a specific key (see the built-in math function @method @GDScript.ease@).
| Sets the transition curve (easing) for a specific key (see the built-in math function @method @GDScript.ease@).
| Sets the value of an existing key.
| Sets the value of an existing key.
| Sets the path of a track. Paths must be valid scene-tree paths to a node, and must be specified starting from the parent node of the node that will reproduce the animation. Tracks that control properties or bones must append their name after the path, separated by @":"@.
For example, @"character/skeleton:ankle"@ or @"character/mesh:transform/local"@.
| Sets the path of a track. Paths must be valid scene-tree paths to a node, and must be specified starting from the parent node of the node that will reproduce the animation. Tracks that control properties or bones must append their name after the path, separated by @":"@.
For example, @"character/skeleton:ankle"@ or @"character/mesh:transform/local"@.
| Insert a transform key for a transform track.
| Insert a transform key for a transform track.
| Returns all the key indices of a value track, given a position and delta time.
| Returns all the key indices of a value track, given a position and delta time.
# NOINLINE bindAnimation_value_track_get_update_mode #
| Returns the update mode of a value track.
| Returns the update mode of a value track. | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.Animation
(Godot.Core.Animation._TYPE_BEZIER,
Godot.Core.Animation._INTERPOLATION_NEAREST,
Godot.Core.Animation._UPDATE_DISCRETE,
Godot.Core.Animation._INTERPOLATION_LINEAR,
Godot.Core.Animation._TYPE_VALUE,
Godot.Core.Animation._UPDATE_CAPTURE,
Godot.Core.Animation._TYPE_METHOD,
Godot.Core.Animation._UPDATE_CONTINUOUS,
Godot.Core.Animation._INTERPOLATION_CUBIC,
Godot.Core.Animation._TYPE_TRANSFORM,
Godot.Core.Animation._UPDATE_TRIGGER,
Godot.Core.Animation._TYPE_AUDIO,
Godot.Core.Animation._TYPE_ANIMATION,
Godot.Core.Animation.sig_tracks_changed,
Godot.Core.Animation.add_track,
Godot.Core.Animation.animation_track_get_key_animation,
Godot.Core.Animation.animation_track_insert_key,
Godot.Core.Animation.animation_track_set_key_animation,
Godot.Core.Animation.audio_track_get_key_end_offset,
Godot.Core.Animation.audio_track_get_key_start_offset,
Godot.Core.Animation.audio_track_get_key_stream,
Godot.Core.Animation.audio_track_insert_key,
Godot.Core.Animation.audio_track_set_key_end_offset,
Godot.Core.Animation.audio_track_set_key_start_offset,
Godot.Core.Animation.audio_track_set_key_stream,
Godot.Core.Animation.bezier_track_get_key_in_handle,
Godot.Core.Animation.bezier_track_get_key_out_handle,
Godot.Core.Animation.bezier_track_get_key_value,
Godot.Core.Animation.bezier_track_insert_key,
Godot.Core.Animation.bezier_track_interpolate,
Godot.Core.Animation.bezier_track_set_key_in_handle,
Godot.Core.Animation.bezier_track_set_key_out_handle,
Godot.Core.Animation.bezier_track_set_key_value,
Godot.Core.Animation.clear, Godot.Core.Animation.copy_track,
Godot.Core.Animation.find_track, Godot.Core.Animation.get_length,
Godot.Core.Animation.get_step,
Godot.Core.Animation.get_track_count,
Godot.Core.Animation.has_loop,
Godot.Core.Animation.method_track_get_key_indices,
Godot.Core.Animation.method_track_get_name,
Godot.Core.Animation.method_track_get_params,
Godot.Core.Animation.remove_track, Godot.Core.Animation.set_length,
Godot.Core.Animation.set_loop, Godot.Core.Animation.set_step,
Godot.Core.Animation.track_find_key,
Godot.Core.Animation.track_get_interpolation_loop_wrap,
Godot.Core.Animation.track_get_interpolation_type,
Godot.Core.Animation.track_get_key_count,
Godot.Core.Animation.track_get_key_time,
Godot.Core.Animation.track_get_key_transition,
Godot.Core.Animation.track_get_key_value,
Godot.Core.Animation.track_get_path,
Godot.Core.Animation.track_get_type,
Godot.Core.Animation.track_insert_key,
Godot.Core.Animation.track_is_enabled,
Godot.Core.Animation.track_is_imported,
Godot.Core.Animation.track_move_down,
Godot.Core.Animation.track_move_to,
Godot.Core.Animation.track_move_up,
Godot.Core.Animation.track_remove_key,
Godot.Core.Animation.track_remove_key_at_position,
Godot.Core.Animation.track_set_enabled,
Godot.Core.Animation.track_set_imported,
Godot.Core.Animation.track_set_interpolation_loop_wrap,
Godot.Core.Animation.track_set_interpolation_type,
Godot.Core.Animation.track_set_key_time,
Godot.Core.Animation.track_set_key_transition,
Godot.Core.Animation.track_set_key_value,
Godot.Core.Animation.track_set_path,
Godot.Core.Animation.track_swap,
Godot.Core.Animation.transform_track_insert_key,
Godot.Core.Animation.transform_track_interpolate,
Godot.Core.Animation.value_track_get_key_indices,
Godot.Core.Animation.value_track_get_update_mode,
Godot.Core.Animation.value_track_set_update_mode)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Resource()
_TYPE_BEZIER :: Int
_TYPE_BEZIER = 3
_INTERPOLATION_NEAREST :: Int
_INTERPOLATION_NEAREST = 0
_UPDATE_DISCRETE :: Int
_UPDATE_DISCRETE = 1
_INTERPOLATION_LINEAR :: Int
_INTERPOLATION_LINEAR = 1
_TYPE_VALUE :: Int
_TYPE_VALUE = 0
_UPDATE_CAPTURE :: Int
_UPDATE_CAPTURE = 3
_TYPE_METHOD :: Int
_TYPE_METHOD = 2
_UPDATE_CONTINUOUS :: Int
_UPDATE_CONTINUOUS = 0
_INTERPOLATION_CUBIC :: Int
_INTERPOLATION_CUBIC = 2
_TYPE_TRANSFORM :: Int
_TYPE_TRANSFORM = 1
_UPDATE_TRIGGER :: Int
_UPDATE_TRIGGER = 2
_TYPE_AUDIO :: Int
_TYPE_AUDIO = 4
_TYPE_ANIMATION :: Int
_TYPE_ANIMATION = 5
sig_tracks_changed :: Godot.Internal.Dispatch.Signal Animation
sig_tracks_changed
= Godot.Internal.Dispatch.Signal "tracks_changed"
instance NodeSignal Animation "tracks_changed" '[]
instance NodeProperty Animation "length" Float 'False where
nodeProperty = (get_length, wrapDroppingSetter set_length, Nothing)
instance NodeProperty Animation "loop" Bool 'False where
nodeProperty = (has_loop, wrapDroppingSetter set_loop, Nothing)
instance NodeProperty Animation "step" Float 'False where
nodeProperty = (get_step, wrapDroppingSetter set_step, Nothing)
# NOINLINE bindAnimation_add_track #
| Adds a track to the Animation .
bindAnimation_add_track :: MethodBind
bindAnimation_add_track
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "add_track" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Adds a track to the Animation .
add_track ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Maybe Int -> IO Int
add_track cls arg1 arg2
= withVariantArray
[toVariant arg1, maybe (VariantInt (-1)) toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_add_track (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "add_track" '[Int, Maybe Int]
(IO Int)
where
nodeMethod = Godot.Core.Animation.add_track
# NOINLINE bindAnimation_animation_track_get_key_animation #
| Returns the animation name at the key identified by @key_idx@. The must be the index of an Animation Track .
bindAnimation_animation_track_get_key_animation :: MethodBind
bindAnimation_animation_track_get_key_animation
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "animation_track_get_key_animation" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the animation name at the key identified by @key_idx@. The must be the index of an Animation Track .
animation_track_get_key_animation ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO GodotString
animation_track_get_key_animation cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_animation_track_get_key_animation
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "animation_track_get_key_animation"
'[Int, Int]
(IO GodotString)
where
nodeMethod = Godot.Core.Animation.animation_track_get_key_animation
# NOINLINE bindAnimation_animation_track_insert_key #
| Inserts a key with value @animation@ at the given @time@ ( in seconds ) . The must be the index of an Animation Track .
bindAnimation_animation_track_insert_key :: MethodBind
bindAnimation_animation_track_insert_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "animation_track_insert_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Inserts a key with value @animation@ at the given @time@ ( in seconds ) . The must be the index of an Animation Track .
animation_track_insert_key ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> GodotString -> IO Int
animation_track_insert_key cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_animation_track_insert_key
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "animation_track_insert_key"
'[Int, Float, GodotString]
(IO Int)
where
nodeMethod = Godot.Core.Animation.animation_track_insert_key
# NOINLINE bindAnimation_animation_track_set_key_animation #
| Sets the key identified by @key_idx@ to value @animation@. The must be the index of an Animation Track .
bindAnimation_animation_track_set_key_animation :: MethodBind
bindAnimation_animation_track_set_key_animation
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "animation_track_set_key_animation" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the key identified by @key_idx@ to value @animation@. The must be the index of an Animation Track .
animation_track_set_key_animation ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> GodotString -> IO ()
animation_track_set_key_animation cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_animation_track_set_key_animation
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "animation_track_set_key_animation"
'[Int, Int, GodotString]
(IO ())
where
nodeMethod = Godot.Core.Animation.animation_track_set_key_animation
# NOINLINE bindAnimation_audio_track_get_key_end_offset #
| Returns the end offset of the key identified by @key_idx@. The must be the index of an Audio Track .
End offset is the number of seconds cut off at the ending of the audio stream .
bindAnimation_audio_track_get_key_end_offset :: MethodBind
bindAnimation_audio_track_get_key_end_offset
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_get_key_end_offset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the end offset of the key identified by @key_idx@. The must be the index of an Audio Track .
End offset is the number of seconds cut off at the ending of the audio stream .
audio_track_get_key_end_offset ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO Float
audio_track_get_key_end_offset cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_audio_track_get_key_end_offset
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_get_key_end_offset"
'[Int, Int]
(IO Float)
where
nodeMethod = Godot.Core.Animation.audio_track_get_key_end_offset
# NOINLINE bindAnimation_audio_track_get_key_start_offset #
| Returns the start offset of the key identified by @key_idx@. The must be the index of an Audio Track .
Start offset is the number of seconds cut off at the beginning of the audio stream .
bindAnimation_audio_track_get_key_start_offset :: MethodBind
bindAnimation_audio_track_get_key_start_offset
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_get_key_start_offset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the start offset of the key identified by @key_idx@. The must be the index of an Audio Track .
Start offset is the number of seconds cut off at the beginning of the audio stream .
audio_track_get_key_start_offset ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO Float
audio_track_get_key_start_offset cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_audio_track_get_key_start_offset
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_get_key_start_offset"
'[Int, Int]
(IO Float)
where
nodeMethod = Godot.Core.Animation.audio_track_get_key_start_offset
# NOINLINE bindAnimation_audio_track_get_key_stream #
| Returns the audio stream of the key identified by @key_idx@. The must be the index of an Audio Track .
bindAnimation_audio_track_get_key_stream :: MethodBind
bindAnimation_audio_track_get_key_stream
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_get_key_stream" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the audio stream of the key identified by @key_idx@. The must be the index of an Audio Track .
audio_track_get_key_stream ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO Resource
audio_track_get_key_stream cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_audio_track_get_key_stream
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_get_key_stream"
'[Int, Int]
(IO Resource)
where
nodeMethod = Godot.Core.Animation.audio_track_get_key_stream
# NOINLINE bindAnimation_audio_track_insert_key #
| Inserts an Audio Track key at the given @time@ in seconds . The must be the index of an Audio Track .
@stream@ is the @AudioStream@ resource to play . @start_offset@ is the number of seconds cut off at the beginning of the audio stream , while @end_offset@ is at the ending .
bindAnimation_audio_track_insert_key :: MethodBind
bindAnimation_audio_track_insert_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_insert_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Inserts an Audio Track key at the given @time@ in seconds . The must be the index of an Audio Track .
@stream@ is the @AudioStream@ resource to play . @start_offset@ is the number of seconds cut off at the beginning of the audio stream , while @end_offset@ is at the ending .
audio_track_insert_key ::
(Animation :< cls, Object :< cls) =>
cls ->
Int -> Float -> Resource -> Maybe Float -> Maybe Float -> IO Int
audio_track_insert_key cls arg1 arg2 arg3 arg4 arg5
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3,
maybe (VariantReal (0)) toVariant arg4,
maybe (VariantReal (0)) toVariant arg5]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_audio_track_insert_key
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_insert_key"
'[Int, Float, Resource, Maybe Float, Maybe Float]
(IO Int)
where
nodeMethod = Godot.Core.Animation.audio_track_insert_key
# NOINLINE bindAnimation_audio_track_set_key_end_offset #
| Sets the end offset of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
bindAnimation_audio_track_set_key_end_offset :: MethodBind
bindAnimation_audio_track_set_key_end_offset
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_set_key_end_offset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the end offset of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
audio_track_set_key_end_offset ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Float -> IO ()
audio_track_set_key_end_offset cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_audio_track_set_key_end_offset
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_set_key_end_offset"
'[Int, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.audio_track_set_key_end_offset
# NOINLINE bindAnimation_audio_track_set_key_start_offset #
| Sets the start offset of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
bindAnimation_audio_track_set_key_start_offset :: MethodBind
bindAnimation_audio_track_set_key_start_offset
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_set_key_start_offset" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the start offset of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
audio_track_set_key_start_offset ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Float -> IO ()
audio_track_set_key_start_offset cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_audio_track_set_key_start_offset
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_set_key_start_offset"
'[Int, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.audio_track_set_key_start_offset
# NOINLINE bindAnimation_audio_track_set_key_stream #
| Sets the stream of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
bindAnimation_audio_track_set_key_stream :: MethodBind
bindAnimation_audio_track_set_key_stream
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "audio_track_set_key_stream" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the stream of the key identified by @key_idx@ to value @offset@. The must be the index of an Audio Track .
audio_track_set_key_stream ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Resource -> IO ()
audio_track_set_key_stream cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_audio_track_set_key_stream
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "audio_track_set_key_stream"
'[Int, Int, Resource]
(IO ())
where
nodeMethod = Godot.Core.Animation.audio_track_set_key_stream
# NOINLINE bindAnimation_bezier_track_get_key_in_handle #
| Returns the in handle of the key identified by @key_idx@. The must be the index of a Bezier Track .
bindAnimation_bezier_track_get_key_in_handle :: MethodBind
bindAnimation_bezier_track_get_key_in_handle
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_get_key_in_handle" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the in handle of the key identified by @key_idx@. The must be the index of a Bezier Track .
bezier_track_get_key_in_handle ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO Vector2
bezier_track_get_key_in_handle cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_get_key_in_handle
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_get_key_in_handle"
'[Int, Int]
(IO Vector2)
where
nodeMethod = Godot.Core.Animation.bezier_track_get_key_in_handle
| Returns the out handle of the key identified by @key_idx@. The must be the index of a Bezier Track .
bindAnimation_bezier_track_get_key_out_handle :: MethodBind
bindAnimation_bezier_track_get_key_out_handle
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_get_key_out_handle" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the out handle of the key identified by @key_idx@. The must be the index of a Bezier Track .
bezier_track_get_key_out_handle ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO Vector2
bezier_track_get_key_out_handle cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_bezier_track_get_key_out_handle
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_get_key_out_handle"
'[Int, Int]
(IO Vector2)
where
nodeMethod = Godot.Core.Animation.bezier_track_get_key_out_handle
# NOINLINE bindAnimation_bezier_track_get_key_value #
| Returns the value of the key identified by @key_idx@. The must be the index of a Bezier Track .
bindAnimation_bezier_track_get_key_value :: MethodBind
bindAnimation_bezier_track_get_key_value
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_get_key_value" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the value of the key identified by @key_idx@. The must be the index of a Bezier Track .
bezier_track_get_key_value ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO Float
bezier_track_get_key_value cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_get_key_value
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_get_key_value"
'[Int, Int]
(IO Float)
where
nodeMethod = Godot.Core.Animation.bezier_track_get_key_value
# NOINLINE bindAnimation_bezier_track_insert_key #
| Inserts a Bezier Track key at the given @time@ in seconds . The must be the index of a Bezier Track .
@in_handle@ is the left - side weight of the added curve point , @out_handle@ is the right - side one , while @value@ is the actual value at this point .
bindAnimation_bezier_track_insert_key :: MethodBind
bindAnimation_bezier_track_insert_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_insert_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Inserts a Bezier Track key at the given @time@ in seconds . The must be the index of a Bezier Track .
@in_handle@ is the left - side weight of the added curve point , @out_handle@ is the right - side one , while @value@ is the actual value at this point .
bezier_track_insert_key ::
(Animation :< cls, Object :< cls) =>
cls ->
Int -> Float -> Float -> Maybe Vector2 -> Maybe Vector2 -> IO Int
bezier_track_insert_key cls arg1 arg2 arg3 arg4 arg5
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3,
defaultedVariant VariantVector2 (V2 0 0) arg4,
defaultedVariant VariantVector2 (V2 0 0) arg5]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_insert_key
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_insert_key"
'[Int, Float, Float, Maybe Vector2, Maybe Vector2]
(IO Int)
where
nodeMethod = Godot.Core.Animation.bezier_track_insert_key
# NOINLINE bindAnimation_bezier_track_interpolate #
| Returns the interpolated value at the given @time@ ( in seconds ) . The must be the index of a Bezier Track .
bindAnimation_bezier_track_interpolate :: MethodBind
bindAnimation_bezier_track_interpolate
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_interpolate" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the interpolated value at the given @time@ ( in seconds ) . The must be the index of a Bezier Track .
bezier_track_interpolate ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> IO Float
bezier_track_interpolate cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_interpolate
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_interpolate"
'[Int, Float]
(IO Float)
where
nodeMethod = Godot.Core.Animation.bezier_track_interpolate
# NOINLINE bindAnimation_bezier_track_set_key_in_handle #
| Sets the in handle of the key identified by @key_idx@ to value @in_handle@. The must be the index of a Bezier Track .
bindAnimation_bezier_track_set_key_in_handle :: MethodBind
bindAnimation_bezier_track_set_key_in_handle
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_set_key_in_handle" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the in handle of the key identified by @key_idx@ to value @in_handle@. The must be the index of a Bezier Track .
bezier_track_set_key_in_handle ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Vector2 -> IO ()
bezier_track_set_key_in_handle cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_set_key_in_handle
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_set_key_in_handle"
'[Int, Int, Vector2]
(IO ())
where
nodeMethod = Godot.Core.Animation.bezier_track_set_key_in_handle
# NOINLINE bindAnimation_bezier_track_set_key_out_handle #
| Sets the out handle of the key identified by @key_idx@ to value @out_handle@. The must be the index of a Bezier Track .
bindAnimation_bezier_track_set_key_out_handle :: MethodBind
bindAnimation_bezier_track_set_key_out_handle
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_set_key_out_handle" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the out handle of the key identified by @key_idx@ to value @out_handle@. The must be the index of a Bezier Track .
bezier_track_set_key_out_handle ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Vector2 -> IO ()
bezier_track_set_key_out_handle cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_bezier_track_set_key_out_handle
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_set_key_out_handle"
'[Int, Int, Vector2]
(IO ())
where
nodeMethod = Godot.Core.Animation.bezier_track_set_key_out_handle
# NOINLINE bindAnimation_bezier_track_set_key_value #
| Sets the value of the key identified by @key_idx@ to the given value . The must be the index of a Bezier Track .
bindAnimation_bezier_track_set_key_value :: MethodBind
bindAnimation_bezier_track_set_key_value
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "bezier_track_set_key_value" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the value of the key identified by @key_idx@ to the given value . The must be the index of a Bezier Track .
bezier_track_set_key_value ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Float -> IO ()
bezier_track_set_key_value cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_bezier_track_set_key_value
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "bezier_track_set_key_value"
'[Int, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.bezier_track_set_key_value
# NOINLINE bindAnimation_clear #
bindAnimation_clear :: MethodBind
bindAnimation_clear
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "clear" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
clear :: (Animation :< cls, Object :< cls) => cls -> IO ()
clear cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_clear (upcast cls) arrPtr len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "clear" '[] (IO ()) where
nodeMethod = Godot.Core.Animation.clear
# NOINLINE bindAnimation_copy_track #
bindAnimation_copy_track :: MethodBind
bindAnimation_copy_track
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "copy_track" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
copy_track ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Animation -> IO ()
copy_track cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_copy_track (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "copy_track" '[Int, Animation]
(IO ())
where
nodeMethod = Godot.Core.Animation.copy_track
# NOINLINE bindAnimation_find_track #
bindAnimation_find_track :: MethodBind
bindAnimation_find_track
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "find_track" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
find_track ::
(Animation :< cls, Object :< cls) => cls -> NodePath -> IO Int
find_track cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_find_track (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "find_track" '[NodePath] (IO Int)
where
nodeMethod = Godot.Core.Animation.find_track
# NOINLINE bindAnimation_get_length #
| The total length of the animation ( in seconds ) .
bindAnimation_get_length :: MethodBind
bindAnimation_get_length
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "get_length" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The total length of the animation ( in seconds ) .
get_length :: (Animation :< cls, Object :< cls) => cls -> IO Float
get_length cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_get_length (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "get_length" '[] (IO Float) where
nodeMethod = Godot.Core.Animation.get_length
# NOINLINE bindAnimation_get_step #
bindAnimation_get_step :: MethodBind
bindAnimation_get_step
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "get_step" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_step :: (Animation :< cls, Object :< cls) => cls -> IO Float
get_step cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_get_step (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "get_step" '[] (IO Float) where
nodeMethod = Godot.Core.Animation.get_step
# NOINLINE bindAnimation_get_track_count #
bindAnimation_get_track_count :: MethodBind
bindAnimation_get_track_count
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "get_track_count" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_track_count ::
(Animation :< cls, Object :< cls) => cls -> IO Int
get_track_count cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_get_track_count (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "get_track_count" '[] (IO Int) where
nodeMethod = Godot.Core.Animation.get_track_count
# NOINLINE bindAnimation_has_loop #
bindAnimation_has_loop :: MethodBind
bindAnimation_has_loop
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "has_loop" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
has_loop :: (Animation :< cls, Object :< cls) => cls -> IO Bool
has_loop cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_has_loop (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "has_loop" '[] (IO Bool) where
nodeMethod = Godot.Core.Animation.has_loop
# NOINLINE bindAnimation_method_track_get_key_indices #
bindAnimation_method_track_get_key_indices :: MethodBind
bindAnimation_method_track_get_key_indices
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "method_track_get_key_indices" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
method_track_get_key_indices ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> Float -> IO PoolIntArray
method_track_get_key_indices cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_method_track_get_key_indices
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "method_track_get_key_indices"
'[Int, Float, Float]
(IO PoolIntArray)
where
nodeMethod = Godot.Core.Animation.method_track_get_key_indices
# NOINLINE bindAnimation_method_track_get_name #
bindAnimation_method_track_get_name :: MethodBind
bindAnimation_method_track_get_name
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "method_track_get_name" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
method_track_get_name ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO GodotString
method_track_get_name cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_method_track_get_name
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "method_track_get_name" '[Int, Int]
(IO GodotString)
where
nodeMethod = Godot.Core.Animation.method_track_get_name
# NOINLINE bindAnimation_method_track_get_params #
bindAnimation_method_track_get_params :: MethodBind
bindAnimation_method_track_get_params
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "method_track_get_params" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
method_track_get_params ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO Array
method_track_get_params cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_method_track_get_params
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "method_track_get_params" '[Int, Int]
(IO Array)
where
nodeMethod = Godot.Core.Animation.method_track_get_params
# NOINLINE bindAnimation_remove_track #
bindAnimation_remove_track :: MethodBind
bindAnimation_remove_track
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "remove_track" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
remove_track ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO ()
remove_track cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_remove_track (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "remove_track" '[Int] (IO ()) where
nodeMethod = Godot.Core.Animation.remove_track
# NOINLINE bindAnimation_set_length #
| The total length of the animation ( in seconds ) .
bindAnimation_set_length :: MethodBind
bindAnimation_set_length
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "set_length" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The total length of the animation ( in seconds ) .
set_length ::
(Animation :< cls, Object :< cls) => cls -> Float -> IO ()
set_length cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_set_length (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "set_length" '[Float] (IO ()) where
nodeMethod = Godot.Core.Animation.set_length
# NOINLINE bindAnimation_set_loop #
bindAnimation_set_loop :: MethodBind
bindAnimation_set_loop
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "set_loop" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
set_loop ::
(Animation :< cls, Object :< cls) => cls -> Bool -> IO ()
set_loop cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_set_loop (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "set_loop" '[Bool] (IO ()) where
nodeMethod = Godot.Core.Animation.set_loop
# NOINLINE bindAnimation_set_step #
bindAnimation_set_step :: MethodBind
bindAnimation_set_step
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "set_step" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
set_step ::
(Animation :< cls, Object :< cls) => cls -> Float -> IO ()
set_step cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_set_step (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "set_step" '[Float] (IO ()) where
nodeMethod = Godot.Core.Animation.set_step
# NOINLINE bindAnimation_track_find_key #
bindAnimation_track_find_key :: MethodBind
bindAnimation_track_find_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_find_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_find_key ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> Maybe Bool -> IO Int
track_find_key cls arg1 arg2 arg3
= withVariantArray
[toVariant arg1, toVariant arg2,
maybe (VariantBool False) toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_find_key (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_find_key"
'[Int, Float, Maybe Bool]
(IO Int)
where
nodeMethod = Godot.Core.Animation.track_find_key
# NOINLINE bindAnimation_track_get_interpolation_loop_wrap #
| Returns @true@ if the track at @idx@ wraps the interpolation loop . New tracks wrap the interpolation loop by default .
bindAnimation_track_get_interpolation_loop_wrap :: MethodBind
bindAnimation_track_get_interpolation_loop_wrap
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_interpolation_loop_wrap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns @true@ if the track at @idx@ wraps the interpolation loop . New tracks wrap the interpolation loop by default .
track_get_interpolation_loop_wrap ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Bool
track_get_interpolation_loop_wrap cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_track_get_interpolation_loop_wrap
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_interpolation_loop_wrap"
'[Int]
(IO Bool)
where
nodeMethod = Godot.Core.Animation.track_get_interpolation_loop_wrap
# NOINLINE bindAnimation_track_get_interpolation_type #
bindAnimation_track_get_interpolation_type :: MethodBind
bindAnimation_track_get_interpolation_type
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_interpolation_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_get_interpolation_type ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Int
track_get_interpolation_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_interpolation_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_interpolation_type" '[Int]
(IO Int)
where
nodeMethod = Godot.Core.Animation.track_get_interpolation_type
# NOINLINE bindAnimation_track_get_key_count #
bindAnimation_track_get_key_count :: MethodBind
bindAnimation_track_get_key_count
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_key_count" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_get_key_count ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Int
track_get_key_count cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_key_count
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_key_count" '[Int] (IO Int)
where
nodeMethod = Godot.Core.Animation.track_get_key_count
# NOINLINE bindAnimation_track_get_key_time #
bindAnimation_track_get_key_time :: MethodBind
bindAnimation_track_get_key_time
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_key_time" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_get_key_time ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO Float
track_get_key_time cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_key_time
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_key_time" '[Int, Int]
(IO Float)
where
nodeMethod = Godot.Core.Animation.track_get_key_time
# NOINLINE bindAnimation_track_get_key_transition #
bindAnimation_track_get_key_transition :: MethodBind
bindAnimation_track_get_key_transition
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_key_transition" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_get_key_transition ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO Float
track_get_key_transition cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_key_transition
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_key_transition"
'[Int, Int]
(IO Float)
where
nodeMethod = Godot.Core.Animation.track_get_key_transition
# NOINLINE bindAnimation_track_get_key_value #
bindAnimation_track_get_key_value :: MethodBind
bindAnimation_track_get_key_value
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_key_value" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_get_key_value ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> IO GodotVariant
track_get_key_value cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_key_value
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_key_value" '[Int, Int]
(IO GodotVariant)
where
nodeMethod = Godot.Core.Animation.track_get_key_value
# NOINLINE bindAnimation_track_get_path #
bindAnimation_track_get_path :: MethodBind
bindAnimation_track_get_path
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_path" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_get_path ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO NodePath
track_get_path cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_path (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_path" '[Int] (IO NodePath)
where
nodeMethod = Godot.Core.Animation.track_get_path
# NOINLINE bindAnimation_track_get_type #
bindAnimation_track_get_type :: MethodBind
bindAnimation_track_get_type
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_get_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_get_type ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Int
track_get_type cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_get_type (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_get_type" '[Int] (IO Int)
where
nodeMethod = Godot.Core.Animation.track_get_type
# NOINLINE bindAnimation_track_insert_key #
bindAnimation_track_insert_key :: MethodBind
bindAnimation_track_insert_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_insert_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_insert_key ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> GodotVariant -> Maybe Float -> IO ()
track_insert_key cls arg1 arg2 arg3 arg4
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3,
maybe (VariantReal (1)) toVariant arg4]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_insert_key (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_insert_key"
'[Int, Float, GodotVariant, Maybe Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_insert_key
# NOINLINE bindAnimation_track_is_enabled #
| Returns @true@ if the track at index @idx@ is enabled .
bindAnimation_track_is_enabled :: MethodBind
bindAnimation_track_is_enabled
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_is_enabled" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns @true@ if the track at index @idx@ is enabled .
track_is_enabled ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Bool
track_is_enabled cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_is_enabled (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_is_enabled" '[Int] (IO Bool)
where
nodeMethod = Godot.Core.Animation.track_is_enabled
# NOINLINE bindAnimation_track_is_imported #
bindAnimation_track_is_imported :: MethodBind
bindAnimation_track_is_imported
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_is_imported" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_is_imported ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Bool
track_is_imported cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_is_imported (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_is_imported" '[Int] (IO Bool)
where
nodeMethod = Godot.Core.Animation.track_is_imported
# NOINLINE bindAnimation_track_move_down #
bindAnimation_track_move_down :: MethodBind
bindAnimation_track_move_down
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_move_down" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_move_down ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO ()
track_move_down cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_move_down (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_move_down" '[Int] (IO ())
where
nodeMethod = Godot.Core.Animation.track_move_down
# NOINLINE bindAnimation_track_move_to #
| Changes the index position of track @idx@ to the one defined in @to_idx@.
bindAnimation_track_move_to :: MethodBind
bindAnimation_track_move_to
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_move_to" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Changes the index position of track @idx@ to the one defined in @to_idx@.
track_move_to ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
track_move_to cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_move_to (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_move_to" '[Int, Int] (IO ())
where
nodeMethod = Godot.Core.Animation.track_move_to
# NOINLINE bindAnimation_track_move_up #
bindAnimation_track_move_up :: MethodBind
bindAnimation_track_move_up
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_move_up" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_move_up ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO ()
track_move_up cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_move_up (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_move_up" '[Int] (IO ()) where
nodeMethod = Godot.Core.Animation.track_move_up
# NOINLINE bindAnimation_track_remove_key #
bindAnimation_track_remove_key :: MethodBind
bindAnimation_track_remove_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_remove_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_remove_key ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
track_remove_key cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_remove_key (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_remove_key" '[Int, Int]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_remove_key
# NOINLINE bindAnimation_track_remove_key_at_position #
| Removes a key by position ( seconds ) in a given track .
bindAnimation_track_remove_key_at_position :: MethodBind
bindAnimation_track_remove_key_at_position
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_remove_key_at_position" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Removes a key by position ( seconds ) in a given track .
track_remove_key_at_position ::
(Animation :< cls, Object :< cls) => cls -> Int -> Float -> IO ()
track_remove_key_at_position cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_remove_key_at_position
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_remove_key_at_position"
'[Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_remove_key_at_position
# NOINLINE bindAnimation_track_set_enabled #
bindAnimation_track_set_enabled :: MethodBind
bindAnimation_track_set_enabled
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_enabled" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_set_enabled ::
(Animation :< cls, Object :< cls) => cls -> Int -> Bool -> IO ()
track_set_enabled cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_enabled (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_enabled" '[Int, Bool]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_enabled
# NOINLINE bindAnimation_track_set_imported #
bindAnimation_track_set_imported :: MethodBind
bindAnimation_track_set_imported
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_imported" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_set_imported ::
(Animation :< cls, Object :< cls) => cls -> Int -> Bool -> IO ()
track_set_imported cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_imported
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_imported" '[Int, Bool]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_imported
# NOINLINE bindAnimation_track_set_interpolation_loop_wrap #
| If @true@ , the track at @idx@ wraps the interpolation loop .
bindAnimation_track_set_interpolation_loop_wrap :: MethodBind
bindAnimation_track_set_interpolation_loop_wrap
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_interpolation_loop_wrap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , the track at @idx@ wraps the interpolation loop .
track_set_interpolation_loop_wrap ::
(Animation :< cls, Object :< cls) => cls -> Int -> Bool -> IO ()
track_set_interpolation_loop_wrap cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call
bindAnimation_track_set_interpolation_loop_wrap
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_interpolation_loop_wrap"
'[Int, Bool]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_interpolation_loop_wrap
# NOINLINE bindAnimation_track_set_interpolation_type #
bindAnimation_track_set_interpolation_type :: MethodBind
bindAnimation_track_set_interpolation_type
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_interpolation_type" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_set_interpolation_type ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
track_set_interpolation_type cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_interpolation_type
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_interpolation_type"
'[Int, Int]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_interpolation_type
# NOINLINE bindAnimation_track_set_key_time #
bindAnimation_track_set_key_time :: MethodBind
bindAnimation_track_set_key_time
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_key_time" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_set_key_time ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Float -> IO ()
track_set_key_time cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_key_time
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_key_time"
'[Int, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_key_time
# NOINLINE bindAnimation_track_set_key_transition #
bindAnimation_track_set_key_transition :: MethodBind
bindAnimation_track_set_key_transition
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_key_transition" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_set_key_transition ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> Float -> IO ()
track_set_key_transition cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_key_transition
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_key_transition"
'[Int, Int, Float]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_key_transition
# NOINLINE bindAnimation_track_set_key_value #
bindAnimation_track_set_key_value :: MethodBind
bindAnimation_track_set_key_value
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_key_value" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_set_key_value ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Int -> GodotVariant -> IO ()
track_set_key_value cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_key_value
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_key_value"
'[Int, Int, GodotVariant]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_key_value
# NOINLINE bindAnimation_track_set_path #
bindAnimation_track_set_path :: MethodBind
bindAnimation_track_set_path
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_set_path" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
track_set_path ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> NodePath -> IO ()
track_set_path cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_set_path (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_set_path" '[Int, NodePath]
(IO ())
where
nodeMethod = Godot.Core.Animation.track_set_path
# NOINLINE bindAnimation_track_swap #
| Swaps the track @idx@ 's index position with the track @with_idx@.
bindAnimation_track_swap :: MethodBind
bindAnimation_track_swap
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "track_swap" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Swaps the track @idx@ 's index position with the track @with_idx@.
track_swap ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
track_swap cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_track_swap (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "track_swap" '[Int, Int] (IO ())
where
nodeMethod = Godot.Core.Animation.track_swap
# NOINLINE bindAnimation_transform_track_insert_key #
bindAnimation_transform_track_insert_key :: MethodBind
bindAnimation_transform_track_insert_key
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "transform_track_insert_key" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
transform_track_insert_key ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> Vector3 -> Quat -> Vector3 -> IO Int
transform_track_insert_key cls arg1 arg2 arg3 arg4 arg5
= withVariantArray
[toVariant arg1, toVariant arg2, toVariant arg3, toVariant arg4,
toVariant arg5]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_transform_track_insert_key
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "transform_track_insert_key"
'[Int, Float, Vector3, Quat, Vector3]
(IO Int)
where
nodeMethod = Godot.Core.Animation.transform_track_insert_key
# NOINLINE bindAnimation_transform_track_interpolate #
| Returns the interpolated value of a transform track at a given time ( in seconds ) . An array consisting of 3 elements : position ( ) , rotation ( @Quat@ ) and scale ( ) .
bindAnimation_transform_track_interpolate :: MethodBind
bindAnimation_transform_track_interpolate
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "transform_track_interpolate" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the interpolated value of a transform track at a given time ( in seconds ) . An array consisting of 3 elements : position ( ) , rotation ( @Quat@ ) and scale ( ) .
transform_track_interpolate ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> IO Array
transform_track_interpolate cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_transform_track_interpolate
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "transform_track_interpolate"
'[Int, Float]
(IO Array)
where
nodeMethod = Godot.Core.Animation.transform_track_interpolate
# NOINLINE bindAnimation_value_track_get_key_indices #
bindAnimation_value_track_get_key_indices :: MethodBind
bindAnimation_value_track_get_key_indices
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "value_track_get_key_indices" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
value_track_get_key_indices ::
(Animation :< cls, Object :< cls) =>
cls -> Int -> Float -> Float -> IO PoolIntArray
value_track_get_key_indices cls arg1 arg2 arg3
= withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_value_track_get_key_indices
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "value_track_get_key_indices"
'[Int, Float, Float]
(IO PoolIntArray)
where
nodeMethod = Godot.Core.Animation.value_track_get_key_indices
bindAnimation_value_track_get_update_mode :: MethodBind
bindAnimation_value_track_get_update_mode
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "value_track_get_update_mode" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
value_track_get_update_mode ::
(Animation :< cls, Object :< cls) => cls -> Int -> IO Int
value_track_get_update_mode cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_value_track_get_update_mode
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "value_track_get_update_mode" '[Int]
(IO Int)
where
nodeMethod = Godot.Core.Animation.value_track_get_update_mode
# NOINLINE bindAnimation_value_track_set_update_mode #
| Sets the update mode ( see @enum UpdateMode@ ) of a value track .
bindAnimation_value_track_set_update_mode :: MethodBind
bindAnimation_value_track_set_update_mode
= unsafePerformIO $
withCString "Animation" $
\ clsNamePtr ->
withCString "value_track_set_update_mode" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the update mode ( see @enum UpdateMode@ ) of a value track .
value_track_set_update_mode ::
(Animation :< cls, Object :< cls) => cls -> Int -> Int -> IO ()
value_track_set_update_mode cls arg1 arg2
= withVariantArray [toVariant arg1, toVariant arg2]
(\ (arrPtr, len) ->
godot_method_bind_call bindAnimation_value_track_set_update_mode
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Animation "value_track_set_update_mode"
'[Int, Int]
(IO ())
where
nodeMethod = Godot.Core.Animation.value_track_set_update_mode |
ece4bf457b05a660d43b1771d5f380f3214f0c5c1e4b654859065bbc89078bfa | sol/doctest | Foo.hs | module Foo where
-- | A failing example
--
> > > 23
42
test :: a
test = undefined
| null | https://raw.githubusercontent.com/sol/doctest/ec6498542986b659f50e961b02144923f6f41eba/test/integration/failing/Foo.hs | haskell | | A failing example
| module Foo where
> > > 23
42
test :: a
test = undefined
|
91350e5386f02918c2a56d79f8ed61a175cc4ae95242d4aa930638534481cbd0 | cnuernber/dtype-next | nippy.clj | (ns tech.v3.datatype.nippy
"Nippy bindings for datatype base types and tensor types"
(:require [taoensso.nippy :as nippy]
[tech.v3.datatype.base :as dtype-base]
[tech.v3.datatype.array-buffer :as array-buffer]
[tech.v3.datatype.copy-make-container :as dtype-cmc]
[tech.v3.tensor :as dtt]
[tech.v3.tensor.dimensions :as dims])
(:import [tech.v3.datatype Buffer]
[tech.v3.datatype.array_buffer ArrayBuffer]
[tech.v3.datatype.native_buffer NativeBuffer]
[tech.v3.tensor_api DataTensor DirectTensor]))
(defn buffer->data
[ary-buf]
{:datatype (dtype-base/elemwise-datatype ary-buf)
:data (dtype-cmc/->array ary-buf)
:metadata (meta ary-buf)})
(defn data->buffer
[{:keys [datatype data metadata]}]
(with-meta
(array-buffer/array-buffer data datatype)
metadata))
(nippy/extend-freeze
ArrayBuffer :tech.v3.datatype/buffer
[buf out]
(nippy/-freeze-without-meta! (buffer->data buf) out))
(nippy/extend-thaw
:tech.v3.datatype/buffer
[in]
(-> (nippy/thaw-from-in! in)
(data->buffer)))
(nippy/extend-freeze
NativeBuffer :tech.v3.datatype/buffer
[buf out]
(nippy/-freeze-without-meta! (buffer->data buf) out))
(nippy/extend-freeze
Buffer :tech.v3.datatype/buffer
[buf out]
(nippy/-freeze-without-meta! (buffer->data buf) out))
(defn tensor->data
[tensor]
{:shape (dtype-base/shape tensor)
:metadata (meta tensor)
:buffer (buffer->data (dtype-base/->buffer tensor))})
(defn data->tensor
[{:keys [shape buffer metadata]}]
(dtt/construct-tensor (data->buffer buffer)
(dims/dimensions shape)
metadata))
(nippy/extend-freeze
DataTensor :tech.v3/tensor
[buf out]
(nippy/-freeze-without-meta! (tensor->data buf) out))
(nippy/extend-freeze
DirectTensor :tech.v3/tensor
[buf out]
(nippy/-freeze-without-meta! (tensor->data buf) out))
(nippy/extend-thaw
:tech.v3/tensor
[in]
(-> (nippy/thaw-from-in! in)
(data->tensor)))
| null | https://raw.githubusercontent.com/cnuernber/dtype-next/228b88af967fef743ef95f3bf3372d08a356d2e8/src/tech/v3/datatype/nippy.clj | clojure | (ns tech.v3.datatype.nippy
"Nippy bindings for datatype base types and tensor types"
(:require [taoensso.nippy :as nippy]
[tech.v3.datatype.base :as dtype-base]
[tech.v3.datatype.array-buffer :as array-buffer]
[tech.v3.datatype.copy-make-container :as dtype-cmc]
[tech.v3.tensor :as dtt]
[tech.v3.tensor.dimensions :as dims])
(:import [tech.v3.datatype Buffer]
[tech.v3.datatype.array_buffer ArrayBuffer]
[tech.v3.datatype.native_buffer NativeBuffer]
[tech.v3.tensor_api DataTensor DirectTensor]))
(defn buffer->data
[ary-buf]
{:datatype (dtype-base/elemwise-datatype ary-buf)
:data (dtype-cmc/->array ary-buf)
:metadata (meta ary-buf)})
(defn data->buffer
[{:keys [datatype data metadata]}]
(with-meta
(array-buffer/array-buffer data datatype)
metadata))
(nippy/extend-freeze
ArrayBuffer :tech.v3.datatype/buffer
[buf out]
(nippy/-freeze-without-meta! (buffer->data buf) out))
(nippy/extend-thaw
:tech.v3.datatype/buffer
[in]
(-> (nippy/thaw-from-in! in)
(data->buffer)))
(nippy/extend-freeze
NativeBuffer :tech.v3.datatype/buffer
[buf out]
(nippy/-freeze-without-meta! (buffer->data buf) out))
(nippy/extend-freeze
Buffer :tech.v3.datatype/buffer
[buf out]
(nippy/-freeze-without-meta! (buffer->data buf) out))
(defn tensor->data
[tensor]
{:shape (dtype-base/shape tensor)
:metadata (meta tensor)
:buffer (buffer->data (dtype-base/->buffer tensor))})
(defn data->tensor
[{:keys [shape buffer metadata]}]
(dtt/construct-tensor (data->buffer buffer)
(dims/dimensions shape)
metadata))
(nippy/extend-freeze
DataTensor :tech.v3/tensor
[buf out]
(nippy/-freeze-without-meta! (tensor->data buf) out))
(nippy/extend-freeze
DirectTensor :tech.v3/tensor
[buf out]
(nippy/-freeze-without-meta! (tensor->data buf) out))
(nippy/extend-thaw
:tech.v3/tensor
[in]
(-> (nippy/thaw-from-in! in)
(data->tensor)))
| |
718d77be4577c9c1a8f62de96808396e4b38cf84aa095083a03ae3fcd717953e | vikram/lisplibraries | time.lisp | -*- Mode : LISP ; Syntax : ANSI - Common - Lisp ; Base : 10 -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: time.lisp
Purpose : UFFI test file , time , use C structures
Author :
Date Started : Feb 2002
;;;;
$ I d : time.lisp 10608 2005 - 07 - 01 00:39:48Z
;;;;
This file , part of UFFI , is Copyright ( c ) 2002 - 2005 by
;;;;
;;;; *************************************************************************
(in-package #:uffi-tests)
(uffi:def-foreign-type time-t :unsigned-long)
(uffi:def-struct tm
(sec :int)
(min :int)
(hour :int)
(mday :int)
(mon :int)
(year :int)
(wday :int)
(yday :int)
(isdst :int)
gmoffset present on SusE SLES9
(gmoffset :long))
(uffi:def-function ("time" c-time)
((time (* time-t)))
:returning time-t)
(uffi:def-function "gmtime"
((time (* time-t)))
:returning (:struct-pointer tm))
(uffi:def-function "asctime"
((time (:struct-pointer tm)))
:returning :cstring)
(uffi:def-type time-t :unsigned-long)
(uffi:def-type tm-pointer (:struct-pointer tm))
(deftest :time.1
(uffi:with-foreign-object (time 'time-t)
(setf (uffi:deref-pointer time :unsigned-long) 7381)
(uffi:deref-pointer time :unsigned-long))
7381)
(deftest :time.2
(uffi:with-foreign-object (time 'time-t)
(setf (uffi:deref-pointer time :unsigned-long) 7381)
(let ((tm-ptr (the tm-pointer (gmtime time))))
(values (1+ (uffi:get-slot-value tm-ptr 'tm 'mon))
(uffi:get-slot-value tm-ptr 'tm 'mday)
(+ 1900 (uffi:get-slot-value tm-ptr 'tm 'year))
(uffi:get-slot-value tm-ptr 'tm 'hour)
(uffi:get-slot-value tm-ptr 'tm 'min)
(uffi:get-slot-value tm-ptr 'tm 'sec)
)))
1 1 1970 2 3 1)
(uffi:def-struct timeval
(secs :long)
(usecs :long))
(uffi:def-struct timezone
(minutes-west :int)
(dsttime :int))
(uffi:def-function ("gettimeofday" c-gettimeofday)
((tv (* timeval))
(tz (* timezone)))
:returning :int)
(defun get-utime ()
(uffi:with-foreign-object (tv 'timeval)
(let ((res (c-gettimeofday tv (uffi:make-null-pointer 'timezone))))
(values
(+ (* 1000000 (uffi:get-slot-value tv 'timeval 'secs))
(uffi:get-slot-value tv 'timeval 'usecs))
res))))
(deftest :timeofday.1
(multiple-value-bind (t1 res1) (get-utime)
(multiple-value-bind (t2 res2) (get-utime)
(and (or (= t2 t1) (> t2 t1))
(> t1 1000000000)
(> t2 1000000000)
(zerop res1)
(zerop res2))))
t)
(defun posix-time-to-asctime (secs)
"Converts number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)"
(string-right-trim
'(#\newline #\return)
(uffi:convert-from-cstring
(uffi:with-foreign-object (time 'time-t)
(setf (uffi:deref-pointer time :unsigned-long) secs)
(asctime (gmtime time))))))
(deftest :time.3
(posix-time-to-asctime 0)
"Thu Jan 1 00:00:00 1970")
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/uffi-1.5.17/tests/time.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 -*-
*************************************************************************
FILE IDENTIFICATION
Name: time.lisp
************************************************************************* | Purpose : UFFI test file , time , use C structures
Author :
Date Started : Feb 2002
$ I d : time.lisp 10608 2005 - 07 - 01 00:39:48Z
This file , part of UFFI , is Copyright ( c ) 2002 - 2005 by
(in-package #:uffi-tests)
(uffi:def-foreign-type time-t :unsigned-long)
(uffi:def-struct tm
(sec :int)
(min :int)
(hour :int)
(mday :int)
(mon :int)
(year :int)
(wday :int)
(yday :int)
(isdst :int)
gmoffset present on SusE SLES9
(gmoffset :long))
(uffi:def-function ("time" c-time)
((time (* time-t)))
:returning time-t)
(uffi:def-function "gmtime"
((time (* time-t)))
:returning (:struct-pointer tm))
(uffi:def-function "asctime"
((time (:struct-pointer tm)))
:returning :cstring)
(uffi:def-type time-t :unsigned-long)
(uffi:def-type tm-pointer (:struct-pointer tm))
(deftest :time.1
(uffi:with-foreign-object (time 'time-t)
(setf (uffi:deref-pointer time :unsigned-long) 7381)
(uffi:deref-pointer time :unsigned-long))
7381)
(deftest :time.2
(uffi:with-foreign-object (time 'time-t)
(setf (uffi:deref-pointer time :unsigned-long) 7381)
(let ((tm-ptr (the tm-pointer (gmtime time))))
(values (1+ (uffi:get-slot-value tm-ptr 'tm 'mon))
(uffi:get-slot-value tm-ptr 'tm 'mday)
(+ 1900 (uffi:get-slot-value tm-ptr 'tm 'year))
(uffi:get-slot-value tm-ptr 'tm 'hour)
(uffi:get-slot-value tm-ptr 'tm 'min)
(uffi:get-slot-value tm-ptr 'tm 'sec)
)))
1 1 1970 2 3 1)
(uffi:def-struct timeval
(secs :long)
(usecs :long))
(uffi:def-struct timezone
(minutes-west :int)
(dsttime :int))
(uffi:def-function ("gettimeofday" c-gettimeofday)
((tv (* timeval))
(tz (* timezone)))
:returning :int)
(defun get-utime ()
(uffi:with-foreign-object (tv 'timeval)
(let ((res (c-gettimeofday tv (uffi:make-null-pointer 'timezone))))
(values
(+ (* 1000000 (uffi:get-slot-value tv 'timeval 'secs))
(uffi:get-slot-value tv 'timeval 'usecs))
res))))
(deftest :timeofday.1
(multiple-value-bind (t1 res1) (get-utime)
(multiple-value-bind (t2 res2) (get-utime)
(and (or (= t2 t1) (> t2 t1))
(> t1 1000000000)
(> t2 1000000000)
(zerop res1)
(zerop res2))))
t)
(defun posix-time-to-asctime (secs)
"Converts number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)"
(string-right-trim
'(#\newline #\return)
(uffi:convert-from-cstring
(uffi:with-foreign-object (time 'time-t)
(setf (uffi:deref-pointer time :unsigned-long) secs)
(asctime (gmtime time))))))
(deftest :time.3
(posix-time-to-asctime 0)
"Thu Jan 1 00:00:00 1970")
|
e699cd8f927bb073e9a78ff3eff3747c6b596c18be50cff6d6f73a4ab74f91b9 | MarcFontaine/stm32hs | Env.hs | ----------------------------------------------------------------------------
-- |
Module : STM32.STLinkUSB.Env
Copyright : ( c ) 2017
-- License : BSD3
--
Maintainer :
-- Stability : experimental
Portability : GHC - only
--
The STLT is just a reader transformer of STLinkEnv .
# LANGUAGE RecordWildCards #
{-# LANGUAGE RankNTypes #-}
module STM32.STLinkUSB.Env
where
import System.USB
import Control.Monad.Trans.Reader
import Control.Monad.IO.Class
import STM32.STLinkUSB.USBUtils
import STM32.STLinkUSB.Commands (API(..))
type STLT m a = ReaderT STLinkEnv m a
type STL a = forall m. MonadIO m => ReaderT STLinkEnv m a
runSTLink :: STLT IO a -> IO a
runSTLink = runSTLink' defaultDebugLogger . runReaderT
runSTLink_verbose :: STLT IO a -> IO a
runSTLink_verbose = runSTLink' verboseDebugLogger . runReaderT
runSTLink' :: Logger -> (STLinkEnv -> IO a) -> IO a
runSTLink' logger action = do
usb <- findDefaultEndpoints
runSTLinkWith logger usb action
runSTLinkWith ::
Logger
-> (Ctx, Device, EndpointAddress, EndpointAddress, EndpointAddress)
-> (STLinkEnv -> IO a)
-> IO a
runSTLinkWith
debugLogger
(usbCtx, device, rxEndpoint, txEndpoint, traceEndpoint)
action
= withUSB device $ \deviceHandle -> (action STLinkEnv {..})
where
dongleAPI = APIV2
data STLinkEnv = STLinkEnv {
usbCtx :: Ctx
,rxEndpoint :: EndpointAddress
,txEndpoint :: EndpointAddress
,traceEndpoint :: EndpointAddress
,deviceHandle :: DeviceHandle
,dongleAPI :: API
,debugLogger :: Logger
}
asksDongleAPI :: STL API
asksDongleAPI = asks dongleAPI
data LogLevel = Debug | Info | Warn | Error deriving (Show,Eq,Ord)
type Logger = LogLevel -> String -> IO ()
debugSTL :: LogLevel -> String -> STL ()
debugSTL ll msg = do
logger <- asks debugLogger
liftIO $ logger ll msg
defaultDebugLogger :: Logger
defaultDebugLogger logLevel msg = case logLevel of
Debug -> return ()
Info -> return ()
_ -> putStrLn (show logLevel ++ " : " ++ msg )
verboseDebugLogger :: Logger
verboseDebugLogger logLevel msg
= putStrLn (show logLevel ++ " : " ++ msg )
| null | https://raw.githubusercontent.com/MarcFontaine/stm32hs/d7afeb8f9d83e01c76003f4b199b45044bd4e383/STLinkUSB/STM32/STLinkUSB/Env.hs | haskell | --------------------------------------------------------------------------
|
License : BSD3
Stability : experimental
# LANGUAGE RankNTypes # | Module : STM32.STLinkUSB.Env
Copyright : ( c ) 2017
Maintainer :
Portability : GHC - only
The STLT is just a reader transformer of STLinkEnv .
# LANGUAGE RecordWildCards #
module STM32.STLinkUSB.Env
where
import System.USB
import Control.Monad.Trans.Reader
import Control.Monad.IO.Class
import STM32.STLinkUSB.USBUtils
import STM32.STLinkUSB.Commands (API(..))
type STLT m a = ReaderT STLinkEnv m a
type STL a = forall m. MonadIO m => ReaderT STLinkEnv m a
runSTLink :: STLT IO a -> IO a
runSTLink = runSTLink' defaultDebugLogger . runReaderT
runSTLink_verbose :: STLT IO a -> IO a
runSTLink_verbose = runSTLink' verboseDebugLogger . runReaderT
runSTLink' :: Logger -> (STLinkEnv -> IO a) -> IO a
runSTLink' logger action = do
usb <- findDefaultEndpoints
runSTLinkWith logger usb action
runSTLinkWith ::
Logger
-> (Ctx, Device, EndpointAddress, EndpointAddress, EndpointAddress)
-> (STLinkEnv -> IO a)
-> IO a
runSTLinkWith
debugLogger
(usbCtx, device, rxEndpoint, txEndpoint, traceEndpoint)
action
= withUSB device $ \deviceHandle -> (action STLinkEnv {..})
where
dongleAPI = APIV2
data STLinkEnv = STLinkEnv {
usbCtx :: Ctx
,rxEndpoint :: EndpointAddress
,txEndpoint :: EndpointAddress
,traceEndpoint :: EndpointAddress
,deviceHandle :: DeviceHandle
,dongleAPI :: API
,debugLogger :: Logger
}
asksDongleAPI :: STL API
asksDongleAPI = asks dongleAPI
data LogLevel = Debug | Info | Warn | Error deriving (Show,Eq,Ord)
type Logger = LogLevel -> String -> IO ()
debugSTL :: LogLevel -> String -> STL ()
debugSTL ll msg = do
logger <- asks debugLogger
liftIO $ logger ll msg
defaultDebugLogger :: Logger
defaultDebugLogger logLevel msg = case logLevel of
Debug -> return ()
Info -> return ()
_ -> putStrLn (show logLevel ++ " : " ++ msg )
verboseDebugLogger :: Logger
verboseDebugLogger logLevel msg
= putStrLn (show logLevel ++ " : " ++ msg )
|
fe122a489455adb8cbb465738615e624090c19d60b61a24304bf6a894b7d97c7 | shayne-fletcher/zen | dict.ml | (*The type of a dictionary with keys of type ['a] and values of type
['b]*)
type ('a, 'b) dict = 'a -> 'b option
(*The empty dictionary maps every key to [None]*)
let empty (k : 'a) : 'b option = None
(*[add d k v] is the dictionary [d] together with a binding of [k] to
[v]*)
let add (d : ('a, 'b) dict) (k : 'a) (v : 'b) : ('a, 'b) dict =
fun k' ->
if k' = k then Some v else d k'
(*[find d k] retrieves the value bound to [k]*)
let find (d : ('a, 'b) dict) (k : 'a) : 'b option = d k
e.g.
Name | Age
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + = = = =
" Felonius Gru " | 53
" Dave the Minion " | 4.54e9
" Dr. " | 80
Name | Age
================================+====
"Felonius Gru" | 53
"Dave the Minion" | 4.54e9
"Dr. Joseph Albert Nefario" | 80
*)
let ages =
add
(add
(add
empty "Felonius Gru" 53
)
"Dave the Minion" (int_of_float 4.54e9)
)
"Dr. Nefario" 80
let _ =
find ages "Dave the Minion" |>
function | Some x -> x | _ -> failwith "Not found"
| null | https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/dict/dict.ml | ocaml | The type of a dictionary with keys of type ['a] and values of type
['b]
The empty dictionary maps every key to [None]
[add d k v] is the dictionary [d] together with a binding of [k] to
[v]
[find d k] retrieves the value bound to [k] | type ('a, 'b) dict = 'a -> 'b option
let empty (k : 'a) : 'b option = None
let add (d : ('a, 'b) dict) (k : 'a) (v : 'b) : ('a, 'b) dict =
fun k' ->
if k' = k then Some v else d k'
let find (d : ('a, 'b) dict) (k : 'a) : 'b option = d k
e.g.
Name | Age
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + = = = =
" Felonius Gru " | 53
" Dave the Minion " | 4.54e9
" Dr. " | 80
Name | Age
================================+====
"Felonius Gru" | 53
"Dave the Minion" | 4.54e9
"Dr. Joseph Albert Nefario" | 80
*)
let ages =
add
(add
(add
empty "Felonius Gru" 53
)
"Dave the Minion" (int_of_float 4.54e9)
)
"Dr. Nefario" 80
let _ =
find ages "Dave the Minion" |>
function | Some x -> x | _ -> failwith "Not found"
|
16103f5f3e7c2608295d7c046543caf0d0d9e604f2dcf6a4698dda4d4c90c45a | S8A/htdp-exercises | ex328.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-intermediate-lambda-reader.ss" "lang")((modname ex328) (read-case-sensitive #t) (teachpacks ((lib "abstraction.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "abstraction.rkt" "teachpack" "2htdp")) #f)))
; .: Data definitions :.
; An Atom is one of:
; – Number
; – String
; – Symbol
An S - expr is one of :
– Atom
– SL
An SL is one of :
; – '()
– ( cons S - expr SL )
; .: Data examples :.
(define a1 'hello)
(define a2 20.12)
(define a3 "world")
(define se1 '())
(define se2 '(hello 20.12 "world"))
(define se3 '((hello 20.12 "world")))
; S-expr Symbol Symbol -> S-expr
; Replaces old with new in the given s-expression
(define (substitute sexp old new)
(cond
[(atom? sexp) (if (equal? sexp old) new sexp)]
[else (map (lambda (s) (substitute s old new)) sexp)]))
(check-expect (substitute '(((world) bye) bye) 'bye '42)
'(((world) 42) 42))
(check-expect (substitute se1 'world 'hello) se1)
(check-expect (substitute se2 'world 'hello) se2)
(check-expect (substitute se3 'world 'hello) se3)
(check-expect (substitute 'world 'world 'hello) 'hello)
(check-expect (substitute '(world hello) 'world 'hello) '(hello hello))
(check-expect (substitute '(((world) hello) hello) 'world 'hello)
'(((hello) hello) hello))
; Any -> Boolean
Checks if x is an Atom
(define (atom? x)
(or (number? x) (string? x) (symbol? x)))
(check-expect (atom? 69420) #true)
(check-expect (atom? "Meshuggah") #true)
(check-expect (atom? 'x) #true)
(check-expect (atom? '()) #false)
(check-expect (atom? #true) #false)
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex328.rkt | racket | about the language level of this file in a form that our tools can easily process.
.: Data definitions :.
An Atom is one of:
– Number
– String
– Symbol
– '()
.: Data examples :.
S-expr Symbol Symbol -> S-expr
Replaces old with new in the given s-expression
Any -> Boolean | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex328) (read-case-sensitive #t) (teachpacks ((lib "abstraction.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "abstraction.rkt" "teachpack" "2htdp")) #f)))
An S - expr is one of :
– Atom
– SL
An SL is one of :
– ( cons S - expr SL )
(define a1 'hello)
(define a2 20.12)
(define a3 "world")
(define se1 '())
(define se2 '(hello 20.12 "world"))
(define se3 '((hello 20.12 "world")))
(define (substitute sexp old new)
(cond
[(atom? sexp) (if (equal? sexp old) new sexp)]
[else (map (lambda (s) (substitute s old new)) sexp)]))
(check-expect (substitute '(((world) bye) bye) 'bye '42)
'(((world) 42) 42))
(check-expect (substitute se1 'world 'hello) se1)
(check-expect (substitute se2 'world 'hello) se2)
(check-expect (substitute se3 'world 'hello) se3)
(check-expect (substitute 'world 'world 'hello) 'hello)
(check-expect (substitute '(world hello) 'world 'hello) '(hello hello))
(check-expect (substitute '(((world) hello) hello) 'world 'hello)
'(((hello) hello) hello))
Checks if x is an Atom
(define (atom? x)
(or (number? x) (string? x) (symbol? x)))
(check-expect (atom? 69420) #true)
(check-expect (atom? "Meshuggah") #true)
(check-expect (atom? 'x) #true)
(check-expect (atom? '()) #false)
(check-expect (atom? #true) #false)
|
127fda71114ce8732a96296cf8e54688c2eba74b4ec24c30997d8f4e8eaabb8f | appleshan/cl-http | http-proxy-6-19.lisp | -*- Mode : LISP ; Syntax : Ansi - common - lisp ; Package : HTTP ; Base : 10 ; Patch - File : T -*-
Patch file for HTTP - PROXY version 6.19
;;; Reason: Variable HTTP::*PROXY-PORT-ACCESS-CONTROL-ALIST*: -
;;; Function HTTP::PROXY-ACCESS-CONTROL: -
;;; Function HTTP::SET-PROXY-ACCESS-CONTROL: -
Function ( CLOS : METHOD HTTP::SET - PROXY - ACCESS - CONTROL ( LISP : INTEGER HTTP : ACCESS - CONTROL ) ): -
Function ( CLOS : METHOD HTTP::SET - PROXY - ACCESS - CONTROL ( T CONS ) ): -
;;; Function HTTP::WITH-PROXY-AUTHENTICATION-ACCESS-CONTROL: -
;;; Function (CLOS:METHOD HTTP::INVOKE-PROXY-SERVICE (HTTP::PROXY-SERVER-MIXIN T T T) :AROUND): install user access control.
Written by JCMa , 4/10/01 20:48:48
while running on FUJI - VLM from FUJI:/usr / lib / symbolics / ComLink-39 - 8 - F - MIT-8 - 5.vlod
with Open Genera 2.0 , Genera 8.5 , Documentation Database 440.12 ,
Logical Pathnames Translation Files NEWEST , CLIM 72.0 , Genera CLIM 72.0 ,
PostScript CLIM 72.0 , MAC 414.0 , 8 - 5 - Patches 2.19 , Statice Runtime 466.1 ,
Statice 466.0 , Statice Browser 466.0 , Statice Documentation 426.0 , ,
CLIM Documentation 72.0 , Showable Procedures 36.3 , Binary Tree 34.0 ,
Mailer 438.0 , Working LispM Mailer 8.0 , HTTP Server 70.118 ,
W3 Presentation System 8.1 , CL - HTTP Server Interface 53.0 ,
Symbolics Common Lisp Compatibility 4.0 , Comlink Packages 6.0 ,
Comlink Utilities 10.3 , COMLINK Cryptography 2.0 , Routing Taxonomy 9.0 ,
COMLINK Database 11.26 , Email Servers 12.0 , Comlink Customized LispM Mailer 7.1 ,
Dynamic Forms 14.5 , Communications Linker Server 39.8 ,
Lambda Information Retrieval System 22.3 , Experimental Genera 8 5 Patches 1.0 ,
Genera 8 5 System Patches 1.26 , 8 5 Mailer Patches 1.1 ,
Genera 8 5 , 8 5 Statice Runtime Patches 1.0 ,
Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 ,
Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.2 ,
Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 ,
Genera 8 5 Clim Doc Patches 1.0 , Genera 8 5 Image Substrate Patches 1.0 ,
Genera 8 5 Lock Simple Patches 1.0 , HTTP Proxy Server 6.18 ,
HTTP Client Substrate 4.9 , Statice Server 466.2 , HTTP Client 50.6 ,
Image Substrate 440.4 , Essential Image Substrate 433.0 , Ivory Revision 5 ,
VLM Debugger 329 , Genera program 8.16 , DEC OSF/1 V4.0 ( Rev. 110 ) ,
1280x976 8 - bit PSEUDO - COLOR X Screen FUJI:0.0 with 224 Genera fonts ( DECWINDOWS Digital Equipment Corporation Digital UNIX V4.0 R1 ) ,
Machine serial number -2141189585 ,
Domain Fixes ( from CML : MAILER;DOMAIN - FIXES.LISP.33 ) ,
Do n't force in the mail - x host ( from CML : MAILER;MAILBOX - FORMAT.LISP.24 ) ,
Make Mailer More Robust ( from CML : MAILER;MAILER - FIXES.LISP.15 ) ,
;;; Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10),
Add CLIM presentation and text style format directives . ( from FV : SCLC;FORMAT.LISP.20 ) ,
Fix Statice Lossage ( from CML : LISPM;STATICE - PATCH.LISP.3 ) ,
Make update schema work on set - value attributes with accessor names ( from CML : LISPM;STATICE - SET - VALUED - UPDATE.LISP.1 ) ,
COMLINK Mailer Patches . ( from CML : LISPM;MAILER - PATCH.LISP.107 ) ,
Clim patches ( from CML : DYNAMIC - FORMS;CLIM - PATCHES.LISP.48 ) ,
Domain ad host patch ( from > domain - ad - host - patch.lisp.21 ) ,
Background dns refreshing ( from > background - dns - refreshing.lisp.7 ) ,
;;; Cname level patch (from W:>Reti>cname-level-patch.lisp.10),
Fix FTP Directory List for Periods in Directory Names ( from > fix - ftp - directory - list.lisp.7 ) ,
TCP - FTP - PARSE - REPLY signal a type error when control connection lost . ( from W:>Reti > tcp - ftp - parse - reply - ) .
(SCT:FILES-PATCHED-IN-THIS-PATCH-FILE
"HTTP:PROXY;CACHE.LISP.156"
"HTTP:PROXY;PROXY.LISP.70")
(EVAL-WHEN (:COMPILE-TOPLEVEL :LOAD-TOPLEVEL)
(SCT:REQUIRE-PATCH-LEVEL-FOR-PATCH '(CL-HTTP 70. 119.)))
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
;;;-------------------------------------------------------------------
;;;
;;; PROXY USER ACCESS CONTROL
;;;
(define-variable *proxy-port-access-control-alist* nil
"Holds an alist mapping proxy ports to access controls.")
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(declaim (inline proxy-access-control))
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(defun proxy-access-control (port)
"Returns the access control for the proxy operating on PORT."
(cdr (assoc port *proxy-port-access-control-alist* :test #'eql)))
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(defmethod set-proxy-access-control ((port integer) (access-control access-control))
(let ((entry (assoc port *proxy-port-access-control-alist* :test #'eql)))
(if entry
(setf (cdr entry) access-control)
(push (list* port access-control) *proxy-port-access-control-alist*)))
access-control)
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(defmethod set-proxy-access-control (port (access-control-spec cons))
(destructuring-bind ((realm-name &rest realm-args) access-control-name &rest access-control-args)
access-control-spec
(declare (dynamic-extent realm-args access-control-args))
(let* ((realm-object (apply #'intern-realm realm-name realm-args))
(access-control-object (apply #'intern-access-control realm-object access-control-name access-control-args)))
(set-proxy-access-control port access-control-object))))
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(defgeneric set-proxy-access-control (port access-control)
(:documentation "Sets user-based access control for the proxy running on port, PORT, to use ACCESS-CONTROL.
ACCESS-CONTROL is either a named access control or NIL. When NIL, user-based access control
is turned off on PORT. When it is a specification suitable for interning the realm and
access control, the syntax for ACCESS-CONTROL is:
((REALM-NAME &REST REALM-ARGS) ACCESS-CONTROL-NAME &REST ACCESS-CONTROL-ARGS)
Where REALM-ARGS are arguments to INTERN-REALM and ACCESS-CONTROL-ARGS are arguments
to INTERN-ACCESS-CONTROL, excluding the realm."))
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(define-macro with-proxy-authentication-access-control ((proxy-access-control method &key rejection-form (server '*server*)) &body body)
"Executes REJECTION-FORM whenever AUTHORIZATION does not qualify for capabilities under PROXY-ACCESS-CONTROL.
Otherwise executes BODY."
`(let (.access-control.)
(cond ((setq .access-control. ,proxy-access-control)
(let ((realm (access-control-realm .access-control.))
authorization user)
(handler-case
(cond ((and (setq authorization (get-header :proxy-authorization *headers*))
(setq user (authenticate-user realm authorization ,method :proxy-access))
(allow-user-access-p .access-control. user ,method))
(setf (server-user-object ,server) user)
,@body)
(t ,rejection-form))
(unknown-authentication-method () ,rejection-form))))
(t ,@body))))
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;PROXY.LISP.70")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Syntax: Ansi-Common-Lisp; Base: 10; Mode: lisp; Package: http -*-")
;;;-------------------------------------------------------------------
;;;
;;; PROXY METHODS
;;;
(defmethod invoke-proxy-service :around ((server proxy-server-mixin) url method http-version)
(flet ((provide-proxy-service (server url method http-version &aux (catch-error-p (not *debug-proxy*)))
(flet ((ensure-live-upstream-connection (condition)
(declare (ignore condition))
(abort-if-connection-inactive *server*)
nil))
(handler-case-if
catch-error-p
;; Nasty signalling ensues if the client has dropped the connection,
so intercept errors here and abort the connection if the client is gone . -- JCMa 5/24/1999 .
(handler-bind-if catch-error-p
((condition #'ensure-live-upstream-connection))
;; Set the life time for the connection
(setf (server-life-time server) *proxy-server-life-time*)
;; call the primary method
(call-next-method server url method http-version))
(unknown-host-name (err) (error 'proxy-unresolvable-domain-name :format-string (report-string err)
:method method :url url))
(protocol-timeout (err) (error 'proxy-connection-timeout :format-string (report-string err)
:method method :url url))
(connection-refused (err) (error 'proxy-connection-refused :format-string (report-string err)
:method method :url url))
(local-network-error (err) (error 'proxy-local-network-error :format-string (report-string err)
:method method :url url :close-connection t))
(remote-network-error (err) (error 'proxy-remote-network-error :format-string (report-string err)
:method method :url url :close-connection t))))))
(let ((proxy-access-control (proxy-access-control 8000)))
(typecase proxy-access-control
(null ;; Always respect subnet security as the default
(with-subnet-access-control
((server-address server) (or *proxy-subnets* *secure-subnets*)
:deny-subnets *disallowed-subnets*
:rejection-form (error 'proxy-access-forbidden :method method :url url))
(provide-proxy-service server url method http-version)))
(basic-access-control ;; Respect subnet security for basic access control
(with-subnet-access-control
((server-address server) (or *proxy-subnets* *secure-subnets*)
:deny-subnets *disallowed-subnets*
:rejection-form (error 'proxy-access-forbidden :method method :url url))
(with-proxy-authentication-access-control
(proxy-access-control
method
:server server
:rejection-form (error 'recoverable-unauthorized-proxy-access :method method :url url
:authentication-realm realm :authentication-method (realm-scheme realm)))
(provide-proxy-service server url method http-version))))
;; Require either subnet security or digest user access. Make this configurable sometime -- JCMa 04/10/2001
(t (with-proxy-authentication-access-control
(proxy-access-control
method
:server server
:rejection-form (with-subnet-access-control
((server-address server) (or *proxy-subnets* *secure-subnets*)
:deny-subnets *disallowed-subnets*
:rejection-form (error 'recoverable-unauthorized-proxy-access :method method :url url
:authentication-realm realm :authentication-method (realm-scheme realm)))
(provide-proxy-service server url method http-version)))
(provide-proxy-service server url method http-version)))))))
| null | https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/lispm/proxy/patch/http-proxy-6/http-proxy-6-19.lisp | lisp | Syntax : Ansi - common - lisp ; Package : HTTP ; Base : 10 ; Patch - File : T -*-
Reason: Variable HTTP::*PROXY-PORT-ACCESS-CONTROL-ALIST*: -
Function HTTP::PROXY-ACCESS-CONTROL: -
Function HTTP::SET-PROXY-ACCESS-CONTROL: -
Function HTTP::WITH-PROXY-AUTHENTICATION-ACCESS-CONTROL: -
Function (CLOS:METHOD HTTP::INVOKE-PROXY-SERVICE (HTTP::PROXY-SERVER-MIXIN T T T) :AROUND): install user access control.
DOMAIN - FIXES.LISP.33 ) ,
MAILBOX - FORMAT.LISP.24 ) ,
MAILER - FIXES.LISP.15 ) ,
Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10),
FORMAT.LISP.20 ) ,
STATICE - PATCH.LISP.3 ) ,
STATICE - SET - VALUED - UPDATE.LISP.1 ) ,
MAILER - PATCH.LISP.107 ) ,
CLIM - PATCHES.LISP.48 ) ,
Cname level patch (from W:>Reti>cname-level-patch.lisp.10),
========================
-------------------------------------------------------------------
PROXY USER ACCESS CONTROL
========================
========================
========================
========================
========================
========================
========================
-------------------------------------------------------------------
PROXY METHODS
Nasty signalling ensues if the client has dropped the connection,
Set the life time for the connection
call the primary method
Always respect subnet security as the default
Respect subnet security for basic access control
Require either subnet security or digest user access. Make this configurable sometime -- JCMa 04/10/2001 | Patch file for HTTP - PROXY version 6.19
Function ( CLOS : METHOD HTTP::SET - PROXY - ACCESS - CONTROL ( LISP : INTEGER HTTP : ACCESS - CONTROL ) ): -
Function ( CLOS : METHOD HTTP::SET - PROXY - ACCESS - CONTROL ( T CONS ) ): -
Written by JCMa , 4/10/01 20:48:48
while running on FUJI - VLM from FUJI:/usr / lib / symbolics / ComLink-39 - 8 - F - MIT-8 - 5.vlod
with Open Genera 2.0 , Genera 8.5 , Documentation Database 440.12 ,
Logical Pathnames Translation Files NEWEST , CLIM 72.0 , Genera CLIM 72.0 ,
PostScript CLIM 72.0 , MAC 414.0 , 8 - 5 - Patches 2.19 , Statice Runtime 466.1 ,
Statice 466.0 , Statice Browser 466.0 , Statice Documentation 426.0 , ,
CLIM Documentation 72.0 , Showable Procedures 36.3 , Binary Tree 34.0 ,
Mailer 438.0 , Working LispM Mailer 8.0 , HTTP Server 70.118 ,
W3 Presentation System 8.1 , CL - HTTP Server Interface 53.0 ,
Symbolics Common Lisp Compatibility 4.0 , Comlink Packages 6.0 ,
Comlink Utilities 10.3 , COMLINK Cryptography 2.0 , Routing Taxonomy 9.0 ,
COMLINK Database 11.26 , Email Servers 12.0 , Comlink Customized LispM Mailer 7.1 ,
Dynamic Forms 14.5 , Communications Linker Server 39.8 ,
Lambda Information Retrieval System 22.3 , Experimental Genera 8 5 Patches 1.0 ,
Genera 8 5 System Patches 1.26 , 8 5 Mailer Patches 1.1 ,
Genera 8 5 , 8 5 Statice Runtime Patches 1.0 ,
Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 ,
Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.2 ,
Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 ,
Genera 8 5 Clim Doc Patches 1.0 , Genera 8 5 Image Substrate Patches 1.0 ,
Genera 8 5 Lock Simple Patches 1.0 , HTTP Proxy Server 6.18 ,
HTTP Client Substrate 4.9 , Statice Server 466.2 , HTTP Client 50.6 ,
Image Substrate 440.4 , Essential Image Substrate 433.0 , Ivory Revision 5 ,
VLM Debugger 329 , Genera program 8.16 , DEC OSF/1 V4.0 ( Rev. 110 ) ,
1280x976 8 - bit PSEUDO - COLOR X Screen FUJI:0.0 with 224 Genera fonts ( DECWINDOWS Digital Equipment Corporation Digital UNIX V4.0 R1 ) ,
Machine serial number -2141189585 ,
Domain ad host patch ( from > domain - ad - host - patch.lisp.21 ) ,
Background dns refreshing ( from > background - dns - refreshing.lisp.7 ) ,
Fix FTP Directory List for Periods in Directory Names ( from > fix - ftp - directory - list.lisp.7 ) ,
TCP - FTP - PARSE - REPLY signal a type error when control connection lost . ( from W:>Reti > tcp - ftp - parse - reply - ) .
(SCT:FILES-PATCHED-IN-THIS-PATCH-FILE
"HTTP:PROXY;CACHE.LISP.156"
"HTTP:PROXY;PROXY.LISP.70")
(EVAL-WHEN (:COMPILE-TOPLEVEL :LOAD-TOPLEVEL)
(SCT:REQUIRE-PATCH-LEVEL-FOR-PATCH '(CL-HTTP 70. 119.)))
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(define-variable *proxy-port-access-control-alist* nil
"Holds an alist mapping proxy ports to access controls.")
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(declaim (inline proxy-access-control))
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(defun proxy-access-control (port)
"Returns the access control for the proxy operating on PORT."
(cdr (assoc port *proxy-port-access-control-alist* :test #'eql)))
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(defmethod set-proxy-access-control ((port integer) (access-control access-control))
(let ((entry (assoc port *proxy-port-access-control-alist* :test #'eql)))
(if entry
(setf (cdr entry) access-control)
(push (list* port access-control) *proxy-port-access-control-alist*)))
access-control)
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(defmethod set-proxy-access-control (port (access-control-spec cons))
(destructuring-bind ((realm-name &rest realm-args) access-control-name &rest access-control-args)
access-control-spec
(declare (dynamic-extent realm-args access-control-args))
(let* ((realm-object (apply #'intern-realm realm-name realm-args))
(access-control-object (apply #'intern-access-control realm-object access-control-name access-control-args)))
(set-proxy-access-control port access-control-object))))
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(defgeneric set-proxy-access-control (port access-control)
(:documentation "Sets user-based access control for the proxy running on port, PORT, to use ACCESS-CONTROL.
ACCESS-CONTROL is either a named access control or NIL. When NIL, user-based access control
is turned off on PORT. When it is a specification suitable for interning the realm and
access control, the syntax for ACCESS-CONTROL is:
((REALM-NAME &REST REALM-ARGS) ACCESS-CONTROL-NAME &REST ACCESS-CONTROL-ARGS)
Where REALM-ARGS are arguments to INTERN-REALM and ACCESS-CONTROL-ARGS are arguments
to INTERN-ACCESS-CONTROL, excluding the realm."))
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;CACHE.LISP.156")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Mode: lisp; Package: HTTP; BASE: 10; Syntax: ANSI-Common-Lisp; Default-Character-Style: (:FIX :ROMAN :NORMAL);-*-")
(define-macro with-proxy-authentication-access-control ((proxy-access-control method &key rejection-form (server '*server*)) &body body)
"Executes REJECTION-FORM whenever AUTHORIZATION does not qualify for capabilities under PROXY-ACCESS-CONTROL.
Otherwise executes BODY."
`(let (.access-control.)
(cond ((setq .access-control. ,proxy-access-control)
(let ((realm (access-control-realm .access-control.))
authorization user)
(handler-case
(cond ((and (setq authorization (get-header :proxy-authorization *headers*))
(setq user (authenticate-user realm authorization ,method :proxy-access))
(allow-user-access-p .access-control. user ,method))
(setf (server-user-object ,server) user)
,@body)
(t ,rejection-form))
(unknown-authentication-method () ,rejection-form))))
(t ,@body))))
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:PROXY;PROXY.LISP.70")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Syntax: Ansi-Common-Lisp; Base: 10; Mode: lisp; Package: http -*-")
(defmethod invoke-proxy-service :around ((server proxy-server-mixin) url method http-version)
(flet ((provide-proxy-service (server url method http-version &aux (catch-error-p (not *debug-proxy*)))
(flet ((ensure-live-upstream-connection (condition)
(declare (ignore condition))
(abort-if-connection-inactive *server*)
nil))
(handler-case-if
catch-error-p
so intercept errors here and abort the connection if the client is gone . -- JCMa 5/24/1999 .
(handler-bind-if catch-error-p
((condition #'ensure-live-upstream-connection))
(setf (server-life-time server) *proxy-server-life-time*)
(call-next-method server url method http-version))
(unknown-host-name (err) (error 'proxy-unresolvable-domain-name :format-string (report-string err)
:method method :url url))
(protocol-timeout (err) (error 'proxy-connection-timeout :format-string (report-string err)
:method method :url url))
(connection-refused (err) (error 'proxy-connection-refused :format-string (report-string err)
:method method :url url))
(local-network-error (err) (error 'proxy-local-network-error :format-string (report-string err)
:method method :url url :close-connection t))
(remote-network-error (err) (error 'proxy-remote-network-error :format-string (report-string err)
:method method :url url :close-connection t))))))
(let ((proxy-access-control (proxy-access-control 8000)))
(typecase proxy-access-control
(with-subnet-access-control
((server-address server) (or *proxy-subnets* *secure-subnets*)
:deny-subnets *disallowed-subnets*
:rejection-form (error 'proxy-access-forbidden :method method :url url))
(provide-proxy-service server url method http-version)))
(with-subnet-access-control
((server-address server) (or *proxy-subnets* *secure-subnets*)
:deny-subnets *disallowed-subnets*
:rejection-form (error 'proxy-access-forbidden :method method :url url))
(with-proxy-authentication-access-control
(proxy-access-control
method
:server server
:rejection-form (error 'recoverable-unauthorized-proxy-access :method method :url url
:authentication-realm realm :authentication-method (realm-scheme realm)))
(provide-proxy-service server url method http-version))))
(t (with-proxy-authentication-access-control
(proxy-access-control
method
:server server
:rejection-form (with-subnet-access-control
((server-address server) (or *proxy-subnets* *secure-subnets*)
:deny-subnets *disallowed-subnets*
:rejection-form (error 'recoverable-unauthorized-proxy-access :method method :url url
:authentication-realm realm :authentication-method (realm-scheme realm)))
(provide-proxy-service server url method http-version)))
(provide-proxy-service server url method http-version)))))))
|
0faccafef6812699f6f90798a2940fa2b2667f691e2efb29e1092c7a8b106c90 | emqx/mria | mria_upstream.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2022 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
%% @doc This module contains functions for updating the upstream
%% of the table.
%%
Upstream means a core node or the local node if we are talking
%% about `local_content' shard.
%%
%% NOTE: All of these functions can be called remotely via RPC
-module(mria_upstream).
%% API:
%% Internal exports
-export([ transactional_wrapper/3
, dirty_wrapper/4
, dirty_write_sync/2
]).
-export_type([]).
%%================================================================================
%% Type declarations
%%================================================================================
%%================================================================================
%% API funcions
%%================================================================================
-spec transactional_wrapper(mria_rlog:shard(), fun(), list()) -> mria:t_result(term()).
transactional_wrapper(Shard, Fun, Args) ->
OldServerPid = whereis(Shard),
ensure_no_transaction(),
mria_rlog:wait_for_shards([Shard], infinity),
mnesia:transaction(fun() ->
Res = apply(Fun, Args),
{_TID, TxStore} = mria_mnesia:get_internals(),
ensure_no_ops_outside_shard(TxStore, Shard, OldServerPid),
Res
end).
%% @doc Perform syncronous dirty operation
-spec dirty_write_sync(mria:table(), tuple()) -> ok.
dirty_write_sync(Table, Record) ->
mnesia:sync_dirty(
fun() ->
mnesia:write(Table, Record, write)
end).
-spec dirty_wrapper(module(), atom(), mria:table(), list()) -> {ok | error | exit, term()}.
dirty_wrapper(Module, Function, Table, Args) ->
try apply(Module, Function, [Table|Args]) of
Result -> {ok, Result}
catch
EC : Err ->
{EC, Err}
end.
%%================================================================================
Internal functions
%%================================================================================
ensure_no_transaction() ->
case mnesia:get_activity_id() of
undefined -> ok;
_ -> error(nested_transaction)
end.
ensure_no_ops_outside_shard(TxStore, Shard, OldServerPid) ->
case mria_config:strict_mode() of
true -> do_ensure_no_ops_outside_shard(TxStore, Shard, OldServerPid);
false -> ok
end.
do_ensure_no_ops_outside_shard(TxStore, Shard, OldServerPid) ->
Tables = ets:match(TxStore, {{'$1', '_'}, '_', '_'}),
lists:foreach( fun([Table]) ->
case mria_config:shard_rlookup(Table) =:= Shard of
true -> ok;
false -> case whereis(Shard) of
OldServerPid ->
mnesia:abort({invalid_transaction, Table, Shard});
ServerPid ->
mnesia:abort({retry, {OldServerPid, ServerPid}})
end
end
end
, Tables
),
ok.
| null | https://raw.githubusercontent.com/emqx/mria/fcec1873582c3a66c960da6c7f6d48ac73c64c13/src/mria_upstream.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
@doc This module contains functions for updating the upstream
of the table.
about `local_content' shard.
NOTE: All of these functions can be called remotely via RPC
API:
Internal exports
================================================================================
Type declarations
================================================================================
================================================================================
API funcions
================================================================================
@doc Perform syncronous dirty operation
================================================================================
================================================================================ | Copyright ( c ) 2022 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
Upstream means a core node or the local node if we are talking
-module(mria_upstream).
-export([ transactional_wrapper/3
, dirty_wrapper/4
, dirty_write_sync/2
]).
-export_type([]).
-spec transactional_wrapper(mria_rlog:shard(), fun(), list()) -> mria:t_result(term()).
transactional_wrapper(Shard, Fun, Args) ->
OldServerPid = whereis(Shard),
ensure_no_transaction(),
mria_rlog:wait_for_shards([Shard], infinity),
mnesia:transaction(fun() ->
Res = apply(Fun, Args),
{_TID, TxStore} = mria_mnesia:get_internals(),
ensure_no_ops_outside_shard(TxStore, Shard, OldServerPid),
Res
end).
-spec dirty_write_sync(mria:table(), tuple()) -> ok.
dirty_write_sync(Table, Record) ->
mnesia:sync_dirty(
fun() ->
mnesia:write(Table, Record, write)
end).
-spec dirty_wrapper(module(), atom(), mria:table(), list()) -> {ok | error | exit, term()}.
dirty_wrapper(Module, Function, Table, Args) ->
try apply(Module, Function, [Table|Args]) of
Result -> {ok, Result}
catch
EC : Err ->
{EC, Err}
end.
Internal functions
ensure_no_transaction() ->
case mnesia:get_activity_id() of
undefined -> ok;
_ -> error(nested_transaction)
end.
ensure_no_ops_outside_shard(TxStore, Shard, OldServerPid) ->
case mria_config:strict_mode() of
true -> do_ensure_no_ops_outside_shard(TxStore, Shard, OldServerPid);
false -> ok
end.
do_ensure_no_ops_outside_shard(TxStore, Shard, OldServerPid) ->
Tables = ets:match(TxStore, {{'$1', '_'}, '_', '_'}),
lists:foreach( fun([Table]) ->
case mria_config:shard_rlookup(Table) =:= Shard of
true -> ok;
false -> case whereis(Shard) of
OldServerPid ->
mnesia:abort({invalid_transaction, Table, Shard});
ServerPid ->
mnesia:abort({retry, {OldServerPid, ServerPid}})
end
end
end
, Tables
),
ok.
|
3852c95b699c9d6089e70a05c63c5fbeb9301097a7b74814e519cf911692fae5 | benzap/eden | async.cljc | (ns eden.stdlib.async
(:require
[eden.def :refer [set-var!]]
[clojure.core.async :as async]))
(def async-ns
{:<!! async/<!!
:>!! async/>!!
:admix async/admix
:alts!! async/alts!!
:buffer async/buffer
:chan async/chan
:close! async/close!
:dropping-buffer async/dropping-buffer
:into async/into
:map async/map
:merge async/merge
:mix async/mix
:mult async/mult
:offer! async/offer!
:onto-chan async/onto-chan
:pipe async/pipe
:pipeline async/pipeline
:pipeline-blocking async/pipeline-blocking
:pipeline-async async/pipeline-async
:poll! async/poll!
:promise-chan async/promise-chan
:pub async/pub
:put! async/put!
:put!! async/>!!
:reduce async/reduce
:sliding-buffer async/sliding-buffer
:solo-mode async/solo-mode
:split async/split
:sub async/sub
:take async/take
:take! async/take!
:take!! async/<!!
:tap async/tap
:timeout async/timeout
:to-chan async/to-chan
:toggle async/toggle
:transduce async/transduce
:unblocking-buffer? async/unblocking-buffer?
:unmix async/unmix
:unmix-all async/unmix-all
:unsub async/unsub
:unsub-all async/unsub-all
:untap async/untap
:untap-all async/untap-all})
(defn import-stdlib-async
[eden]
(-> eden
(set-var! 'async async-ns)))
| null | https://raw.githubusercontent.com/benzap/eden/dbfa63dc18dbc5ef18a9b2b16dbb7af0e633f6d0/src/eden/stdlib/async.cljc | clojure | (ns eden.stdlib.async
(:require
[eden.def :refer [set-var!]]
[clojure.core.async :as async]))
(def async-ns
{:<!! async/<!!
:>!! async/>!!
:admix async/admix
:alts!! async/alts!!
:buffer async/buffer
:chan async/chan
:close! async/close!
:dropping-buffer async/dropping-buffer
:into async/into
:map async/map
:merge async/merge
:mix async/mix
:mult async/mult
:offer! async/offer!
:onto-chan async/onto-chan
:pipe async/pipe
:pipeline async/pipeline
:pipeline-blocking async/pipeline-blocking
:pipeline-async async/pipeline-async
:poll! async/poll!
:promise-chan async/promise-chan
:pub async/pub
:put! async/put!
:put!! async/>!!
:reduce async/reduce
:sliding-buffer async/sliding-buffer
:solo-mode async/solo-mode
:split async/split
:sub async/sub
:take async/take
:take! async/take!
:take!! async/<!!
:tap async/tap
:timeout async/timeout
:to-chan async/to-chan
:toggle async/toggle
:transduce async/transduce
:unblocking-buffer? async/unblocking-buffer?
:unmix async/unmix
:unmix-all async/unmix-all
:unsub async/unsub
:unsub-all async/unsub-all
:untap async/untap
:untap-all async/untap-all})
(defn import-stdlib-async
[eden]
(-> eden
(set-var! 'async async-ns)))
| |
33f0fbfae895dc4bacbd91709508c69c183b9b3767b1e4212d15a8fa6c59b153 | circleci/mongofinil | test_hooks.clj | (ns mongofinil.test-hooks
(:require [bond.james :as bond]
[midje.sweet :refer (anything contains fact)]
[mongofinil.core :as core]
[mongofinil.testing-utils :as utils]))
(utils/setup-test-db)
(utils/setup-midje)
(defn update-hook [row]
(update-in row [:hook-count] (fnil inc 0)))
(defn pre-update-hook [query]
(update-in query [:pre-hooks] (fnil inc 0)))
(defn load-hook [row]
(update-in row [:loaded] (fnil inc 0)))
(core/defmodel :xs
:fields [{:name :x :findable true}]
:hooks {:update {:post #'update-hook
:pre #'pre-update-hook}
:load {:post #'load-hook}})
(fact "post hooks are triggered"
(bond/with-spy [load-hook]
(let [orig (create! {:x "x"})]
orig => (contains {:hook-count 1})
(-> load-hook bond/calls count) => 1))
(bond/with-spy [load-hook]
(find-one-by-x "x")
(-> load-hook bond/calls count) => 1)
(create! {:x "x"})
(bond/with-spy [load-hook]
(let [results-count (count (find-by-x "x"))]
(-> load-hook bond/calls count) => results-count)))
(fact "pre hooks are triggered"
(bond/with-spy [pre-update-hook]
(let [orig (create! {})]
orig => (contains {:pre-hooks 1})
(-> pre-update-hook bond/calls count) => 1
(let [update (set-fields! orig {:c 1})]
update => (contains {:pre-hooks 2})
(-> pre-update-hook bond/calls count) => 2))))
(fact "post hooks aren't called when no rows are returned"
(bond/with-spy [load-hook]
(seq (find-one :where {:bogus 987})) => nil
(-> load-hook bond/calls count) => 0))
(fact "pre hooks aren't called when there is no query"
(bond/with-spy [pre-update-hook]
(find-one) => anything
(-> pre-update-hook bond/calls count) => 0))
(fact "handles options to find-and-modify"
(bond/with-spy [pre-update-hook]
(find-and-modify! {:bogus 987} {:$set {:b 2}} :upsert? false)
(-> (all) count) => 0
(-> pre-update-hook bond/calls count) => 1
(find-and-modify! {:bogus 987} {:$set {:b 2}} :upsert? true)
(-> (all) count) => 1
(-> pre-update-hook bond/calls count) => 2))
| null | https://raw.githubusercontent.com/circleci/mongofinil/bceedb4f0d7d49934410131be8e29ba3c21ad3ad/test/mongofinil/test_hooks.clj | clojure | (ns mongofinil.test-hooks
(:require [bond.james :as bond]
[midje.sweet :refer (anything contains fact)]
[mongofinil.core :as core]
[mongofinil.testing-utils :as utils]))
(utils/setup-test-db)
(utils/setup-midje)
(defn update-hook [row]
(update-in row [:hook-count] (fnil inc 0)))
(defn pre-update-hook [query]
(update-in query [:pre-hooks] (fnil inc 0)))
(defn load-hook [row]
(update-in row [:loaded] (fnil inc 0)))
(core/defmodel :xs
:fields [{:name :x :findable true}]
:hooks {:update {:post #'update-hook
:pre #'pre-update-hook}
:load {:post #'load-hook}})
(fact "post hooks are triggered"
(bond/with-spy [load-hook]
(let [orig (create! {:x "x"})]
orig => (contains {:hook-count 1})
(-> load-hook bond/calls count) => 1))
(bond/with-spy [load-hook]
(find-one-by-x "x")
(-> load-hook bond/calls count) => 1)
(create! {:x "x"})
(bond/with-spy [load-hook]
(let [results-count (count (find-by-x "x"))]
(-> load-hook bond/calls count) => results-count)))
(fact "pre hooks are triggered"
(bond/with-spy [pre-update-hook]
(let [orig (create! {})]
orig => (contains {:pre-hooks 1})
(-> pre-update-hook bond/calls count) => 1
(let [update (set-fields! orig {:c 1})]
update => (contains {:pre-hooks 2})
(-> pre-update-hook bond/calls count) => 2))))
(fact "post hooks aren't called when no rows are returned"
(bond/with-spy [load-hook]
(seq (find-one :where {:bogus 987})) => nil
(-> load-hook bond/calls count) => 0))
(fact "pre hooks aren't called when there is no query"
(bond/with-spy [pre-update-hook]
(find-one) => anything
(-> pre-update-hook bond/calls count) => 0))
(fact "handles options to find-and-modify"
(bond/with-spy [pre-update-hook]
(find-and-modify! {:bogus 987} {:$set {:b 2}} :upsert? false)
(-> (all) count) => 0
(-> pre-update-hook bond/calls count) => 1
(find-and-modify! {:bogus 987} {:$set {:b 2}} :upsert? true)
(-> (all) count) => 1
(-> pre-update-hook bond/calls count) => 2))
| |
842a2a701d100d723abd2812799ccba88b141cfd737ec5dc9fa8066e8cae902f | logseq/logseq | graph.cljs | (ns frontend.handler.graph
"Provides util handler fns for graph view"
(:require [clojure.set :as set]
[clojure.string :as string]
[frontend.db :as db]
[logseq.db.default :as default-db]
[frontend.state :as state]
[frontend.util :as util]))
(defn- build-links
[links]
(map (fn [[from to]]
{:source from
:target to})
links))
(defn- build-nodes
[dark? current-page page-links tags nodes namespaces]
(let [parents (set (map last namespaces))
current-page (or current-page "")
pages (set (flatten nodes))]
(->>
pages
(remove nil?)
(mapv (fn [p]
(let [p (str p)
current-page? (= p current-page)
color (case [dark? current-page?] ; FIXME: Put it into CSS
[false false] "#999"
[false true] "#045591"
[true false] "#93a1a1"
[true true] "#ffffff")
color (if (contains? tags p)
(if dark? "orange" "green")
color)
n (get page-links p 1)
size (int (* 8 (max 1.0 (js/Math.cbrt n))))]
(cond->
{:id p
:label p
:size size
:color color}
(contains? parents p)
(assoc :parent true))))))))
;; slow
(defn- uuid-or-asset?
[id]
(or (util/uuid-string? id)
(string/starts-with? id "../assets/")
(= id "..")
(string/starts-with? id "assets/")
(string/ends-with? id ".gif")
(string/ends-with? id ".jpg")
(string/ends-with? id ".png")))
(defn- remove-uuids-and-files!
[nodes]
(remove
(fn [node] (uuid-or-asset? (:id node)))
nodes))
(defn- normalize-page-name
[{:keys [nodes links page-name->original-name]}]
(let [links (->>
(map
(fn [{:keys [source target]}]
(let [source (get page-name->original-name source)
target (get page-name->original-name target)]
(when (and source target)
{:source source :target target})))
links)
(remove nil?))
nodes (->> (remove-uuids-and-files! nodes)
(util/distinct-by (fn [node] (:id node)))
(map (fn [node]
(if-let [original-name (get page-name->original-name (:id node))]
(assoc node :id original-name :label original-name)
nil)))
(remove nil?))]
{:nodes nodes
:links links}))
(defn build-global-graph
[theme {:keys [journal? orphan-pages? builtin-pages? excluded-pages?]}]
(let [dark? (= "dark" theme)
current-page (or (:block/name (db/get-current-page)) "")]
(when-let [repo (state/get-current-repo)]
(let [relation (db/get-pages-relation repo journal?)
tagged-pages (db/get-all-tagged-pages repo)
namespaces (db/get-all-namespace-relation repo)
tags (set (map second tagged-pages))
full-pages (db/get-all-pages repo)
all-pages (map db/get-original-name full-pages)
page-name->original-name (zipmap (map :block/name full-pages) all-pages)
pages-after-journal-filter (if-not journal?
(remove :block/journal? full-pages)
full-pages)
pages-after-exclude-filter (cond->> pages-after-journal-filter
(not excluded-pages?)
(remove (fn [p] (= true (:exclude-from-graph-view (:block/properties p))))))
links (concat (seq relation)
(seq tagged-pages)
(seq namespaces))
linked (set (flatten links))
build-in-pages (set (map string/lower-case default-db/built-in-pages-names))
nodes (cond->> (map :block/name pages-after-exclude-filter)
(not builtin-pages?)
(remove (fn [p] (contains? build-in-pages (string/lower-case p))))
(not orphan-pages?)
(filter #(contains? linked (string/lower-case %))))
page-links (reduce (fn [m [k v]] (-> (update m k inc)
(update v inc))) {} links)
links (build-links (remove (fn [[_ to]] (nil? to)) links))
nodes (build-nodes dark? (string/lower-case current-page) page-links tags nodes namespaces)]
(normalize-page-name
{:nodes nodes
:links links
:page-name->original-name page-name->original-name})))))
(defn build-page-graph
[page theme show-journal]
(let [dark? (= "dark" theme)]
(when-let [repo (state/get-current-repo)]
(let [page (util/page-name-sanity-lc page)
page-entity (db/entity [:block/name page])
tags (:tags (:block/properties page-entity))
tags (remove #(= page %) tags)
ref-pages (db/get-page-referenced-pages repo page)
mentioned-pages (db/get-pages-that-mentioned-page repo page show-journal)
namespaces (db/get-all-namespace-relation repo)
links (concat
namespaces
(map (fn [[p _aliases]]
[page p]) ref-pages)
(map (fn [[p _aliases]]
[p page]) mentioned-pages)
(map (fn [tag]
[page tag])
tags))
other-pages (->> (concat (map first ref-pages)
(map first mentioned-pages))
(remove nil?)
(set))
other-pages-links (mapcat
(fn [page]
(let [ref-pages (-> (map first (db/get-page-referenced-pages repo page))
(set)
(set/intersection other-pages))
mentioned-pages (-> (map first (db/get-pages-that-mentioned-page repo page show-journal))
(set)
(set/intersection other-pages))]
(concat
(map (fn [p] [page p]) ref-pages)
(map (fn [p] [p page]) mentioned-pages))))
other-pages)
links (->> (concat links other-pages-links)
(remove nil?)
(distinct)
(build-links))
nodes (->> (concat
[page]
(map first ref-pages)
(map first mentioned-pages)
tags)
(remove nil?)
(distinct))
nodes (build-nodes dark? page links (set tags) nodes namespaces)
full-pages (db/get-all-pages repo)
all-pages (map db/get-original-name full-pages)
page-name->original-name (zipmap (map :block/name full-pages) all-pages)]
(normalize-page-name
{:nodes nodes
:links links
:page-name->original-name page-name->original-name})))))
(defn build-block-graph
"Builds a citation/reference graph for a given block uuid."
[block theme]
(let [dark? (= "dark" theme)]
(when-let [repo (state/get-current-repo)]
(let [ref-blocks (db/get-block-referenced-blocks block)
namespaces (db/get-all-namespace-relation repo)
links (concat
(map (fn [[p _aliases]]
[block p]) ref-blocks)
namespaces)
other-blocks (->> (concat (map first ref-blocks))
(remove nil?)
(set))
other-blocks-links (mapcat
(fn [block]
(let [ref-blocks (-> (map first (db/get-block-referenced-blocks block))
(set)
(set/intersection other-blocks))]
(concat
(map (fn [p] [block p]) ref-blocks))))
other-blocks)
links (->> (concat links other-blocks-links)
(remove nil?)
(distinct)
(build-links))
nodes (->> (concat
[block]
(map first ref-blocks))
(remove nil?)
(distinct)
FIXME : get block tags
)
nodes (build-nodes dark? block links #{} nodes namespaces)]
(normalize-page-name
{:nodes nodes
:links links})))))
(defn n-hops
"Get all nodes that are n hops from nodes (a collection of node ids)"
[{:keys [links] :as graph} nodes level]
(let [search-nodes (fn [forward?]
(let [links (group-by (if forward? :source :target) links)]
(loop [nodes nodes
level level]
(if (zero? level)
nodes
(recur (distinct (apply concat nodes
(map
(fn [id]
(->> (get links id) (map (if forward? :target :source))))
nodes)))
(dec level))))))
nodes (concat (search-nodes true) (search-nodes false))
nodes (set nodes)]
(update graph :nodes
(fn [full-nodes]
(filter (fn [node] (contains? nodes (:id node)))
full-nodes)))))
| null | https://raw.githubusercontent.com/logseq/logseq/9c7b4ea2016fb28b16ee42a7136c73dd52d8ce4b/src/main/frontend/handler/graph.cljs | clojure | FIXME: Put it into CSS
slow | (ns frontend.handler.graph
"Provides util handler fns for graph view"
(:require [clojure.set :as set]
[clojure.string :as string]
[frontend.db :as db]
[logseq.db.default :as default-db]
[frontend.state :as state]
[frontend.util :as util]))
(defn- build-links
[links]
(map (fn [[from to]]
{:source from
:target to})
links))
(defn- build-nodes
[dark? current-page page-links tags nodes namespaces]
(let [parents (set (map last namespaces))
current-page (or current-page "")
pages (set (flatten nodes))]
(->>
pages
(remove nil?)
(mapv (fn [p]
(let [p (str p)
current-page? (= p current-page)
[false false] "#999"
[false true] "#045591"
[true false] "#93a1a1"
[true true] "#ffffff")
color (if (contains? tags p)
(if dark? "orange" "green")
color)
n (get page-links p 1)
size (int (* 8 (max 1.0 (js/Math.cbrt n))))]
(cond->
{:id p
:label p
:size size
:color color}
(contains? parents p)
(assoc :parent true))))))))
(defn- uuid-or-asset?
[id]
(or (util/uuid-string? id)
(string/starts-with? id "../assets/")
(= id "..")
(string/starts-with? id "assets/")
(string/ends-with? id ".gif")
(string/ends-with? id ".jpg")
(string/ends-with? id ".png")))
(defn- remove-uuids-and-files!
[nodes]
(remove
(fn [node] (uuid-or-asset? (:id node)))
nodes))
(defn- normalize-page-name
[{:keys [nodes links page-name->original-name]}]
(let [links (->>
(map
(fn [{:keys [source target]}]
(let [source (get page-name->original-name source)
target (get page-name->original-name target)]
(when (and source target)
{:source source :target target})))
links)
(remove nil?))
nodes (->> (remove-uuids-and-files! nodes)
(util/distinct-by (fn [node] (:id node)))
(map (fn [node]
(if-let [original-name (get page-name->original-name (:id node))]
(assoc node :id original-name :label original-name)
nil)))
(remove nil?))]
{:nodes nodes
:links links}))
(defn build-global-graph
[theme {:keys [journal? orphan-pages? builtin-pages? excluded-pages?]}]
(let [dark? (= "dark" theme)
current-page (or (:block/name (db/get-current-page)) "")]
(when-let [repo (state/get-current-repo)]
(let [relation (db/get-pages-relation repo journal?)
tagged-pages (db/get-all-tagged-pages repo)
namespaces (db/get-all-namespace-relation repo)
tags (set (map second tagged-pages))
full-pages (db/get-all-pages repo)
all-pages (map db/get-original-name full-pages)
page-name->original-name (zipmap (map :block/name full-pages) all-pages)
pages-after-journal-filter (if-not journal?
(remove :block/journal? full-pages)
full-pages)
pages-after-exclude-filter (cond->> pages-after-journal-filter
(not excluded-pages?)
(remove (fn [p] (= true (:exclude-from-graph-view (:block/properties p))))))
links (concat (seq relation)
(seq tagged-pages)
(seq namespaces))
linked (set (flatten links))
build-in-pages (set (map string/lower-case default-db/built-in-pages-names))
nodes (cond->> (map :block/name pages-after-exclude-filter)
(not builtin-pages?)
(remove (fn [p] (contains? build-in-pages (string/lower-case p))))
(not orphan-pages?)
(filter #(contains? linked (string/lower-case %))))
page-links (reduce (fn [m [k v]] (-> (update m k inc)
(update v inc))) {} links)
links (build-links (remove (fn [[_ to]] (nil? to)) links))
nodes (build-nodes dark? (string/lower-case current-page) page-links tags nodes namespaces)]
(normalize-page-name
{:nodes nodes
:links links
:page-name->original-name page-name->original-name})))))
(defn build-page-graph
[page theme show-journal]
(let [dark? (= "dark" theme)]
(when-let [repo (state/get-current-repo)]
(let [page (util/page-name-sanity-lc page)
page-entity (db/entity [:block/name page])
tags (:tags (:block/properties page-entity))
tags (remove #(= page %) tags)
ref-pages (db/get-page-referenced-pages repo page)
mentioned-pages (db/get-pages-that-mentioned-page repo page show-journal)
namespaces (db/get-all-namespace-relation repo)
links (concat
namespaces
(map (fn [[p _aliases]]
[page p]) ref-pages)
(map (fn [[p _aliases]]
[p page]) mentioned-pages)
(map (fn [tag]
[page tag])
tags))
other-pages (->> (concat (map first ref-pages)
(map first mentioned-pages))
(remove nil?)
(set))
other-pages-links (mapcat
(fn [page]
(let [ref-pages (-> (map first (db/get-page-referenced-pages repo page))
(set)
(set/intersection other-pages))
mentioned-pages (-> (map first (db/get-pages-that-mentioned-page repo page show-journal))
(set)
(set/intersection other-pages))]
(concat
(map (fn [p] [page p]) ref-pages)
(map (fn [p] [p page]) mentioned-pages))))
other-pages)
links (->> (concat links other-pages-links)
(remove nil?)
(distinct)
(build-links))
nodes (->> (concat
[page]
(map first ref-pages)
(map first mentioned-pages)
tags)
(remove nil?)
(distinct))
nodes (build-nodes dark? page links (set tags) nodes namespaces)
full-pages (db/get-all-pages repo)
all-pages (map db/get-original-name full-pages)
page-name->original-name (zipmap (map :block/name full-pages) all-pages)]
(normalize-page-name
{:nodes nodes
:links links
:page-name->original-name page-name->original-name})))))
(defn build-block-graph
"Builds a citation/reference graph for a given block uuid."
[block theme]
(let [dark? (= "dark" theme)]
(when-let [repo (state/get-current-repo)]
(let [ref-blocks (db/get-block-referenced-blocks block)
namespaces (db/get-all-namespace-relation repo)
links (concat
(map (fn [[p _aliases]]
[block p]) ref-blocks)
namespaces)
other-blocks (->> (concat (map first ref-blocks))
(remove nil?)
(set))
other-blocks-links (mapcat
(fn [block]
(let [ref-blocks (-> (map first (db/get-block-referenced-blocks block))
(set)
(set/intersection other-blocks))]
(concat
(map (fn [p] [block p]) ref-blocks))))
other-blocks)
links (->> (concat links other-blocks-links)
(remove nil?)
(distinct)
(build-links))
nodes (->> (concat
[block]
(map first ref-blocks))
(remove nil?)
(distinct)
FIXME : get block tags
)
nodes (build-nodes dark? block links #{} nodes namespaces)]
(normalize-page-name
{:nodes nodes
:links links})))))
(defn n-hops
"Get all nodes that are n hops from nodes (a collection of node ids)"
[{:keys [links] :as graph} nodes level]
(let [search-nodes (fn [forward?]
(let [links (group-by (if forward? :source :target) links)]
(loop [nodes nodes
level level]
(if (zero? level)
nodes
(recur (distinct (apply concat nodes
(map
(fn [id]
(->> (get links id) (map (if forward? :target :source))))
nodes)))
(dec level))))))
nodes (concat (search-nodes true) (search-nodes false))
nodes (set nodes)]
(update graph :nodes
(fn [full-nodes]
(filter (fn [node] (contains? nodes (:id node)))
full-nodes)))))
|
4296e717376ac9b55cfa2399769f3ba829384363f1aaaa248519d7d182af5556 | herd/herdtools7 | indent.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2012 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
(* General indented printers *)
type t = string
let as_string s = s
let indent0 = ""
let indent = " "
let tab s = s ^ indent
let indent2 = tab indent
let indent3 = tab indent2
let indent4 = tab indent3
let indent5 = tab indent4
module type S = sig
val hexa : bool
val out : out_channel
val fprintf : ('a, out_channel, unit, unit) format4 -> 'a
val fx : t -> ('a, out_channel, unit, unit) format4 -> 'a
val f : ('a, out_channel, unit, unit) format4 -> 'a
val fi : ('a, out_channel, unit, unit) format4 -> 'a
val fii : ('a, out_channel, unit, unit) format4 -> 'a
val fiii : ('a, out_channel, unit, unit) format4 -> 'a
val fiv : ('a, out_channel, unit, unit) format4 -> 'a
val fv : ('a, out_channel, unit, unit) format4 -> 'a
val output : string -> unit
val ox : t -> string -> unit
val oy : t -> string -> unit
val o : string -> unit
val oi : string -> unit
val oii : string -> unit
val oiii : string -> unit
val oiv : string -> unit
val ov : string -> unit
end
module Make (Chan : sig val hexa : bool val out : out_channel end) = struct
open Printf
let hexa = Chan.hexa
let out = Chan.out
let fprintf fmt = Printf.fprintf Chan.out fmt
let fx indent fmt =
output_string Chan.out indent ;
kfprintf (fun chan -> output_char chan '\n')
Chan.out fmt
let f fmt = fx indent0 fmt
let fi fmt = fx indent fmt
let fii fmt = fx indent2 fmt
let fiii fmt = fx indent3 fmt
let fiv fmt = fx indent4 fmt
let fv fmt = fx indent5 fmt
let output s = output_string Chan.out s
let ox i s =
output_string Chan.out i ;
output_string Chan.out s ;
output_char Chan.out '\n'
let oy i s =
output_string Chan.out i ;
output_string Chan.out indent ;
output_string Chan.out s ;
output_char Chan.out '\n'
let o s =
output_string Chan.out s ;
output_char Chan.out '\n'
let oi s = ox indent s
let oii s = ox indent2 s
let oiii s = ox indent3 s
let oiv s = ox indent4 s
let ov s = ox indent5 s
end
| null | https://raw.githubusercontent.com/herd/herdtools7/b86aec8db64f8812e19468893deb1cdf5bbcfb83/litmus/indent.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
General indented printers | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2012 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
type t = string
let as_string s = s
let indent0 = ""
let indent = " "
let tab s = s ^ indent
let indent2 = tab indent
let indent3 = tab indent2
let indent4 = tab indent3
let indent5 = tab indent4
module type S = sig
val hexa : bool
val out : out_channel
val fprintf : ('a, out_channel, unit, unit) format4 -> 'a
val fx : t -> ('a, out_channel, unit, unit) format4 -> 'a
val f : ('a, out_channel, unit, unit) format4 -> 'a
val fi : ('a, out_channel, unit, unit) format4 -> 'a
val fii : ('a, out_channel, unit, unit) format4 -> 'a
val fiii : ('a, out_channel, unit, unit) format4 -> 'a
val fiv : ('a, out_channel, unit, unit) format4 -> 'a
val fv : ('a, out_channel, unit, unit) format4 -> 'a
val output : string -> unit
val ox : t -> string -> unit
val oy : t -> string -> unit
val o : string -> unit
val oi : string -> unit
val oii : string -> unit
val oiii : string -> unit
val oiv : string -> unit
val ov : string -> unit
end
module Make (Chan : sig val hexa : bool val out : out_channel end) = struct
open Printf
let hexa = Chan.hexa
let out = Chan.out
let fprintf fmt = Printf.fprintf Chan.out fmt
let fx indent fmt =
output_string Chan.out indent ;
kfprintf (fun chan -> output_char chan '\n')
Chan.out fmt
let f fmt = fx indent0 fmt
let fi fmt = fx indent fmt
let fii fmt = fx indent2 fmt
let fiii fmt = fx indent3 fmt
let fiv fmt = fx indent4 fmt
let fv fmt = fx indent5 fmt
let output s = output_string Chan.out s
let ox i s =
output_string Chan.out i ;
output_string Chan.out s ;
output_char Chan.out '\n'
let oy i s =
output_string Chan.out i ;
output_string Chan.out indent ;
output_string Chan.out s ;
output_char Chan.out '\n'
let o s =
output_string Chan.out s ;
output_char Chan.out '\n'
let oi s = ox indent s
let oii s = ox indent2 s
let oiii s = ox indent3 s
let oiv s = ox indent4 s
let ov s = ox indent5 s
end
|
43c445ea57e3395159361e52e16c504ca2b168fe3780948332568bbcd0407516 | reasonml/reason | ppx_here.ml | open Migrate_parsetree
Define the rewriter on OCaml 4.05 AST
open Ast_405
let ocaml_version = Versions.ocaml_405
(* Action of the rewriter: replace __HERE__ expression by a tuple ("filename",
line, col) *)
let mapper _config _cookies =
let open Ast_mapper in
let open Ast_helper in
let expr mapper pexp =
match pexp.Parsetree.pexp_desc with
| Parsetree.Pexp_ident {Location.txt = Longident.Lident "__HERE__"; loc} ->
let {Lexing. pos_fname; pos_lnum; pos_cnum; pos_bol} =
loc.Location.loc_start in
let loc = {loc with Location.loc_ghost = true} in
let fname = Exp.constant ~loc (Const.string pos_fname) in
let line = Exp.constant ~loc (Const.int pos_lnum) in
let col = Exp.constant ~loc (Const.int (pos_cnum - pos_bol)) in
{pexp with Parsetree.pexp_desc =
Parsetree.Pexp_tuple [fname; line; col]}
| _ -> default_mapper.expr mapper pexp
in
{default_mapper with expr}
(* Register the rewriter in the driver *)
let () =
Driver.register ~name:"ppx_here" ocaml_version mapper
| null | https://raw.githubusercontent.com/reasonml/reason/4f6ff7616bfa699059d642a3d16d8905d83555f6/src/vendored-omp/examples/omp_ppx_here/ppx_here.ml | ocaml | Action of the rewriter: replace __HERE__ expression by a tuple ("filename",
line, col)
Register the rewriter in the driver | open Migrate_parsetree
Define the rewriter on OCaml 4.05 AST
open Ast_405
let ocaml_version = Versions.ocaml_405
let mapper _config _cookies =
let open Ast_mapper in
let open Ast_helper in
let expr mapper pexp =
match pexp.Parsetree.pexp_desc with
| Parsetree.Pexp_ident {Location.txt = Longident.Lident "__HERE__"; loc} ->
let {Lexing. pos_fname; pos_lnum; pos_cnum; pos_bol} =
loc.Location.loc_start in
let loc = {loc with Location.loc_ghost = true} in
let fname = Exp.constant ~loc (Const.string pos_fname) in
let line = Exp.constant ~loc (Const.int pos_lnum) in
let col = Exp.constant ~loc (Const.int (pos_cnum - pos_bol)) in
{pexp with Parsetree.pexp_desc =
Parsetree.Pexp_tuple [fname; line; col]}
| _ -> default_mapper.expr mapper pexp
in
{default_mapper with expr}
let () =
Driver.register ~name:"ppx_here" ocaml_version mapper
|
c9db157931b50e3d5f5020b8990b53be88bbed540d43653ec47f100b58b5eee2 | clojang/jiface | erlang.clj | (ns jiface.erlang
(:require
[jiface.core :as jiface])
(:import
(clojure.lang Keyword)))
(defn create [& args]
"Common function for type instantiation.
Having a single function which is ultimately responsible for creating
objects allows us to handle instantiation errors easily, adding one handler
for ``#'init`` instead of a bunch of handlers, one for each data type."
(jiface/dynamic-init :erlang args))
;;; Aliases
(def init #'create)
| null | https://raw.githubusercontent.com/clojang/jiface/dcc9e9463eec143b99ce5cf104b5201f7847a1dd/src/jiface/erlang.clj | clojure | Aliases | (ns jiface.erlang
(:require
[jiface.core :as jiface])
(:import
(clojure.lang Keyword)))
(defn create [& args]
"Common function for type instantiation.
Having a single function which is ultimately responsible for creating
objects allows us to handle instantiation errors easily, adding one handler
for ``#'init`` instead of a bunch of handlers, one for each data type."
(jiface/dynamic-init :erlang args))
(def init #'create)
|
bd8d10fbc835f4e4ebe4ce4d03a7aa6836e2f364294e2cdf2348a1621509d83f | dselsam/arc | TSpec.hs | Copyright ( c ) 2020 Microsoft Corporation . All rights reserved .
Released under Apache 2.0 license as described in the file LICENSE .
Authors : , , .
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE StrictData #-}
module Synth.Spec.TSpec where
import Util.Imports
import Search.SearchT
import Search.DFS
import Synth.Ex (Ex(Ex), ForTrain, ForTest)
import Synth.ExInfo
import qualified Synth.Ex as Ex
import Synth.Spec
import Synth.Context
import qualified Util.List as List
import qualified Synth.Context as Context
data TSpec ctx a = TSpec {
info :: ExInfo,
ctx :: ctx
} deriving (Show)
instance Spec TSpec ctx a where
info (TSpec info _ ) = info
ctx (TSpec _ inputs) = inputs
check (TSpec _ _ ) guesses = True
| null | https://raw.githubusercontent.com/dselsam/arc/7e68a7ed9508bf26926b0f68336db05505f4e765/src/Synth/Spec/TSpec.hs | haskell | # LANGUAGE StrictData # | Copyright ( c ) 2020 Microsoft Corporation . All rights reserved .
Released under Apache 2.0 license as described in the file LICENSE .
Authors : , , .
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
module Synth.Spec.TSpec where
import Util.Imports
import Search.SearchT
import Search.DFS
import Synth.Ex (Ex(Ex), ForTrain, ForTest)
import Synth.ExInfo
import qualified Synth.Ex as Ex
import Synth.Spec
import Synth.Context
import qualified Util.List as List
import qualified Synth.Context as Context
data TSpec ctx a = TSpec {
info :: ExInfo,
ctx :: ctx
} deriving (Show)
instance Spec TSpec ctx a where
info (TSpec info _ ) = info
ctx (TSpec _ inputs) = inputs
check (TSpec _ _ ) guesses = True
|
9fad8ce547061d42b407e5721d2817fcd66fe78cc2fc2646f3f33c59c4a7dd1b | janestreet/krb | mode.mli | open! Core
* A [ Mode.t ] specifies whether a client or server should use Kerberos for authentication
or use a test mode where clients / servers can pretend to be any principal . All
production clients and servers should use [ Kerberized ] mode .
When you use the default kerberized mode on both client and server , you will end up
with encrypted connections . Secure by default ! Note that full encryption has a
performance cost .
Note that clients can only talk to servers that are running with the same mode
constructor : a client using [ ] can only talk to a server using [ ] .
Same goes for [ Test_with_principal ]
or use a test mode where clients/servers can pretend to be any principal. All
production clients and servers should use [Kerberized] mode.
When you use the default kerberized mode on both client and server, you will end up
with encrypted connections. Secure by default! Note that full encryption has a
performance cost.
Note that clients can only talk to servers that are running with the same mode
constructor: a client using [Kerberized] can only talk to a server using [Kerberized].
Same goes for [Test_with_principal]
*)
type 'a mode =
| Kerberized of 'a (** The connection will be kerberized. *)
| Test_with_principal of Principal.Name.t
(** In test mode, clients/servers can pretend to be any principal. Please note that this
mode provides NO Kerberos protection. The connection will be plain TCP. *)
[@@deriving compare, hash, sexp_of]
module Client : sig
type t = Conn_type_preference.t mode [@@deriving compare, hash, sexp_of]
val kerberized
: ?conn_type_preference:Conn_type_preference.t (** default: [accept_all] *)
-> unit
-> t
val test_with_principal
: ?test_principal:Principal.Name.t (** default: [User (Unix.getlogin ())] *)
-> unit
-> t
end
module Server : sig
type t = (Server_key_source.t * Conn_type_preference.t) mode
[@@deriving compare, hash, sexp_of]
(** Construct a [Kerberized] mode with [Server_key_source.default ()]
This function will not raise an exception. See [Server_key_source.default]. *)
val kerberized
: ?conn_type_preference:Conn_type_preference.t (** default: [accept_all] *)
-> key_source:Server_key_source.t
-> t
val test_with_principal
: ?test_principal:Principal.Name.t (** default: [User (Unix.getlogin ())] *)
-> unit
-> t
end
* The [ * _ with_auth_conn_type ] modes are used for RPC transports that do n't support
transforming data , and thus only support the [ Auth ] connection type .
transforming data, and thus only support the [Auth] connection type. *)
module Client_with_auth_conn_type : sig
type t = unit mode [@@deriving compare, hash, sexp_of]
val kerberized : unit -> t
val test_with_principal
: ?test_principal:Principal.Name.t (** default: [User (Unix.getlogin ())] *)
-> unit
-> t
val full_mode : t -> Client.t
end
module Server_with_auth_conn_type : sig
type t = Server_key_source.t mode [@@deriving compare, hash, sexp_of]
val kerberized : key_source:Server_key_source.t -> t
val test_with_principal
: ?test_principal:Principal.Name.t (** default: [User (Unix.getlogin ())] *)
-> unit
-> t
val full_mode : t -> Server.t
end
module Stable : sig
module V4 : sig
type nonrec 'a mode = 'a mode [@@deriving bin_io, compare, sexp]
module Client : Stable_without_comparator with type t = Client.t
module Server : Stable_without_comparator with type t = Server.t
module Client_with_auth_conn_type :
Stable_without_comparator with type t = Client_with_auth_conn_type.t
module Server_with_auth_conn_type :
Stable_without_comparator with type t = Server_with_auth_conn_type.t
end
end
| null | https://raw.githubusercontent.com/janestreet/krb/50993f4d8a5d42974a72e160b7b54613568184c1/src/mode.mli | ocaml | * The connection will be kerberized.
* In test mode, clients/servers can pretend to be any principal. Please note that this
mode provides NO Kerberos protection. The connection will be plain TCP.
* default: [accept_all]
* default: [User (Unix.getlogin ())]
* Construct a [Kerberized] mode with [Server_key_source.default ()]
This function will not raise an exception. See [Server_key_source.default].
* default: [accept_all]
* default: [User (Unix.getlogin ())]
* default: [User (Unix.getlogin ())]
* default: [User (Unix.getlogin ())] | open! Core
* A [ Mode.t ] specifies whether a client or server should use Kerberos for authentication
or use a test mode where clients / servers can pretend to be any principal . All
production clients and servers should use [ Kerberized ] mode .
When you use the default kerberized mode on both client and server , you will end up
with encrypted connections . Secure by default ! Note that full encryption has a
performance cost .
Note that clients can only talk to servers that are running with the same mode
constructor : a client using [ ] can only talk to a server using [ ] .
Same goes for [ Test_with_principal ]
or use a test mode where clients/servers can pretend to be any principal. All
production clients and servers should use [Kerberized] mode.
When you use the default kerberized mode on both client and server, you will end up
with encrypted connections. Secure by default! Note that full encryption has a
performance cost.
Note that clients can only talk to servers that are running with the same mode
constructor: a client using [Kerberized] can only talk to a server using [Kerberized].
Same goes for [Test_with_principal]
*)
type 'a mode =
| Test_with_principal of Principal.Name.t
[@@deriving compare, hash, sexp_of]
module Client : sig
type t = Conn_type_preference.t mode [@@deriving compare, hash, sexp_of]
val kerberized
-> unit
-> t
val test_with_principal
-> unit
-> t
end
module Server : sig
type t = (Server_key_source.t * Conn_type_preference.t) mode
[@@deriving compare, hash, sexp_of]
val kerberized
-> key_source:Server_key_source.t
-> t
val test_with_principal
-> unit
-> t
end
* The [ * _ with_auth_conn_type ] modes are used for RPC transports that do n't support
transforming data , and thus only support the [ Auth ] connection type .
transforming data, and thus only support the [Auth] connection type. *)
module Client_with_auth_conn_type : sig
type t = unit mode [@@deriving compare, hash, sexp_of]
val kerberized : unit -> t
val test_with_principal
-> unit
-> t
val full_mode : t -> Client.t
end
module Server_with_auth_conn_type : sig
type t = Server_key_source.t mode [@@deriving compare, hash, sexp_of]
val kerberized : key_source:Server_key_source.t -> t
val test_with_principal
-> unit
-> t
val full_mode : t -> Server.t
end
module Stable : sig
module V4 : sig
type nonrec 'a mode = 'a mode [@@deriving bin_io, compare, sexp]
module Client : Stable_without_comparator with type t = Client.t
module Server : Stable_without_comparator with type t = Server.t
module Client_with_auth_conn_type :
Stable_without_comparator with type t = Client_with_auth_conn_type.t
module Server_with_auth_conn_type :
Stable_without_comparator with type t = Server_with_auth_conn_type.t
end
end
|
af82fb772c86730929e52cf737c457d29d249f0c84e416454da79cafe0389dbe | threatgrid/ctia | jmx.clj | (ns ctia.lib.metrics.jmx
(:require [clj-momo.lib.metrics.jmx :as jmx]
[puppetlabs.trapperkeeper.core :as tk]))
(defn start! [get-in-config]
(when (get-in-config [:ctia :metrics :jmx :enabled])
(jmx/start)))
(defprotocol JMXMetricsService)
(tk/defservice jmx-metrics-service
JMXMetricsService
[[:ConfigService get-in-config]]
(start [this context]
(start! get-in-config)
context))
| null | https://raw.githubusercontent.com/threatgrid/ctia/32857663cdd7ac385161103dbafa8dc4f98febf0/src/ctia/lib/metrics/jmx.clj | clojure | (ns ctia.lib.metrics.jmx
(:require [clj-momo.lib.metrics.jmx :as jmx]
[puppetlabs.trapperkeeper.core :as tk]))
(defn start! [get-in-config]
(when (get-in-config [:ctia :metrics :jmx :enabled])
(jmx/start)))
(defprotocol JMXMetricsService)
(tk/defservice jmx-metrics-service
JMXMetricsService
[[:ConfigService get-in-config]]
(start [this context]
(start! get-in-config)
context))
| |
f564ba61b6e86e523c75f6d27b29e85a83ae09ebd5af2fb5ae0dfd343327414a | provinciesincijfers/gebiedsniveaus | 05verwerking_bevolking_antwerpen.sps | * Encoding: UTF-8.
* bron van de bevolkingsdata: #filter=path%7C%2FGegevens%2FRijksregister%7C&page=1
* todo: statsec meepakken uit bevolking!
get sas data="C:\Users\plu3532\Documents\gebiedsindelingen\verwerking\werkbestanden_bevolking\ipa2016c.sas7bdat"
/formats="C:\Users\plu3532\Documents\gebiedsindelingen\verwerking\werkbestanden_bevolking\formout.sas7bdat".
DATASET NAME bevolking.
* aanpassing: gegevens van gezinshoofd meenemen, want er gebeurt een correctie op basis van gezinshoofd voor alle afgeleide variabelen, edoch niet voor de adrescode van de persoon.
DATASET ACTIVATE bevolking.
AGGREGATE
/OUTFILE=* MODE=ADDVARIABLES
/BREAK=RRNR_HOOFDPERSOON
/inwoners_gezin=N.
FILTER OFF.
USE ALL.
SELECT IF (RRNR_HOOFDPERSOON = NATIONAAL_NUMMER).
EXECUTE.
DATASET ACTIVATE bevolking.
DATASET DECLARE adresinwoners.
AGGREGATE
/OUTFILE='adresinwoners'
/BREAK=ADRESCODE sscode
/inwoners2016=sum(inwoners_gezin).
dataset activate adresinwoners.
dataset close bevolking.
* er zijn 7 gevallen waar eenzelfde adres aan meerdere statsec is gekoppeld.
* hou het adres en de inwoners over van het meest bevolkte adres.
DATASET ACTIVATE adresinwoners.
* Identify Duplicate Cases.
SORT CASES BY ADRESCODE(A) inwoners2016(A).
MATCH FILES
/FILE=*
/BY ADRESCODE
/LAST=PrimaryLast.
VARIABLE LABELS PrimaryLast 'Indicator of each last matching case as Primary'.
VALUE LABELS PrimaryLast 0 'Duplicate Case' 1 'Primary Case'.
VARIABLE LEVEL PrimaryLast (ORDINAL).
EXECUTE.
FILTER OFF.
USE ALL.
SELECT IF (PrimaryLast = 1).
EXECUTE.
delete variables primarylast.
* uitbreiden met x-y coordinaten.
GET DATA /TYPE=TXT
/FILE="C:\Users\plu3532\Documents\gebiedsindelingen\verwerking\werkbestanden_bevolking\Correspondentietabel_Antwerpen.txt"
/ENCODING='UTF8'
/DELCASE=LINE
/DELIMITERS="\t"
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/DATATYPEMIN PERCENTAGE=95.0
/VARIABLES=
Niscode AUTO
Adrescode AUTO
Bouwblok AUTO
Stat_sector AUTO
X A12
Y A12
Herkomst AUTO
Niscodevansectorkaart AUTO
/MAP.
RESTORE.
CACHE.
EXECUTE.
DATASET NAME correspondentie WINDOW=FRONT.
* nogal een gedoe om de x-y'tjes proper ingelezen te krijgen.
COMPUTE x=REPLACE(X,".",",").
alter type x (f12.5).
COMPUTE y=REPLACE(Y,".",",").
alter type y (f12.5).
match files
/file=*
/keep=adrescode x y.
sort cases adrescode (a).
DATASET ACTIVATE adresinwoners.
sort cases adrescode (a).
MATCH FILES /FILE=*
/TABLE='correspondentie'
/BY Adrescode.
EXECUTE.
dataset close correspondentie.
* verwijder adrescodes zonder coordinaten.
FILTER OFF.
USE ALL.
SELECT IF (X > 0).
EXECUTE.
* helaas is niet elke XY steeds in dezelfde sector.
* wat niet logisch coherent is natuurlijk. Wellicht te verklaren doordat de toewijzing van sector niet puur geografisch gebeurt.
* we houden enkel de x y - statsec combinatie over met de meeste inwoners en houden enkel die inwoners over.
DATASET DECLARE xyinwoner.
AGGREGATE
/OUTFILE='xyinwoner'
/BREAK=X Y sscode
/inwoners2016=SUM(inwoners2016).
dataset activate xyinwoner.
DATASET ACTIVATE xyinwoner.
AGGREGATE
/OUTFILE=* MODE=ADDVARIABLES
/BREAK=X Y
/twijfelsector=N.
DATASET DECLARE xyinwonerplat.
AGGREGATE
/OUTFILE='xyinwonerplat'
/BREAK=X Y
/inwoners2016_max=MAX(inwoners2016)
/twijfelsector=N.
DATASET ACTIVATE xyinwonerplat.
dataset close xyinwoner.
dataset close adresinwoners.
SAVE OUTFILE='C:\Users\plu3532\Documents\gebiedsindelingen\bevolking_xy\xy_inwoners_antwerpen.sav'
/COMPRESSED.
* definieer programma.
BEGIN PROGRAM Python.
# Building a function to assign a point to a polygon
# dit vereist dat je SPSS versie een Python versie heeft die shapefile, rtree en shapely kent
import shapefile
from rtree import index
from shapely.geometry import Polygon, Point
# kies je shapefile: eerst de map, in de regel erna het bestand
# de eerste betekenisvolle kolom wordt genomen als identificator. Hier is dat de kolom waar vb A01-A1 in staat
# (en waarmee je dus kan hercoderen naar de juiste buurt en wijk)
# de naam bg_statsec is willekeurig, en je hoeft die dus niet aan te passen met een andere bron
# je polygonen moeten wel steeds wederzijds uitsluitend zijn (dus een punt kan steeds slechts in een enkel gebied liggen)
data = r'C:\Users\plu3532\Documents\gebiedsindelingen\verwerking'
bg_statsec = shapefile.Reader(data + r'\statsec_deelgemeente_av_72_minimal.shp')
bg_shapes = bg_statsec.shapes() #convert to shapely objects
bg_points = [q.points for q in bg_shapes]
polygons = [Polygon(q) for q in bg_points]
#looking at the fields and records
#bg_fields = bg_statsec.fields
bg_records = bg_statsec.records()
print bg_records[0][1] #als je hier commentaar uitzet, dan laat je de eerste record zien
#build spatial index from bounding boxes
#also has a second vector associating
#area IDs to numeric id
idx = index.Index()
c_id = 0
area_match = []
for a,b in zip(bg_shapes,bg_records):
area_match.append(b[1])
idx.insert(c_id,a.bbox,obj=b[1])
c_id += 1
#now can define function with polygons, area_match, and idx as globals
def assign_area(x,y):
if x == None or y == None: return None
point = Point(x,y)
for i in idx.intersection((x,y,x,y)):
if point.within(polygons[i]):
return area_match[i]
return None
#note points on the borders will return None
END PROGRAM.
rename variables x=x_adres.
rename variables y=y_adres.
* roep het programma op, zeg welke variabele opgevuld moet worden (hier statsec_splits) en hoeveel tekens deze mag hebben (type=7).
* type=0 betekent numeriek.
* geef vervolgens aan in welke variabele x en y teruggevonden kunnen worden.
SPSSINC TRANS RESULT=statsec_splits TYPE=20
/FORMULA "assign_area(x=x_adres,y=y_adres)".
DATASET DECLARE population2016.
AGGREGATE
/OUTFILE='population2016'
/BREAK=statsec_splits
/inwoners2016=SUM(inwoners2016_max).
dataset activate population2016.
DATASET ACTIVATE population2016.
FILTER OFF.
USE ALL.
SELECT IF (statsec_splits ~= "").
EXECUTE.
SAVE OUTFILE='C:\Users\plu3532\Documents\gebiedsindelingen\bevolking_xy\statsec_antwerpen.sav'
/COMPRESSED.
| null | https://raw.githubusercontent.com/provinciesincijfers/gebiedsniveaus/84bd86174f5e155aae431010acbb7949e0be9e80/deelgemeenten/scripts/05verwerking_bevolking_antwerpen.sps | scheme | * Encoding: UTF-8.
* bron van de bevolkingsdata: #filter=path%7C%2FGegevens%2FRijksregister%7C&page=1
* todo: statsec meepakken uit bevolking!
get sas data="C:\Users\plu3532\Documents\gebiedsindelingen\verwerking\werkbestanden_bevolking\ipa2016c.sas7bdat"
/formats="C:\Users\plu3532\Documents\gebiedsindelingen\verwerking\werkbestanden_bevolking\formout.sas7bdat".
DATASET NAME bevolking.
* aanpassing: gegevens van gezinshoofd meenemen, want er gebeurt een correctie op basis van gezinshoofd voor alle afgeleide variabelen, edoch niet voor de adrescode van de persoon.
DATASET ACTIVATE bevolking.
AGGREGATE
/OUTFILE=* MODE=ADDVARIABLES
/BREAK=RRNR_HOOFDPERSOON
/inwoners_gezin=N.
FILTER OFF.
USE ALL.
SELECT IF (RRNR_HOOFDPERSOON = NATIONAAL_NUMMER).
EXECUTE.
DATASET ACTIVATE bevolking.
DATASET DECLARE adresinwoners.
AGGREGATE
/OUTFILE='adresinwoners'
/BREAK=ADRESCODE sscode
/inwoners2016=sum(inwoners_gezin).
dataset activate adresinwoners.
dataset close bevolking.
* er zijn 7 gevallen waar eenzelfde adres aan meerdere statsec is gekoppeld.
* hou het adres en de inwoners over van het meest bevolkte adres.
DATASET ACTIVATE adresinwoners.
* Identify Duplicate Cases.
SORT CASES BY ADRESCODE(A) inwoners2016(A).
MATCH FILES
/FILE=*
/BY ADRESCODE
/LAST=PrimaryLast.
VARIABLE LABELS PrimaryLast 'Indicator of each last matching case as Primary'.
VALUE LABELS PrimaryLast 0 'Duplicate Case' 1 'Primary Case'.
VARIABLE LEVEL PrimaryLast (ORDINAL).
EXECUTE.
FILTER OFF.
USE ALL.
SELECT IF (PrimaryLast = 1).
EXECUTE.
delete variables primarylast.
* uitbreiden met x-y coordinaten.
GET DATA /TYPE=TXT
/FILE="C:\Users\plu3532\Documents\gebiedsindelingen\verwerking\werkbestanden_bevolking\Correspondentietabel_Antwerpen.txt"
/ENCODING='UTF8'
/DELCASE=LINE
/DELIMITERS="\t"
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/DATATYPEMIN PERCENTAGE=95.0
/VARIABLES=
Niscode AUTO
Adrescode AUTO
Bouwblok AUTO
Stat_sector AUTO
X A12
Y A12
Herkomst AUTO
Niscodevansectorkaart AUTO
/MAP.
RESTORE.
CACHE.
EXECUTE.
DATASET NAME correspondentie WINDOW=FRONT.
* nogal een gedoe om de x-y'tjes proper ingelezen te krijgen.
COMPUTE x=REPLACE(X,".",",").
alter type x (f12.5).
COMPUTE y=REPLACE(Y,".",",").
alter type y (f12.5).
match files
/file=*
/keep=adrescode x y.
sort cases adrescode (a).
DATASET ACTIVATE adresinwoners.
sort cases adrescode (a).
MATCH FILES /FILE=*
/TABLE='correspondentie'
/BY Adrescode.
EXECUTE.
dataset close correspondentie.
* verwijder adrescodes zonder coordinaten.
FILTER OFF.
USE ALL.
SELECT IF (X > 0).
EXECUTE.
* helaas is niet elke XY steeds in dezelfde sector.
* wat niet logisch coherent is natuurlijk. Wellicht te verklaren doordat de toewijzing van sector niet puur geografisch gebeurt.
* we houden enkel de x y - statsec combinatie over met de meeste inwoners en houden enkel die inwoners over.
DATASET DECLARE xyinwoner.
AGGREGATE
/OUTFILE='xyinwoner'
/BREAK=X Y sscode
/inwoners2016=SUM(inwoners2016).
dataset activate xyinwoner.
DATASET ACTIVATE xyinwoner.
AGGREGATE
/OUTFILE=* MODE=ADDVARIABLES
/BREAK=X Y
/twijfelsector=N.
DATASET DECLARE xyinwonerplat.
AGGREGATE
/OUTFILE='xyinwonerplat'
/BREAK=X Y
/inwoners2016_max=MAX(inwoners2016)
/twijfelsector=N.
DATASET ACTIVATE xyinwonerplat.
dataset close xyinwoner.
dataset close adresinwoners.
SAVE OUTFILE='C:\Users\plu3532\Documents\gebiedsindelingen\bevolking_xy\xy_inwoners_antwerpen.sav'
/COMPRESSED.
* definieer programma.
BEGIN PROGRAM Python.
# Building a function to assign a point to a polygon
# dit vereist dat je SPSS versie een Python versie heeft die shapefile, rtree en shapely kent
import shapefile
from rtree import index
from shapely.geometry import Polygon, Point
# kies je shapefile: eerst de map, in de regel erna het bestand
# de eerste betekenisvolle kolom wordt genomen als identificator. Hier is dat de kolom waar vb A01-A1 in staat
# (en waarmee je dus kan hercoderen naar de juiste buurt en wijk)
# de naam bg_statsec is willekeurig, en je hoeft die dus niet aan te passen met een andere bron
# je polygonen moeten wel steeds wederzijds uitsluitend zijn (dus een punt kan steeds slechts in een enkel gebied liggen)
data = r'C:\Users\plu3532\Documents\gebiedsindelingen\verwerking'
bg_statsec = shapefile.Reader(data + r'\statsec_deelgemeente_av_72_minimal.shp')
bg_shapes = bg_statsec.shapes() #convert to shapely objects
bg_points = [q.points for q in bg_shapes]
polygons = [Polygon(q) for q in bg_points]
#looking at the fields and records
#bg_fields = bg_statsec.fields
bg_records = bg_statsec.records()
print bg_records[0][1] #als je hier commentaar uitzet, dan laat je de eerste record zien
#build spatial index from bounding boxes
#also has a second vector associating
#area IDs to numeric id
idx = index.Index()
c_id = 0
area_match = []
for a,b in zip(bg_shapes,bg_records):
area_match.append(b[1])
idx.insert(c_id,a.bbox,obj=b[1])
c_id += 1
#now can define function with polygons, area_match, and idx as globals
def assign_area(x,y):
if x == None or y == None: return None
point = Point(x,y)
for i in idx.intersection((x,y,x,y)):
if point.within(polygons[i]):
return area_match[i]
return None
#note points on the borders will return None
END PROGRAM.
rename variables x=x_adres.
rename variables y=y_adres.
* roep het programma op, zeg welke variabele opgevuld moet worden (hier statsec_splits) en hoeveel tekens deze mag hebben (type=7).
* type=0 betekent numeriek.
* geef vervolgens aan in welke variabele x en y teruggevonden kunnen worden.
SPSSINC TRANS RESULT=statsec_splits TYPE=20
/FORMULA "assign_area(x=x_adres,y=y_adres)".
DATASET DECLARE population2016.
AGGREGATE
/OUTFILE='population2016'
/BREAK=statsec_splits
/inwoners2016=SUM(inwoners2016_max).
dataset activate population2016.
DATASET ACTIVATE population2016.
FILTER OFF.
USE ALL.
SELECT IF (statsec_splits ~= "").
EXECUTE.
SAVE OUTFILE='C:\Users\plu3532\Documents\gebiedsindelingen\bevolking_xy\statsec_antwerpen.sav'
/COMPRESSED.
| |
8dc4c6e5fe85eb453c26753056cfa65a85550a4e2b451bb5fcd23005a782ccf1 | serokell/qtah | QAbstractItemModel.hs | This file is part of Qtah .
--
Copyright 2015 - 2018 The Qtah Authors .
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation , either version 3 of the License , or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details .
--
You should have received a copy of the GNU Lesser General Public License
-- along with this program. If not, see </>.
module Graphics.UI.Qtah.Generator.Interface.Core.QAbstractItemModel (
aModule,
c_QAbstractItemModel,
) where
import Foreign.Hoppy.Generator.Spec (
Export (ExportEnum, ExportClass),
addReqIncludes,
classSetEntityPrefix,
ident,
ident1,
includeStd,
makeClass,
mkConstMethod,
mkConstMethod',
mkMethod,
mkMethod',
)
import Foreign.Hoppy.Generator.Types (
bitspaceT,
boolT,
enumT,
intT,
objT,
voidT,
)
import Foreign.Hoppy.Generator.Version (collect, just, test)
import Graphics.UI.Qtah.Generator.Flags (qtVersion)
import Graphics.UI.Qtah.Generator.Interface.Core.QModelIndex (c_QModelIndex)
import Graphics.UI.Qtah.Generator.Interface.Core.QObject (c_QObject)
import Graphics.UI.Qtah.Generator.Interface.Core.QSize (c_QSize)
import Graphics.UI.Qtah.Generator.Interface.Core.QVariant (c_QVariant)
import Graphics.UI.Qtah.Generator.Interface.Core.Types (
bs_ItemFlags,
e_ItemDataRole,
e_Orientation,
e_SortOrder,
)
import {-# SOURCE #-} Graphics.UI.Qtah.Generator.Interface.Internal.Listener (
c_Listener,
c_ListenerQModelIndexIntInt,
c_ListenerQModelIndexIntIntQModelIndexInt,
c_ListenerQModelIndexQModelIndexQVectorInt,
)
import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule)
import Graphics.UI.Qtah.Generator.Types
{-# ANN module "HLint: ignore Use camelCase" #-}
aModule =
AQtModule $
makeQtModule ["Core", "QAbstractItemModel"] $
QtExport (ExportClass c_QAbstractItemModel) :
map QtExportSignal signals ++
[ QtExport $ ExportEnum e_LayoutChangeHint ]
c_QAbstractItemModel =
addReqIncludes [includeStd "QAbstractItemModel"] $
classSetEntityPrefix "" $
makeClass (ident "QAbstractItemModel") Nothing [c_QObject] $
collect
[ just $ mkConstMethod "buddy" [objT c_QModelIndex] $ objT c_QModelIndex
-- TODO canDropMimeData
, just $ mkConstMethod "canFetchMore" [objT c_QModelIndex] boolT
, just $ mkConstMethod' "columnCount" "columnCount" [] intT
, just $ mkConstMethod' "columnCount" "columnCountAt" [objT c_QModelIndex] intT
, just $ mkConstMethod' "data" "getData" [objT c_QModelIndex] $ objT c_QVariant
, just $ mkConstMethod' "data" "getDataWithRole"
[objT c_QModelIndex, enumT e_ItemDataRole] $ objT c_QVariant
TODO dropMimeData
, just $ mkMethod "fetchMore" [objT c_QModelIndex] voidT
, just $ mkConstMethod "flags" [objT c_QModelIndex] $ bitspaceT bs_ItemFlags
, just $ mkConstMethod' "hasChildren" "hasChildren" [] boolT
, just $ mkConstMethod' "hasChildren" "hasChildrenAt" [objT c_QModelIndex] boolT
, just $ mkConstMethod' "hasIndex" "hasIndex" [intT, intT] boolT
, just $ mkConstMethod' "hasIndex" "hasIndexAt" [intT, intT, objT c_QModelIndex] boolT
, just $ mkConstMethod' "headerData" "headerData" [intT, enumT e_Orientation] $ objT c_QVariant
, just $ mkConstMethod' "headerData" "headerDataWithRole"
[intT, enumT e_Orientation, enumT e_ItemDataRole] $ objT c_QVariant
, just $ mkConstMethod' "index" "index" [intT, intT] $ objT c_QModelIndex
, just $ mkConstMethod' "index" "indexAt" [intT, intT, objT c_QModelIndex] $ objT c_QModelIndex
, just $ mkMethod' "insertColumn" "insertColumn" [intT] boolT
, just $ mkMethod' "insertColumn" "insertColumnAt" [intT, objT c_QModelIndex] boolT
, just $ mkMethod' "insertColumns" "insertColumns" [intT, intT] boolT
, just $ mkMethod' "insertColumns" "insertColumnsAt" [intT, intT, objT c_QModelIndex] boolT
, just $ mkMethod' "insertRow" "insertRow" [intT] boolT
, just $ mkMethod' "insertRow" "insertRowAt" [intT, objT c_QModelIndex] boolT
, just $ mkMethod' "insertRows" "insertRows" [intT, intT] boolT
, just $ mkMethod' "insertRows" "insertRowsAt" [intT, intT, objT c_QModelIndex] boolT
-- TODO itemData
TODO match
TODO mimeData
-- TODO mimeTypes
, test (qtVersion >= [5, 0]) $ mkMethod "moveColumn"
[objT c_QModelIndex, intT, objT c_QModelIndex, intT] boolT
, test (qtVersion >= [5, 0]) $ mkMethod "moveColumns"
[objT c_QModelIndex, intT, intT, objT c_QModelIndex, intT] boolT
, test (qtVersion >= [5, 0]) $ mkMethod "moveRow"
[objT c_QModelIndex, intT, objT c_QModelIndex, intT] boolT
, test (qtVersion >= [5, 0]) $ mkMethod "moveRows"
[objT c_QModelIndex, intT, intT, objT c_QModelIndex, intT] boolT
, just $ mkConstMethod "parent" [objT c_QModelIndex] $ objT c_QModelIndex
, just $ mkMethod' "removeColumn" "removeColumn" [intT] boolT
, just $ mkMethod' "removeColumn" "removeColumnAt" [intT, objT c_QModelIndex] boolT
, just $ mkMethod' "removeColumns" "removeColumns" [intT, intT] boolT
, just $ mkMethod' "removeColumns" "removeColumnsAt" [intT, intT, objT c_QModelIndex] boolT
, just $ mkMethod' "removeRow" "removeRow" [intT] boolT
, just $ mkMethod' "removeRow" "removeRowAt" [intT, objT c_QModelIndex] boolT
, just $ mkMethod' "removeRows" "removeRows" [intT, intT] boolT
, just $ mkMethod' "removeRows" "removeRowsAt" [intT, intT, objT c_QModelIndex] boolT
, just $ mkMethod "revert" [] voidT
TODO roleNames ( > = 4.6 )
, just $ mkConstMethod' "rowCount" "rowCount" [] intT
, just $ mkConstMethod' "rowCount" "rowCountAt" [objT c_QModelIndex] intT
, just $ mkMethod' "setData" "setData" [objT c_QModelIndex, objT c_QVariant] boolT
, just $ mkMethod' "setData" "setDataWithRole"
[objT c_QModelIndex, objT c_QVariant, enumT e_ItemDataRole] boolT
, just $ mkMethod' "setHeaderData" "setHeaderData"
[intT, enumT e_Orientation, objT c_QVariant] boolT
, just $ mkMethod' "setHeaderData" "setHeaderDataWithRole"
[intT, enumT e_Orientation, objT c_QVariant, enumT e_ItemDataRole] boolT
TODO setItemData
, just $ mkConstMethod "sibling" [intT, intT, objT c_QModelIndex] $ objT c_QModelIndex
, just $ mkMethod' "sort" "sort" [intT] voidT
, just $ mkMethod' "sort" "sortWithOrder" [intT, enumT e_SortOrder] voidT
, just $ mkConstMethod "span" [objT c_QModelIndex] $ objT c_QSize
, just $ mkMethod "submit" [] boolT
TODO suportedDragActions
TODO supportedDropActions ( > = 4.2 )
]
signals =
collect
[ just $ makeSignal c_QAbstractItemModel "columnsAboutToBeInserted" c_ListenerQModelIndexIntInt
, test (qtVersion >= [4, 6]) $ makeSignal c_QAbstractItemModel "columnsAboutToBeMoved"
c_ListenerQModelIndexIntIntQModelIndexInt
, just $ makeSignal c_QAbstractItemModel "columnsAboutToBeRemoved" c_ListenerQModelIndexIntInt
, just $ makeSignal c_QAbstractItemModel "columnsInserted" c_ListenerQModelIndexIntInt
, test (qtVersion >= [4, 6]) $ makeSignal c_QAbstractItemModel "columnsMoved"
c_ListenerQModelIndexIntIntQModelIndexInt
, just $ makeSignal c_QAbstractItemModel "columnsRemoved" c_ListenerQModelIndexIntInt
, just $ makeSignal c_QAbstractItemModel "dataChanged" c_ListenerQModelIndexQModelIndexQVectorInt
TODO layoutAboutToBeChanged ( > = 5.0 )
TODO layoutChanged ( > = 5.0 )
, test (qtVersion >= [4, 2]) $ makeSignal c_QAbstractItemModel "modelAboutToBeReset" c_Listener
, test (qtVersion >= [4, 1]) $ makeSignal c_QAbstractItemModel "modelReset" c_Listener
, just $ makeSignal c_QAbstractItemModel "rowsAboutToBeInserted" c_ListenerQModelIndexIntInt
, test (qtVersion >= [4, 6]) $ makeSignal c_QAbstractItemModel "rowsAboutToBeMoved"
c_ListenerQModelIndexIntIntQModelIndexInt
, just $ makeSignal c_QAbstractItemModel "rowsAboutToBeRemoved" c_ListenerQModelIndexIntInt
, just $ makeSignal c_QAbstractItemModel "rowsInserted" c_ListenerQModelIndexIntInt
, test (qtVersion >= [4, 6]) $ makeSignal c_QAbstractItemModel "rowsMoved"
c_ListenerQModelIndexIntIntQModelIndexInt
, just $ makeSignal c_QAbstractItemModel "rowsRemoved" c_ListenerQModelIndexIntInt
]
e_LayoutChangeHint =
makeQtEnum (ident1 "QAbstractItemModel" "LayoutChangeHint") [includeStd "QAbstractItemModel"]
[ (0, ["no", "layout", "change", "hint"])
, (1, ["vertical", "sort", "hint"])
, (2, ["horizontal", "sort", "hint"])
]
| null | https://raw.githubusercontent.com/serokell/qtah/abb4932248c82dc5c662a20d8f177acbc7cfa722/qtah-generator/src/Graphics/UI/Qtah/Generator/Interface/Core/QAbstractItemModel.hs | haskell |
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
(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
along with this program. If not, see </>.
# SOURCE #
# ANN module "HLint: ignore Use camelCase" #
TODO canDropMimeData
TODO itemData
TODO mimeTypes | This file is part of Qtah .
Copyright 2015 - 2018 The Qtah Authors .
the Free Software Foundation , either version 3 of the License , or
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
module Graphics.UI.Qtah.Generator.Interface.Core.QAbstractItemModel (
aModule,
c_QAbstractItemModel,
) where
import Foreign.Hoppy.Generator.Spec (
Export (ExportEnum, ExportClass),
addReqIncludes,
classSetEntityPrefix,
ident,
ident1,
includeStd,
makeClass,
mkConstMethod,
mkConstMethod',
mkMethod,
mkMethod',
)
import Foreign.Hoppy.Generator.Types (
bitspaceT,
boolT,
enumT,
intT,
objT,
voidT,
)
import Foreign.Hoppy.Generator.Version (collect, just, test)
import Graphics.UI.Qtah.Generator.Flags (qtVersion)
import Graphics.UI.Qtah.Generator.Interface.Core.QModelIndex (c_QModelIndex)
import Graphics.UI.Qtah.Generator.Interface.Core.QObject (c_QObject)
import Graphics.UI.Qtah.Generator.Interface.Core.QSize (c_QSize)
import Graphics.UI.Qtah.Generator.Interface.Core.QVariant (c_QVariant)
import Graphics.UI.Qtah.Generator.Interface.Core.Types (
bs_ItemFlags,
e_ItemDataRole,
e_Orientation,
e_SortOrder,
)
c_Listener,
c_ListenerQModelIndexIntInt,
c_ListenerQModelIndexIntIntQModelIndexInt,
c_ListenerQModelIndexQModelIndexQVectorInt,
)
import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule)
import Graphics.UI.Qtah.Generator.Types
aModule =
AQtModule $
makeQtModule ["Core", "QAbstractItemModel"] $
QtExport (ExportClass c_QAbstractItemModel) :
map QtExportSignal signals ++
[ QtExport $ ExportEnum e_LayoutChangeHint ]
c_QAbstractItemModel =
addReqIncludes [includeStd "QAbstractItemModel"] $
classSetEntityPrefix "" $
makeClass (ident "QAbstractItemModel") Nothing [c_QObject] $
collect
[ just $ mkConstMethod "buddy" [objT c_QModelIndex] $ objT c_QModelIndex
, just $ mkConstMethod "canFetchMore" [objT c_QModelIndex] boolT
, just $ mkConstMethod' "columnCount" "columnCount" [] intT
, just $ mkConstMethod' "columnCount" "columnCountAt" [objT c_QModelIndex] intT
, just $ mkConstMethod' "data" "getData" [objT c_QModelIndex] $ objT c_QVariant
, just $ mkConstMethod' "data" "getDataWithRole"
[objT c_QModelIndex, enumT e_ItemDataRole] $ objT c_QVariant
TODO dropMimeData
, just $ mkMethod "fetchMore" [objT c_QModelIndex] voidT
, just $ mkConstMethod "flags" [objT c_QModelIndex] $ bitspaceT bs_ItemFlags
, just $ mkConstMethod' "hasChildren" "hasChildren" [] boolT
, just $ mkConstMethod' "hasChildren" "hasChildrenAt" [objT c_QModelIndex] boolT
, just $ mkConstMethod' "hasIndex" "hasIndex" [intT, intT] boolT
, just $ mkConstMethod' "hasIndex" "hasIndexAt" [intT, intT, objT c_QModelIndex] boolT
, just $ mkConstMethod' "headerData" "headerData" [intT, enumT e_Orientation] $ objT c_QVariant
, just $ mkConstMethod' "headerData" "headerDataWithRole"
[intT, enumT e_Orientation, enumT e_ItemDataRole] $ objT c_QVariant
, just $ mkConstMethod' "index" "index" [intT, intT] $ objT c_QModelIndex
, just $ mkConstMethod' "index" "indexAt" [intT, intT, objT c_QModelIndex] $ objT c_QModelIndex
, just $ mkMethod' "insertColumn" "insertColumn" [intT] boolT
, just $ mkMethod' "insertColumn" "insertColumnAt" [intT, objT c_QModelIndex] boolT
, just $ mkMethod' "insertColumns" "insertColumns" [intT, intT] boolT
, just $ mkMethod' "insertColumns" "insertColumnsAt" [intT, intT, objT c_QModelIndex] boolT
, just $ mkMethod' "insertRow" "insertRow" [intT] boolT
, just $ mkMethod' "insertRow" "insertRowAt" [intT, objT c_QModelIndex] boolT
, just $ mkMethod' "insertRows" "insertRows" [intT, intT] boolT
, just $ mkMethod' "insertRows" "insertRowsAt" [intT, intT, objT c_QModelIndex] boolT
TODO match
TODO mimeData
, test (qtVersion >= [5, 0]) $ mkMethod "moveColumn"
[objT c_QModelIndex, intT, objT c_QModelIndex, intT] boolT
, test (qtVersion >= [5, 0]) $ mkMethod "moveColumns"
[objT c_QModelIndex, intT, intT, objT c_QModelIndex, intT] boolT
, test (qtVersion >= [5, 0]) $ mkMethod "moveRow"
[objT c_QModelIndex, intT, objT c_QModelIndex, intT] boolT
, test (qtVersion >= [5, 0]) $ mkMethod "moveRows"
[objT c_QModelIndex, intT, intT, objT c_QModelIndex, intT] boolT
, just $ mkConstMethod "parent" [objT c_QModelIndex] $ objT c_QModelIndex
, just $ mkMethod' "removeColumn" "removeColumn" [intT] boolT
, just $ mkMethod' "removeColumn" "removeColumnAt" [intT, objT c_QModelIndex] boolT
, just $ mkMethod' "removeColumns" "removeColumns" [intT, intT] boolT
, just $ mkMethod' "removeColumns" "removeColumnsAt" [intT, intT, objT c_QModelIndex] boolT
, just $ mkMethod' "removeRow" "removeRow" [intT] boolT
, just $ mkMethod' "removeRow" "removeRowAt" [intT, objT c_QModelIndex] boolT
, just $ mkMethod' "removeRows" "removeRows" [intT, intT] boolT
, just $ mkMethod' "removeRows" "removeRowsAt" [intT, intT, objT c_QModelIndex] boolT
, just $ mkMethod "revert" [] voidT
TODO roleNames ( > = 4.6 )
, just $ mkConstMethod' "rowCount" "rowCount" [] intT
, just $ mkConstMethod' "rowCount" "rowCountAt" [objT c_QModelIndex] intT
, just $ mkMethod' "setData" "setData" [objT c_QModelIndex, objT c_QVariant] boolT
, just $ mkMethod' "setData" "setDataWithRole"
[objT c_QModelIndex, objT c_QVariant, enumT e_ItemDataRole] boolT
, just $ mkMethod' "setHeaderData" "setHeaderData"
[intT, enumT e_Orientation, objT c_QVariant] boolT
, just $ mkMethod' "setHeaderData" "setHeaderDataWithRole"
[intT, enumT e_Orientation, objT c_QVariant, enumT e_ItemDataRole] boolT
TODO setItemData
, just $ mkConstMethod "sibling" [intT, intT, objT c_QModelIndex] $ objT c_QModelIndex
, just $ mkMethod' "sort" "sort" [intT] voidT
, just $ mkMethod' "sort" "sortWithOrder" [intT, enumT e_SortOrder] voidT
, just $ mkConstMethod "span" [objT c_QModelIndex] $ objT c_QSize
, just $ mkMethod "submit" [] boolT
TODO suportedDragActions
TODO supportedDropActions ( > = 4.2 )
]
signals =
collect
[ just $ makeSignal c_QAbstractItemModel "columnsAboutToBeInserted" c_ListenerQModelIndexIntInt
, test (qtVersion >= [4, 6]) $ makeSignal c_QAbstractItemModel "columnsAboutToBeMoved"
c_ListenerQModelIndexIntIntQModelIndexInt
, just $ makeSignal c_QAbstractItemModel "columnsAboutToBeRemoved" c_ListenerQModelIndexIntInt
, just $ makeSignal c_QAbstractItemModel "columnsInserted" c_ListenerQModelIndexIntInt
, test (qtVersion >= [4, 6]) $ makeSignal c_QAbstractItemModel "columnsMoved"
c_ListenerQModelIndexIntIntQModelIndexInt
, just $ makeSignal c_QAbstractItemModel "columnsRemoved" c_ListenerQModelIndexIntInt
, just $ makeSignal c_QAbstractItemModel "dataChanged" c_ListenerQModelIndexQModelIndexQVectorInt
TODO layoutAboutToBeChanged ( > = 5.0 )
TODO layoutChanged ( > = 5.0 )
, test (qtVersion >= [4, 2]) $ makeSignal c_QAbstractItemModel "modelAboutToBeReset" c_Listener
, test (qtVersion >= [4, 1]) $ makeSignal c_QAbstractItemModel "modelReset" c_Listener
, just $ makeSignal c_QAbstractItemModel "rowsAboutToBeInserted" c_ListenerQModelIndexIntInt
, test (qtVersion >= [4, 6]) $ makeSignal c_QAbstractItemModel "rowsAboutToBeMoved"
c_ListenerQModelIndexIntIntQModelIndexInt
, just $ makeSignal c_QAbstractItemModel "rowsAboutToBeRemoved" c_ListenerQModelIndexIntInt
, just $ makeSignal c_QAbstractItemModel "rowsInserted" c_ListenerQModelIndexIntInt
, test (qtVersion >= [4, 6]) $ makeSignal c_QAbstractItemModel "rowsMoved"
c_ListenerQModelIndexIntIntQModelIndexInt
, just $ makeSignal c_QAbstractItemModel "rowsRemoved" c_ListenerQModelIndexIntInt
]
e_LayoutChangeHint =
makeQtEnum (ident1 "QAbstractItemModel" "LayoutChangeHint") [includeStd "QAbstractItemModel"]
[ (0, ["no", "layout", "change", "hint"])
, (1, ["vertical", "sort", "hint"])
, (2, ["horizontal", "sort", "hint"])
]
|
b7ac90f2c98054284e5dee78b620cc5587305dd17e3f49e1decf433960cdaf26 | gafiatulin/codewars | RelativePrimes.hs | -- Relatively Prime Numbers
module Haskell.Codewars.RelativePrimes where
relativelyPrime :: Integral t => t -> [t] -> [t]
relativelyPrime n = filter ((== 1) . gcd n)
| null | https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/8%20kyu/RelativePrimes.hs | haskell | Relatively Prime Numbers |
module Haskell.Codewars.RelativePrimes where
relativelyPrime :: Integral t => t -> [t] -> [t]
relativelyPrime n = filter ((== 1) . gcd n)
|
a29b5c519e82ec4dc7b9984b8a6008a92badc3ff80eabb9d4d6edfb56fa95fa0 | psg-mit/twist-popl22 | check.mli | open Core
exception TypeError of string
module VarMap = String.Map
val synth
: Ast.purity Ast.typ VarMap.t
-> Ast.purity Ast.typ VarMap.t
-> Ast.exp
-> Ast.purity Ast.typ VarMap.t * Ast.purity Ast.typ * Ast.exp
val check : Ast.decl list -> Ast.program
val quick_synth : Ast.exp VarMap.t -> Ast.purity Ast.typ VarMap.t -> Ast.exp -> Ast.purity Ast.typ
| null | https://raw.githubusercontent.com/psg-mit/twist-popl22/fa495479ff021fb8793ae20d8cf786ed048f503d/src/check.mli | ocaml | open Core
exception TypeError of string
module VarMap = String.Map
val synth
: Ast.purity Ast.typ VarMap.t
-> Ast.purity Ast.typ VarMap.t
-> Ast.exp
-> Ast.purity Ast.typ VarMap.t * Ast.purity Ast.typ * Ast.exp
val check : Ast.decl list -> Ast.program
val quick_synth : Ast.exp VarMap.t -> Ast.purity Ast.typ VarMap.t -> Ast.exp -> Ast.purity Ast.typ
| |
5451c89d15f7455b011e44a7f6fc6232f15c607be15d161b7d1f857c8c9321b3 | argp/bap | arch.mli | * Supported BAP architectures
type arch =
| X86_32
| X86_64
val arch_to_string : arch -> string
val arch_of_string : string -> arch
val type_of_arch : arch -> Type.typ
val bits_of_arch : arch -> int
val bytes_of_arch : arch -> int
val mode_of_arch : arch -> Disasm_i386.mode
val mem_of_arch : arch -> Var.t
val sp_of_arch : arch -> Var.t
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/ocaml/arch.mli | ocaml | * Supported BAP architectures
type arch =
| X86_32
| X86_64
val arch_to_string : arch -> string
val arch_of_string : string -> arch
val type_of_arch : arch -> Type.typ
val bits_of_arch : arch -> int
val bytes_of_arch : arch -> int
val mode_of_arch : arch -> Disasm_i386.mode
val mem_of_arch : arch -> Var.t
val sp_of_arch : arch -> Var.t
| |
d581a95fea1a2b0bde25dc256aaf4bdd84f205ed9b59941c2304efcd3279912c | uswitch/bifrost | user.clj | (ns user
(:require [uswitch.bifrost.system :refer (make-system)]
[clojure.tools.logging :refer (error)]
[clojure.tools.namespace.repl :refer (refresh)]
[com.stuartsierra.component :as component]))
(def system nil)
(defn init []
(alter-var-root #'system
(constantly (make-system (read-string (slurp "./etc/config.edn"))))))
(defn start []
(alter-var-root #'system (fn [s] (try (component/start s)
(catch Exception e
(error e "Error when starting system")
nil))) ))
(defn stop []
(alter-var-root #'system (fn [s] (when s (try (component/stop s)
(catch Exception e
(error e "Error when stopping system")
nil))))))
(defn go []
(init)
(start))
(defn reset []
(stop)
(refresh :after 'user/go))
| null | https://raw.githubusercontent.com/uswitch/bifrost/40a2bbb8af5c3b6d65930511c141c777a9585942/dev/user.clj | clojure | (ns user
(:require [uswitch.bifrost.system :refer (make-system)]
[clojure.tools.logging :refer (error)]
[clojure.tools.namespace.repl :refer (refresh)]
[com.stuartsierra.component :as component]))
(def system nil)
(defn init []
(alter-var-root #'system
(constantly (make-system (read-string (slurp "./etc/config.edn"))))))
(defn start []
(alter-var-root #'system (fn [s] (try (component/start s)
(catch Exception e
(error e "Error when starting system")
nil))) ))
(defn stop []
(alter-var-root #'system (fn [s] (when s (try (component/stop s)
(catch Exception e
(error e "Error when stopping system")
nil))))))
(defn go []
(init)
(start))
(defn reset []
(stop)
(refresh :after 'user/go))
| |
d0150d03bca1300f54805eea1e2916ebf1f802c5dd3e332d6f0f18abae9d4a4a | okuoku/nausicaa | proof-ssl.sps | -*- coding : utf-8 - unix -*-
;;;
Part of : Nausicaa / cURL
;;;Contents: test downloading web pages with SSL
Date : Sun Nov 22 , 2009
;;;
;;;Abstract
;;;
;;;
;;;
Copyright ( c ) 2009 < >
;;;
;;;This program is free software: you can redistribute it and/or modify
;;;it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or ( at
;;;your option) any later version.
;;;
;;;This program is distributed in the hope that it will be useful, but
;;;WITHOUT ANY WARRANTY; without even the implied warranty of
;;;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details .
;;;
You should have received a copy of the GNU General Public License
;;;along with this program. If not, see </>.
;;;
(import (nausicaa)
(compensations)
(foreign ffi)
(foreign net curl)
(foreign net curl compensated)
(foreign memory)
(foreign cstrings)
(strings)
(irregex)
(checks))
(check-set-mode! 'report-failed)
(display "*** proof of SSL\n")
(parametrise ((check-test-name 'gna)
(debugging #t))
(check
(with-compensations
(let* ((handle (curl-easy-init/c))
(out "")
(cb (lambda (buffer item-size item-count)
(let ((len (* item-size item-count)))
(set! out (string-append out (cstring->string buffer len)))
len))))
(curl-easy-setopt handle CURLOPT_URL "/")
(curl-easy-setopt handle CURLOPT_WRITEFUNCTION (curl-make-write-callback cb))
(curl-easy-setopt handle CURLOPT_WRITEDATA pointer-null)
(curl-easy-setopt handle CURLOPT_SSL_VERIFYPEER #f)
(curl-easy-perform handle)
(irregex-match-data? (irregex-search "</html>" out))))
=> #t)
(check 'this
(with-compensations
(let* ((handle (curl-easy-init/c))
(out "")
(cb (lambda (buffer item-size item-count)
(let ((len (* item-size item-count)))
(set! out (string-append out (cstring->string buffer len)))
len))))
(curl-easy-setopt handle CURLOPT_URL "/")
(curl-easy-setopt handle CURLOPT_WRITEFUNCTION (curl-make-write-callback cb))
(curl-easy-setopt handle CURLOPT_WRITEDATA pointer-null)
(curl-easy-setopt handle CURLOPT_SSL_VERIFYPEER #f)
(curl-easy-setopt handle CURLOPT_CERTINFO #t)
(curl-easy-perform handle)
(write (curl-easy-getinfo handle CURLINFO_CERTINFO))
(newline)
(irregex-match-data? (irregex-search "</html>" out))))
=> #t)
#t)
;;;; done
(check-report)
;;; end of file
| null | https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/curl/proofs/proof-ssl.sps | scheme |
Contents: test downloading web pages with SSL
Abstract
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
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
along with this program. If not, see </>.
done
end of file | -*- coding : utf-8 - unix -*-
Part of : Nausicaa / cURL
Date : Sun Nov 22 , 2009
Copyright ( c ) 2009 < >
the Free Software Foundation , either version 3 of the License , or ( at
General Public License for more details .
You should have received a copy of the GNU General Public License
(import (nausicaa)
(compensations)
(foreign ffi)
(foreign net curl)
(foreign net curl compensated)
(foreign memory)
(foreign cstrings)
(strings)
(irregex)
(checks))
(check-set-mode! 'report-failed)
(display "*** proof of SSL\n")
(parametrise ((check-test-name 'gna)
(debugging #t))
(check
(with-compensations
(let* ((handle (curl-easy-init/c))
(out "")
(cb (lambda (buffer item-size item-count)
(let ((len (* item-size item-count)))
(set! out (string-append out (cstring->string buffer len)))
len))))
(curl-easy-setopt handle CURLOPT_URL "/")
(curl-easy-setopt handle CURLOPT_WRITEFUNCTION (curl-make-write-callback cb))
(curl-easy-setopt handle CURLOPT_WRITEDATA pointer-null)
(curl-easy-setopt handle CURLOPT_SSL_VERIFYPEER #f)
(curl-easy-perform handle)
(irregex-match-data? (irregex-search "</html>" out))))
=> #t)
(check 'this
(with-compensations
(let* ((handle (curl-easy-init/c))
(out "")
(cb (lambda (buffer item-size item-count)
(let ((len (* item-size item-count)))
(set! out (string-append out (cstring->string buffer len)))
len))))
(curl-easy-setopt handle CURLOPT_URL "/")
(curl-easy-setopt handle CURLOPT_WRITEFUNCTION (curl-make-write-callback cb))
(curl-easy-setopt handle CURLOPT_WRITEDATA pointer-null)
(curl-easy-setopt handle CURLOPT_SSL_VERIFYPEER #f)
(curl-easy-setopt handle CURLOPT_CERTINFO #t)
(curl-easy-perform handle)
(write (curl-easy-getinfo handle CURLINFO_CERTINFO))
(newline)
(irregex-match-data? (irregex-search "</html>" out))))
=> #t)
#t)
(check-report)
|
e9f87335593d4c80079064f17f5c3d411b8ea1a86adbb74bc07f40e51101b3aa | lab-79/dspec | project.clj | (defproject lab79/dspec "0.3.8"
:description "Stronger semantics on top of Datomic, with clojure.spec goodies."
:url "-79/dspec"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:source-paths ["src/clj"]
:test-paths ["test"]
:dependencies [
[org.clojure/clojure "1.9.0-alpha12"]
[org.clojure/core.match "0.3.0-alpha4"]
[com.rpl/specter "0.12.0"]
[com.stuartsierra/dependency "0.2.0"]
[org.clojure/test.check "0.9.0"]
[lab79/datomic-spec "0.1.2"]
]
:profiles {:dev {:dependencies
[
[bolth "0.1.0"]
[org.clojure/tools.nrepl "0.2.11"]
[org.clojure/tools.namespace "0.2.11"]
[com.datomic/datomic-free "0.9.5390"]
]}}
:plugins [[lein-cloverage "1.0.7-SNAPSHOT"]])
| null | https://raw.githubusercontent.com/lab-79/dspec/26f88e74066e381c8569d175c1bd5948a8005bd0/project.clj | clojure | (defproject lab79/dspec "0.3.8"
:description "Stronger semantics on top of Datomic, with clojure.spec goodies."
:url "-79/dspec"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:source-paths ["src/clj"]
:test-paths ["test"]
:dependencies [
[org.clojure/clojure "1.9.0-alpha12"]
[org.clojure/core.match "0.3.0-alpha4"]
[com.rpl/specter "0.12.0"]
[com.stuartsierra/dependency "0.2.0"]
[org.clojure/test.check "0.9.0"]
[lab79/datomic-spec "0.1.2"]
]
:profiles {:dev {:dependencies
[
[bolth "0.1.0"]
[org.clojure/tools.nrepl "0.2.11"]
[org.clojure/tools.namespace "0.2.11"]
[com.datomic/datomic-free "0.9.5390"]
]}}
:plugins [[lein-cloverage "1.0.7-SNAPSHOT"]])
| |
d9475a14ceb5dc04a8788a496cd169e690d456764f6b71f64fbef032d76eae3c | matterandvoid-space/todomvc-fulcro-subscriptions | subscriptions.clj | (ns space.matterandvoid.todomvc.todo.subscriptions
(:require
[space.matterandvoid.subscriptions.datalevin-eql :as subs.eql]
[space.matterandvoid.todomvc.server.db :as-alias system.db]
[space.matterandvoid.todomvc.todo.model :as todo.model]
[space.matterandvoid.todomvc.todo.db :as todo.db]))
(def todo-eql (subs.eql/create-component-subs todo.model/todo-db-component {}))
(defn complete-todos [conn] (filterv todo.model/todo-completed? (todo.db/get-todos conn)))
(defn incomplete-todos [conn] (vec (remove todo.model/todo-completed? (todo.db/get-todos conn))))
(defn all-complete? [todos] (every? todo.model/todo-completed? todos))
(defn sorted-todos [conn] (sort-by ::system.db/created-at (todo.db/get-todos conn)))
| null | https://raw.githubusercontent.com/matterandvoid-space/todomvc-fulcro-subscriptions/e2e244936efe1005fa2cac204a24758b067aac4e/src/main/space/matterandvoid/todomvc/todo/subscriptions.clj | clojure | (ns space.matterandvoid.todomvc.todo.subscriptions
(:require
[space.matterandvoid.subscriptions.datalevin-eql :as subs.eql]
[space.matterandvoid.todomvc.server.db :as-alias system.db]
[space.matterandvoid.todomvc.todo.model :as todo.model]
[space.matterandvoid.todomvc.todo.db :as todo.db]))
(def todo-eql (subs.eql/create-component-subs todo.model/todo-db-component {}))
(defn complete-todos [conn] (filterv todo.model/todo-completed? (todo.db/get-todos conn)))
(defn incomplete-todos [conn] (vec (remove todo.model/todo-completed? (todo.db/get-todos conn))))
(defn all-complete? [todos] (every? todo.model/todo-completed? todos))
(defn sorted-todos [conn] (sort-by ::system.db/created-at (todo.db/get-todos conn)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.