_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
6836b4ef12d3675745bd8c8c63a15288801dbfec14b2f252ae8d882d07af286e
Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library
PostSetupIntentsIntentCancel.hs
{-# LANGUAGE ExplicitForAll #-} {-# LANGUAGE MultiWayIf #-} CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . {-# LANGUAGE OverloadedStrings #-} | Contains the different functions to run the operation postSetupIntentsIntentCancel module StripeAPI.Operations.PostSetupIntentsIntentCancel where import qualified Control.Monad.Fail import qualified Control.Monad.Trans.Reader import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Either import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified Data.Vector import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified Network.HTTP.Client import qualified Network.HTTP.Client as Network.HTTP.Client.Request import qualified Network.HTTP.Client as Network.HTTP.Client.Types import qualified Network.HTTP.Simple import qualified Network.HTTP.Types import qualified Network.HTTP.Types as Network.HTTP.Types.Status import qualified Network.HTTP.Types as Network.HTTP.Types.URI import qualified StripeAPI.Common import StripeAPI.Types import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe -- | > POST /v1/setup_intents/{intent}/cancel -- \<p > A SetupIntent object can be canceled when it is in one of these statuses : \<code > requires_payment_method\<\/code > , \<code > requires_confirmation\<\/code > , or \<code > requires_action\<\/code > . \<\/p > -- \<p > Once canceled , setup is abandoned and any operations on the SetupIntent will fail with an error.\<\/p > postSetupIntentsIntentCancel :: forall m. StripeAPI.Common.MonadHTTP m => | intent | Constraints : Maximum length of 5000 Data.Text.Internal.Text -> -- | The request body to send GHC.Maybe.Maybe PostSetupIntentsIntentCancelRequestBody -> -- | Monadic computation which returns the result of the operation StripeAPI.Common.ClientT m (Network.HTTP.Client.Types.Response PostSetupIntentsIntentCancelResponse) postSetupIntentsIntentCancel intent body = GHC.Base.fmap ( \response_0 -> GHC.Base.fmap ( Data.Either.either PostSetupIntentsIntentCancelResponseError GHC.Base.id GHC.Base.. ( \response body -> if | (\status_1 -> Network.HTTP.Types.Status.statusCode status_1 GHC.Classes.== 200) (Network.HTTP.Client.Types.responseStatus response) -> PostSetupIntentsIntentCancelResponse200 Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body :: Data.Either.Either GHC.Base.String SetupIntent ) | GHC.Base.const GHC.Types.True (Network.HTTP.Client.Types.responseStatus response) -> PostSetupIntentsIntentCancelResponseDefault Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body :: Data.Either.Either GHC.Base.String Error ) | GHC.Base.otherwise -> Data.Either.Left "Missing default response type" ) response_0 ) response_0 ) (StripeAPI.Common.doBodyCallWithConfigurationM (Data.Text.toUpper GHC.Base.$ Data.Text.pack "POST") (Data.Text.pack ("/v1/setup_intents/" GHC.Base.++ (Data.ByteString.Char8.unpack (Network.HTTP.Types.URI.urlEncode GHC.Types.True GHC.Base.$ (Data.ByteString.Char8.pack GHC.Base.$ StripeAPI.Common.stringifyModel intent)) GHC.Base.++ "/cancel"))) GHC.Base.mempty body StripeAPI.Common.RequestBodyEncodingFormData) -- | Defines the object schema located at @paths.\/v1\/setup_intents\/{intent}\/cancel.POST.requestBody.content.application\/x-www-form-urlencoded.schema@ in the specification. data PostSetupIntentsIntentCancelRequestBody = PostSetupIntentsIntentCancelRequestBody | cancellation_reason : Reason for canceling this SetupIntent . Possible values are \`abandoned\ ` , \`requested_by_customer\ ` , or \`duplicate\ ` -- -- Constraints: -- * Maximum length of 5000 postSetupIntentsIntentCancelRequestBodyCancellationReason :: (GHC.Maybe.Maybe PostSetupIntentsIntentCancelRequestBodyCancellationReason'), -- | expand: Specifies which fields in the response should be expanded. postSetupIntentsIntentCancelRequestBodyExpand :: (GHC.Maybe.Maybe ([Data.Text.Internal.Text])) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON PostSetupIntentsIntentCancelRequestBody where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("cancellation_reason" Data.Aeson.Types.ToJSON..=)) (postSetupIntentsIntentCancelRequestBodyCancellationReason obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("expand" Data.Aeson.Types.ToJSON..=)) (postSetupIntentsIntentCancelRequestBodyExpand obj) : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("cancellation_reason" Data.Aeson.Types.ToJSON..=)) (postSetupIntentsIntentCancelRequestBodyCancellationReason obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("expand" Data.Aeson.Types.ToJSON..=)) (postSetupIntentsIntentCancelRequestBodyExpand obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON PostSetupIntentsIntentCancelRequestBody where parseJSON = Data.Aeson.Types.FromJSON.withObject "PostSetupIntentsIntentCancelRequestBody" (\obj -> (GHC.Base.pure PostSetupIntentsIntentCancelRequestBody GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "cancellation_reason")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "expand")) -- | Create a new 'PostSetupIntentsIntentCancelRequestBody' with all required fields. mkPostSetupIntentsIntentCancelRequestBody :: PostSetupIntentsIntentCancelRequestBody mkPostSetupIntentsIntentCancelRequestBody = PostSetupIntentsIntentCancelRequestBody { postSetupIntentsIntentCancelRequestBodyCancellationReason = GHC.Maybe.Nothing, postSetupIntentsIntentCancelRequestBodyExpand = GHC.Maybe.Nothing } -- | Defines the enum schema located at @paths.\/v1\/setup_intents\/{intent}\/cancel.POST.requestBody.content.application\/x-www-form-urlencoded.schema.properties.cancellation_reason@ in the specification. -- Reason for canceling this SetupIntent . Possible values are \`abandoned\ ` , \`requested_by_customer\ ` , or \`duplicate\ ` data PostSetupIntentsIntentCancelRequestBodyCancellationReason' = -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification. PostSetupIntentsIntentCancelRequestBodyCancellationReason'Other Data.Aeson.Types.Internal.Value | -- | This constructor can be used to send values to the server which are not present in the specification yet. PostSetupIntentsIntentCancelRequestBodyCancellationReason'Typed Data.Text.Internal.Text | -- | Represents the JSON value @"abandoned"@ PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumAbandoned | -- | Represents the JSON value @"duplicate"@ PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumDuplicate | -- | Represents the JSON value @"requested_by_customer"@ PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumRequestedByCustomer deriving (GHC.Show.Show, GHC.Classes.Eq) instance Data.Aeson.Types.ToJSON.ToJSON PostSetupIntentsIntentCancelRequestBodyCancellationReason' where toJSON (PostSetupIntentsIntentCancelRequestBodyCancellationReason'Other val) = val toJSON (PostSetupIntentsIntentCancelRequestBodyCancellationReason'Typed val) = Data.Aeson.Types.ToJSON.toJSON val toJSON (PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumAbandoned) = "abandoned" toJSON (PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumDuplicate) = "duplicate" toJSON (PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumRequestedByCustomer) = "requested_by_customer" instance Data.Aeson.Types.FromJSON.FromJSON PostSetupIntentsIntentCancelRequestBodyCancellationReason' where parseJSON val = GHC.Base.pure ( if | val GHC.Classes.== "abandoned" -> PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumAbandoned | val GHC.Classes.== "duplicate" -> PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumDuplicate | val GHC.Classes.== "requested_by_customer" -> PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumRequestedByCustomer | GHC.Base.otherwise -> PostSetupIntentsIntentCancelRequestBodyCancellationReason'Other val ) -- | Represents a response of the operation 'postSetupIntentsIntentCancel'. -- -- The response constructor is chosen by the status code of the response. If no case matches (no specific case for the response code, no range case, no default case), 'PostSetupIntentsIntentCancelResponseError' is used. data PostSetupIntentsIntentCancelResponse = -- | Means either no matching case available or a parse error PostSetupIntentsIntentCancelResponseError GHC.Base.String | -- | Successful response. PostSetupIntentsIntentCancelResponse200 SetupIntent | -- | Error response. PostSetupIntentsIntentCancelResponseDefault Error deriving (GHC.Show.Show, GHC.Classes.Eq)
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Operations/PostSetupIntentsIntentCancel.hs
haskell
# LANGUAGE ExplicitForAll # # LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # | > POST /v1/setup_intents/{intent}/cancel | The request body to send | Monadic computation which returns the result of the operation | Defines the object schema located at @paths.\/v1\/setup_intents\/{intent}\/cancel.POST.requestBody.content.application\/x-www-form-urlencoded.schema@ in the specification. Constraints: | expand: Specifies which fields in the response should be expanded. | Create a new 'PostSetupIntentsIntentCancelRequestBody' with all required fields. | Defines the enum schema located at @paths.\/v1\/setup_intents\/{intent}\/cancel.POST.requestBody.content.application\/x-www-form-urlencoded.schema.properties.cancellation_reason@ in the specification. | This case is used if the value encountered during decoding does not match any of the provided cases in the specification. | This constructor can be used to send values to the server which are not present in the specification yet. | Represents the JSON value @"abandoned"@ | Represents the JSON value @"duplicate"@ | Represents the JSON value @"requested_by_customer"@ | Represents a response of the operation 'postSetupIntentsIntentCancel'. The response constructor is chosen by the status code of the response. If no case matches (no specific case for the response code, no range case, no default case), 'PostSetupIntentsIntentCancelResponseError' is used. | Means either no matching case available or a parse error | Successful response. | Error response.
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . | Contains the different functions to run the operation postSetupIntentsIntentCancel module StripeAPI.Operations.PostSetupIntentsIntentCancel where import qualified Control.Monad.Fail import qualified Control.Monad.Trans.Reader import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Either import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified Data.Vector import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified Network.HTTP.Client import qualified Network.HTTP.Client as Network.HTTP.Client.Request import qualified Network.HTTP.Client as Network.HTTP.Client.Types import qualified Network.HTTP.Simple import qualified Network.HTTP.Types import qualified Network.HTTP.Types as Network.HTTP.Types.Status import qualified Network.HTTP.Types as Network.HTTP.Types.URI import qualified StripeAPI.Common import StripeAPI.Types import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe \<p > A SetupIntent object can be canceled when it is in one of these statuses : \<code > requires_payment_method\<\/code > , \<code > requires_confirmation\<\/code > , or \<code > requires_action\<\/code > . \<\/p > \<p > Once canceled , setup is abandoned and any operations on the SetupIntent will fail with an error.\<\/p > postSetupIntentsIntentCancel :: forall m. StripeAPI.Common.MonadHTTP m => | intent | Constraints : Maximum length of 5000 Data.Text.Internal.Text -> GHC.Maybe.Maybe PostSetupIntentsIntentCancelRequestBody -> StripeAPI.Common.ClientT m (Network.HTTP.Client.Types.Response PostSetupIntentsIntentCancelResponse) postSetupIntentsIntentCancel intent body = GHC.Base.fmap ( \response_0 -> GHC.Base.fmap ( Data.Either.either PostSetupIntentsIntentCancelResponseError GHC.Base.id GHC.Base.. ( \response body -> if | (\status_1 -> Network.HTTP.Types.Status.statusCode status_1 GHC.Classes.== 200) (Network.HTTP.Client.Types.responseStatus response) -> PostSetupIntentsIntentCancelResponse200 Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body :: Data.Either.Either GHC.Base.String SetupIntent ) | GHC.Base.const GHC.Types.True (Network.HTTP.Client.Types.responseStatus response) -> PostSetupIntentsIntentCancelResponseDefault Data.Functor.<$> ( Data.Aeson.eitherDecodeStrict body :: Data.Either.Either GHC.Base.String Error ) | GHC.Base.otherwise -> Data.Either.Left "Missing default response type" ) response_0 ) response_0 ) (StripeAPI.Common.doBodyCallWithConfigurationM (Data.Text.toUpper GHC.Base.$ Data.Text.pack "POST") (Data.Text.pack ("/v1/setup_intents/" GHC.Base.++ (Data.ByteString.Char8.unpack (Network.HTTP.Types.URI.urlEncode GHC.Types.True GHC.Base.$ (Data.ByteString.Char8.pack GHC.Base.$ StripeAPI.Common.stringifyModel intent)) GHC.Base.++ "/cancel"))) GHC.Base.mempty body StripeAPI.Common.RequestBodyEncodingFormData) data PostSetupIntentsIntentCancelRequestBody = PostSetupIntentsIntentCancelRequestBody | cancellation_reason : Reason for canceling this SetupIntent . Possible values are \`abandoned\ ` , \`requested_by_customer\ ` , or \`duplicate\ ` * Maximum length of 5000 postSetupIntentsIntentCancelRequestBodyCancellationReason :: (GHC.Maybe.Maybe PostSetupIntentsIntentCancelRequestBodyCancellationReason'), postSetupIntentsIntentCancelRequestBodyExpand :: (GHC.Maybe.Maybe ([Data.Text.Internal.Text])) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON PostSetupIntentsIntentCancelRequestBody where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("cancellation_reason" Data.Aeson.Types.ToJSON..=)) (postSetupIntentsIntentCancelRequestBodyCancellationReason obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("expand" Data.Aeson.Types.ToJSON..=)) (postSetupIntentsIntentCancelRequestBodyExpand obj) : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("cancellation_reason" Data.Aeson.Types.ToJSON..=)) (postSetupIntentsIntentCancelRequestBodyCancellationReason obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("expand" Data.Aeson.Types.ToJSON..=)) (postSetupIntentsIntentCancelRequestBodyExpand obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON PostSetupIntentsIntentCancelRequestBody where parseJSON = Data.Aeson.Types.FromJSON.withObject "PostSetupIntentsIntentCancelRequestBody" (\obj -> (GHC.Base.pure PostSetupIntentsIntentCancelRequestBody GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "cancellation_reason")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "expand")) mkPostSetupIntentsIntentCancelRequestBody :: PostSetupIntentsIntentCancelRequestBody mkPostSetupIntentsIntentCancelRequestBody = PostSetupIntentsIntentCancelRequestBody { postSetupIntentsIntentCancelRequestBodyCancellationReason = GHC.Maybe.Nothing, postSetupIntentsIntentCancelRequestBodyExpand = GHC.Maybe.Nothing } Reason for canceling this SetupIntent . Possible values are \`abandoned\ ` , \`requested_by_customer\ ` , or \`duplicate\ ` data PostSetupIntentsIntentCancelRequestBodyCancellationReason' PostSetupIntentsIntentCancelRequestBodyCancellationReason'Other Data.Aeson.Types.Internal.Value PostSetupIntentsIntentCancelRequestBodyCancellationReason'Typed Data.Text.Internal.Text PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumAbandoned PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumDuplicate PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumRequestedByCustomer deriving (GHC.Show.Show, GHC.Classes.Eq) instance Data.Aeson.Types.ToJSON.ToJSON PostSetupIntentsIntentCancelRequestBodyCancellationReason' where toJSON (PostSetupIntentsIntentCancelRequestBodyCancellationReason'Other val) = val toJSON (PostSetupIntentsIntentCancelRequestBodyCancellationReason'Typed val) = Data.Aeson.Types.ToJSON.toJSON val toJSON (PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumAbandoned) = "abandoned" toJSON (PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumDuplicate) = "duplicate" toJSON (PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumRequestedByCustomer) = "requested_by_customer" instance Data.Aeson.Types.FromJSON.FromJSON PostSetupIntentsIntentCancelRequestBodyCancellationReason' where parseJSON val = GHC.Base.pure ( if | val GHC.Classes.== "abandoned" -> PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumAbandoned | val GHC.Classes.== "duplicate" -> PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumDuplicate | val GHC.Classes.== "requested_by_customer" -> PostSetupIntentsIntentCancelRequestBodyCancellationReason'EnumRequestedByCustomer | GHC.Base.otherwise -> PostSetupIntentsIntentCancelRequestBodyCancellationReason'Other val ) data PostSetupIntentsIntentCancelResponse PostSetupIntentsIntentCancelResponseError GHC.Base.String PostSetupIntentsIntentCancelResponse200 SetupIntent PostSetupIntentsIntentCancelResponseDefault Error deriving (GHC.Show.Show, GHC.Classes.Eq)
da6599fa1005d42cce079acec43a80155cc840eb9dfc622dd681302d5b41f597
avsm/eeww
buf_read.ml
exception Buffer_limit_exceeded type t = { mutable buf : Cstruct.buffer; mutable pos : int; mutable len : int; mutable flow : Flow.source option; (* None if we've seen eof *) mutable consumed : int; (* Total bytes consumed so far *) max_size : int; } type 'a parser = t -> 'a let return = Fun.const let map f x r = f (x r) let pair x y r = let a = x r in let b = y r in a, b let bind x f r = f (x r) r module Syntax = struct let ( let+ ) x f r = f (x r) let ( let* ) = bind let ( and* ) = pair let ( and+ ) = pair let ( <*> ) = pair let ( <* ) a b t = let x = a t in ignore (b t); x let ( *> ) a b t = ignore (a t); b t end open Syntax let capacity t = Bigarray.Array1.dim t.buf let of_flow ?initial_size ~max_size flow = let flow = (flow :> Flow.source) in if max_size <= 0 then Fmt.invalid_arg "Max size %d should be positive!" max_size; let initial_size = Option.value initial_size ~default:(min 4096 max_size) in let buf = Bigarray.(Array1.create char c_layout initial_size) in { buf; pos = 0; len = 0; flow = Some flow; max_size; consumed = 0 } let of_buffer buf = let len = Bigarray.Array1.dim buf in { buf; pos = 0; len; flow = None; max_size = max_int; consumed = 0 } let of_string s = let len = String.length s in let buf = Bigarray.(Array1.create char c_layout) len in Cstruct.blit_from_string s 0 (Cstruct.of_bigarray buf) 0 len; of_buffer buf let peek t = Cstruct.of_bigarray ~off:t.pos ~len:t.len t.buf let consume_err t n = Fmt.invalid_arg "Can't consume %d bytes of a %d byte buffer!" n t.len let [@inline] consume t n = if n < 0 || n > t.len then consume_err t n; t.pos <- t.pos + n; t.len <- t.len - n; t.consumed <- t.consumed + n let consume_all t = t.consumed <- t.consumed + t.len; t.len <- 0 let buffered_bytes t = t.len let consumed_bytes t = t.consumed let eof_seen t = t.flow = None let ensure_slow_path t n = assert (n >= 0); if n > t.max_size then raise Buffer_limit_exceeded; (* We don't have enough data yet, so we'll need to do a read. *) match t.flow with | None -> raise End_of_file | Some flow -> (* If the buffer is empty, we might as well use all of it: *) if t.len = 0 then t.pos <- 0; let () = let cap = capacity t in if n > cap then ( (* [n] bytes won't fit. We need to resize the buffer. *) let new_size = max n (min t.max_size (cap * 2)) in let new_buf = Bigarray.(Array1.create char c_layout new_size) in Cstruct.blit (peek t) 0 (Cstruct.of_bigarray new_buf) 0 t.len; t.pos <- 0; t.buf <- new_buf ) else if t.pos + n > cap then ( [ n ] bytes will fit in the existing buffer , but we need to compact it first . Cstruct.blit (peek t) 0 (Cstruct.of_bigarray t.buf) 0 t.len; t.pos <- 0 ) in try while t.len < n do let free_space = Cstruct.of_bigarray t.buf ~off:(t.pos + t.len) in assert (t.len + Cstruct.length free_space >= n); let got = Flow.single_read flow free_space in t.len <- t.len + got done; assert (buffered_bytes t >= n) with End_of_file -> t.flow <- None; raise End_of_file let ensure t n = if t.len < n then ensure_slow_path t n let as_flow t = object inherit Flow.source method read_into dst = ensure t 1; let len = min (buffered_bytes t) (Cstruct.length dst) in Cstruct.blit (peek t) 0 dst 0 len; consume t len; len end let get t i = Bigarray.Array1.get t.buf (t.pos + i) module BE = struct let uint16 t = ensure t 2; let data = Bigstringaf.get_int16_be t.buf t.pos in consume t 2; data let uint32 t = ensure t 4; let data = Bigstringaf.get_int32_be t.buf t.pos in consume t 4; data let uint48 t = ensure t 6; let upper_32 = Bigstringaf.get_int32_be t.buf t.pos |> Int64.of_int32 |> Int64.logand 0xffffffffL in let lower_16 = Bigstringaf.get_int16_be t.buf (t.pos + 4) |> Int64.of_int in consume t 6; Int64.( logor (lower_16) (shift_left upper_32 16) ) let uint64 t = ensure t 8; let data = Bigstringaf.get_int64_be t.buf t.pos in consume t 8; data let float t = ensure t 4; let data = Bigstringaf.unsafe_get_int32_be t.buf t.pos in consume t 4; Int32.float_of_bits data let double t = ensure t 8; let data = Bigstringaf.unsafe_get_int64_be t.buf t.pos in consume t 8; Int64.float_of_bits data end module LE = struct let uint16 t = ensure t 2; let data = Bigstringaf.get_int16_le t.buf t.pos in consume t 2; data let uint32 t = ensure t 4; let data = Bigstringaf.get_int32_le t.buf t.pos in consume t 4; data let uint48 t = ensure t 6; let lower_32 = Bigstringaf.get_int32_le t.buf t.pos |> Int64.of_int32 |> Int64.logand 0xffffffffL in let upper_16 = Bigstringaf.get_int16_le t.buf (t.pos + 4) |> Int64.of_int in consume t 6; Int64.( logor (shift_left upper_16 32) lower_32 ) let uint64 t = ensure t 8; let data = Bigstringaf.get_int64_le t.buf t.pos in consume t 8; data let float t = ensure t 4; let data = Bigstringaf.unsafe_get_int32_le t.buf t.pos in consume t 4; Int32.float_of_bits data let double t = ensure t 8; let data = Bigstringaf.unsafe_get_int64_le t.buf t.pos in consume t 8; Int64.float_of_bits data end let char c t = ensure t 1; let c2 = get t 0 in if c <> c2 then Fmt.failwith "Expected %C but got %C" c c2; consume t 1 let any_char t = ensure t 1; let c = get t 0 in consume t 1; c let uint8 t = Char.code (any_char t) let peek_char t = match ensure t 1 with | () -> Some (get t 0) | exception End_of_file -> None let take len t = if len < 0 then Fmt.invalid_arg "take: %d is negative!" len; ensure t len; let data = Cstruct.to_string (Cstruct.of_bigarray t.buf ~off:t.pos ~len) in consume t len; data let string s t = let rec aux i = if i = String.length s then ( consume t i ) else if i < t.len then ( if get t i = s.[i] then aux (i + 1) else ( let buf = peek t in let len = min (String.length s) (Cstruct.length buf) in Fmt.failwith "Expected %S but got %S" s (Cstruct.to_string buf ~off:0 ~len) ) ) else ( ensure t (t.len + 1); aux i ) in aux 0 let take_all t = try while true do ensure t (t.len + 1) done; assert false with End_of_file -> let data = Cstruct.to_string (peek t) in consume t t.len; data let count_while p t = let rec aux i = if i < t.len then ( if p (get t i) then aux (i + 1) else i ) else ( ensure t (t.len + 1); aux i ) in try aux 0 with End_of_file -> t.len let take_while p t = let len = count_while p t in let data = Cstruct.to_string (Cstruct.of_bigarray t.buf ~off:t.pos ~len) in consume t len; data let take_while1 p t = let len = count_while p t in if len < 1 then Fmt.failwith "take_while1" else let data = Cstruct.to_string (Cstruct.of_bigarray t.buf ~off:t.pos ~len) in consume t len; data let skip_while p t = let rec aux i = if i < t.len then ( if p (get t i) then aux (i + 1) else consume t i ) else ( consume t t.len; ensure t 1; aux 0 ) in try aux 0 with End_of_file -> () let skip_while1 p t = let len = count_while p t in if len < 1 then Fmt.failwith "skip_while1" else consume t len let rec skip n t = if n <= t.len then ( consume t n ) else ( let n = n - t.len in consume_all t; ensure t (min n (capacity t)); skip n t ) let skip n t = if n < 0 then Fmt.invalid_arg "skip: %d is negative!" n; try skip n t with End_of_file -> (* Skip isn't atomic, so discard everything in this case for consistency. *) consume t t.len; raise End_of_file let line t = Return the index of the first ' \n ' , reading more data as needed . let rec aux i = if i = t.len then ( ensure t (t.len + 1); aux i ) else if get t i = '\n' then ( i ) else ( aux (i + 1) ) in match aux 0 with | exception End_of_file when t.len > 0 -> take_all t | nl -> let len = if nl > 0 && get t (nl - 1) = '\r' then nl - 1 else nl in let line = Cstruct.to_string (Cstruct.of_bigarray t.buf ~off:t.pos ~len) in consume t (nl + 1); line let at_end_of_input t = if t.len = 0 && eof_seen t then true else ( match ensure t 1 with | () -> false | exception End_of_file -> true ) let end_of_input t = if not (at_end_of_input t) then failwith "Unexpected data after parsing" let pp_pos f t = Fmt.pf f "at offset %d" (consumed_bytes t) let format_errors p t = match p t with | v -> Ok v | exception Failure msg -> Fmt.error_msg "%s (%a)" msg pp_pos t | exception End_of_file -> Fmt.error_msg "Unexpected end-of-file at offset %d" (t.consumed + t.len) | exception Buffer_limit_exceeded -> Fmt.error_msg "Buffer size limit exceeded when reading %a" pp_pos t let parse ?initial_size ~max_size p flow = let buf = of_flow flow ?initial_size ~max_size in format_errors (p <* end_of_input) buf let parse_exn ?initial_size ~max_size p flow = match parse ?initial_size ~max_size p flow with | Ok x -> x | Error (`Msg m) -> failwith m let parse_string p s = format_errors (p <* end_of_input) (of_string s) let parse_string_exn p s = match parse_string p s with | Ok x -> x | Error (`Msg m) -> failwith m [@@inline never] let bad_offset ~expected actual = Fmt.invalid_arg "Sequence is stale (expected to be used at offset %d, but stream is now at %d)" expected actual let seq ?(stop=at_end_of_input) p t = let rec aux offset () = if offset <> t.consumed then bad_offset ~expected:offset t.consumed; if stop t then Seq.Nil else ( let item = p t in Seq.Cons (item, aux t.consumed) ) in aux t.consumed let lines t = seq line t
null
https://raw.githubusercontent.com/avsm/eeww/684af99c194ff082836dbb1ada05c8a023dbd844/lib/eio/lib_eio/buf_read.ml
ocaml
None if we've seen eof Total bytes consumed so far We don't have enough data yet, so we'll need to do a read. If the buffer is empty, we might as well use all of it: [n] bytes won't fit. We need to resize the buffer. Skip isn't atomic, so discard everything in this case for consistency.
exception Buffer_limit_exceeded type t = { mutable buf : Cstruct.buffer; mutable pos : int; mutable len : int; max_size : int; } type 'a parser = t -> 'a let return = Fun.const let map f x r = f (x r) let pair x y r = let a = x r in let b = y r in a, b let bind x f r = f (x r) r module Syntax = struct let ( let+ ) x f r = f (x r) let ( let* ) = bind let ( and* ) = pair let ( and+ ) = pair let ( <*> ) = pair let ( <* ) a b t = let x = a t in ignore (b t); x let ( *> ) a b t = ignore (a t); b t end open Syntax let capacity t = Bigarray.Array1.dim t.buf let of_flow ?initial_size ~max_size flow = let flow = (flow :> Flow.source) in if max_size <= 0 then Fmt.invalid_arg "Max size %d should be positive!" max_size; let initial_size = Option.value initial_size ~default:(min 4096 max_size) in let buf = Bigarray.(Array1.create char c_layout initial_size) in { buf; pos = 0; len = 0; flow = Some flow; max_size; consumed = 0 } let of_buffer buf = let len = Bigarray.Array1.dim buf in { buf; pos = 0; len; flow = None; max_size = max_int; consumed = 0 } let of_string s = let len = String.length s in let buf = Bigarray.(Array1.create char c_layout) len in Cstruct.blit_from_string s 0 (Cstruct.of_bigarray buf) 0 len; of_buffer buf let peek t = Cstruct.of_bigarray ~off:t.pos ~len:t.len t.buf let consume_err t n = Fmt.invalid_arg "Can't consume %d bytes of a %d byte buffer!" n t.len let [@inline] consume t n = if n < 0 || n > t.len then consume_err t n; t.pos <- t.pos + n; t.len <- t.len - n; t.consumed <- t.consumed + n let consume_all t = t.consumed <- t.consumed + t.len; t.len <- 0 let buffered_bytes t = t.len let consumed_bytes t = t.consumed let eof_seen t = t.flow = None let ensure_slow_path t n = assert (n >= 0); if n > t.max_size then raise Buffer_limit_exceeded; match t.flow with | None -> raise End_of_file | Some flow -> if t.len = 0 then t.pos <- 0; let () = let cap = capacity t in if n > cap then ( let new_size = max n (min t.max_size (cap * 2)) in let new_buf = Bigarray.(Array1.create char c_layout new_size) in Cstruct.blit (peek t) 0 (Cstruct.of_bigarray new_buf) 0 t.len; t.pos <- 0; t.buf <- new_buf ) else if t.pos + n > cap then ( [ n ] bytes will fit in the existing buffer , but we need to compact it first . Cstruct.blit (peek t) 0 (Cstruct.of_bigarray t.buf) 0 t.len; t.pos <- 0 ) in try while t.len < n do let free_space = Cstruct.of_bigarray t.buf ~off:(t.pos + t.len) in assert (t.len + Cstruct.length free_space >= n); let got = Flow.single_read flow free_space in t.len <- t.len + got done; assert (buffered_bytes t >= n) with End_of_file -> t.flow <- None; raise End_of_file let ensure t n = if t.len < n then ensure_slow_path t n let as_flow t = object inherit Flow.source method read_into dst = ensure t 1; let len = min (buffered_bytes t) (Cstruct.length dst) in Cstruct.blit (peek t) 0 dst 0 len; consume t len; len end let get t i = Bigarray.Array1.get t.buf (t.pos + i) module BE = struct let uint16 t = ensure t 2; let data = Bigstringaf.get_int16_be t.buf t.pos in consume t 2; data let uint32 t = ensure t 4; let data = Bigstringaf.get_int32_be t.buf t.pos in consume t 4; data let uint48 t = ensure t 6; let upper_32 = Bigstringaf.get_int32_be t.buf t.pos |> Int64.of_int32 |> Int64.logand 0xffffffffL in let lower_16 = Bigstringaf.get_int16_be t.buf (t.pos + 4) |> Int64.of_int in consume t 6; Int64.( logor (lower_16) (shift_left upper_32 16) ) let uint64 t = ensure t 8; let data = Bigstringaf.get_int64_be t.buf t.pos in consume t 8; data let float t = ensure t 4; let data = Bigstringaf.unsafe_get_int32_be t.buf t.pos in consume t 4; Int32.float_of_bits data let double t = ensure t 8; let data = Bigstringaf.unsafe_get_int64_be t.buf t.pos in consume t 8; Int64.float_of_bits data end module LE = struct let uint16 t = ensure t 2; let data = Bigstringaf.get_int16_le t.buf t.pos in consume t 2; data let uint32 t = ensure t 4; let data = Bigstringaf.get_int32_le t.buf t.pos in consume t 4; data let uint48 t = ensure t 6; let lower_32 = Bigstringaf.get_int32_le t.buf t.pos |> Int64.of_int32 |> Int64.logand 0xffffffffL in let upper_16 = Bigstringaf.get_int16_le t.buf (t.pos + 4) |> Int64.of_int in consume t 6; Int64.( logor (shift_left upper_16 32) lower_32 ) let uint64 t = ensure t 8; let data = Bigstringaf.get_int64_le t.buf t.pos in consume t 8; data let float t = ensure t 4; let data = Bigstringaf.unsafe_get_int32_le t.buf t.pos in consume t 4; Int32.float_of_bits data let double t = ensure t 8; let data = Bigstringaf.unsafe_get_int64_le t.buf t.pos in consume t 8; Int64.float_of_bits data end let char c t = ensure t 1; let c2 = get t 0 in if c <> c2 then Fmt.failwith "Expected %C but got %C" c c2; consume t 1 let any_char t = ensure t 1; let c = get t 0 in consume t 1; c let uint8 t = Char.code (any_char t) let peek_char t = match ensure t 1 with | () -> Some (get t 0) | exception End_of_file -> None let take len t = if len < 0 then Fmt.invalid_arg "take: %d is negative!" len; ensure t len; let data = Cstruct.to_string (Cstruct.of_bigarray t.buf ~off:t.pos ~len) in consume t len; data let string s t = let rec aux i = if i = String.length s then ( consume t i ) else if i < t.len then ( if get t i = s.[i] then aux (i + 1) else ( let buf = peek t in let len = min (String.length s) (Cstruct.length buf) in Fmt.failwith "Expected %S but got %S" s (Cstruct.to_string buf ~off:0 ~len) ) ) else ( ensure t (t.len + 1); aux i ) in aux 0 let take_all t = try while true do ensure t (t.len + 1) done; assert false with End_of_file -> let data = Cstruct.to_string (peek t) in consume t t.len; data let count_while p t = let rec aux i = if i < t.len then ( if p (get t i) then aux (i + 1) else i ) else ( ensure t (t.len + 1); aux i ) in try aux 0 with End_of_file -> t.len let take_while p t = let len = count_while p t in let data = Cstruct.to_string (Cstruct.of_bigarray t.buf ~off:t.pos ~len) in consume t len; data let take_while1 p t = let len = count_while p t in if len < 1 then Fmt.failwith "take_while1" else let data = Cstruct.to_string (Cstruct.of_bigarray t.buf ~off:t.pos ~len) in consume t len; data let skip_while p t = let rec aux i = if i < t.len then ( if p (get t i) then aux (i + 1) else consume t i ) else ( consume t t.len; ensure t 1; aux 0 ) in try aux 0 with End_of_file -> () let skip_while1 p t = let len = count_while p t in if len < 1 then Fmt.failwith "skip_while1" else consume t len let rec skip n t = if n <= t.len then ( consume t n ) else ( let n = n - t.len in consume_all t; ensure t (min n (capacity t)); skip n t ) let skip n t = if n < 0 then Fmt.invalid_arg "skip: %d is negative!" n; try skip n t with End_of_file -> consume t t.len; raise End_of_file let line t = Return the index of the first ' \n ' , reading more data as needed . let rec aux i = if i = t.len then ( ensure t (t.len + 1); aux i ) else if get t i = '\n' then ( i ) else ( aux (i + 1) ) in match aux 0 with | exception End_of_file when t.len > 0 -> take_all t | nl -> let len = if nl > 0 && get t (nl - 1) = '\r' then nl - 1 else nl in let line = Cstruct.to_string (Cstruct.of_bigarray t.buf ~off:t.pos ~len) in consume t (nl + 1); line let at_end_of_input t = if t.len = 0 && eof_seen t then true else ( match ensure t 1 with | () -> false | exception End_of_file -> true ) let end_of_input t = if not (at_end_of_input t) then failwith "Unexpected data after parsing" let pp_pos f t = Fmt.pf f "at offset %d" (consumed_bytes t) let format_errors p t = match p t with | v -> Ok v | exception Failure msg -> Fmt.error_msg "%s (%a)" msg pp_pos t | exception End_of_file -> Fmt.error_msg "Unexpected end-of-file at offset %d" (t.consumed + t.len) | exception Buffer_limit_exceeded -> Fmt.error_msg "Buffer size limit exceeded when reading %a" pp_pos t let parse ?initial_size ~max_size p flow = let buf = of_flow flow ?initial_size ~max_size in format_errors (p <* end_of_input) buf let parse_exn ?initial_size ~max_size p flow = match parse ?initial_size ~max_size p flow with | Ok x -> x | Error (`Msg m) -> failwith m let parse_string p s = format_errors (p <* end_of_input) (of_string s) let parse_string_exn p s = match parse_string p s with | Ok x -> x | Error (`Msg m) -> failwith m [@@inline never] let bad_offset ~expected actual = Fmt.invalid_arg "Sequence is stale (expected to be used at offset %d, but stream is now at %d)" expected actual let seq ?(stop=at_end_of_input) p t = let rec aux offset () = if offset <> t.consumed then bad_offset ~expected:offset t.consumed; if stop t then Seq.Nil else ( let item = p t in Seq.Cons (item, aux t.consumed) ) in aux t.consumed let lines t = seq line t
617a6239613b05e4d1f8e73f71aa3d17b2479aefa730598ac5d2c73962a42605
senapk/funcional_arcade
solver.hs
sequencia 0 x = [] sequencia n m = m:(sequencia (n-1) (m+1))
null
https://raw.githubusercontent.com/senapk/funcional_arcade/70fa04b4799d5a8c7e5add39d9f217f38f418600/base/032/solver.hs
haskell
sequencia 0 x = [] sequencia n m = m:(sequencia (n-1) (m+1))
5dc601fc897763e0163fcb76d762727e839020da539730761fbaed9b7f8c2e1d
stepcut/plugins
Plugin1.hs
module Plugin1 where import API import Data.Char resource = plugin { valueOf = map toUpper }
null
https://raw.githubusercontent.com/stepcut/plugins/52c660b5bc71182627d14c1d333d0234050cac01/testsuite/multi/3plugins/Plugin1.hs
haskell
module Plugin1 where import API import Data.Char resource = plugin { valueOf = map toUpper }
e620566ca43189a34e6367a44353e02a203287167b5780a4e4d39e3830b1e0b6
haskell-opengl/OpenGLRaw
Evaluators.hs
# LANGUAGE PatternSynonyms # -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.NV.Evaluators Copyright : ( c ) 2019 -- License : BSD3 -- Maintainer : < > -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.NV.Evaluators ( -- * Extension Support glGetNVEvaluators, gl_NV_evaluators, -- * Enums pattern GL_EVAL_2D_NV, pattern GL_EVAL_FRACTIONAL_TESSELLATION_NV, pattern GL_EVAL_TRIANGULAR_2D_NV, pattern GL_EVAL_VERTEX_ATTRIB0_NV, pattern GL_EVAL_VERTEX_ATTRIB10_NV, pattern GL_EVAL_VERTEX_ATTRIB11_NV, pattern GL_EVAL_VERTEX_ATTRIB12_NV, pattern GL_EVAL_VERTEX_ATTRIB13_NV, pattern GL_EVAL_VERTEX_ATTRIB14_NV, pattern GL_EVAL_VERTEX_ATTRIB15_NV, pattern GL_EVAL_VERTEX_ATTRIB1_NV, pattern GL_EVAL_VERTEX_ATTRIB2_NV, pattern GL_EVAL_VERTEX_ATTRIB3_NV, pattern GL_EVAL_VERTEX_ATTRIB4_NV, pattern GL_EVAL_VERTEX_ATTRIB5_NV, pattern GL_EVAL_VERTEX_ATTRIB6_NV, pattern GL_EVAL_VERTEX_ATTRIB7_NV, pattern GL_EVAL_VERTEX_ATTRIB8_NV, pattern GL_EVAL_VERTEX_ATTRIB9_NV, pattern GL_MAP_ATTRIB_U_ORDER_NV, pattern GL_MAP_ATTRIB_V_ORDER_NV, pattern GL_MAP_TESSELLATION_NV, pattern GL_MAX_MAP_TESSELLATION_NV, pattern GL_MAX_RATIONAL_EVAL_ORDER_NV, -- * Functions glEvalMapsNV, glGetMapAttribParameterfvNV, glGetMapAttribParameterivNV, glGetMapControlPointsNV, glGetMapParameterfvNV, glGetMapParameterivNV, glMapControlPointsNV, glMapParameterfvNV, glMapParameterivNV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
null
https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/NV/Evaluators.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.GL.NV.Evaluators License : BSD3 Stability : stable Portability : portable ------------------------------------------------------------------------------ * Extension Support * Enums * Functions
# LANGUAGE PatternSynonyms # Copyright : ( c ) 2019 Maintainer : < > module Graphics.GL.NV.Evaluators ( glGetNVEvaluators, gl_NV_evaluators, pattern GL_EVAL_2D_NV, pattern GL_EVAL_FRACTIONAL_TESSELLATION_NV, pattern GL_EVAL_TRIANGULAR_2D_NV, pattern GL_EVAL_VERTEX_ATTRIB0_NV, pattern GL_EVAL_VERTEX_ATTRIB10_NV, pattern GL_EVAL_VERTEX_ATTRIB11_NV, pattern GL_EVAL_VERTEX_ATTRIB12_NV, pattern GL_EVAL_VERTEX_ATTRIB13_NV, pattern GL_EVAL_VERTEX_ATTRIB14_NV, pattern GL_EVAL_VERTEX_ATTRIB15_NV, pattern GL_EVAL_VERTEX_ATTRIB1_NV, pattern GL_EVAL_VERTEX_ATTRIB2_NV, pattern GL_EVAL_VERTEX_ATTRIB3_NV, pattern GL_EVAL_VERTEX_ATTRIB4_NV, pattern GL_EVAL_VERTEX_ATTRIB5_NV, pattern GL_EVAL_VERTEX_ATTRIB6_NV, pattern GL_EVAL_VERTEX_ATTRIB7_NV, pattern GL_EVAL_VERTEX_ATTRIB8_NV, pattern GL_EVAL_VERTEX_ATTRIB9_NV, pattern GL_MAP_ATTRIB_U_ORDER_NV, pattern GL_MAP_ATTRIB_V_ORDER_NV, pattern GL_MAP_TESSELLATION_NV, pattern GL_MAX_MAP_TESSELLATION_NV, pattern GL_MAX_RATIONAL_EVAL_ORDER_NV, glEvalMapsNV, glGetMapAttribParameterfvNV, glGetMapAttribParameterivNV, glGetMapControlPointsNV, glGetMapParameterfvNV, glGetMapParameterivNV, glMapControlPointsNV, glMapParameterfvNV, glMapParameterivNV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
bbcf8b875b3deb471e7c0b11c43833a8f8413814449aaac9bb5f8bed831d2387
VitorCBSB/HetrisV2
CountingDown.hs
module CountingDown ( inputCountingDown, tickCountingDown, renderCountingDown, ) where import Constants (windowSize) import Control.Lens import qualified Data.Text as T import Game (renderGame) import InitialStates (initialPauseState) import qualified SDL import qualified SDL.Mixer as Mixer import Types import UtilsSDL (renderTextCentered) inputCountingDown :: SDL.EventPayload -> Assets -> CountingDownState -> IO MainStatePhase inputCountingDown ev gameAssets cds = case ev of SDL.KeyboardEvent evData -> if SDL.keyboardEventKeyMotion evData == SDL.Pressed && ((SDL.keysymScancode . SDL.keyboardEventKeysym) evData == SDL.ScancodeEscape || (SDL.keysymScancode . SDL.keyboardEventKeysym) evData == SDL.ScancodeF1) then do let (initPauseState, pauseSfx) = initialPauseState (gameAssets ^. soundAssets) (cds ^. gameStateToReturnTo) mapM_ applySideEffect pauseSfx return $ Paused initPauseState else return $ CountingDown cds _ -> return (CountingDown cds) tickCountingDown :: Double -> Assets -> CountingDownState -> IO MainStatePhase tickCountingDown dt assets cds = if cds ^. countdownTime >= 1.0 then if cds ^. countdown <= 1 then do applySideEffect (PlayAudio (assets ^. soundAssets . countdownGoSfx)) applySideEffect ResumeMusic return $ Game (cds ^. gameStateToReturnTo) else do applySideEffect (PlayAudio (assets ^. soundAssets . countdownSfx)) return $ CountingDown $ cds & countdown -~ 1 & countdownTime -~ 1 else return $ CountingDown $ cds & countdownTime +~ dt renderCountingDown :: SDL.Renderer -> Assets -> CountingDownState -> IO () renderCountingDown renderer assets cds = do renderGame renderer assets (cds ^. gameStateToReturnTo) (0, 0) renderTextCentered (assets ^. textAssets . font) renderer (T.pack $ show $ cds ^. countdown) (windowSize ^. _1 `div` 2, windowSize ^. _2 `div` 2)
null
https://raw.githubusercontent.com/VitorCBSB/HetrisV2/2544e8ce56a4d0daba9126642118f0504215f742/app/CountingDown.hs
haskell
module CountingDown ( inputCountingDown, tickCountingDown, renderCountingDown, ) where import Constants (windowSize) import Control.Lens import qualified Data.Text as T import Game (renderGame) import InitialStates (initialPauseState) import qualified SDL import qualified SDL.Mixer as Mixer import Types import UtilsSDL (renderTextCentered) inputCountingDown :: SDL.EventPayload -> Assets -> CountingDownState -> IO MainStatePhase inputCountingDown ev gameAssets cds = case ev of SDL.KeyboardEvent evData -> if SDL.keyboardEventKeyMotion evData == SDL.Pressed && ((SDL.keysymScancode . SDL.keyboardEventKeysym) evData == SDL.ScancodeEscape || (SDL.keysymScancode . SDL.keyboardEventKeysym) evData == SDL.ScancodeF1) then do let (initPauseState, pauseSfx) = initialPauseState (gameAssets ^. soundAssets) (cds ^. gameStateToReturnTo) mapM_ applySideEffect pauseSfx return $ Paused initPauseState else return $ CountingDown cds _ -> return (CountingDown cds) tickCountingDown :: Double -> Assets -> CountingDownState -> IO MainStatePhase tickCountingDown dt assets cds = if cds ^. countdownTime >= 1.0 then if cds ^. countdown <= 1 then do applySideEffect (PlayAudio (assets ^. soundAssets . countdownGoSfx)) applySideEffect ResumeMusic return $ Game (cds ^. gameStateToReturnTo) else do applySideEffect (PlayAudio (assets ^. soundAssets . countdownSfx)) return $ CountingDown $ cds & countdown -~ 1 & countdownTime -~ 1 else return $ CountingDown $ cds & countdownTime +~ dt renderCountingDown :: SDL.Renderer -> Assets -> CountingDownState -> IO () renderCountingDown renderer assets cds = do renderGame renderer assets (cds ^. gameStateToReturnTo) (0, 0) renderTextCentered (assets ^. textAssets . font) renderer (T.pack $ show $ cds ^. countdown) (windowSize ^. _1 `div` 2, windowSize ^. _2 `div` 2)
c75c1ed1b749909b6a85ef7616912682083827f3e25d0207b491ee8e08435ff9
harpocrates/language-rust
DiffUtils.hs
# LANGUAGE CPP # #if __GLASGOW_HASKELL__ >= 800 # OPTIONS_GHC -Wno - missing - methods # #endif module DiffUtils where import qualified Data.Aeson as Aeson import qualified Data.HashMap.Lazy as HM import qualified Data.Vector as V import qualified Data.List.NonEmpty as N import Control.Monad import Data.String import Data.ByteString.Lazy.Char8 (unpack) import Control.Exception import Data.Typeable import Data.Foldable import Data.Word (Word8) -- | This type is a straightforward hack to let me index by both 'String' and 'Int' in '(!)' below. data AesonKey = Index Int | Key String instance Num AesonKey where fromInteger = Index . fromIntegral instance IsString AesonKey where fromString = Key -- | Accessor method for JSON with helpful error messages. (!) :: Aeson.Value -> AesonKey -> Aeson.Value val@(Aeson.Object hashmap) ! Key key = case HM.lookup (fromString key) hashmap of Nothing -> error $ "No key `" ++ key ++ "' on JSON object `" ++ showAeson val ++ "'" Just v -> v val ! Key key = error $ "Cannot lookup key `" ++ key ++ "' on non-object JSON `" ++ showAeson val ++ "'" val@(Aeson.Array vect) ! Index key = case vect V.!? key of Nothing -> error $ "Index `" ++ show key ++ "' is OOB on JSON array `" ++ showAeson val ++ "'" Just v -> v val ! Index key = error $ "Cannot lookup index `" ++ show key ++ "' on non-array JSON `" ++ showAeson val ++ "'" -- | Pretty print 'Value' showAeson :: Aeson.Value -> String showAeson = unpack . Aeson.encode -- | Accessor method for JSON which fails with 'Nothing' (!?) :: Aeson.Value -> AesonKey -> Maybe Aeson.Value Aeson.Object hashmap !? Key key = HM.lookup (fromString key) hashmap Aeson.Array vect !? Index key = vect V.!? key _ !? _ = Nothing -- | This lets us do whatever we want while comparing @rustc@ with our parser type Diff = IO () -- | This data type exists only as an easy way to throw a new type of error data DiffError = DiffError String deriving (Typeable) instance Exception DiffError instance Show DiffError where show (DiffError msg) = msg -- | Class of things that can be diff-ed against their JSON debug output class Show a => Diffable a where (===) :: a -> Aeson.Value -> Diff instance Diffable a => Diffable (N.NonEmpty a) where xs === json = toList xs === json instance Diffable a => Diffable [a] where xs === json@(Aeson.Array v) = do let xs' = toList v when (length xs /= length xs') $ diff ("arrays have different lengths " ++ show (length xs) ++ " /= " ++ show (length xs')) xs json sequence_ (zipWith (===) xs xs') xs === json = diff "comparing array to non-array" xs json | Solely for an instance of [ a ] ' where the empty list = = null newtype NullList a = NullList [a] deriving (Show) instance Diffable a => Diffable (NullList a) where NullList xs === val = (if null xs then Nothing else Just xs) === val -- | a comparision to accept 'null' as 'Nothing' instance Diffable a => Diffable (Maybe a) where Just x === json = x === json Nothing === Aeson.Null = pure () n@Nothing === json = diff "expected the JSON to be null" n json instance Diffable Bool where b1 === j@(Aeson.Bool b2) | b1 == b2 = pure () | otherwise = diff "boolean values are different" b1 j b === j = diff "expected the JSON to be a boolean" b j instance Diffable Word8 where (===) = diffIntegral instance Diffable Int where (===) = diffIntegral instance Diffable Integer where (===) = diffIntegral -- | Diff something that is a number and can be shown diffIntegral :: (Show i, Integral i) => i -> Aeson.Value -> Diff diffIntegral i (Aeson.Number s) | fromIntegral i == s = pure () diffIntegral i val = diff "different integral values" i val -- | Report a difference diff :: Show a => String -> a -> Aeson.Value -> IO b diff explanation v j = throw (DiffError msg) where msg = unlines [ explanation ++ " in" , " * parsed AST" , cropped (show v) , " * dumped JSON" , cropped (unpack (Aeson.encode j)) ] cropped msg' | length msg' > 500 = take 500 msg' ++ "..." | otherwise = msg'
null
https://raw.githubusercontent.com/harpocrates/language-rust/9d509c450d009cc99f1180b3f2f30247dfb1cfce/test/rustc-tests/DiffUtils.hs
haskell
| This type is a straightforward hack to let me index by both 'String' and 'Int' in '(!)' below. | Accessor method for JSON with helpful error messages. | Pretty print 'Value' | Accessor method for JSON which fails with 'Nothing' | This lets us do whatever we want while comparing @rustc@ with our parser | This data type exists only as an easy way to throw a new type of error | Class of things that can be diff-ed against their JSON debug output | a comparision to accept 'null' as 'Nothing' | Diff something that is a number and can be shown | Report a difference
# LANGUAGE CPP # #if __GLASGOW_HASKELL__ >= 800 # OPTIONS_GHC -Wno - missing - methods # #endif module DiffUtils where import qualified Data.Aeson as Aeson import qualified Data.HashMap.Lazy as HM import qualified Data.Vector as V import qualified Data.List.NonEmpty as N import Control.Monad import Data.String import Data.ByteString.Lazy.Char8 (unpack) import Control.Exception import Data.Typeable import Data.Foldable import Data.Word (Word8) data AesonKey = Index Int | Key String instance Num AesonKey where fromInteger = Index . fromIntegral instance IsString AesonKey where fromString = Key (!) :: Aeson.Value -> AesonKey -> Aeson.Value val@(Aeson.Object hashmap) ! Key key = case HM.lookup (fromString key) hashmap of Nothing -> error $ "No key `" ++ key ++ "' on JSON object `" ++ showAeson val ++ "'" Just v -> v val ! Key key = error $ "Cannot lookup key `" ++ key ++ "' on non-object JSON `" ++ showAeson val ++ "'" val@(Aeson.Array vect) ! Index key = case vect V.!? key of Nothing -> error $ "Index `" ++ show key ++ "' is OOB on JSON array `" ++ showAeson val ++ "'" Just v -> v val ! Index key = error $ "Cannot lookup index `" ++ show key ++ "' on non-array JSON `" ++ showAeson val ++ "'" showAeson :: Aeson.Value -> String showAeson = unpack . Aeson.encode (!?) :: Aeson.Value -> AesonKey -> Maybe Aeson.Value Aeson.Object hashmap !? Key key = HM.lookup (fromString key) hashmap Aeson.Array vect !? Index key = vect V.!? key _ !? _ = Nothing type Diff = IO () data DiffError = DiffError String deriving (Typeable) instance Exception DiffError instance Show DiffError where show (DiffError msg) = msg class Show a => Diffable a where (===) :: a -> Aeson.Value -> Diff instance Diffable a => Diffable (N.NonEmpty a) where xs === json = toList xs === json instance Diffable a => Diffable [a] where xs === json@(Aeson.Array v) = do let xs' = toList v when (length xs /= length xs') $ diff ("arrays have different lengths " ++ show (length xs) ++ " /= " ++ show (length xs')) xs json sequence_ (zipWith (===) xs xs') xs === json = diff "comparing array to non-array" xs json | Solely for an instance of [ a ] ' where the empty list = = null newtype NullList a = NullList [a] deriving (Show) instance Diffable a => Diffable (NullList a) where NullList xs === val = (if null xs then Nothing else Just xs) === val instance Diffable a => Diffable (Maybe a) where Just x === json = x === json Nothing === Aeson.Null = pure () n@Nothing === json = diff "expected the JSON to be null" n json instance Diffable Bool where b1 === j@(Aeson.Bool b2) | b1 == b2 = pure () | otherwise = diff "boolean values are different" b1 j b === j = diff "expected the JSON to be a boolean" b j instance Diffable Word8 where (===) = diffIntegral instance Diffable Int where (===) = diffIntegral instance Diffable Integer where (===) = diffIntegral diffIntegral :: (Show i, Integral i) => i -> Aeson.Value -> Diff diffIntegral i (Aeson.Number s) | fromIntegral i == s = pure () diffIntegral i val = diff "different integral values" i val diff :: Show a => String -> a -> Aeson.Value -> IO b diff explanation v j = throw (DiffError msg) where msg = unlines [ explanation ++ " in" , " * parsed AST" , cropped (show v) , " * dumped JSON" , cropped (unpack (Aeson.encode j)) ] cropped msg' | length msg' > 500 = take 500 msg' ++ "..." | otherwise = msg'
be7695ef01f4fd8339b920b77a32cb57d6b83f45cf00529e680a327a9dc0a302
matthiasn/systems-toolbox
index.clj
(ns example.index (:require [hiccup.core :refer [html]])) (defn index-page "Generates index page HTML with the specified page title." [dev?] (html [:html {:lang "en"} [:head [:meta {:name "viewport" :content "width=device-width, minimum-scale=1.0"}] [:title "Systems-Toolbox: Trailing Mouse Pointer Example"] [:link {:href "/css/tufte-css/tufte.css" :media "screen" :rel "stylesheet"}] [:link {:href "/css/example.css" :media "screen" :rel "stylesheet"}] [:link {:href "/images/favicon.png" :rel "shortcut icon" :type "image/png"}]] [:body [:div#ui] [:div#jvm-stats-frame] [:script {:src "/js/build/example.js"}] Google Analytics for tracking demo page [:script {:async "" :src "-analytics.com/analytics.js"}] [:script (str "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), a.async=1;a.src = g;m.parentNode.insertBefore(a , m ) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-40261983-6', 'auto'); ga('send', 'pageview');")]]])) (def sente-map "Configuration map for sente-cmp." {:index-page-fn index-page :port 8763 :relay-types #{:mouse/pos :mouse/hist}})
null
https://raw.githubusercontent.com/matthiasn/systems-toolbox/6bcc44af449b4a5d4e9128cd0f2129b58619a5dc/examples/trailing-mouse-pointer/src/clj/example/index.clj
clojure
i[r]=i[r]||function(){ a=s.createElement(o), a.src = g;m.parentNode.insertBefore(a , m ) ga('send', 'pageview');")]]]))
(ns example.index (:require [hiccup.core :refer [html]])) (defn index-page "Generates index page HTML with the specified page title." [dev?] (html [:html {:lang "en"} [:head [:meta {:name "viewport" :content "width=device-width, minimum-scale=1.0"}] [:title "Systems-Toolbox: Trailing Mouse Pointer Example"] [:link {:href "/css/tufte-css/tufte.css" :media "screen" :rel "stylesheet"}] [:link {:href "/css/example.css" :media "screen" :rel "stylesheet"}] [:link {:href "/images/favicon.png" :rel "shortcut icon" :type "image/png"}]] [:body [:div#ui] [:div#jvm-stats-frame] [:script {:src "/js/build/example.js"}] Google Analytics for tracking demo page [:script {:async "" :src "-analytics.com/analytics.js"}] (def sente-map "Configuration map for sente-cmp." {:index-page-fn index-page :port 8763 :relay-types #{:mouse/pos :mouse/hist}})
ae2da6ac1ccd33d000550125595883f566e08690bae7bf6dbb3e2cf97aef20b7
jqueiroz/lojban.io
Translations.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TemplateHaskell # -- | This module defines translations for the course. module Study.Courses.English.Vocabulary.Brivla.Translations where import Core import Study.Framework.Lojban.TranslationLoaders (loadTranslationsByExpressionFromYamlCode) import Data.FileEmbed (embedStringFile) -- | Translations for the corresponding lesson. translationsByExpression01 :: TranslationsByExpression translationsByExpression01 = loadTranslationsByExpressionFromYamlCode $(embedStringFile "resources/decks/english/brivla/sentences/01.yaml") -- | Translations for the corresponding lesson. translationsByExpression02 :: TranslationsByExpression translationsByExpression02 = loadTranslationsByExpressionFromYamlCode $(embedStringFile "resources/decks/english/brivla/sentences/02.yaml") -- | Translations for the corresponding lesson. translationsByExpression03 :: TranslationsByExpression translationsByExpression03 = loadTranslationsByExpressionFromYamlCode $(embedStringFile "resources/decks/english/brivla/sentences/03.yaml") -- | Translations for the corresponding lesson. translationsByExpression04 :: TranslationsByExpression translationsByExpression04 = loadTranslationsByExpressionFromYamlCode $(embedStringFile "resources/decks/english/brivla/sentences/04.yaml") -- | Translations for the corresponding lesson. translationsByExpression05 :: TranslationsByExpression translationsByExpression05 = loadTranslationsByExpressionFromYamlCode $(embedStringFile "resources/decks/english/brivla/sentences/05.yaml") -- | All translations. translationsByExpression :: TranslationsByExpression translationsByExpression = mconcat [translationsByExpression01, translationsByExpression02, translationsByExpression03, translationsByExpression04, translationsByExpression05]
null
https://raw.githubusercontent.com/jqueiroz/lojban.io/68c3e919f92ea1294f32ee7772662ab5667ecef6/haskell/src/Study/Courses/English/Vocabulary/Brivla/Translations.hs
haskell
# LANGUAGE OverloadedStrings # | This module defines translations for the course. | Translations for the corresponding lesson. | Translations for the corresponding lesson. | Translations for the corresponding lesson. | Translations for the corresponding lesson. | Translations for the corresponding lesson. | All translations.
# LANGUAGE TemplateHaskell # module Study.Courses.English.Vocabulary.Brivla.Translations where import Core import Study.Framework.Lojban.TranslationLoaders (loadTranslationsByExpressionFromYamlCode) import Data.FileEmbed (embedStringFile) translationsByExpression01 :: TranslationsByExpression translationsByExpression01 = loadTranslationsByExpressionFromYamlCode $(embedStringFile "resources/decks/english/brivla/sentences/01.yaml") translationsByExpression02 :: TranslationsByExpression translationsByExpression02 = loadTranslationsByExpressionFromYamlCode $(embedStringFile "resources/decks/english/brivla/sentences/02.yaml") translationsByExpression03 :: TranslationsByExpression translationsByExpression03 = loadTranslationsByExpressionFromYamlCode $(embedStringFile "resources/decks/english/brivla/sentences/03.yaml") translationsByExpression04 :: TranslationsByExpression translationsByExpression04 = loadTranslationsByExpressionFromYamlCode $(embedStringFile "resources/decks/english/brivla/sentences/04.yaml") translationsByExpression05 :: TranslationsByExpression translationsByExpression05 = loadTranslationsByExpressionFromYamlCode $(embedStringFile "resources/decks/english/brivla/sentences/05.yaml") translationsByExpression :: TranslationsByExpression translationsByExpression = mconcat [translationsByExpression01, translationsByExpression02, translationsByExpression03, translationsByExpression04, translationsByExpression05]
fe6b108b99dec7e1c336eb1ed820bd8ce8e835cf1fb611200f3bf5917804ad2e
uzh/ask
model.mli
module AnswerInput : sig type uuid = string option type filename = string type size = int type mime_type = string type data = string type text_answer = string type asset_answer = uuid * filename * size * mime_type * data type t = | Text of text_answer | Asset of asset_answer val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or val pp : Format.formatter -> t -> unit val show : t -> string val text : t -> string val mime_to_ext : string -> string val equal : t -> t -> bool end module Event : sig type questionnaire_id = string type question_id = string type t = | TextAnswerCreated of questionnaire_id * question_id * AnswerInput.text_answer | TextAnswerUpdated of questionnaire_id * question_id * AnswerInput.text_answer | AssetAnswerCreated of questionnaire_id * question_id * AnswerInput.asset_answer | AssetAnswerUpdated of questionnaire_id * question_id * AnswerInput.asset_answer | AssetAnswerDelete of questionnaire_id * question_id val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or val pp : Format.formatter -> t -> unit val equal : t -> t -> bool val show : t -> string end module Question : sig type required = bool type label = string option type help_text = string option type text = string type id = string type regex = string type possible_options = string list type mime_types = string list type max_file_size = int type t = | Text of id * label * help_text * text * string option * regex * required | Country of id * label * help_text * text * required | Select of id * label * help_text * text * possible_options * required | YesNo of id * label * help_text * text * required | Date of id * label * help_text * text * required | File of id * label * help_text * text * mime_types * max_file_size * required | Year of id * label * help_text * text * required val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or val pp : Format.formatter -> t -> unit val equal : t -> t -> bool val show : t -> string val uuid : t -> string val label : t -> string val help_text : t -> string option val text : t -> string val is_file : t -> bool val is_required : t -> bool val set_optional : t -> t val is_valid : t -> AnswerInput.t -> bool val validate : t -> AnswerInput.t option -> (unit, string) Result.t end module QuestionAnswer : sig type t = Question.t * AnswerInput.t option val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or val pp : Format.formatter -> t -> unit val equal : t -> t -> bool val show : t -> string val can_questions_answered_get_submitted : t list -> bool val filter_asset_out : t list -> t list val update : (Question.t * AnswerInput.t) list -> Question.t -> AnswerInput.t -> (Question.t * AnswerInput.t) list val event : string -> t -> t -> Event.t option end module Questionnaire : sig type t val questions : t -> QuestionAnswer.t list val description : t -> string val label : t -> string val template_uuid : t -> string val uuid : t -> string val set_questions : QuestionAnswer.t list -> t -> t val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or val pp : Format.formatter -> t -> unit val show : t -> string val equal : t -> t -> bool val make : uuid:string -> template_uuid:string -> label:string -> description:string -> ?questions:QuestionAnswer.t list -> unit -> t val is_ready_for_submission : t -> bool val set_question_to_optional : Question.t * 'a -> Question.t * 'a val set_question_with_id_to_optional : question_id:string -> questions:(Question.t * 'a) list -> (Question.t * 'a) list val set_all_questions_to_optional : t -> t val answer : t -> QuestionAnswer.t list -> (Event.t list, string list) Result.t end
null
https://raw.githubusercontent.com/uzh/ask/5ba939c7ccbe20251b26f8d691635d94e65e518f/ask/src/model/model.mli
ocaml
module AnswerInput : sig type uuid = string option type filename = string type size = int type mime_type = string type data = string type text_answer = string type asset_answer = uuid * filename * size * mime_type * data type t = | Text of text_answer | Asset of asset_answer val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or val pp : Format.formatter -> t -> unit val show : t -> string val text : t -> string val mime_to_ext : string -> string val equal : t -> t -> bool end module Event : sig type questionnaire_id = string type question_id = string type t = | TextAnswerCreated of questionnaire_id * question_id * AnswerInput.text_answer | TextAnswerUpdated of questionnaire_id * question_id * AnswerInput.text_answer | AssetAnswerCreated of questionnaire_id * question_id * AnswerInput.asset_answer | AssetAnswerUpdated of questionnaire_id * question_id * AnswerInput.asset_answer | AssetAnswerDelete of questionnaire_id * question_id val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or val pp : Format.formatter -> t -> unit val equal : t -> t -> bool val show : t -> string end module Question : sig type required = bool type label = string option type help_text = string option type text = string type id = string type regex = string type possible_options = string list type mime_types = string list type max_file_size = int type t = | Text of id * label * help_text * text * string option * regex * required | Country of id * label * help_text * text * required | Select of id * label * help_text * text * possible_options * required | YesNo of id * label * help_text * text * required | Date of id * label * help_text * text * required | File of id * label * help_text * text * mime_types * max_file_size * required | Year of id * label * help_text * text * required val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or val pp : Format.formatter -> t -> unit val equal : t -> t -> bool val show : t -> string val uuid : t -> string val label : t -> string val help_text : t -> string option val text : t -> string val is_file : t -> bool val is_required : t -> bool val set_optional : t -> t val is_valid : t -> AnswerInput.t -> bool val validate : t -> AnswerInput.t option -> (unit, string) Result.t end module QuestionAnswer : sig type t = Question.t * AnswerInput.t option val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or val pp : Format.formatter -> t -> unit val equal : t -> t -> bool val show : t -> string val can_questions_answered_get_submitted : t list -> bool val filter_asset_out : t list -> t list val update : (Question.t * AnswerInput.t) list -> Question.t -> AnswerInput.t -> (Question.t * AnswerInput.t) list val event : string -> t -> t -> Event.t option end module Questionnaire : sig type t val questions : t -> QuestionAnswer.t list val description : t -> string val label : t -> string val template_uuid : t -> string val uuid : t -> string val set_questions : QuestionAnswer.t list -> t -> t val to_yojson : t -> Yojson.Safe.t val of_yojson : Yojson.Safe.t -> t Ppx_deriving_yojson_runtime.error_or val pp : Format.formatter -> t -> unit val show : t -> string val equal : t -> t -> bool val make : uuid:string -> template_uuid:string -> label:string -> description:string -> ?questions:QuestionAnswer.t list -> unit -> t val is_ready_for_submission : t -> bool val set_question_to_optional : Question.t * 'a -> Question.t * 'a val set_question_with_id_to_optional : question_id:string -> questions:(Question.t * 'a) list -> (Question.t * 'a) list val set_all_questions_to_optional : t -> t val answer : t -> QuestionAnswer.t list -> (Event.t list, string list) Result.t end
fdb8af4c5da5c423abc9969f55294d2226a2cbe5dc25d47691119542e0ca1aa4
anoma/juvix
Positive.hs
module Reachability.Positive where import Base import Data.HashSet qualified as HashSet import Juvix.Compiler.Builtins (iniState) import Juvix.Compiler.Internal.Language qualified as Internal import Juvix.Compiler.Internal.Translation.FromInternal.Analysis.TypeChecking.Data.Context qualified as Internal import Juvix.Compiler.Pipeline data PosTest = PosTest { _name :: String, _relDir :: Path Rel Dir, _stdlibMode :: StdlibMode, _file :: Path Rel File, _reachable :: HashSet String } makeLenses ''PosTest root :: Path Abs Dir root = relToProject $(mkRelDir "tests/positive") testDescr :: PosTest -> TestDescr testDescr PosTest {..} = let tRoot = root <//> _relDir file' = tRoot <//> _file in TestDescr { _testName = _name, _testRoot = tRoot, _testAssertion = Steps $ \step -> do let noStdlib = _stdlibMode == StdlibExclude entryPoint = (defaultEntryPoint tRoot file') { _entryPointRoot = tRoot, _entryPointNoStdlib = noStdlib } step "Pipeline up to reachability" p :: Internal.InternalTypedResult <- snd <$> runIO' iniState entryPoint upToInternalReachability step "Check reachability results" let names = concatMap getNames (p ^. Internal.resultModules) mapM_ check names } where check n = assertBool ("unreachable not filtered: " ++ unpack n) (HashSet.member (unpack n) _reachable) getNames :: Internal.Module -> [Text] getNames m = concatMap getDeclName (m ^. (Internal.moduleBody . Internal.moduleStatements)) where getDeclName :: Internal.Statement -> [Text] getDeclName = \case Internal.StatementInductive i -> [i ^. (Internal.inductiveName . Internal.nameText)] Internal.StatementFunction (Internal.MutualBlock f) -> map (^. Internal.funDefName . Internal.nameText) (toList f) Internal.StatementForeign {} -> [] Internal.StatementAxiom ax -> [ax ^. (Internal.axiomName . Internal.nameText)] Internal.StatementInclude i -> getNames (i ^. Internal.includeModule) allTests :: TestTree allTests = testGroup "Reachability positive tests" (map (mkTest . testDescr) tests) tests :: [PosTest] tests = [ PosTest "Reachability with modules" $(mkRelDir "Reachability") StdlibInclude $(mkRelFile "M.juvix") ( HashSet.fromList ["f", "g", "h", "Bool", "Maybe"] ), PosTest "Reachability with modules and standard library" $(mkRelDir "Reachability") StdlibInclude $(mkRelFile "N.juvix") ( HashSet.fromList ["test", "Unit", "Bool", "Nat"] ), PosTest "Reachability with public imports" $(mkRelDir "Reachability") StdlibInclude $(mkRelFile "O.juvix") ( HashSet.fromList ["f", "g", "h", "k", "Bool", "Maybe", "Nat"] ) ]
null
https://raw.githubusercontent.com/anoma/juvix/5ab9969a9587798a0094d2d575d083e3aef6e612/test/Reachability/Positive.hs
haskell
module Reachability.Positive where import Base import Data.HashSet qualified as HashSet import Juvix.Compiler.Builtins (iniState) import Juvix.Compiler.Internal.Language qualified as Internal import Juvix.Compiler.Internal.Translation.FromInternal.Analysis.TypeChecking.Data.Context qualified as Internal import Juvix.Compiler.Pipeline data PosTest = PosTest { _name :: String, _relDir :: Path Rel Dir, _stdlibMode :: StdlibMode, _file :: Path Rel File, _reachable :: HashSet String } makeLenses ''PosTest root :: Path Abs Dir root = relToProject $(mkRelDir "tests/positive") testDescr :: PosTest -> TestDescr testDescr PosTest {..} = let tRoot = root <//> _relDir file' = tRoot <//> _file in TestDescr { _testName = _name, _testRoot = tRoot, _testAssertion = Steps $ \step -> do let noStdlib = _stdlibMode == StdlibExclude entryPoint = (defaultEntryPoint tRoot file') { _entryPointRoot = tRoot, _entryPointNoStdlib = noStdlib } step "Pipeline up to reachability" p :: Internal.InternalTypedResult <- snd <$> runIO' iniState entryPoint upToInternalReachability step "Check reachability results" let names = concatMap getNames (p ^. Internal.resultModules) mapM_ check names } where check n = assertBool ("unreachable not filtered: " ++ unpack n) (HashSet.member (unpack n) _reachable) getNames :: Internal.Module -> [Text] getNames m = concatMap getDeclName (m ^. (Internal.moduleBody . Internal.moduleStatements)) where getDeclName :: Internal.Statement -> [Text] getDeclName = \case Internal.StatementInductive i -> [i ^. (Internal.inductiveName . Internal.nameText)] Internal.StatementFunction (Internal.MutualBlock f) -> map (^. Internal.funDefName . Internal.nameText) (toList f) Internal.StatementForeign {} -> [] Internal.StatementAxiom ax -> [ax ^. (Internal.axiomName . Internal.nameText)] Internal.StatementInclude i -> getNames (i ^. Internal.includeModule) allTests :: TestTree allTests = testGroup "Reachability positive tests" (map (mkTest . testDescr) tests) tests :: [PosTest] tests = [ PosTest "Reachability with modules" $(mkRelDir "Reachability") StdlibInclude $(mkRelFile "M.juvix") ( HashSet.fromList ["f", "g", "h", "Bool", "Maybe"] ), PosTest "Reachability with modules and standard library" $(mkRelDir "Reachability") StdlibInclude $(mkRelFile "N.juvix") ( HashSet.fromList ["test", "Unit", "Bool", "Nat"] ), PosTest "Reachability with public imports" $(mkRelDir "Reachability") StdlibInclude $(mkRelFile "O.juvix") ( HashSet.fromList ["f", "g", "h", "k", "Bool", "Maybe", "Nat"] ) ]
7f45f9e8da50ede5edf0c04b59e462dacb1d07339aabc8b89993f50e80f71cf9
manuel-serrano/bigloo
des.scm
(module __crypto-des (import __crypto-util __crypto-block-ciphers) (static (final-class DES-Param (buff32a::bstring read-only) (buff32b::bstring read-only) (buff64::bstring read-only) (keys::bstring read-only) (initial-permutation?::bool read-only)) (final-class DES3-Param (buff32a::bstring read-only) (buff32b::bstring read-only) (buff64::bstring read-only) (keys1::bstring read-only) (keys2::bstring read-only) (keys3::bstring read-only) (initial-permutation?::bool read-only)))) (define *des-rounds* 16) (define *block-size* 64) (define *key-size* 56) ;; real key-size (define (DES-key->param key encrypt? initial-permutation?) (let ((key-len (*fx 8 (string-length key)))) (when (not (or (=fx key-len 56) (=fx key-len 64))) (error 'des "Key-length must be 56 or 64 bits" key-len)) (let* ((buff32a (make-des-buffer 32)) (buff32b (make-des-buffer 32)) (buff64 (make-des-buffer 64)) (expanded-keys (key-expansion key 0 key-len encrypt?))) (instantiate::DES-Param (buff32a buff32a) (buff32b buff32b) (buff64 buff64) (keys expanded-keys) (initial-permutation? initial-permutation?))))) (define (DES-key->encrypt-param key) (DES-key->param key #t #t)) (define (DES-key->encrypt-param-no-permutation key) (DES-key->param key #t #f)) (define (DES-key->decrypt-param key) (DES-key->param key #f #t)) (define (DES-key->decrypt-param-no-permutation key) (DES-key->param key #f #f)) (register-cipher! 'des (instantiate::Block-Cipher (name "DES (Data Encryption Standard)") (block-size (/fx *block-size* 8)) (preferred-key-length 7) (encrypt! en/decrypt-DES) (decrypt! en/decrypt-DES) (key->encrypt-param DES-key->encrypt-param) (key->decrypt-param DES-key->decrypt-param))) (register-cipher! 'des-np (instantiate::Block-Cipher (name "DES (Data Encryption Standard). No initial Permutation") (block-size (/fx *block-size* 8)) (preferred-key-length 7) (encrypt! en/decrypt-DES) (decrypt! en/decrypt-DES) (key->encrypt-param DES-key->encrypt-param-no-permutation) (key->decrypt-param DES-key->decrypt-param-no-permutation))) (define (DES3-key->param key encrypt? initial-permutation?) (let* ((key-len (*fx 8 (string-length key))) (nb-keys (if (<=fx key-len 128) 2 3)) (subkey-len (/fx key-len nb-keys))) (when (not (or (=fx key-len 112) (=fx key-len 128) (=fx key-len 168) (=fx key-len 192))) (error 'des "Key-length must be 112/128 or 168/192 bits" key-len)) (let* ((buff32a (make-des-buffer 32)) (buff32b (make-des-buffer 32)) (buff64 (make-des-buffer 64))) (if encrypt? (let* ((keys1 (key-expansion key 0 subkey-len #t)) (keys2 (key-expansion key subkey-len subkey-len #f)) (keys3 (if (=fx nb-keys 3) (key-expansion key (*fx 2 subkey-len) subkey-len #t) keys1))) (instantiate::DES3-Param (buff32a buff32a) (buff32b buff32b) (buff64 buff64) (keys1 keys1) (keys2 keys2) (keys3 keys3) (initial-permutation? initial-permutation?))) (let* ((keys3-inv (key-expansion key 0 subkey-len #f)) (keys2-inv (key-expansion key subkey-len subkey-len #t)) (keys1-inv (if (=fx nb-keys 3) (key-expansion key (*fx 2 subkey-len) subkey-len #f) keys3-inv))) (instantiate::DES3-Param (buff32a buff32a) (buff32b buff32b) (buff64 buff64) (keys1 keys1-inv) (keys2 keys2-inv) (keys3 keys3-inv) (initial-permutation? initial-permutation?))))))) (define (DES3-key->encrypt-param key) (DES3-key->param key #t #t)) (define (DES3-key->encrypt-param-no-permutation key) (DES3-key->param key #t #f)) (define (DES3-key->decrypt-param key) (DES3-key->param key #f #t)) (define (DES3-key->decrypt-param-no-permutation key) (DES3-key->param key #f #f)) (register-cipher! 'des3 (instantiate::Block-Cipher (name "Triple DES, Triple Data Encryption Algorithm (DES3, TDEA)") (block-size (/fx *block-size* 8)) (preferred-key-length 14) (encrypt! en/decrypt-DES3) (decrypt! en/decrypt-DES3) (key->encrypt-param DES3-key->encrypt-param) (key->decrypt-param DES3-key->decrypt-param))) (register-cipher! 'des3-np (instantiate::Block-Cipher (name "Triple DES, Triple Data Encryption Algorithm (DES3, TDEA). No initial Permutation.") (block-size (/fx *block-size* 8)) (preferred-key-length 14) (encrypt! en/decrypt-DES3) (decrypt! en/decrypt-DES3) (key->encrypt-param DES3-key->encrypt-param-no-permutation) (key->decrypt-param DES3-key->decrypt-param-no-permutation))) ;; --- byte oriented: each byte represents a bit. -> faster... (define (bit-ref str::bstring i) (char->integer (string-ref str i))) (define (bit-set! str::bstring i val) (string-set! str i (integer->char-ur val))) (define (make-des-buffer size) (make-string size #a000)) (define des-buffer-blit! blit-string!) (define (tt b from len sp) (with-output-to-string (lambda () (display-des-buffer b from len sp)))) (define (display-des-buffer buff from len sp) (let loop ((i 0)) (unless (=fx i len) (when (zerofx? (remainderfx i sp)) (display " " )) (display (bit-ref buff (+fx from i))) (loop (+fx i 1))))) ;; len in bits. (define (des-buffer-xor! target target-pos buffer buf-pos len) (let loop ((i 0)) (unless (=fx i len) (string-set! target (+fx target-pos i) (char-xor (string-ref target (+fx target-pos i)) (string-ref buffer (+fx buf-pos i)))) (loop (+fx i 1))))) (define (copy-bits->des-buffer from::bstring from-pos-bits::long to::bstring to-pos::long nb-bits::long) (let ((nb-bytes (/fx nb-bits 8)) (from-pos (/fx from-pos-bits 8))) ;; from is native bits ;; to is our byte-oriented representation. (let loop ((i 0)) (unless (=fx i nb-bytes) (let liip ((j 0) (ci (char->integer (string-ref from (+fx from-pos i))))) (unless (=fx j 8) (bit-set! to (+fx to-pos (+fx (*fx i 8) j)) (bit-and #x01 (bit-rsh ci 7))) (liip (+fx j 1) (bit-lsh ci 1)))) (loop (+fx i 1)))))) (define (copy-des-buffer->bits from::bstring from-pos::long to::bstring to-pos-bits::long nb-bits::long table) (let ((nb-bytes (/fx nb-bits 8)) (to-pos (/fx to-pos-bits 8))) ;; from is our byte-oriented representation. ;; to is native bits (let loop ((i 0)) (unless (=fx i nb-bytes) (let liip ((j 0) (ci 0)) (if (=fx j 8) (string-set! to (+fx to-pos i) (integer->char ci)) (liip (+fx j 1) (+fx (*fx ci 2) (bit-ref from (+fx from-pos (table-ref table (+fx (*fx i 8) j)))))))) (loop (+fx i 1)))))) (define (permutation-copy source source-pos target target-pos table) (let loop ((i 0)) (unless (=fx i (table-length table)) (bit-set! target (+fx target-pos i) (bit-ref source (+fx source-pos (table-ref table i)))) (loop (+fx i 1))))) ;; ------ bit-oriented ( define ( octet - set ! str i ) ( string - set ! str i ( ) ) ) ; (define (octet-ref str i) (char->integer (string-ref str i))) ; (define (permutation-copy source target table) ; (let loop ((i 0)) ; (unless (=fx i (/fx (table-length table) 8)) ; (let liip ((j 0) ; (ci 0)) ; (cond ; ((=fx j 8) ; (octet-set! target i ci)) ; (else ; (loop (+fx j 1) ( + fx ( * fx ci 2 ) ; (bit-ref source (table-ref table (+fx (*fx i 8) j)))))))) ; (loop (+fx i 1))))) Note : most tables are taken from wikipedia . The start numbering the bits with 1 . (define-macro (make-table t) (apply string (map (lambda (i) (integer->char-ur (-fx i 1))) ;; t is of form (quote (i0 i1 ...)) (cadr t)))) (define (table-length table) (string-length table)) (define (table-ref t i) (char->integer (string-ref t i))) ;; initial permutation first bit of output is taken from 58 . bit of input . Note : everything starts with 1 . However tables are automatically converted ;; so they start with 0. (make-table macro). (define *IP-L* (make-table '(58 50 42 34 26 18 10 2 60 52 44 36 28 20 12 4 62 54 46 38 30 22 14 6 64 56 48 40 32 24 16 8))) (define *IP-R* (make-table '(57 49 41 33 25 17 9 1 59 51 43 35 27 19 11 3 61 53 45 37 29 21 13 5 63 55 47 39 31 23 15 7))) (define-macro (make-identity-table nb) (apply string (map integer->char (iota nb)))) (define *IP-id* (make-identity-table 32)) ;; inversio of initial permutation. Note : everything starts with 1 . However tables are automatically converted ;; so they start with 0. (make-table macro). (define *IP-1* (make-table '(40 8 48 16 56 24 64 32 39 7 47 15 55 23 63 31 38 6 46 14 54 22 62 30 37 5 45 13 53 21 61 29 36 4 44 12 52 20 60 28 35 3 43 11 51 19 59 27 34 2 42 10 50 18 58 26 33 1 41 9 49 17 57 25))) ;; expansion function Note : everything starts with 1 . However tables are automatically converted ;; so they start with 0. (make-table macro). (define *E* (make-table '(32 1 2 3 4 5 4 5 6 7 8 9 8 9 10 11 12 13 12 13 14 15 16 17 16 17 18 19 20 21 20 21 22 23 24 25 24 25 26 27 28 29 28 29 30 31 32 1))) Note : everything starts with 1 . However tables are automatically converted ;; so they start with 0. (make-table macro). (define *P* (make-table '(16 7 20 21 29 12 28 17 1 15 23 26 5 18 31 10 2 8 24 14 32 27 3 9 19 13 30 6 22 11 4 25))) Note : everything starts with 1 . However tables are automatically converted ;; so they start with 0. (make-table macro). (define *PC1* (make-table '(;; L 57 49 41 33 25 17 9 1 58 50 42 34 26 18 10 2 59 51 43 35 27 19 11 3 60 52 44 36 ;; R 63 55 47 39 31 23 15 7 62 54 46 38 30 22 14 6 61 53 45 37 29 21 13 5 28 20 12 4))) PC1 - 56 is used when the password comes as 56bit string . (define *PC1-56* (make-table '(;; L 50 43 36 29 22 15 8 1 51 44 37 30 23 16 9 2 52 45 38 31 24 17 10 3 53 46 39 32 ;; R 56 49 42 35 28 21 14 7 55 48 41 34 27 20 13 6 54 47 40 33 26 19 12 5 25 18 11 4))) Note : everything starts with 1 . However tables are automatically converted ;; so they start with 0. (make-table macro). (define *PC2* (make-table '(14 17 11 24 1 5 3 28 15 6 21 10 23 19 12 4 26 8 16 7 27 20 13 2 41 52 31 37 47 55 30 40 51 45 33 48 44 49 39 56 34 53 46 42 50 36 29 32))) (define-macro (create-s-boxes . s-boxes) ;; s-boxes (as given here) are indexed as follows: ;; x0000x, x0001x, .... x1111x 0yyyy0 14 4 ... 0yyyy1 0 15 ... 1yyyy0 4 1 ... 1yyyy1 15 12 ... ;; ;; However we want to be able to index directly into the vector using xyyyyx - > rearrange . (define (rearrange v) (let ((res (make-vector 64))) (let loop ((i 0)) (cond ((=fx i 64) res) (else (let ((index (+ (bit-and #x0F (bit-rsh i 1)) (bit-and #x20 i) (bit-lsh (bit-and i 1) 4)))) (vector-set! res i (vector-ref v index))) (loop (+fx i 1))))))) (define (list->strings l) (apply string (map integer->char-ur l))) (let* ((boxes1 (map (lambda (box) box is of form ( quote ( 14 4 ... ) ) (rearrange (list->vector (cadr box)))) s-boxes)) (boxes2 (map vector->list boxes1)) (boxes3 (map list->strings boxes2))) (list 'quote (list->vector boxes3)))) (define *s-boxes* (create-s-boxes '(14 4 13 1 2 15 11 8 3 10 6 12 5 9 0 7 0 15 7 4 14 2 13 1 10 6 12 11 9 5 3 8 4 1 14 8 13 6 2 11 15 12 9 7 3 10 5 0 15 12 8 2 4 9 1 7 5 11 3 14 10 0 6 13) '(15 1 8 14 6 11 3 4 9 7 2 13 12 0 5 10 3 13 4 7 15 2 8 14 12 0 1 10 6 9 11 5 0 14 7 11 10 4 13 1 5 8 12 6 9 3 2 15 13 8 10 1 3 15 4 2 11 6 7 12 0 5 14 9) '(10 0 9 14 6 3 15 5 1 13 12 7 11 4 2 8 13 7 0 9 3 4 6 10 2 8 5 14 12 11 15 1 13 6 4 9 8 15 3 0 11 1 2 12 5 10 14 7 1 10 13 0 6 9 8 7 4 15 14 3 11 5 2 12) '(7 13 14 3 0 6 9 10 1 2 8 5 11 12 4 15 13 8 11 5 6 15 0 3 4 7 2 12 1 10 14 9 10 6 9 0 12 11 7 13 15 1 3 14 5 2 8 4 3 15 0 6 10 1 13 8 9 4 5 11 12 7 2 14) '(2 12 4 1 7 10 11 6 8 5 3 15 13 0 14 9 14 11 2 12 4 7 13 1 5 0 15 10 3 9 8 6 4 2 1 11 10 13 7 8 15 9 12 5 6 3 0 14 11 8 12 7 1 14 2 13 6 15 0 9 10 4 5 3) '(12 1 10 15 9 2 6 8 0 13 3 4 14 7 5 11 10 15 4 2 7 12 9 5 6 1 13 14 0 11 3 8 9 14 15 5 2 8 12 3 7 0 4 10 1 13 11 6 4 3 2 12 9 5 15 10 11 14 1 7 6 0 8 13) '(4 11 2 14 15 0 8 13 3 12 9 7 5 10 6 1 13 0 11 7 4 9 1 10 14 3 5 12 2 15 8 6 1 4 11 13 12 3 7 14 10 15 6 8 0 5 9 2 6 11 13 8 1 4 10 7 9 5 0 15 14 2 3 12) '(13 2 8 4 6 15 11 1 10 9 3 14 5 0 12 7 1 15 13 8 10 3 7 4 12 5 6 11 0 14 9 2 7 11 4 1 9 12 14 2 0 6 10 13 15 3 5 8 2 1 14 7 4 10 8 13 15 12 9 0 3 5 6 11))) (define (s-box box val) (char->integer (string-ref (vector-ref *s-boxes* box) val))) (define *rotations* '#(1 1 2 2 2 2 2 2 1 2 2 2 2 2 2 1)) (define (round-rotation i) (vector-ref *rotations* i)) (define (final-permutation from to) (permutation-copy from 0 to 0 *IP-1*)) (define (pc2 subkeys buffer) (permutation-copy subkeys 0 buffer 0 *PC2*)) (define *subkey-size* 28) (define *round-key-size* 48) (define (key-rotation! key by) key has 1 byte we can " abuse " ( at the end ) (bit-set! key *key-size* (bit-ref key *subkey-size*)) (bit-set! key *subkey-size* (bit-ref key 0)) (when (=fx by 2) (bit-set! key (+fx *key-size* 1) (bit-ref key (+fx *subkey-size* 1))) (bit-set! key (+fx *subkey-size* 1) (bit-ref key 1))) (let loop ((i 0)) (unless (=fx i *key-size*) (bit-set! key i (bit-ref key (+fx i by))) (loop (+fx i 1))))) (define (key-expansion key::bstring at::long len::long encrypt?::bool) 16 rounds of 48 bit keys . (let ((res (make-des-buffer (*fx *round-key-size* *des-rounds*))) one byte copy the key temporarily into the res - buffer . Just for one instruction . (copy-bits->des-buffer key at res 0 len) (case len ((56) ;; without parity-bits (permutation-copy res 0 key-buffer 0 *PC1-56*)) ((64) ;; with parity-bits (that we don't look at) (permutation-copy res 0 key-buffer 0 *PC1*)) (else (error "DES key expansion" "Key must be either 56 or 64 bits long" len))) (let loop ((i 0)) (unless (=fx i *des-rounds*) (key-rotation! key-buffer (round-rotation i)) (let ((round-pos (if encrypt? i (-fx (-fx *des-rounds* i) 1)))) (permutation-copy key-buffer 0 res (*fx round-pos *round-key-size*) *PC2*) (loop (+fx i 1))))) res)) (define *block-size/2* (/fx *block-size* 2)) (define (do-round! L R i buffer64 keys) ;; expansion (permutation-copy R 0 buffer64 0 *E*) ;; key mixing (des-buffer-xor! buffer64 0 keys (*fx *round-key-size* i) *round-key-size*) ;; substitution (let loop ((i 0)) (unless (=fx i 8) (let* ((b0 (bit-ref buffer64 (+fx (*fx i 6) 0))) (b1 (bit-ref buffer64 (+fx (*fx i 6) 1))) (b2 (bit-ref buffer64 (+fx (*fx i 6) 2))) (b3 (bit-ref buffer64 (+fx (*fx i 6) 3))) (b4 (bit-ref buffer64 (+fx (*fx i 6) 4))) (b5 (bit-ref buffer64 (+fx (*fx i 6) 5))) (s-box-index (+fx+ (bit-lsh b0 5) (bit-lsh b1 4) (bit-lsh b2 3) (bit-lsh b3 2) (bit-lsh b4 1) b5)) (subs (s-box i s-box-index))) (bit-set! buffer64 (+fx (*fx i 4) 0) (bit-and 1 (bit-rsh subs 3))) (bit-set! buffer64 (+fx (*fx i 4) 1) (bit-and 1 (bit-rsh subs 2))) (bit-set! buffer64 (+fx (*fx i 4) 2) (bit-and 1 (bit-rsh subs 1))) (bit-set! buffer64 (+fx (*fx i 4) 3) (bit-and 1 subs)) (loop (+fx i 1))))) we do P and at the same time . ( just more efficient ) . (let loop ((i 0)) (unless (=fx i *block-size/2*) (bit-set! L i (bit-xor (bit-ref L i) (bit-ref buffer64 (table-ref *P* i)))) (loop (+fx i 1))))) (define-inline (do-des-rounds! L R keys buffer64) (let loop ((i 0) (L L) (R R)) (unless (=fx i *des-rounds*) (do-round! L R i buffer64 keys) (loop (+fx i 1) R L)))) (define (init! in-block in-pos L R buffer64 permute?) (if permute? (begin (copy-bits->des-buffer in-block in-pos buffer64 0 *block-size*) (permutation-copy buffer64 0 L 0 *IP-L*) (permutation-copy buffer64 0 R 0 *IP-R*)) (let ((bs/2 *block-size/2*)) (copy-bits->des-buffer in-block in-pos L 0 bs/2) (copy-bits->des-buffer in-block (+fx in-pos bs/2) R 0 bs/2)))) (define (finalize out-block out-pos L R buffer64 permute?) (if permute? (begin (des-buffer-blit! R 0 buffer64 0 *block-size/2*) (des-buffer-blit! L 0 buffer64 *block-size/2* *block-size/2*) (copy-des-buffer->bits buffer64 0 out-block out-pos *block-size* *IP-1*)) (begin (copy-des-buffer->bits R 0 out-block out-pos *block-size/2* *IP-id*) (copy-des-buffer->bits L 0 out-block (+fx out-pos *block-size/2*) *block-size/2* *IP-id*)))) (define (en/decrypt-DES in-block::bstring in-pos::long out-block::bstring out-pos::long param::DES-Param) (with-access::DES-Param param (buff32a buff32b buff64 keys initial-permutation?) (let ((L buff32a) (R buff32b) (buffer64 buff64) (permute? initial-permutation?)) (init! in-block in-pos L R buffer64 permute?) (do-des-rounds! L R keys buffer64) (finalize out-block out-pos L R buffer64 permute?)))) (define (en/decrypt-DES3 in-block::bstring in-pos::long out-block::bstring out-pos::long param::DES3-Param) (with-access::DES3-Param param (buff32a buff32b buff64 keys1 keys2 keys3 initial-permutation?) (let ((L buff32a) (R buff32b) (buffer64 buff64) (permute? initial-permutation?)) (init! in-block in-pos L R buffer64 permute?) (do-des-rounds! L R keys1 buffer64) (do-des-rounds! R L keys2 buffer64) (do-des-rounds! L R keys3 buffer64) (finalize out-block out-pos L R buffer64 permute?))))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/api/crypto/src/Llib/des.scm
scheme
real key-size --- byte oriented: each byte represents a bit. -> faster... len in bits. from is native bits to is our byte-oriented representation. from is our byte-oriented representation. to is native bits ------ bit-oriented (define (octet-ref str i) (char->integer (string-ref str i))) (define (permutation-copy source target table) (let loop ((i 0)) (unless (=fx i (/fx (table-length table) 8)) (let liip ((j 0) (ci 0)) (cond ((=fx j 8) (octet-set! target i ci)) (else (loop (+fx j 1) (bit-ref source (table-ref table (+fx (*fx i 8) j)))))))) (loop (+fx i 1))))) t is of form (quote (i0 i1 ...)) initial permutation so they start with 0. (make-table macro). inversio of initial permutation. so they start with 0. (make-table macro). expansion function so they start with 0. (make-table macro). so they start with 0. (make-table macro). so they start with 0. (make-table macro). L R L R so they start with 0. (make-table macro). s-boxes (as given here) are indexed as follows: x0000x, x0001x, .... x1111x However we want to be able to index directly into the vector using without parity-bits with parity-bits (that we don't look at) expansion key mixing substitution
(module __crypto-des (import __crypto-util __crypto-block-ciphers) (static (final-class DES-Param (buff32a::bstring read-only) (buff32b::bstring read-only) (buff64::bstring read-only) (keys::bstring read-only) (initial-permutation?::bool read-only)) (final-class DES3-Param (buff32a::bstring read-only) (buff32b::bstring read-only) (buff64::bstring read-only) (keys1::bstring read-only) (keys2::bstring read-only) (keys3::bstring read-only) (initial-permutation?::bool read-only)))) (define *des-rounds* 16) (define *block-size* 64) (define (DES-key->param key encrypt? initial-permutation?) (let ((key-len (*fx 8 (string-length key)))) (when (not (or (=fx key-len 56) (=fx key-len 64))) (error 'des "Key-length must be 56 or 64 bits" key-len)) (let* ((buff32a (make-des-buffer 32)) (buff32b (make-des-buffer 32)) (buff64 (make-des-buffer 64)) (expanded-keys (key-expansion key 0 key-len encrypt?))) (instantiate::DES-Param (buff32a buff32a) (buff32b buff32b) (buff64 buff64) (keys expanded-keys) (initial-permutation? initial-permutation?))))) (define (DES-key->encrypt-param key) (DES-key->param key #t #t)) (define (DES-key->encrypt-param-no-permutation key) (DES-key->param key #t #f)) (define (DES-key->decrypt-param key) (DES-key->param key #f #t)) (define (DES-key->decrypt-param-no-permutation key) (DES-key->param key #f #f)) (register-cipher! 'des (instantiate::Block-Cipher (name "DES (Data Encryption Standard)") (block-size (/fx *block-size* 8)) (preferred-key-length 7) (encrypt! en/decrypt-DES) (decrypt! en/decrypt-DES) (key->encrypt-param DES-key->encrypt-param) (key->decrypt-param DES-key->decrypt-param))) (register-cipher! 'des-np (instantiate::Block-Cipher (name "DES (Data Encryption Standard). No initial Permutation") (block-size (/fx *block-size* 8)) (preferred-key-length 7) (encrypt! en/decrypt-DES) (decrypt! en/decrypt-DES) (key->encrypt-param DES-key->encrypt-param-no-permutation) (key->decrypt-param DES-key->decrypt-param-no-permutation))) (define (DES3-key->param key encrypt? initial-permutation?) (let* ((key-len (*fx 8 (string-length key))) (nb-keys (if (<=fx key-len 128) 2 3)) (subkey-len (/fx key-len nb-keys))) (when (not (or (=fx key-len 112) (=fx key-len 128) (=fx key-len 168) (=fx key-len 192))) (error 'des "Key-length must be 112/128 or 168/192 bits" key-len)) (let* ((buff32a (make-des-buffer 32)) (buff32b (make-des-buffer 32)) (buff64 (make-des-buffer 64))) (if encrypt? (let* ((keys1 (key-expansion key 0 subkey-len #t)) (keys2 (key-expansion key subkey-len subkey-len #f)) (keys3 (if (=fx nb-keys 3) (key-expansion key (*fx 2 subkey-len) subkey-len #t) keys1))) (instantiate::DES3-Param (buff32a buff32a) (buff32b buff32b) (buff64 buff64) (keys1 keys1) (keys2 keys2) (keys3 keys3) (initial-permutation? initial-permutation?))) (let* ((keys3-inv (key-expansion key 0 subkey-len #f)) (keys2-inv (key-expansion key subkey-len subkey-len #t)) (keys1-inv (if (=fx nb-keys 3) (key-expansion key (*fx 2 subkey-len) subkey-len #f) keys3-inv))) (instantiate::DES3-Param (buff32a buff32a) (buff32b buff32b) (buff64 buff64) (keys1 keys1-inv) (keys2 keys2-inv) (keys3 keys3-inv) (initial-permutation? initial-permutation?))))))) (define (DES3-key->encrypt-param key) (DES3-key->param key #t #t)) (define (DES3-key->encrypt-param-no-permutation key) (DES3-key->param key #t #f)) (define (DES3-key->decrypt-param key) (DES3-key->param key #f #t)) (define (DES3-key->decrypt-param-no-permutation key) (DES3-key->param key #f #f)) (register-cipher! 'des3 (instantiate::Block-Cipher (name "Triple DES, Triple Data Encryption Algorithm (DES3, TDEA)") (block-size (/fx *block-size* 8)) (preferred-key-length 14) (encrypt! en/decrypt-DES3) (decrypt! en/decrypt-DES3) (key->encrypt-param DES3-key->encrypt-param) (key->decrypt-param DES3-key->decrypt-param))) (register-cipher! 'des3-np (instantiate::Block-Cipher (name "Triple DES, Triple Data Encryption Algorithm (DES3, TDEA). No initial Permutation.") (block-size (/fx *block-size* 8)) (preferred-key-length 14) (encrypt! en/decrypt-DES3) (decrypt! en/decrypt-DES3) (key->encrypt-param DES3-key->encrypt-param-no-permutation) (key->decrypt-param DES3-key->decrypt-param-no-permutation))) (define (bit-ref str::bstring i) (char->integer (string-ref str i))) (define (bit-set! str::bstring i val) (string-set! str i (integer->char-ur val))) (define (make-des-buffer size) (make-string size #a000)) (define des-buffer-blit! blit-string!) (define (tt b from len sp) (with-output-to-string (lambda () (display-des-buffer b from len sp)))) (define (display-des-buffer buff from len sp) (let loop ((i 0)) (unless (=fx i len) (when (zerofx? (remainderfx i sp)) (display " " )) (display (bit-ref buff (+fx from i))) (loop (+fx i 1))))) (define (des-buffer-xor! target target-pos buffer buf-pos len) (let loop ((i 0)) (unless (=fx i len) (string-set! target (+fx target-pos i) (char-xor (string-ref target (+fx target-pos i)) (string-ref buffer (+fx buf-pos i)))) (loop (+fx i 1))))) (define (copy-bits->des-buffer from::bstring from-pos-bits::long to::bstring to-pos::long nb-bits::long) (let ((nb-bytes (/fx nb-bits 8)) (from-pos (/fx from-pos-bits 8))) (let loop ((i 0)) (unless (=fx i nb-bytes) (let liip ((j 0) (ci (char->integer (string-ref from (+fx from-pos i))))) (unless (=fx j 8) (bit-set! to (+fx to-pos (+fx (*fx i 8) j)) (bit-and #x01 (bit-rsh ci 7))) (liip (+fx j 1) (bit-lsh ci 1)))) (loop (+fx i 1)))))) (define (copy-des-buffer->bits from::bstring from-pos::long to::bstring to-pos-bits::long nb-bits::long table) (let ((nb-bytes (/fx nb-bits 8)) (to-pos (/fx to-pos-bits 8))) (let loop ((i 0)) (unless (=fx i nb-bytes) (let liip ((j 0) (ci 0)) (if (=fx j 8) (string-set! to (+fx to-pos i) (integer->char ci)) (liip (+fx j 1) (+fx (*fx ci 2) (bit-ref from (+fx from-pos (table-ref table (+fx (*fx i 8) j)))))))) (loop (+fx i 1)))))) (define (permutation-copy source source-pos target target-pos table) (let loop ((i 0)) (unless (=fx i (table-length table)) (bit-set! target (+fx target-pos i) (bit-ref source (+fx source-pos (table-ref table i)))) (loop (+fx i 1))))) ( define ( octet - set ! str i ) ( string - set ! str i ( ) ) ) ( + fx ( * fx ci 2 ) Note : most tables are taken from wikipedia . The start numbering the bits with 1 . (define-macro (make-table t) (apply string (map (lambda (i) (integer->char-ur (-fx i 1))) (cadr t)))) (define (table-length table) (string-length table)) (define (table-ref t i) (char->integer (string-ref t i))) first bit of output is taken from 58 . bit of input . Note : everything starts with 1 . However tables are automatically converted (define *IP-L* (make-table '(58 50 42 34 26 18 10 2 60 52 44 36 28 20 12 4 62 54 46 38 30 22 14 6 64 56 48 40 32 24 16 8))) (define *IP-R* (make-table '(57 49 41 33 25 17 9 1 59 51 43 35 27 19 11 3 61 53 45 37 29 21 13 5 63 55 47 39 31 23 15 7))) (define-macro (make-identity-table nb) (apply string (map integer->char (iota nb)))) (define *IP-id* (make-identity-table 32)) Note : everything starts with 1 . However tables are automatically converted (define *IP-1* (make-table '(40 8 48 16 56 24 64 32 39 7 47 15 55 23 63 31 38 6 46 14 54 22 62 30 37 5 45 13 53 21 61 29 36 4 44 12 52 20 60 28 35 3 43 11 51 19 59 27 34 2 42 10 50 18 58 26 33 1 41 9 49 17 57 25))) Note : everything starts with 1 . However tables are automatically converted (define *E* (make-table '(32 1 2 3 4 5 4 5 6 7 8 9 8 9 10 11 12 13 12 13 14 15 16 17 16 17 18 19 20 21 20 21 22 23 24 25 24 25 26 27 28 29 28 29 30 31 32 1))) Note : everything starts with 1 . However tables are automatically converted (define *P* (make-table '(16 7 20 21 29 12 28 17 1 15 23 26 5 18 31 10 2 8 24 14 32 27 3 9 19 13 30 6 22 11 4 25))) Note : everything starts with 1 . However tables are automatically converted 57 49 41 33 25 17 9 1 58 50 42 34 26 18 10 2 59 51 43 35 27 19 11 3 60 52 44 36 63 55 47 39 31 23 15 7 62 54 46 38 30 22 14 6 61 53 45 37 29 21 13 5 28 20 12 4))) PC1 - 56 is used when the password comes as 56bit string . 50 43 36 29 22 15 8 1 51 44 37 30 23 16 9 2 52 45 38 31 24 17 10 3 53 46 39 32 56 49 42 35 28 21 14 7 55 48 41 34 27 20 13 6 54 47 40 33 26 19 12 5 25 18 11 4))) Note : everything starts with 1 . However tables are automatically converted (define *PC2* (make-table '(14 17 11 24 1 5 3 28 15 6 21 10 23 19 12 4 26 8 16 7 27 20 13 2 41 52 31 37 47 55 30 40 51 45 33 48 44 49 39 56 34 53 46 42 50 36 29 32))) (define-macro (create-s-boxes . s-boxes) 0yyyy0 14 4 ... 0yyyy1 0 15 ... 1yyyy0 4 1 ... 1yyyy1 15 12 ... xyyyyx - > rearrange . (define (rearrange v) (let ((res (make-vector 64))) (let loop ((i 0)) (cond ((=fx i 64) res) (else (let ((index (+ (bit-and #x0F (bit-rsh i 1)) (bit-and #x20 i) (bit-lsh (bit-and i 1) 4)))) (vector-set! res i (vector-ref v index))) (loop (+fx i 1))))))) (define (list->strings l) (apply string (map integer->char-ur l))) (let* ((boxes1 (map (lambda (box) box is of form ( quote ( 14 4 ... ) ) (rearrange (list->vector (cadr box)))) s-boxes)) (boxes2 (map vector->list boxes1)) (boxes3 (map list->strings boxes2))) (list 'quote (list->vector boxes3)))) (define *s-boxes* (create-s-boxes '(14 4 13 1 2 15 11 8 3 10 6 12 5 9 0 7 0 15 7 4 14 2 13 1 10 6 12 11 9 5 3 8 4 1 14 8 13 6 2 11 15 12 9 7 3 10 5 0 15 12 8 2 4 9 1 7 5 11 3 14 10 0 6 13) '(15 1 8 14 6 11 3 4 9 7 2 13 12 0 5 10 3 13 4 7 15 2 8 14 12 0 1 10 6 9 11 5 0 14 7 11 10 4 13 1 5 8 12 6 9 3 2 15 13 8 10 1 3 15 4 2 11 6 7 12 0 5 14 9) '(10 0 9 14 6 3 15 5 1 13 12 7 11 4 2 8 13 7 0 9 3 4 6 10 2 8 5 14 12 11 15 1 13 6 4 9 8 15 3 0 11 1 2 12 5 10 14 7 1 10 13 0 6 9 8 7 4 15 14 3 11 5 2 12) '(7 13 14 3 0 6 9 10 1 2 8 5 11 12 4 15 13 8 11 5 6 15 0 3 4 7 2 12 1 10 14 9 10 6 9 0 12 11 7 13 15 1 3 14 5 2 8 4 3 15 0 6 10 1 13 8 9 4 5 11 12 7 2 14) '(2 12 4 1 7 10 11 6 8 5 3 15 13 0 14 9 14 11 2 12 4 7 13 1 5 0 15 10 3 9 8 6 4 2 1 11 10 13 7 8 15 9 12 5 6 3 0 14 11 8 12 7 1 14 2 13 6 15 0 9 10 4 5 3) '(12 1 10 15 9 2 6 8 0 13 3 4 14 7 5 11 10 15 4 2 7 12 9 5 6 1 13 14 0 11 3 8 9 14 15 5 2 8 12 3 7 0 4 10 1 13 11 6 4 3 2 12 9 5 15 10 11 14 1 7 6 0 8 13) '(4 11 2 14 15 0 8 13 3 12 9 7 5 10 6 1 13 0 11 7 4 9 1 10 14 3 5 12 2 15 8 6 1 4 11 13 12 3 7 14 10 15 6 8 0 5 9 2 6 11 13 8 1 4 10 7 9 5 0 15 14 2 3 12) '(13 2 8 4 6 15 11 1 10 9 3 14 5 0 12 7 1 15 13 8 10 3 7 4 12 5 6 11 0 14 9 2 7 11 4 1 9 12 14 2 0 6 10 13 15 3 5 8 2 1 14 7 4 10 8 13 15 12 9 0 3 5 6 11))) (define (s-box box val) (char->integer (string-ref (vector-ref *s-boxes* box) val))) (define *rotations* '#(1 1 2 2 2 2 2 2 1 2 2 2 2 2 2 1)) (define (round-rotation i) (vector-ref *rotations* i)) (define (final-permutation from to) (permutation-copy from 0 to 0 *IP-1*)) (define (pc2 subkeys buffer) (permutation-copy subkeys 0 buffer 0 *PC2*)) (define *subkey-size* 28) (define *round-key-size* 48) (define (key-rotation! key by) key has 1 byte we can " abuse " ( at the end ) (bit-set! key *key-size* (bit-ref key *subkey-size*)) (bit-set! key *subkey-size* (bit-ref key 0)) (when (=fx by 2) (bit-set! key (+fx *key-size* 1) (bit-ref key (+fx *subkey-size* 1))) (bit-set! key (+fx *subkey-size* 1) (bit-ref key 1))) (let loop ((i 0)) (unless (=fx i *key-size*) (bit-set! key i (bit-ref key (+fx i by))) (loop (+fx i 1))))) (define (key-expansion key::bstring at::long len::long encrypt?::bool) 16 rounds of 48 bit keys . (let ((res (make-des-buffer (*fx *round-key-size* *des-rounds*))) one byte copy the key temporarily into the res - buffer . Just for one instruction . (copy-bits->des-buffer key at res 0 len) (case len (permutation-copy res 0 key-buffer 0 *PC1-56*)) (permutation-copy res 0 key-buffer 0 *PC1*)) (else (error "DES key expansion" "Key must be either 56 or 64 bits long" len))) (let loop ((i 0)) (unless (=fx i *des-rounds*) (key-rotation! key-buffer (round-rotation i)) (let ((round-pos (if encrypt? i (-fx (-fx *des-rounds* i) 1)))) (permutation-copy key-buffer 0 res (*fx round-pos *round-key-size*) *PC2*) (loop (+fx i 1))))) res)) (define *block-size/2* (/fx *block-size* 2)) (define (do-round! L R i buffer64 keys) (permutation-copy R 0 buffer64 0 *E*) (des-buffer-xor! buffer64 0 keys (*fx *round-key-size* i) *round-key-size*) (let loop ((i 0)) (unless (=fx i 8) (let* ((b0 (bit-ref buffer64 (+fx (*fx i 6) 0))) (b1 (bit-ref buffer64 (+fx (*fx i 6) 1))) (b2 (bit-ref buffer64 (+fx (*fx i 6) 2))) (b3 (bit-ref buffer64 (+fx (*fx i 6) 3))) (b4 (bit-ref buffer64 (+fx (*fx i 6) 4))) (b5 (bit-ref buffer64 (+fx (*fx i 6) 5))) (s-box-index (+fx+ (bit-lsh b0 5) (bit-lsh b1 4) (bit-lsh b2 3) (bit-lsh b3 2) (bit-lsh b4 1) b5)) (subs (s-box i s-box-index))) (bit-set! buffer64 (+fx (*fx i 4) 0) (bit-and 1 (bit-rsh subs 3))) (bit-set! buffer64 (+fx (*fx i 4) 1) (bit-and 1 (bit-rsh subs 2))) (bit-set! buffer64 (+fx (*fx i 4) 2) (bit-and 1 (bit-rsh subs 1))) (bit-set! buffer64 (+fx (*fx i 4) 3) (bit-and 1 subs)) (loop (+fx i 1))))) we do P and at the same time . ( just more efficient ) . (let loop ((i 0)) (unless (=fx i *block-size/2*) (bit-set! L i (bit-xor (bit-ref L i) (bit-ref buffer64 (table-ref *P* i)))) (loop (+fx i 1))))) (define-inline (do-des-rounds! L R keys buffer64) (let loop ((i 0) (L L) (R R)) (unless (=fx i *des-rounds*) (do-round! L R i buffer64 keys) (loop (+fx i 1) R L)))) (define (init! in-block in-pos L R buffer64 permute?) (if permute? (begin (copy-bits->des-buffer in-block in-pos buffer64 0 *block-size*) (permutation-copy buffer64 0 L 0 *IP-L*) (permutation-copy buffer64 0 R 0 *IP-R*)) (let ((bs/2 *block-size/2*)) (copy-bits->des-buffer in-block in-pos L 0 bs/2) (copy-bits->des-buffer in-block (+fx in-pos bs/2) R 0 bs/2)))) (define (finalize out-block out-pos L R buffer64 permute?) (if permute? (begin (des-buffer-blit! R 0 buffer64 0 *block-size/2*) (des-buffer-blit! L 0 buffer64 *block-size/2* *block-size/2*) (copy-des-buffer->bits buffer64 0 out-block out-pos *block-size* *IP-1*)) (begin (copy-des-buffer->bits R 0 out-block out-pos *block-size/2* *IP-id*) (copy-des-buffer->bits L 0 out-block (+fx out-pos *block-size/2*) *block-size/2* *IP-id*)))) (define (en/decrypt-DES in-block::bstring in-pos::long out-block::bstring out-pos::long param::DES-Param) (with-access::DES-Param param (buff32a buff32b buff64 keys initial-permutation?) (let ((L buff32a) (R buff32b) (buffer64 buff64) (permute? initial-permutation?)) (init! in-block in-pos L R buffer64 permute?) (do-des-rounds! L R keys buffer64) (finalize out-block out-pos L R buffer64 permute?)))) (define (en/decrypt-DES3 in-block::bstring in-pos::long out-block::bstring out-pos::long param::DES3-Param) (with-access::DES3-Param param (buff32a buff32b buff64 keys1 keys2 keys3 initial-permutation?) (let ((L buff32a) (R buff32b) (buffer64 buff64) (permute? initial-permutation?)) (init! in-block in-pos L R buffer64 permute?) (do-des-rounds! L R keys1 buffer64) (do-des-rounds! R L keys2 buffer64) (do-des-rounds! L R keys3 buffer64) (finalize out-block out-pos L R buffer64 permute?))))
e111047d6573052a236882bed086994f1322874496109ff2b5b93192bdbe2151
ostera/serde.ml
sequence_access.ml
type ('value, 'error) t = { next_element : 'element_value. deser_element:(unit -> ('element_value, 'error Error.de_error) result) -> ('element_value option, 'error Error.de_error) result; } let next_element t ~deser_element = t.next_element ~deser_element
null
https://raw.githubusercontent.com/ostera/serde.ml/ed4d0d1e3ec9b017904cb9497f9d81677e6b36a3/serde/de/sequence_access.ml
ocaml
type ('value, 'error) t = { next_element : 'element_value. deser_element:(unit -> ('element_value, 'error Error.de_error) result) -> ('element_value option, 'error Error.de_error) result; } let next_element t ~deser_element = t.next_element ~deser_element
00a458eb542a2410bb336e966ce0b871ca3ef1e374f5aaf880c3a00b6d4d219a
Elzair/nazghul
bill.scm
;;---------------------------------------------------------------------------- ;; Constants ;;---------------------------------------------------------------------------- (define bill-start-lvl 3) ;;---------------------------------------------------------------------------- ;; Schedule ;; In Bole . ;;---------------------------------------------------------------------------- (kern-mk-sched 'sch_bill (list 0 0 bole-bed-bill "sleeping") (list 6 0 bole-table-1 "idle") (list 7 0 bole-n-woods "working") (list 12 0 bole-table-2 "eating") (list 13 0 bole-n-woods "working") (list 18 0 bole-table-2 "eating") (list 19 0 bole-dining-hall "idle") (list 21 0 bole-bills-hut "idle") (list 22 0 bole-bed-bill "sleeping") ) ;;---------------------------------------------------------------------------- ;; Gob ;; Quest flags , etc , go here . ;;---------------------------------------------------------------------------- (define (bill-mk) nil) ;;---------------------------------------------------------------------------- ;; Conv ;; Bill is a woodcutter who lives in Bole . ;; Not the sharpest tool in the shed. ;;---------------------------------------------------------------------------- (define bill-catalog (list (list t_staff 10 "It's hard tuh find branches straight enought to make a staff.") ;; rather cheap (list t_torch 3 "Ah always like tuh see at night, so I make torches.") ;; rather cheap (list t_arrow 3 "The rangers from Green Tower sometimes buy my arrows.") (list t_bolt 4 "Not many folks use crossbows 'round here.") )) (define bill-merch-msgs (list nil ;; closed "I make all this stuff my self." ;; buy nil ;; sell nil ;; trade "I hope they work ok for you." ;; sold-something "If ye change yer mind ah'll be around." ;; sold-nothing nil ;; bought-something nil ;; bought-nothing nil ;; traded-something nil ;; traded-nothing )) (define (bill-buy knpc kpc) (conv-trade knpc kpc "buy" bill-merch-msgs bill-catalog)) (define (bill-goods knpc kpc) (say knpc "Want to buy some?") (if (kern-conv-get-yes-no? kpc) (bill-buy knpc kpc) (say knpc "Just ask if you ever do."))) (define (bill-may knpc kpc) (say knpc "She runs the tavern in town an' is a good lady.")) (define (bill-lady knpc kpc) (say knpc "There's uh lady in town now. She's real pretty. But she has " "a big, mean boyfrien'.")) (define (bill-bole knpc kpc) (say knpc "Yeah, Ah like Bole. " "There's uh tavern, where Ah eat an' get shit-faced. " "An' muh house is there.")) (define (bill-wolves knpc kpc) (say knpc "I hafta wach out for them. " "They stays mostly inna south, away from town.")) (define (bill-scared knpc kpc) (say knpc "Ah wuz west o' the town, " "where's I hardly never go on account o' the wulves. " "There was a great big, old, dead oak. " "I sez to myself, that's a good-un! " "Well, no sooner had muh axe bit into the bark " "but it wakes up!")) (define (bill-thie knpc kpc) (say knpc "There wuz a right nervous feller at the tavern not long ago. " "He had some words with the pretty lady. I think they got in uh " "argument over somethin'. I saw him go into the hills in the " "northeast cornah uh town, you know? And he never came out. I " "don' know where he went! Them hills is uh dead-end! Plumb strange " "if'n you ask me.")) (define (bill-mous knpc kpc) (say knpc "Therez mice all over. Jus' the other day I saw a man what " "scurried lak a mouse!")) (define bill-conv (ifc nil (method 'default (lambda (knpc kpc) (say knpc "[He shrugs]"))) (method 'hail (lambda (knpc kpc) (say knpc "Hi-dee."))) (method 'bye (lambda (knpc kpc) (say knpc "Fare thee well."))) (method 'job (lambda (knpc kpc) (say knpc "I's a woodcutter."))) (method 'name (lambda (knpc kpc) (say knpc "Called Bill."))) (method 'join (lambda (knpc kpc) (say knpc "No, sirree! Yousa ass-kicker, " "and I'sa woodcutter. Not a good match, no " "offense."))) (method 'arro bill-goods) (method 'axe (lambda (knpc kpc) (say knpc "It works better than muh knife on most trees."))) (method 'buy bill-buy) (method 'bole bill-bole) (method 'chop (lambda (knpc kpc) (say knpc "Ah use muh axe."))) (method 'fore (lambda (knpc kpc) (say knpc "Yeah, the forest is plumb full o' trees. " "And wolves, too."))) (method 'haun (lambda (knpc kpc) (say knpc "[He leans in close and whispers] " "Thar's a haunted tree west o' the town. " "Scared the jinkins outta me! Har!"))) (method 'jink bill-scared) (method 'ladi bill-lady) (method 'lady bill-lady) (method 'may bill-may) (method 'wood (lambda (knpc kpc) (say knpc "I cuts down trees and chops 'em into firewood. " "Sometimes Ah make torches or arrows, too. Um-hm."))) (method 'shit (lambda (knpc kpc) (say knpc "Oops! Sorry. I's not supposed to say that. " "May's alwiz tellin' me not tuh say words lak shit and " "damn. Ladies don' lak that, you know."))) (method 'scar bill-scared) (method 'thie bill-thie) (method 'mous bill-mous) (method 'man bill-thie) (method 'scur bill-thie) (method 'torc bill-goods) (method 'town bill-bole) (method 'trad bill-buy) (method 'tree (lambda (knpc kpc) (say knpc "There be all kinds uh trees in this forest. " "Why, t'other day I even came me across a haunted " "tree!"))) (method 'wake (lambda (knpc kpc) (say knpc "Aye! That old dead oak came alive! " "It bellered like a bull and two great eyes opened " "und stared right at me! Uh jumped out of my britches!" "I dropped muh axe and ran like nothing!"))) (method 'wolv bill-wolves) (method 'wulv bill-wolves) )) ;;---------------------------------------------------------------------------- First - time constructor ;;---------------------------------------------------------------------------- (define (mk-bill) (bind (kern-char-arm-self (kern-mk-char 'ch_bill ;;......tag "Bill" ;;.......name sp_human ;;.....species nil ;;..........occupation s_townsman ;;...sprite faction-men ;;..faction 2 ;;............custom strength modifier 0 ;;............custom intelligence modifier 0 ;;............custom dexterity modifier ............ custom base hp modifier ............ custom hp multiplier ( per - level ) 0 ;;............custom base mp modifier 0 ;;............custom mp multiplier (per-level) max-health ;;..current hit points -1 ;;...........current experience points max-health ;;..current magic points 0 bill-start-lvl ;;..current level #f ;;...........dead? 'bill-conv ;;...conversation (optional) sch_bill ;;.....schedule (optional) 'townsman-ai ;;..........custom ai (optional) ;;..............container (and contents) (mk-inventory (list (list 10 t_torch) (list 100 t_arrow) (list 1 t_2h_axe) )) nil ;;.........readied arms (in addition to the container contents) nil ;;..........hooks in effect )) (bill-mk)))
null
https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.002/bill.scm
scheme
---------------------------------------------------------------------------- Constants ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Schedule ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Gob ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Conv Not the sharpest tool in the shed. ---------------------------------------------------------------------------- rather cheap rather cheap closed buy sell trade sold-something sold-nothing bought-something bought-nothing traded-something traded-nothing ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ......tag .......name .....species ..........occupation ...sprite ..faction ............custom strength modifier ............custom intelligence modifier ............custom dexterity modifier ............custom base mp modifier ............custom mp multiplier (per-level) ..current hit points ...........current experience points ..current magic points ..current level ...........dead? ...conversation (optional) .....schedule (optional) ..........custom ai (optional) ..............container (and contents) .........readied arms (in addition to the container contents) ..........hooks in effect
(define bill-start-lvl 3) In Bole . (kern-mk-sched 'sch_bill (list 0 0 bole-bed-bill "sleeping") (list 6 0 bole-table-1 "idle") (list 7 0 bole-n-woods "working") (list 12 0 bole-table-2 "eating") (list 13 0 bole-n-woods "working") (list 18 0 bole-table-2 "eating") (list 19 0 bole-dining-hall "idle") (list 21 0 bole-bills-hut "idle") (list 22 0 bole-bed-bill "sleeping") ) Quest flags , etc , go here . (define (bill-mk) nil) Bill is a woodcutter who lives in Bole . (define bill-catalog (list (list t_arrow 3 "The rangers from Green Tower sometimes buy my arrows.") (list t_bolt 4 "Not many folks use crossbows 'round here.") )) (define bill-merch-msgs )) (define (bill-buy knpc kpc) (conv-trade knpc kpc "buy" bill-merch-msgs bill-catalog)) (define (bill-goods knpc kpc) (say knpc "Want to buy some?") (if (kern-conv-get-yes-no? kpc) (bill-buy knpc kpc) (say knpc "Just ask if you ever do."))) (define (bill-may knpc kpc) (say knpc "She runs the tavern in town an' is a good lady.")) (define (bill-lady knpc kpc) (say knpc "There's uh lady in town now. She's real pretty. But she has " "a big, mean boyfrien'.")) (define (bill-bole knpc kpc) (say knpc "Yeah, Ah like Bole. " "There's uh tavern, where Ah eat an' get shit-faced. " "An' muh house is there.")) (define (bill-wolves knpc kpc) (say knpc "I hafta wach out for them. " "They stays mostly inna south, away from town.")) (define (bill-scared knpc kpc) (say knpc "Ah wuz west o' the town, " "where's I hardly never go on account o' the wulves. " "There was a great big, old, dead oak. " "I sez to myself, that's a good-un! " "Well, no sooner had muh axe bit into the bark " "but it wakes up!")) (define (bill-thie knpc kpc) (say knpc "There wuz a right nervous feller at the tavern not long ago. " "He had some words with the pretty lady. I think they got in uh " "argument over somethin'. I saw him go into the hills in the " "northeast cornah uh town, you know? And he never came out. I " "don' know where he went! Them hills is uh dead-end! Plumb strange " "if'n you ask me.")) (define (bill-mous knpc kpc) (say knpc "Therez mice all over. Jus' the other day I saw a man what " "scurried lak a mouse!")) (define bill-conv (ifc nil (method 'default (lambda (knpc kpc) (say knpc "[He shrugs]"))) (method 'hail (lambda (knpc kpc) (say knpc "Hi-dee."))) (method 'bye (lambda (knpc kpc) (say knpc "Fare thee well."))) (method 'job (lambda (knpc kpc) (say knpc "I's a woodcutter."))) (method 'name (lambda (knpc kpc) (say knpc "Called Bill."))) (method 'join (lambda (knpc kpc) (say knpc "No, sirree! Yousa ass-kicker, " "and I'sa woodcutter. Not a good match, no " "offense."))) (method 'arro bill-goods) (method 'axe (lambda (knpc kpc) (say knpc "It works better than muh knife on most trees."))) (method 'buy bill-buy) (method 'bole bill-bole) (method 'chop (lambda (knpc kpc) (say knpc "Ah use muh axe."))) (method 'fore (lambda (knpc kpc) (say knpc "Yeah, the forest is plumb full o' trees. " "And wolves, too."))) (method 'haun (lambda (knpc kpc) (say knpc "[He leans in close and whispers] " "Thar's a haunted tree west o' the town. " "Scared the jinkins outta me! Har!"))) (method 'jink bill-scared) (method 'ladi bill-lady) (method 'lady bill-lady) (method 'may bill-may) (method 'wood (lambda (knpc kpc) (say knpc "I cuts down trees and chops 'em into firewood. " "Sometimes Ah make torches or arrows, too. Um-hm."))) (method 'shit (lambda (knpc kpc) (say knpc "Oops! Sorry. I's not supposed to say that. " "May's alwiz tellin' me not tuh say words lak shit and " "damn. Ladies don' lak that, you know."))) (method 'scar bill-scared) (method 'thie bill-thie) (method 'mous bill-mous) (method 'man bill-thie) (method 'scur bill-thie) (method 'torc bill-goods) (method 'town bill-bole) (method 'trad bill-buy) (method 'tree (lambda (knpc kpc) (say knpc "There be all kinds uh trees in this forest. " "Why, t'other day I even came me across a haunted " "tree!"))) (method 'wake (lambda (knpc kpc) (say knpc "Aye! That old dead oak came alive! " "It bellered like a bull and two great eyes opened " "und stared right at me! Uh jumped out of my britches!" "I dropped muh axe and ran like nothing!"))) (method 'wolv bill-wolves) (method 'wulv bill-wolves) )) First - time constructor (define (mk-bill) (bind (kern-char-arm-self (kern-mk-char ............ custom base hp modifier ............ custom hp multiplier ( per - level ) 0 (mk-inventory (list (list 10 t_torch) (list 100 t_arrow) (list 1 t_2h_axe) )) )) (bill-mk)))
f08830b300f9ae649dc718e24942358ba81b4a26931af6c8dcfd72d89b3a0c5f
nextjournal/viewers
d3_require.cljs
(ns nextjournal.ui.components.d3-require (:require ["d3-require" :as d3] [applied-science.js-interop :as j] [reagent.core :as r])) (defn with [{:keys [package loading-view] :or {loading-view "Loading..."}} f] (r/with-let [!package (r/atom nil)] (case @!package nil (do (reset! !package :loading) (-> (if (string? package) (d3/require package) (apply d3/require package)) (j/call :then #(reset! !package %))) loading-view) :loading loading-view (into (f @!package))))) (comment ;; Usage [with {:package ["[email protected]"]} (j/fn [^:js {:keys [embed]}] [:div {:ref #(when % (embed % (clj->js value)))}])])
null
https://raw.githubusercontent.com/nextjournal/viewers/1a8e3300601780dccb18d5548f7d35b31b7934f9/modules/ui/src/nextjournal/ui/components/d3_require.cljs
clojure
Usage
(ns nextjournal.ui.components.d3-require (:require ["d3-require" :as d3] [applied-science.js-interop :as j] [reagent.core :as r])) (defn with [{:keys [package loading-view] :or {loading-view "Loading..."}} f] (r/with-let [!package (r/atom nil)] (case @!package nil (do (reset! !package :loading) (-> (if (string? package) (d3/require package) (apply d3/require package)) (j/call :then #(reset! !package %))) loading-view) :loading loading-view (into (f @!package))))) (comment [with {:package ["[email protected]"]} (j/fn [^:js {:keys [embed]}] [:div {:ref #(when % (embed % (clj->js value)))}])])
9890fab231e867162b7e8d6993764ea2d9ad8e2878dc8d13f420b488ae7354fa
nyu-acsys/drift
exception.ml
Leroy & Pessaux , " Type - Based Analysis of Uncaught Exceptionis , " TOPLAS , 2000 let ff n = if n > = 0 then ( ) else raise 0 in try ff ? n ? with Failer 0 - > ( ) Leroy & Pessaux, "Type-Based Analysis of Uncaught Exceptionis, " TOPLAS, 2000 let ff n = if n >= 0 then () else raise 0 in try ff ?n? with Failer 0 -> () *) let f n k = if n >= 0 then () else k 0 let g n = assert (n = 0) let main (n:int(*-:{v:Int | true}*)) = f n g
null
https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks/r_type/high/exception.ml
ocaml
-:{v:Int | true}
Leroy & Pessaux , " Type - Based Analysis of Uncaught Exceptionis , " TOPLAS , 2000 let ff n = if n > = 0 then ( ) else raise 0 in try ff ? n ? with Failer 0 - > ( ) Leroy & Pessaux, "Type-Based Analysis of Uncaught Exceptionis, " TOPLAS, 2000 let ff n = if n >= 0 then () else raise 0 in try ff ?n? with Failer 0 -> () *) let f n k = if n >= 0 then () else k 0 let g n = assert (n = 0) f n g
e89d2ba2fdeccadc24c825f7b083daf3be4516c7a64a65912413ed8d92317463
kappelmann/eidi2_repetitorium_tum
Comparable.mli
module type Comparable = sig type value val is_smaller : value -> value -> bool val is_equal : value -> value -> bool end
null
https://raw.githubusercontent.com/kappelmann/eidi2_repetitorium_tum/1d16bbc498487a85960e0d83152249eb13944611/2017/ocaml/functors/case_example_priority_queue/Comparable.mli
ocaml
module type Comparable = sig type value val is_smaller : value -> value -> bool val is_equal : value -> value -> bool end
4687c974717172ec2eddf5514a83cb9eda1bc9cff790881d3a7e944ee6f3a280
amccausl/Swish
GraphPartitionTest.hs
-------------------------------------------------------------------------------- $ I d : GraphPartitionTest.hs , v 1.2 2004/02/10 20:24:48 graham Exp $ -- Copyright ( c ) 2003 , . All rights reserved . -- See end of this file for licence information. -------------------------------------------------------------------------------- -- | -- Module : GraphPartitionTest Copyright : ( c ) 2003 , License : GPL V2 -- Maintainer : -- Stability : provisional -- Portability : H98 -- -- This module contains test cases for graph partitioning logic. -- -------------------------------------------------------------------------------- module Swish . HaskellRDF.GraphPartitionTest where module ) where -- WNH import Swish.HaskellRDF.GraphPartition ( PartitionedGraph(..), getArcs , GraphPartition(..), node, toArcs , partitionGraph, comparePartitions ) import Swish.HaskellRDF.GraphClass ( Label(..) , Arc(..), arcSubj, arcPred, arcObj, arc, arcToTriple, arcFromTriple , , arcLabels ) import Swish.HaskellRDF.GraphMem ( GraphMem ( .. ) -- , setArcs, getArcs, add, delete, extract, labels ( LabelMem(..) , labelIsVar, labelHash ) import Swish.HaskellUtils.TestHelpers ( test, testEq, -- WNH FIX testNe, testLe, testGe, testElem , testJust, testNothing , testEqv, WNH FIXtestNotEqv , testEqv2, testHasEqv, testMaybeEqv ) import Swish.HaskellUtils.ListHelpers ( equiv ) import Test.HUnit ( Test(TestCase,TestList,TestLabel) , Assertion , assertBool, assertEqual, assertString, assertFailure , runTestTT, runTestText, putTextToHandle ) import System.IO ( Handle, IOMode(WriteMode) , openFile, hClose, hPutStr, hPutStrLn ) import Control.Monad ( unless ) import Data.List ( sort, union, intersect ) import Data.Maybe ( isJust, fromJust, fromMaybe ) ------------------------------------------------------------ -- Basic GraphPartition tests ------------------------------------------------------------ gp1 = PartitionedGraph [ p11 ] gp2 = PartitionedGraph [ p11, p12 ] gp3 = PartitionedGraph [ p11, p13 ] gp4 = PartitionedGraph [ p11, p14 ] gp5 = PartitionedGraph [ p11, p12, p15 ] p11 = PartSub (LF "s1") [ (LF "p11",PartObj (LF "o11")) ] p12 = PartSub (LF "s2") [ (LF "p21",PartObj (LF "o21")) , (LF "p22",PartObj (LF "o22")) ] p13 = PartSub (LF "s3") [ (LF "p31",PartObj (LF "o31")) , (LF "p32",p12) , (LF "p33",PartObj (LF "s3")) ] p14 = PartSub (LF "s3") [ (LF "p31",PartObj (LF "o31")) , (LF "p33",PartObj (LF "s3")) , (LF "p32",p12) ] p15 = PartSub (LF "s3") [ (LF "p31",PartObj (LF "o31")) , (LF "p32",PartObj (LF "s2")) , (LF "p33",PartObj (LF "s3")) ] ga1 = [ Arc (LF "s1") (LF "p11") (LF "o11") ] ga2 = [ Arc (LF "s1") (LF "p11") (LF "o11") , Arc (LF "s2") (LF "p21") (LF "o21") , Arc (LF "s2") (LF "p22") (LF "o22") ] ga3 = [ Arc (LF "s1") (LF "p11") (LF "o11") , Arc (LF "s3") (LF "p31") (LF "o31") , Arc (LF "s3") (LF "p32") (LF "s2") , Arc (LF "s2") (LF "p21") (LF "o21") , Arc (LF "s2") (LF "p22") (LF "o22") , Arc (LF "s3") (LF "p33") (LF "s3") ] ga4 = [ Arc (LF "s1") (LF "p11") (LF "o11") , Arc (LF "s3") (LF "p31") (LF "o31") , Arc (LF "s3") (LF "p33") (LF "s3") , Arc (LF "s3") (LF "p32") (LF "s2") , Arc (LF "s2") (LF "p21") (LF "o21") , Arc (LF "s2") (LF "p22") (LF "o22") ] ga5 = [ Arc (LF "s1") (LF "p11") (LF "o11") , Arc (LF "s2") (LF "p21") (LF "o21") , Arc (LF "s2") (LF "p22") (LF "o22") , Arc (LF "s3") (LF "p31") (LF "o31") , Arc (LF "s3") (LF "p32") (LF "s2") , Arc (LF "s3") (LF "p33") (LF "s3") ] testBasic01 = testEq "testBasic01" gp1 gp1 testBasic02 = testEq "testBasic02" gp2 gp2 testBasic03 = testEq "testBasic03" gp3 gp3 testBasic04 = testEq "testBasic04" gp4 gp4 testBasic05 = testEq "testBasic05" gp5 gp5 {- WNH FIX testBasic06 = testNe "testBasic06" gp2 gp3 testBasic07 = testNe "testBasic07" gp3 gp4 -} testBasic11 = testEq "testBasic11" "PartitionedGraph [(!s1 !p11 !o11)]" (show gp1) testBasic12 = testEq "testBasic12" ( "PartitionedGraph "++ "[(!s1 !p11 !o11)"++ ",(!s2 !p21 !o21 ; !p22 !o22)"++ "]" ) (show gp2) testBasic13 = testEq "testBasic13" ( "PartitionedGraph "++ "[(!s1 !p11 !o11)"++ ",(!s3 !p31 !o31 ; !p32 (!s2 !p21 !o21 ; !p22 !o22) ; !p33 !s3)"++ "]" ) (show gp3) testBasic14 = testEq "testBasic14" ( "PartitionedGraph "++ "[(!s1 !p11 !o11)"++ ",(!s3 !p31 !o31 ; !p33 !s3 ; !p32 (!s2 !p21 !o21 ; !p22 !o22))"++ "]" ) (show gp4) testBasic15 = testEq "testBasic15" ( "PartitionedGraph "++ "[(!s1 !p11 !o11)"++ ",(!s2 !p21 !o21 ; !p22 !o22)"++ ",(!s3 !p31 !o31 ; !p32 !s2 ; !p33 !s3)"++ "]" ) (show gp5) testBasic21 = testEq "testBasic21" (LF "s1") (node p11) testBasic22 = testEq "testBasic22" (LF "s2") (node p12) testBasic23 = testEq "testBasic23" (LF "s3") (node p13) testBasic24 = testEq "testBasic24" (LF "s3") (node p14) testBasic25 = testEq "testBasic25" (LF "s3") (node p15) testBasic31 = testEq "testBasic31" ga1 (getArcs gp1) testBasic32 = testEq "testBasic32" ga2 (getArcs gp2) testBasic33 = testEq "testBasic33" ga3 (getArcs gp3) testBasic34 = testEq "testBasic34" ga4 (getArcs gp4) testBasic35 = testEq "testBasic35" ga5 (getArcs gp5) -- WNH FIX testBasic36 = testNotEqv "testBasic36" (getArcs gp2) (getArcs gp3) testBasic37 = testEqv "testBasic37" (getArcs gp3) (getArcs gp4) testBasic38 = testEqv "testBasic38" (getArcs gp3) (getArcs gp5) testBasicSuite = TestList [ testBasic01 , testBasic02 , testBasic03 , testBasic04 , testBasic05 -- WNH FIX, testBasic06 -- WNH FIX, testBasic07 , testBasic11 , testBasic12 , testBasic13 , testBasic14 , testBasic15 , testBasic21 , testBasic22 , testBasic23 , testBasic24 , testBasic25 , testBasic31 , testBasic32 , testBasic33 , testBasic34 , testBasic35 -- WNH FIX, testBasic36 , testBasic37 , testBasic38 ] ------------------------------------------------------------ -- Creating GraphPartition tests ------------------------------------------------------------ pa1 = [ Arc (LF "s1") (LF "p") (LF "o11") ] pa2 = [ Arc (LF "s1") (LF "p") (LF "o11") , Arc (LF "s2") (LF "p1") (LF "o21") , Arc (LF "s2") (LF "p2") (LF "o22") ] pa3 = [ Arc (LF "s1") (LF "p") (LF "o11") , Arc (LF "s2") (LF "p1") (LF "o21") , Arc (LF "s2") (LF "p2") (LF "o22") , Arc (LV "b3") (LF "p") (LF "o31") , Arc (LV "b3") (LF "p") (LF "s2") , Arc (LV "b3") (LF "p") (LV "b3") ] pa4 = [ Arc (LF "s1") (LF "p") (LF "o11") , Arc (LF "s2") (LF "p1") (LF "o21") , Arc (LF "s2") (LF "p2") (LF "o22") , Arc (LV "b3") (LF "p") (LF "o31") , Arc (LV "b3") (LF "p") (LF "s2") , Arc (LV "b3") (LF "p") (LV "b3") , Arc (LV "b3") (LF "p") (LV "b4") , Arc (LV "b4") (LF "p") (LF "s2") , Arc (LV "b4") (LF "p") (LV "b3") ] pa5 = [ Arc (LF "s1") (LF "p") (LF "o11") , Arc (LF "s2") (LF "p1") (LF "o21") , Arc (LF "s2") (LF "p2") (LF "o22") , Arc (LV "b3") (LF "p") (LF "o31") , Arc (LV "b3") (LF "p") (LF "s2") , Arc (LV "b3") (LF "p") (LV "b3") , Arc (LV "b3") (LF "p") (LV "b4") , Arc (LV "b4") (LF "p") (LF "s2") , Arc (LV "b4") (LF "p") (LV "b3") , Arc (LV "b5a") (LF "p") (LV "b5b") , Arc (LV "b5b") (LF "p") (LV "b5c") , Arc (LV "b5c") (LF "p") (LV "b5a") ] pa6 = [ Arc (LF "s1") (LF "p") (LF "o11") , Arc (LF "s2") (LF "p1") (LF "o21") , Arc (LF "s2") (LF "p2") (LF "o22") , Arc (LV "b3") (LF "p") (LF "o31") , Arc (LV "b3") (LF "p") (LF "s2") , Arc (LV "b3") (LF "p") (LV "b3") , Arc (LV "b3") (LF "p") (LV "b4") , Arc (LV "b4") (LF "p") (LF "s2") , Arc (LV "b4") (LF "p") (LV "b3") , Arc (LV "b4") (LF "p") (LV "b5b") , Arc (LV "b5a") (LF "p") (LV "b5b") , Arc (LV "b5b") (LF "p") (LV "b5c") , Arc (LV "b5c") (LF "p") (LV "b5a") ] pp1 = PartitionedGraph [ ps1 ] pp2f = PartitionedGraph [ ps1, ps2f ] pp2r = PartitionedGraph [ ps2r, ps1 ] pp3f = PartitionedGraph [ ps1, ps2f, pb3f ] pp3r = PartitionedGraph [ ps2r, ps1, pb3r ] pp4f = PartitionedGraph [ ps1, ps2f, pb3af ] pp4r = PartitionedGraph [ ps2r, ps1, pb3ar ] pp5f = PartitionedGraph [ ps1, ps2f, pb3af, pb5a1 ] pp5r = PartitionedGraph [ ps2r, ps1, pb3ar, pb5c3 ] pp6f = PartitionedGraph [ ps1, ps2f, pb3bf, pb5b2 ] pp6r = PartitionedGraph [ ps2r, ps1, pb5b2, pb3br ] ps1 = PartSub (LF "s1") [ (LF "p",PartObj (LF "o11")) ] ps2f = PartSub (LF "s2") [ (LF "p1",PartObj (LF "o21")) , (LF "p2",PartObj (LF "o22")) ] ps2r = PartSub (LF "s2") [ (LF "p2",PartObj (LF "o22")) , (LF "p1",PartObj (LF "o21")) ] pb3f = PartSub (LV "b3") [ (LF "p",PartObj (LF "o31")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LV "b3")) ] pb3r = PartSub (LV "b3") [ (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LF "o31")) ] pb3af = PartSub (LV "b3") [ (LF "p",PartObj (LF "o31")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LV "b3")) , (LF "p",pb4af) ] pb3ar = PartSub (LV "b3") [ (LF "p",pb4ar) , (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LF "o31")) ] pb4af = PartSub (LV "b4") [ (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LV "b3")) ] pb4ar = PartSub (LV "b4") [ (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LF "s2")) ] pb5a1 = PartSub (LV "b5a") [ (LF "p",pb5b1) ] pb5b1 = PartSub (LV "b5b") [ (LF "p",pb5c1) ] pb5c1 = PartSub (LV "b5c") [ (LF "p",PartObj (LV "b5a")) ] pb3bf = PartSub (LV "b3") [ (LF "p",PartObj (LF "o31")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LV "b3")) , (LF "p",pb4bf) ] pb3br = PartSub (LV "b3") [ (LF "p",pb4br) , (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LF "o31")) ] pb4bf = PartSub (LV "b4") [ (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LV "b5b")) ] pb4br = PartSub (LV "b4") [ (LF "p",PartObj (LV "b5b")) , (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LF "s2")) ] pb5a2 = PartSub (LV "b5a") [ (LF "p",PartObj (LV "b5b")) ] pb5b2 = PartSub (LV "b5b") [ (LF "p",pb5c2) ] pb5c2 = PartSub (LV "b5c") [ (LF "p",pb5a2) ] pb5a3 = PartSub (LV "b5a") [ (LF "p",pb5b3) ] pb5b3 = PartSub (LV "b5b") [ (LF "p",PartObj (LV "b5c")) ] pb5c3 = PartSub (LV "b5c") [ (LF "p",pb5a3) ] testPartition11 = testEq "testPartition11" pp1 (partitionGraph pa1) testPartition12 = testEq "testPartition12" pp2f (partitionGraph pa2) testPartition13 = testEq "testPartition13" pp3f (partitionGraph pa3) testPartition14 = testEq "testPartition15" pp4f (partitionGraph pa4) testPartition15 = testEq "testPartition14" pp5f (partitionGraph pa5) testPartition16 = testEq "testPartition16" pp6f (partitionGraph pa6) testPartition21 = testEq "testPartition21" pp1 (partitionGraph $ reverse pa1) testPartition22 = testEq "testPartition22" pp2r (partitionGraph $ reverse pa2) testPartition23 = testEq "testPartition23" pp3r (partitionGraph $ reverse pa3) testPartition24 = testEq "testPartition24" pp4r (partitionGraph $ reverse pa4) testPartition25 = testEq "testPartition25" pp5r (partitionGraph $ reverse pa5) testPartition26 = testEq "testPartition26" pp6r (partitionGraph $ reverse pa6) testPartition31 = testEqv "testPartition31" pa1 (getArcs pp1) testPartition32 = testEqv "testPartition32" pa2 (getArcs pp2f) testPartition33 = testEqv "testPartition33" pa3 (getArcs pp3f) testPartition34 = testEqv "testPartition35" pa4 (getArcs pp4f) testPartition35 = testEqv "testPartition34" pa5 (getArcs pp5f) testPartition36 = testEqv "testPartition36" pa6 (getArcs pp6f) testPartition41 = testEqv "testPartition41" pa1 (getArcs pp1 ) testPartition42 = testEqv "testPartition42" pa2 (getArcs pp2r) testPartition43 = testEqv "testPartition43" pa3 (getArcs pp3r) testPartition44 = testEqv "testPartition44" pa4 (getArcs pp4r) testPartition45 = testEqv "testPartition45" pa5 (getArcs pp5r) testPartition46 = testEqv "testPartition46" pa6 (getArcs pp6r) testPartition51 = testEqv "testPartition51" [] (comparePartitions pp1 pp1) testPartition52 = testEqv "testPartition52" [] (comparePartitions pp2f pp2r) testPartition53 = testEqv "testPartition53" [] (comparePartitions pp3f pp3r) testPartition54 = testEqv "testPartition54" [] (comparePartitions pp4f pp4r) testPartition55 = testEqv "testPartition55" [] (comparePartitions pp5f pp5r) testPartition56 = testEqv "testPartition56" [] (comparePartitions pp6f pp6r) testPartition57 = testEqv "testPartition57" [(Nothing,Just $ PartSub (LV "b3") [(LF "p",pb4af)])] (comparePartitions pp3f pp4f) testPartition58 = testEqv "testPartition58" [(Nothing,Just pb5a1)] (comparePartitions pp4f pp5f) testPartition59 = testEqv "testPartition59" [(Nothing,Just $ PartSub (LV "b4") [(LF "p",PartObj (LV "b5b"))])] (comparePartitions pp5f pp6f) testPartitionSuite = TestList [ testPartition11 , testPartition12 , testPartition13 , testPartition14 , testPartition15 , testPartition16 , testPartition21 , testPartition22 , testPartition23 , testPartition24 , testPartition25 , testPartition26 , testPartition31 , testPartition32 , testPartition33 , testPartition34 , testPartition35 , testPartition36 , testPartition41 , testPartition42 , testPartition43 , testPartition44 , testPartition45 , testPartition46 , testPartition51 , testPartition52 , testPartition53 , testPartition54 , testPartition55 , testPartition56 , testPartition57 , testPartition58 , testPartition59 ] ------------------------------------------------------------ GraphPartition compare test with partial matching ------------------------------------------------------------ pgc1a = PartitionedGraph [ c11, c12a ] pgc1b = PartitionedGraph [ c11, c12b ] c11 = PartSub (LF "s1") [ (LF "p11",PartObj (LF "o11")) ] c12a = PartSub (LF "s2") [ (LF "p21",c13a) , (LF "p22",PartObj (LF "o22")) ] c12b = PartSub (LF "s2") [ (LF "p22",PartObj (LF "o22")) , (LF "p21",c13b) ] c13a = PartSub (LV "b3") [ (LF "p31",PartObj (LF "o31")) , (LF "p33",PartObj (LF "o33a")) ] c13b = PartSub (LV "b3") [ (LF "p31",PartObj (LF "o31")) , (LF "p33",PartObj (LF "o33b")) ] testCompare01 = testEqv "testCompare01" [(Just (PartObj (LF "o33a")),Just (PartObj (LF "o33b")))] (comparePartitions pgc1a pgc1b) testCompareSuite = TestList [ testCompare01 ] ------------------------------------------------------------ -- All tests ------------------------------------------------------------ allTests = TestList [ testBasicSuite , testPartitionSuite , testCompareSuite ] main = runTestTT allTests runTestFile t = do h <- openFile "a.tmp" WriteMode runTestText (putTextToHandle h False) t hClose h tf = runTestFile tt = runTestTT -------------------------------------------------------------------------------- -- Copyright ( c ) 2003 , . All rights reserved . -- This file is part of Swish . -- Swish is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or -- (at your option) any later version. -- Swish 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 Swish ; if not , write to : The Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA -- -------------------------------------------------------------------------------- $ Source : /file / / HaskellRDF / GraphPartitionTest.hs , v $ $ Author : $ Revision : 1.2 $ -- $Log: GraphPartitionTest.hs,v $ -- Revision 1.2 2004/02/10 20:24:48 graham -- Graph difference code now works. -- Revision 1.1 2004/02/09 22:22:44 graham -- Graph matching updates: change return value to give some indication -- of the extent match achieved in the case of no match. Added new module GraphPartition and test cases . -- Add VehicleCapcity demonstration script.
null
https://raw.githubusercontent.com/amccausl/Swish/9a7356300960c62e3f0468067bda0c34ee3606bd/Swish/HaskellRDF/GraphPartitionTest.hs
haskell
------------------------------------------------------------------------------ See end of this file for licence information. ------------------------------------------------------------------------------ | Module : GraphPartitionTest Stability : provisional Portability : H98 This module contains test cases for graph partitioning logic. ------------------------------------------------------------------------------ WNH , setArcs, getArcs, add, delete, extract, labels WNH FIX testNe, ---------------------------------------------------------- Basic GraphPartition tests ---------------------------------------------------------- WNH FIX testBasic06 = testNe "testBasic06" gp2 gp3 testBasic07 = testNe "testBasic07" gp3 gp4 WNH FIX testBasic36 = testNotEqv "testBasic36" (getArcs gp2) (getArcs gp3) WNH FIX, testBasic06 WNH FIX, testBasic07 WNH FIX, testBasic36 ---------------------------------------------------------- Creating GraphPartition tests ---------------------------------------------------------- ---------------------------------------------------------- ---------------------------------------------------------- ---------------------------------------------------------- All tests ---------------------------------------------------------- ------------------------------------------------------------------------------ (at your option) any later version. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ $Log: GraphPartitionTest.hs,v $ Revision 1.2 2004/02/10 20:24:48 graham Graph difference code now works. Graph matching updates: change return value to give some indication of the extent match achieved in the case of no match. Add VehicleCapcity demonstration script.
$ I d : GraphPartitionTest.hs , v 1.2 2004/02/10 20:24:48 graham Exp $ Copyright ( c ) 2003 , . All rights reserved . Copyright : ( c ) 2003 , License : GPL V2 Maintainer : module Swish . HaskellRDF.GraphPartitionTest where import Swish.HaskellRDF.GraphPartition ( PartitionedGraph(..), getArcs , GraphPartition(..), node, toArcs , partitionGraph, comparePartitions ) import Swish.HaskellRDF.GraphClass ( Label(..) , Arc(..), arcSubj, arcPred, arcObj, arc, arcToTriple, arcFromTriple , , arcLabels ) import Swish.HaskellRDF.GraphMem ( GraphMem ( .. ) ( LabelMem(..) , labelIsVar, labelHash ) import Swish.HaskellUtils.TestHelpers ( test, testEq, testLe, testGe, testElem , testJust, testNothing , testEqv, WNH FIXtestNotEqv , testEqv2, testHasEqv, testMaybeEqv ) import Swish.HaskellUtils.ListHelpers ( equiv ) import Test.HUnit ( Test(TestCase,TestList,TestLabel) , Assertion , assertBool, assertEqual, assertString, assertFailure , runTestTT, runTestText, putTextToHandle ) import System.IO ( Handle, IOMode(WriteMode) , openFile, hClose, hPutStr, hPutStrLn ) import Control.Monad ( unless ) import Data.List ( sort, union, intersect ) import Data.Maybe ( isJust, fromJust, fromMaybe ) gp1 = PartitionedGraph [ p11 ] gp2 = PartitionedGraph [ p11, p12 ] gp3 = PartitionedGraph [ p11, p13 ] gp4 = PartitionedGraph [ p11, p14 ] gp5 = PartitionedGraph [ p11, p12, p15 ] p11 = PartSub (LF "s1") [ (LF "p11",PartObj (LF "o11")) ] p12 = PartSub (LF "s2") [ (LF "p21",PartObj (LF "o21")) , (LF "p22",PartObj (LF "o22")) ] p13 = PartSub (LF "s3") [ (LF "p31",PartObj (LF "o31")) , (LF "p32",p12) , (LF "p33",PartObj (LF "s3")) ] p14 = PartSub (LF "s3") [ (LF "p31",PartObj (LF "o31")) , (LF "p33",PartObj (LF "s3")) , (LF "p32",p12) ] p15 = PartSub (LF "s3") [ (LF "p31",PartObj (LF "o31")) , (LF "p32",PartObj (LF "s2")) , (LF "p33",PartObj (LF "s3")) ] ga1 = [ Arc (LF "s1") (LF "p11") (LF "o11") ] ga2 = [ Arc (LF "s1") (LF "p11") (LF "o11") , Arc (LF "s2") (LF "p21") (LF "o21") , Arc (LF "s2") (LF "p22") (LF "o22") ] ga3 = [ Arc (LF "s1") (LF "p11") (LF "o11") , Arc (LF "s3") (LF "p31") (LF "o31") , Arc (LF "s3") (LF "p32") (LF "s2") , Arc (LF "s2") (LF "p21") (LF "o21") , Arc (LF "s2") (LF "p22") (LF "o22") , Arc (LF "s3") (LF "p33") (LF "s3") ] ga4 = [ Arc (LF "s1") (LF "p11") (LF "o11") , Arc (LF "s3") (LF "p31") (LF "o31") , Arc (LF "s3") (LF "p33") (LF "s3") , Arc (LF "s3") (LF "p32") (LF "s2") , Arc (LF "s2") (LF "p21") (LF "o21") , Arc (LF "s2") (LF "p22") (LF "o22") ] ga5 = [ Arc (LF "s1") (LF "p11") (LF "o11") , Arc (LF "s2") (LF "p21") (LF "o21") , Arc (LF "s2") (LF "p22") (LF "o22") , Arc (LF "s3") (LF "p31") (LF "o31") , Arc (LF "s3") (LF "p32") (LF "s2") , Arc (LF "s3") (LF "p33") (LF "s3") ] testBasic01 = testEq "testBasic01" gp1 gp1 testBasic02 = testEq "testBasic02" gp2 gp2 testBasic03 = testEq "testBasic03" gp3 gp3 testBasic04 = testEq "testBasic04" gp4 gp4 testBasic05 = testEq "testBasic05" gp5 gp5 testBasic11 = testEq "testBasic11" "PartitionedGraph [(!s1 !p11 !o11)]" (show gp1) testBasic12 = testEq "testBasic12" ( "PartitionedGraph "++ "[(!s1 !p11 !o11)"++ ",(!s2 !p21 !o21 ; !p22 !o22)"++ "]" ) (show gp2) testBasic13 = testEq "testBasic13" ( "PartitionedGraph "++ "[(!s1 !p11 !o11)"++ ",(!s3 !p31 !o31 ; !p32 (!s2 !p21 !o21 ; !p22 !o22) ; !p33 !s3)"++ "]" ) (show gp3) testBasic14 = testEq "testBasic14" ( "PartitionedGraph "++ "[(!s1 !p11 !o11)"++ ",(!s3 !p31 !o31 ; !p33 !s3 ; !p32 (!s2 !p21 !o21 ; !p22 !o22))"++ "]" ) (show gp4) testBasic15 = testEq "testBasic15" ( "PartitionedGraph "++ "[(!s1 !p11 !o11)"++ ",(!s2 !p21 !o21 ; !p22 !o22)"++ ",(!s3 !p31 !o31 ; !p32 !s2 ; !p33 !s3)"++ "]" ) (show gp5) testBasic21 = testEq "testBasic21" (LF "s1") (node p11) testBasic22 = testEq "testBasic22" (LF "s2") (node p12) testBasic23 = testEq "testBasic23" (LF "s3") (node p13) testBasic24 = testEq "testBasic24" (LF "s3") (node p14) testBasic25 = testEq "testBasic25" (LF "s3") (node p15) testBasic31 = testEq "testBasic31" ga1 (getArcs gp1) testBasic32 = testEq "testBasic32" ga2 (getArcs gp2) testBasic33 = testEq "testBasic33" ga3 (getArcs gp3) testBasic34 = testEq "testBasic34" ga4 (getArcs gp4) testBasic35 = testEq "testBasic35" ga5 (getArcs gp5) testBasic37 = testEqv "testBasic37" (getArcs gp3) (getArcs gp4) testBasic38 = testEqv "testBasic38" (getArcs gp3) (getArcs gp5) testBasicSuite = TestList [ testBasic01 , testBasic02 , testBasic03 , testBasic04 , testBasic05 , testBasic11 , testBasic12 , testBasic13 , testBasic14 , testBasic15 , testBasic21 , testBasic22 , testBasic23 , testBasic24 , testBasic25 , testBasic31 , testBasic32 , testBasic33 , testBasic34 , testBasic35 , testBasic37 , testBasic38 ] pa1 = [ Arc (LF "s1") (LF "p") (LF "o11") ] pa2 = [ Arc (LF "s1") (LF "p") (LF "o11") , Arc (LF "s2") (LF "p1") (LF "o21") , Arc (LF "s2") (LF "p2") (LF "o22") ] pa3 = [ Arc (LF "s1") (LF "p") (LF "o11") , Arc (LF "s2") (LF "p1") (LF "o21") , Arc (LF "s2") (LF "p2") (LF "o22") , Arc (LV "b3") (LF "p") (LF "o31") , Arc (LV "b3") (LF "p") (LF "s2") , Arc (LV "b3") (LF "p") (LV "b3") ] pa4 = [ Arc (LF "s1") (LF "p") (LF "o11") , Arc (LF "s2") (LF "p1") (LF "o21") , Arc (LF "s2") (LF "p2") (LF "o22") , Arc (LV "b3") (LF "p") (LF "o31") , Arc (LV "b3") (LF "p") (LF "s2") , Arc (LV "b3") (LF "p") (LV "b3") , Arc (LV "b3") (LF "p") (LV "b4") , Arc (LV "b4") (LF "p") (LF "s2") , Arc (LV "b4") (LF "p") (LV "b3") ] pa5 = [ Arc (LF "s1") (LF "p") (LF "o11") , Arc (LF "s2") (LF "p1") (LF "o21") , Arc (LF "s2") (LF "p2") (LF "o22") , Arc (LV "b3") (LF "p") (LF "o31") , Arc (LV "b3") (LF "p") (LF "s2") , Arc (LV "b3") (LF "p") (LV "b3") , Arc (LV "b3") (LF "p") (LV "b4") , Arc (LV "b4") (LF "p") (LF "s2") , Arc (LV "b4") (LF "p") (LV "b3") , Arc (LV "b5a") (LF "p") (LV "b5b") , Arc (LV "b5b") (LF "p") (LV "b5c") , Arc (LV "b5c") (LF "p") (LV "b5a") ] pa6 = [ Arc (LF "s1") (LF "p") (LF "o11") , Arc (LF "s2") (LF "p1") (LF "o21") , Arc (LF "s2") (LF "p2") (LF "o22") , Arc (LV "b3") (LF "p") (LF "o31") , Arc (LV "b3") (LF "p") (LF "s2") , Arc (LV "b3") (LF "p") (LV "b3") , Arc (LV "b3") (LF "p") (LV "b4") , Arc (LV "b4") (LF "p") (LF "s2") , Arc (LV "b4") (LF "p") (LV "b3") , Arc (LV "b4") (LF "p") (LV "b5b") , Arc (LV "b5a") (LF "p") (LV "b5b") , Arc (LV "b5b") (LF "p") (LV "b5c") , Arc (LV "b5c") (LF "p") (LV "b5a") ] pp1 = PartitionedGraph [ ps1 ] pp2f = PartitionedGraph [ ps1, ps2f ] pp2r = PartitionedGraph [ ps2r, ps1 ] pp3f = PartitionedGraph [ ps1, ps2f, pb3f ] pp3r = PartitionedGraph [ ps2r, ps1, pb3r ] pp4f = PartitionedGraph [ ps1, ps2f, pb3af ] pp4r = PartitionedGraph [ ps2r, ps1, pb3ar ] pp5f = PartitionedGraph [ ps1, ps2f, pb3af, pb5a1 ] pp5r = PartitionedGraph [ ps2r, ps1, pb3ar, pb5c3 ] pp6f = PartitionedGraph [ ps1, ps2f, pb3bf, pb5b2 ] pp6r = PartitionedGraph [ ps2r, ps1, pb5b2, pb3br ] ps1 = PartSub (LF "s1") [ (LF "p",PartObj (LF "o11")) ] ps2f = PartSub (LF "s2") [ (LF "p1",PartObj (LF "o21")) , (LF "p2",PartObj (LF "o22")) ] ps2r = PartSub (LF "s2") [ (LF "p2",PartObj (LF "o22")) , (LF "p1",PartObj (LF "o21")) ] pb3f = PartSub (LV "b3") [ (LF "p",PartObj (LF "o31")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LV "b3")) ] pb3r = PartSub (LV "b3") [ (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LF "o31")) ] pb3af = PartSub (LV "b3") [ (LF "p",PartObj (LF "o31")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LV "b3")) , (LF "p",pb4af) ] pb3ar = PartSub (LV "b3") [ (LF "p",pb4ar) , (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LF "o31")) ] pb4af = PartSub (LV "b4") [ (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LV "b3")) ] pb4ar = PartSub (LV "b4") [ (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LF "s2")) ] pb5a1 = PartSub (LV "b5a") [ (LF "p",pb5b1) ] pb5b1 = PartSub (LV "b5b") [ (LF "p",pb5c1) ] pb5c1 = PartSub (LV "b5c") [ (LF "p",PartObj (LV "b5a")) ] pb3bf = PartSub (LV "b3") [ (LF "p",PartObj (LF "o31")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LV "b3")) , (LF "p",pb4bf) ] pb3br = PartSub (LV "b3") [ (LF "p",pb4br) , (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LF "o31")) ] pb4bf = PartSub (LV "b4") [ (LF "p",PartObj (LF "s2")) , (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LV "b5b")) ] pb4br = PartSub (LV "b4") [ (LF "p",PartObj (LV "b5b")) , (LF "p",PartObj (LV "b3")) , (LF "p",PartObj (LF "s2")) ] pb5a2 = PartSub (LV "b5a") [ (LF "p",PartObj (LV "b5b")) ] pb5b2 = PartSub (LV "b5b") [ (LF "p",pb5c2) ] pb5c2 = PartSub (LV "b5c") [ (LF "p",pb5a2) ] pb5a3 = PartSub (LV "b5a") [ (LF "p",pb5b3) ] pb5b3 = PartSub (LV "b5b") [ (LF "p",PartObj (LV "b5c")) ] pb5c3 = PartSub (LV "b5c") [ (LF "p",pb5a3) ] testPartition11 = testEq "testPartition11" pp1 (partitionGraph pa1) testPartition12 = testEq "testPartition12" pp2f (partitionGraph pa2) testPartition13 = testEq "testPartition13" pp3f (partitionGraph pa3) testPartition14 = testEq "testPartition15" pp4f (partitionGraph pa4) testPartition15 = testEq "testPartition14" pp5f (partitionGraph pa5) testPartition16 = testEq "testPartition16" pp6f (partitionGraph pa6) testPartition21 = testEq "testPartition21" pp1 (partitionGraph $ reverse pa1) testPartition22 = testEq "testPartition22" pp2r (partitionGraph $ reverse pa2) testPartition23 = testEq "testPartition23" pp3r (partitionGraph $ reverse pa3) testPartition24 = testEq "testPartition24" pp4r (partitionGraph $ reverse pa4) testPartition25 = testEq "testPartition25" pp5r (partitionGraph $ reverse pa5) testPartition26 = testEq "testPartition26" pp6r (partitionGraph $ reverse pa6) testPartition31 = testEqv "testPartition31" pa1 (getArcs pp1) testPartition32 = testEqv "testPartition32" pa2 (getArcs pp2f) testPartition33 = testEqv "testPartition33" pa3 (getArcs pp3f) testPartition34 = testEqv "testPartition35" pa4 (getArcs pp4f) testPartition35 = testEqv "testPartition34" pa5 (getArcs pp5f) testPartition36 = testEqv "testPartition36" pa6 (getArcs pp6f) testPartition41 = testEqv "testPartition41" pa1 (getArcs pp1 ) testPartition42 = testEqv "testPartition42" pa2 (getArcs pp2r) testPartition43 = testEqv "testPartition43" pa3 (getArcs pp3r) testPartition44 = testEqv "testPartition44" pa4 (getArcs pp4r) testPartition45 = testEqv "testPartition45" pa5 (getArcs pp5r) testPartition46 = testEqv "testPartition46" pa6 (getArcs pp6r) testPartition51 = testEqv "testPartition51" [] (comparePartitions pp1 pp1) testPartition52 = testEqv "testPartition52" [] (comparePartitions pp2f pp2r) testPartition53 = testEqv "testPartition53" [] (comparePartitions pp3f pp3r) testPartition54 = testEqv "testPartition54" [] (comparePartitions pp4f pp4r) testPartition55 = testEqv "testPartition55" [] (comparePartitions pp5f pp5r) testPartition56 = testEqv "testPartition56" [] (comparePartitions pp6f pp6r) testPartition57 = testEqv "testPartition57" [(Nothing,Just $ PartSub (LV "b3") [(LF "p",pb4af)])] (comparePartitions pp3f pp4f) testPartition58 = testEqv "testPartition58" [(Nothing,Just pb5a1)] (comparePartitions pp4f pp5f) testPartition59 = testEqv "testPartition59" [(Nothing,Just $ PartSub (LV "b4") [(LF "p",PartObj (LV "b5b"))])] (comparePartitions pp5f pp6f) testPartitionSuite = TestList [ testPartition11 , testPartition12 , testPartition13 , testPartition14 , testPartition15 , testPartition16 , testPartition21 , testPartition22 , testPartition23 , testPartition24 , testPartition25 , testPartition26 , testPartition31 , testPartition32 , testPartition33 , testPartition34 , testPartition35 , testPartition36 , testPartition41 , testPartition42 , testPartition43 , testPartition44 , testPartition45 , testPartition46 , testPartition51 , testPartition52 , testPartition53 , testPartition54 , testPartition55 , testPartition56 , testPartition57 , testPartition58 , testPartition59 ] GraphPartition compare test with partial matching pgc1a = PartitionedGraph [ c11, c12a ] pgc1b = PartitionedGraph [ c11, c12b ] c11 = PartSub (LF "s1") [ (LF "p11",PartObj (LF "o11")) ] c12a = PartSub (LF "s2") [ (LF "p21",c13a) , (LF "p22",PartObj (LF "o22")) ] c12b = PartSub (LF "s2") [ (LF "p22",PartObj (LF "o22")) , (LF "p21",c13b) ] c13a = PartSub (LV "b3") [ (LF "p31",PartObj (LF "o31")) , (LF "p33",PartObj (LF "o33a")) ] c13b = PartSub (LV "b3") [ (LF "p31",PartObj (LF "o31")) , (LF "p33",PartObj (LF "o33b")) ] testCompare01 = testEqv "testCompare01" [(Just (PartObj (LF "o33a")),Just (PartObj (LF "o33b")))] (comparePartitions pgc1a pgc1b) testCompareSuite = TestList [ testCompare01 ] allTests = TestList [ testBasicSuite , testPartitionSuite , testCompareSuite ] main = runTestTT allTests runTestFile t = do h <- openFile "a.tmp" WriteMode runTestText (putTextToHandle h False) t hClose h tf = runTestFile tt = runTestTT Copyright ( c ) 2003 , . All rights reserved . This file is part of Swish . Swish is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or Swish is distributed in the hope that it will be useful , You should have received a copy of the GNU General Public License along with Swish ; if not , write to : The Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA $ Source : /file / / HaskellRDF / GraphPartitionTest.hs , v $ $ Author : $ Revision : 1.2 $ Revision 1.1 2004/02/09 22:22:44 graham Added new module GraphPartition and test cases .
e1d08de796496ef63f10fc551e20ff315692907e75f6d437cc0ac6c80b7b964d
mdebski/zpf-outsidein
Main.hs
import OIDefs import OIMonad import ConGen import Solve import OutsideIn import Control.Exception import Control.Monad stdlib :: OIExpr -> OIExpr stdlib = foldl (.) id -- Some types and standard functions, without real implementations, but with correct types. [ LetD "T" [(-1)] [ ("T1", [], [CEq (TVar (-1)) TBool], [TInt]), ("T2", [], [], [TVar (-1)]) ] , LetD "Pair" [(-2), (-3)] [ ("MkP", [], [], [TVar (-2), TVar (-3)]) ] , LetD "S" [] [ ("MkS", [(-4), (-5)], [CEq (TVar (-4)) (TVar (-5))], [TVar (-4), TVar (-5)]) ] , LetA "neg" (TFun TInt TInt) $ Lam "_1" $ Var "_1" , LetA "not" (TFun TBool TBool) $ Lam "_2" $ Var "_2" , LetA "and" (TFun TBool (TFun TBool TBool)) $ Lam "_3" $ Lam "_4" $ Var "_4" , LetA "plus" (TFun TInt (TFun TInt TInt)) $ Lam "_5" $ Lam "_6" $ Var "_5" , LetA "cmp" (TFun TInt (TFun TInt TBool)) $ Lam "_7" $ Lam "_8" $ BLit True , LetA "id" (TForall [(-11)] [] (TFun (TVar (-11)) (TVar (-11)))) $ Lam "_9" $ Var "_9" , LetA "cmpa" (TForall [(-12)] [] (TFun (TVar (-12)) (TFun (TVar (-12)) TBool))) $ Lam "_10" $ Lam "_11" $ BLit False ] apps :: OIExpr -> [OIExpr] -> OIExpr -- apply function to subsequent arguments apps f [] = f apps f (e:es) = apps (App f e) es mkp = apps (Con "MkP") expr0 :: OIExpr let id2 = \x - > x in i d ( i d id2 ) expr0 = Let "id2" (Lam "x" (Var "x")) (App (App (Var "id") (Var "id")) (Var "id2")) expr1 :: OIExpr let g = \x - > x & & True in g expr1 = Let "g" ((Lam "x") (App (App (Var "and") (Var "x")) (BLit True))) (Var "g") expr2 :: OIExpr expr2 = mkp [ILit 3, BLit True] expr3 :: OIExpr expr3 = mkp [(Var "id"), (BLit True)] expr4 :: OIExpr expr4 = apps (Var "cmp") [ILit 1, ILit 2] expr5 :: OIExpr expr5 = mkp [mkp [ILit 3, mkp [expr4, ILit 4]], (Var "id")] expr01 :: OIExpr expr01 = apps (Con "MkP") [expr0, expr1] gadt_expr1_simp :: OIExpr gadt_expr1_simp = (Lam "x" $ Case (Var "x") [ (PCon "T1" ["n"], App (App (Var "cmp") (Var "n")) (ILit 0)) ]) gadt_expr1 :: OIExpr gadt_expr1 = Let "f1" gadt_expr1_simp (Var "f1") gadt_expr2_simp :: OIExpr gadt_expr2_simp = Lam "x" $ Case (Var "x") [ (PCon "T1" ["n"], App (App (Var "cmp") (Var "n")) (ILit 0)) , (PCon "T2" ["a"], (BLit True)) ] gadt_expr2 :: OIExpr gadt_expr2 = Let "f2" gadt_expr2_simp (Var "f2") gadt_expr3 :: OIExpr gadt_expr3 = Let "h1" (Lam "x" $ Lam "y" $ Case (Var "y") [ (PCon "T1" ["n"], App (App (Var "and") (Var "x")) (App (App (Var "cmp") (Var "n")) (ILit 0))) , (PCon "T2" ["a"], (BLit True)) ]) (Var "h1") gadt_expr4 :: OIExpr gadt_expr4 = Let "h2" (Lam "x" $ Lam "y" $ Case (Var "y") [ (PCon "T1" ["n"], App (App (Var "and") (Var "x")) (App (App (Var "cmp") (Var "n")) (ILit 0))) , (PCon "T2" ["a"], App (Var "not") (Var "x")) ]) (Var "h2") main = do putStrLn "==================== simple ===================" outsideIn (stdlib expr01) putStrLn "==================== f1 (FAILS) ===================" catch (void $ outsideIn (stdlib gadt_expr1)) (\e -> putStrLn $ "FAILED: " ++ (show (e::SomeException))) putStrLn "==================== f2 ===================" outsideIn (stdlib gadt_expr2) putStrLn "==================== h1 (FAILS) ===================" catch (void $ outsideIn (stdlib gadt_expr3)) (\e -> putStrLn $ "FAILED: " ++ (show (e::SomeException))) putStrLn "==================== h2 ===================" outsideIn (stdlib gadt_expr4)
null
https://raw.githubusercontent.com/mdebski/zpf-outsidein/10b0ed6c4346b348c188c582a4b0381d34f28f2d/Main.hs
haskell
Some types and standard functions, without real implementations, but with correct types. apply function to subsequent arguments
import OIDefs import OIMonad import ConGen import Solve import OutsideIn import Control.Exception import Control.Monad stdlib :: OIExpr -> OIExpr stdlib = foldl (.) id [ LetD "T" [(-1)] [ ("T1", [], [CEq (TVar (-1)) TBool], [TInt]), ("T2", [], [], [TVar (-1)]) ] , LetD "Pair" [(-2), (-3)] [ ("MkP", [], [], [TVar (-2), TVar (-3)]) ] , LetD "S" [] [ ("MkS", [(-4), (-5)], [CEq (TVar (-4)) (TVar (-5))], [TVar (-4), TVar (-5)]) ] , LetA "neg" (TFun TInt TInt) $ Lam "_1" $ Var "_1" , LetA "not" (TFun TBool TBool) $ Lam "_2" $ Var "_2" , LetA "and" (TFun TBool (TFun TBool TBool)) $ Lam "_3" $ Lam "_4" $ Var "_4" , LetA "plus" (TFun TInt (TFun TInt TInt)) $ Lam "_5" $ Lam "_6" $ Var "_5" , LetA "cmp" (TFun TInt (TFun TInt TBool)) $ Lam "_7" $ Lam "_8" $ BLit True , LetA "id" (TForall [(-11)] [] (TFun (TVar (-11)) (TVar (-11)))) $ Lam "_9" $ Var "_9" , LetA "cmpa" (TForall [(-12)] [] (TFun (TVar (-12)) (TFun (TVar (-12)) TBool))) $ Lam "_10" $ Lam "_11" $ BLit False ] apps :: OIExpr -> [OIExpr] -> OIExpr apps f [] = f apps f (e:es) = apps (App f e) es mkp = apps (Con "MkP") expr0 :: OIExpr let id2 = \x - > x in i d ( i d id2 ) expr0 = Let "id2" (Lam "x" (Var "x")) (App (App (Var "id") (Var "id")) (Var "id2")) expr1 :: OIExpr let g = \x - > x & & True in g expr1 = Let "g" ((Lam "x") (App (App (Var "and") (Var "x")) (BLit True))) (Var "g") expr2 :: OIExpr expr2 = mkp [ILit 3, BLit True] expr3 :: OIExpr expr3 = mkp [(Var "id"), (BLit True)] expr4 :: OIExpr expr4 = apps (Var "cmp") [ILit 1, ILit 2] expr5 :: OIExpr expr5 = mkp [mkp [ILit 3, mkp [expr4, ILit 4]], (Var "id")] expr01 :: OIExpr expr01 = apps (Con "MkP") [expr0, expr1] gadt_expr1_simp :: OIExpr gadt_expr1_simp = (Lam "x" $ Case (Var "x") [ (PCon "T1" ["n"], App (App (Var "cmp") (Var "n")) (ILit 0)) ]) gadt_expr1 :: OIExpr gadt_expr1 = Let "f1" gadt_expr1_simp (Var "f1") gadt_expr2_simp :: OIExpr gadt_expr2_simp = Lam "x" $ Case (Var "x") [ (PCon "T1" ["n"], App (App (Var "cmp") (Var "n")) (ILit 0)) , (PCon "T2" ["a"], (BLit True)) ] gadt_expr2 :: OIExpr gadt_expr2 = Let "f2" gadt_expr2_simp (Var "f2") gadt_expr3 :: OIExpr gadt_expr3 = Let "h1" (Lam "x" $ Lam "y" $ Case (Var "y") [ (PCon "T1" ["n"], App (App (Var "and") (Var "x")) (App (App (Var "cmp") (Var "n")) (ILit 0))) , (PCon "T2" ["a"], (BLit True)) ]) (Var "h1") gadt_expr4 :: OIExpr gadt_expr4 = Let "h2" (Lam "x" $ Lam "y" $ Case (Var "y") [ (PCon "T1" ["n"], App (App (Var "and") (Var "x")) (App (App (Var "cmp") (Var "n")) (ILit 0))) , (PCon "T2" ["a"], App (Var "not") (Var "x")) ]) (Var "h2") main = do putStrLn "==================== simple ===================" outsideIn (stdlib expr01) putStrLn "==================== f1 (FAILS) ===================" catch (void $ outsideIn (stdlib gadt_expr1)) (\e -> putStrLn $ "FAILED: " ++ (show (e::SomeException))) putStrLn "==================== f2 ===================" outsideIn (stdlib gadt_expr2) putStrLn "==================== h1 (FAILS) ===================" catch (void $ outsideIn (stdlib gadt_expr3)) (\e -> putStrLn $ "FAILED: " ++ (show (e::SomeException))) putStrLn "==================== h2 ===================" outsideIn (stdlib gadt_expr4)
6df3d2a6999a32e8557e834a8d64dac6bd02cf160123e6c4948a758c9da818ed
vaibhavsagar/experiments
XmlNode.hs
module Dotnet.System.Xml.XmlNode ( module Dotnet.System.Xml.XmlNode, module Dotnet.System.Xml.XmlNodeTy ) where import Dotnet import qualified Dotnet.System.Object import Dotnet.System.Xml.XmlNodeTy import Dotnet . System . Xml . . XPathNavigator import Dotnet.System.Xml.XmlElementTy import Dotnet.System.Xml.XmlWriter import Dotnet.System.Xml.XmlDocumentTy import Dotnet.System.Xml.XmlAttributeCollectionTy import Dotnet.System.Xml.XmlNodeList import Dotnet.System.Xml.XmlNodeType import Dotnet.System.Xml.XmlNamespaceManager import Dotnet.System.Collections.IEnumerator foreign import dotnet " method Dotnet . System . Xml . XmlNode . CreateNavigator " createNavigator : : XmlNode obj - > IO ( Dotnet . System . Xml . . XPathNavigator . XPathNavigator a0 ) foreign import dotnet "method Dotnet.System.Xml.XmlNode.CreateNavigator" createNavigator :: XmlNode obj -> IO (Dotnet.System.Xml.XPath.XPathNavigator.XPathNavigator a0) -} foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Item" get_Item :: String -> String -> XmlNode obj -> IO (Dotnet.System.Xml.XmlElementTy.XmlElement a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Item" get_Item_1 :: String -> XmlNode obj -> IO (Dotnet.System.Xml.XmlElementTy.XmlElement a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.GetPrefixOfNamespace" getPrefixOfNamespace :: String -> XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.GetNamespaceOfPrefix" getNamespaceOfPrefix :: String -> XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.RemoveAll" removeAll :: XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.WriteContentTo" writeContentTo :: Dotnet.System.Xml.XmlWriter.XmlWriter a0 -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.WriteTo" writeTo :: Dotnet.System.Xml.XmlWriter.XmlWriter a0 -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_BaseURI" get_BaseURI :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.set_InnerXml" set_InnerXml :: String -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_InnerXml" get_InnerXml :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_OuterXml" get_OuterXml :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.set_InnerText" set_InnerText :: String -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_InnerText" get_InnerText :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.Clone" clone :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_IsReadOnly" get_IsReadOnly :: XmlNode obj -> IO (Bool) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_LocalName" get_LocalName :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.set_Prefix" set_Prefix :: String -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Prefix" get_Prefix :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_NamespaceURI" get_NamespaceURI :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.Supports" supports :: String -> String -> XmlNode obj -> IO (Bool) foreign import dotnet "method Dotnet.System.Xml.XmlNode.Normalize" normalize :: XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.CloneNode" cloneNode :: Bool -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_HasChildNodes" get_HasChildNodes :: XmlNode obj -> IO (Bool) foreign import dotnet "method Dotnet.System.Xml.XmlNode.AppendChild" appendChild :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.PrependChild" prependChild :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.RemoveChild" removeChild :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.ReplaceChild" replaceChild :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> Dotnet.System.Xml.XmlNode.XmlNode a1 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.InsertAfter" insertAfter :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> Dotnet.System.Xml.XmlNode.XmlNode a1 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.InsertBefore" insertBefore :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> Dotnet.System.Xml.XmlNode.XmlNode a1 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_LastChild" get_LastChild :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_FirstChild" get_FirstChild :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_OwnerDocument" get_OwnerDocument :: XmlNode obj -> IO (Dotnet.System.Xml.XmlDocumentTy.XmlDocument a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Attributes" get_Attributes :: XmlNode obj -> IO (Dotnet.System.Xml.XmlAttributeCollectionTy.XmlAttributeCollection a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_NextSibling" get_NextSibling :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_PreviousSibling" get_PreviousSibling :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_ChildNodes" get_ChildNodes :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNodeList.XmlNodeList a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_ParentNode" get_ParentNode :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_NodeType" get_NodeType :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNodeType.XmlNodeType a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.set_Value" set_Value :: String -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Value" get_Value :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Name" get_Name :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.SelectSingleNode" selectSingleNode :: String -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.SelectSingleNode" selectSingleNode_1 :: String -> Dotnet.System.Xml.XmlNamespaceManager.XmlNamespaceManager a1 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.SelectNodes" selectNodes :: String -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNodeList.XmlNodeList a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.SelectNodes" selectNodes_1 :: String -> Dotnet.System.Xml.XmlNamespaceManager.XmlNamespaceManager a1 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNodeList.XmlNodeList a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.GetEnumerator" getEnumerator :: XmlNode obj -> IO (Dotnet.System.Collections.IEnumerator.IEnumerator a0)
null
https://raw.githubusercontent.com/vaibhavsagar/experiments/378d7ba97eabfc7bbeaa4116380369ea6612bfeb/hugs/dotnet/lib/Dotnet/System/Xml/XmlNode.hs
haskell
module Dotnet.System.Xml.XmlNode ( module Dotnet.System.Xml.XmlNode, module Dotnet.System.Xml.XmlNodeTy ) where import Dotnet import qualified Dotnet.System.Object import Dotnet.System.Xml.XmlNodeTy import Dotnet . System . Xml . . XPathNavigator import Dotnet.System.Xml.XmlElementTy import Dotnet.System.Xml.XmlWriter import Dotnet.System.Xml.XmlDocumentTy import Dotnet.System.Xml.XmlAttributeCollectionTy import Dotnet.System.Xml.XmlNodeList import Dotnet.System.Xml.XmlNodeType import Dotnet.System.Xml.XmlNamespaceManager import Dotnet.System.Collections.IEnumerator foreign import dotnet " method Dotnet . System . Xml . XmlNode . CreateNavigator " createNavigator : : XmlNode obj - > IO ( Dotnet . System . Xml . . XPathNavigator . XPathNavigator a0 ) foreign import dotnet "method Dotnet.System.Xml.XmlNode.CreateNavigator" createNavigator :: XmlNode obj -> IO (Dotnet.System.Xml.XPath.XPathNavigator.XPathNavigator a0) -} foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Item" get_Item :: String -> String -> XmlNode obj -> IO (Dotnet.System.Xml.XmlElementTy.XmlElement a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Item" get_Item_1 :: String -> XmlNode obj -> IO (Dotnet.System.Xml.XmlElementTy.XmlElement a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.GetPrefixOfNamespace" getPrefixOfNamespace :: String -> XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.GetNamespaceOfPrefix" getNamespaceOfPrefix :: String -> XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.RemoveAll" removeAll :: XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.WriteContentTo" writeContentTo :: Dotnet.System.Xml.XmlWriter.XmlWriter a0 -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.WriteTo" writeTo :: Dotnet.System.Xml.XmlWriter.XmlWriter a0 -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_BaseURI" get_BaseURI :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.set_InnerXml" set_InnerXml :: String -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_InnerXml" get_InnerXml :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_OuterXml" get_OuterXml :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.set_InnerText" set_InnerText :: String -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_InnerText" get_InnerText :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.Clone" clone :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_IsReadOnly" get_IsReadOnly :: XmlNode obj -> IO (Bool) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_LocalName" get_LocalName :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.set_Prefix" set_Prefix :: String -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Prefix" get_Prefix :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_NamespaceURI" get_NamespaceURI :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.Supports" supports :: String -> String -> XmlNode obj -> IO (Bool) foreign import dotnet "method Dotnet.System.Xml.XmlNode.Normalize" normalize :: XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.CloneNode" cloneNode :: Bool -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_HasChildNodes" get_HasChildNodes :: XmlNode obj -> IO (Bool) foreign import dotnet "method Dotnet.System.Xml.XmlNode.AppendChild" appendChild :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.PrependChild" prependChild :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.RemoveChild" removeChild :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.ReplaceChild" replaceChild :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> Dotnet.System.Xml.XmlNode.XmlNode a1 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.InsertAfter" insertAfter :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> Dotnet.System.Xml.XmlNode.XmlNode a1 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.InsertBefore" insertBefore :: Dotnet.System.Xml.XmlNode.XmlNode a0 -> Dotnet.System.Xml.XmlNode.XmlNode a1 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_LastChild" get_LastChild :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_FirstChild" get_FirstChild :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_OwnerDocument" get_OwnerDocument :: XmlNode obj -> IO (Dotnet.System.Xml.XmlDocumentTy.XmlDocument a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Attributes" get_Attributes :: XmlNode obj -> IO (Dotnet.System.Xml.XmlAttributeCollectionTy.XmlAttributeCollection a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_NextSibling" get_NextSibling :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_PreviousSibling" get_PreviousSibling :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_ChildNodes" get_ChildNodes :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNodeList.XmlNodeList a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_ParentNode" get_ParentNode :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_NodeType" get_NodeType :: XmlNode obj -> IO (Dotnet.System.Xml.XmlNodeType.XmlNodeType a0) foreign import dotnet "method Dotnet.System.Xml.XmlNode.set_Value" set_Value :: String -> XmlNode obj -> IO (()) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Value" get_Value :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.get_Name" get_Name :: XmlNode obj -> IO (String) foreign import dotnet "method Dotnet.System.Xml.XmlNode.SelectSingleNode" selectSingleNode :: String -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.SelectSingleNode" selectSingleNode_1 :: String -> Dotnet.System.Xml.XmlNamespaceManager.XmlNamespaceManager a1 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNode.XmlNode a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.SelectNodes" selectNodes :: String -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNodeList.XmlNodeList a1) foreign import dotnet "method Dotnet.System.Xml.XmlNode.SelectNodes" selectNodes_1 :: String -> Dotnet.System.Xml.XmlNamespaceManager.XmlNamespaceManager a1 -> XmlNode obj -> IO (Dotnet.System.Xml.XmlNodeList.XmlNodeList a2) foreign import dotnet "method Dotnet.System.Xml.XmlNode.GetEnumerator" getEnumerator :: XmlNode obj -> IO (Dotnet.System.Collections.IEnumerator.IEnumerator a0)
849f62a221d405a4b17131d64679ad1d82359860305ccc46b498ce2e3a5b47f9
penpot/penpot
fills.cljs
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. ;; ;; Copyright (c) KALEIDOS INC (ns app.main.ui.shapes.fills (:require [app.common.data :as d] [app.common.data.macros :as dm] [app.common.geom.shapes :as gsh] [app.config :as cfg] [app.main.ui.shapes.attrs :as attrs] [app.main.ui.shapes.embed :as embed] [app.main.ui.shapes.gradients :as grad] [app.util.object :as obj] [rumext.v2 :as mf])) (mf/defc fills {::mf/wrap-props false} [props] (let [shape (obj/get props "shape") render-id (obj/get props "render-id")] (when (or (some? (:fill-image shape)) (#{:image :text} (:type shape)) (> (count (:fills shape)) 1) (some :fill-color-gradient (:fills shape))) (let [{:keys [x y width height]} (:selrect shape) {:keys [metadata]} shape has-image? (or metadata (:fill-image shape)) uri (cond metadata (cfg/resolve-file-media metadata) (:fill-image shape) (cfg/resolve-file-media (:fill-image shape))) embed (embed/use-data-uris [uri]) transform (gsh/transform-str shape) ;; When true the image has not loaded yet loading? (and (some? uri) (not (contains? embed uri))) pattern-attrs (cond-> #js {:patternUnits "userSpaceOnUse" :x x :y y :height height :width width :data-loading loading?} (= :path (:type shape)) (obj/set! "patternTransform" transform)) type (:type shape)] (for [[shape-index shape] (d/enumerate (or (:position-data shape) [shape]))] [:* {:key (dm/str shape-index)} (for [[fill-index value] (-> (d/enumerate (:fills shape [])) reverse)] (when (some? (:fill-color-gradient value)) (let [props #js {:id (dm/str "fill-color-gradient_" render-id "_" fill-index) :key (dm/str fill-index) :gradient (:fill-color-gradient value) :shape shape}] (case (d/name (:type (:fill-color-gradient value))) "linear" [:> grad/linear-gradient props] "radial" [:> grad/radial-gradient props])))) (let [fill-id (dm/str "fill-" shape-index "-" render-id)] [:> :pattern (-> (obj/clone pattern-attrs) (obj/set! "id" fill-id)) [:g (for [[fill-index value] (-> (d/enumerate (:fills shape [])) reverse)] [:> :rect (-> (attrs/extract-fill-attrs value render-id fill-index type) (obj/set! "key" (dm/str fill-index)) (obj/set! "width" width) (obj/set! "height" height))]) (when has-image? [:image {:href (or (:data-uri shape) (get embed uri uri)) :preserveAspectRatio "none" :width width :height height}])]])])))))
null
https://raw.githubusercontent.com/penpot/penpot/5463671db13441ba3f730a34118547d34a5a36f1/frontend/src/app/main/ui/shapes/fills.cljs
clojure
Copyright (c) KALEIDOS INC When true the image has not loaded yet
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns app.main.ui.shapes.fills (:require [app.common.data :as d] [app.common.data.macros :as dm] [app.common.geom.shapes :as gsh] [app.config :as cfg] [app.main.ui.shapes.attrs :as attrs] [app.main.ui.shapes.embed :as embed] [app.main.ui.shapes.gradients :as grad] [app.util.object :as obj] [rumext.v2 :as mf])) (mf/defc fills {::mf/wrap-props false} [props] (let [shape (obj/get props "shape") render-id (obj/get props "render-id")] (when (or (some? (:fill-image shape)) (#{:image :text} (:type shape)) (> (count (:fills shape)) 1) (some :fill-color-gradient (:fills shape))) (let [{:keys [x y width height]} (:selrect shape) {:keys [metadata]} shape has-image? (or metadata (:fill-image shape)) uri (cond metadata (cfg/resolve-file-media metadata) (:fill-image shape) (cfg/resolve-file-media (:fill-image shape))) embed (embed/use-data-uris [uri]) transform (gsh/transform-str shape) loading? (and (some? uri) (not (contains? embed uri))) pattern-attrs (cond-> #js {:patternUnits "userSpaceOnUse" :x x :y y :height height :width width :data-loading loading?} (= :path (:type shape)) (obj/set! "patternTransform" transform)) type (:type shape)] (for [[shape-index shape] (d/enumerate (or (:position-data shape) [shape]))] [:* {:key (dm/str shape-index)} (for [[fill-index value] (-> (d/enumerate (:fills shape [])) reverse)] (when (some? (:fill-color-gradient value)) (let [props #js {:id (dm/str "fill-color-gradient_" render-id "_" fill-index) :key (dm/str fill-index) :gradient (:fill-color-gradient value) :shape shape}] (case (d/name (:type (:fill-color-gradient value))) "linear" [:> grad/linear-gradient props] "radial" [:> grad/radial-gradient props])))) (let [fill-id (dm/str "fill-" shape-index "-" render-id)] [:> :pattern (-> (obj/clone pattern-attrs) (obj/set! "id" fill-id)) [:g (for [[fill-index value] (-> (d/enumerate (:fills shape [])) reverse)] [:> :rect (-> (attrs/extract-fill-attrs value render-id fill-index type) (obj/set! "key" (dm/str fill-index)) (obj/set! "width" width) (obj/set! "height" height))]) (when has-image? [:image {:href (or (:data-uri shape) (get embed uri uri)) :preserveAspectRatio "none" :width width :height height}])]])])))))
c0432c774ca3c8b261001a1a44525b8a79ff3a626a983e7760872d59a5d98e1f
dgiot/dgiot
dgiot_tables.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(dgiot_tables). -export([ new/1 , new/2 ]). -export([ lookup_value/2 , lookup_value/3 ]). -export([delete/1]). %% Create an ets table. -spec(new(atom()) -> ok). new(Tab) -> new(Tab, []). %% Create a named_table ets. -spec(new(atom(), list()) -> ok). new(Tab, Opts) -> case ets:info(Tab, name) of undefined -> _ = ets:new(Tab, lists:usort([named_table | Opts])), ok; Tab -> ok end. KV lookup -spec(lookup_value(ets:tab(), term()) -> any()). lookup_value(Tab, Key) -> lookup_value(Tab, Key, undefined). -spec(lookup_value(ets:tab(), term(), any()) -> any()). lookup_value(Tab, Key, Def) -> try ets:lookup_element(Tab, Key, 2) catch error:badarg -> Def end. %% Delete the ets table. -spec(delete(ets:tab()) -> ok). delete(Tab) -> case ets:info(Tab, name) of undefined -> ok; Tab -> ets:delete(Tab), ok end.
null
https://raw.githubusercontent.com/dgiot/dgiot/c9f2f78af71692ba532e4806621b611db2afe0c9/apps/dgiot/src/storage/dgiot_tables.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. -------------------------------------------------------------------- Create an ets table. Create a named_table ets. Delete the ets table.
Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(dgiot_tables). -export([ new/1 , new/2 ]). -export([ lookup_value/2 , lookup_value/3 ]). -export([delete/1]). -spec(new(atom()) -> ok). new(Tab) -> new(Tab, []). -spec(new(atom(), list()) -> ok). new(Tab, Opts) -> case ets:info(Tab, name) of undefined -> _ = ets:new(Tab, lists:usort([named_table | Opts])), ok; Tab -> ok end. KV lookup -spec(lookup_value(ets:tab(), term()) -> any()). lookup_value(Tab, Key) -> lookup_value(Tab, Key, undefined). -spec(lookup_value(ets:tab(), term(), any()) -> any()). lookup_value(Tab, Key, Def) -> try ets:lookup_element(Tab, Key, 2) catch error:badarg -> Def end. -spec(delete(ets:tab()) -> ok). delete(Tab) -> case ets:info(Tab, name) of undefined -> ok; Tab -> ets:delete(Tab), ok end.
6c947259fdcc55374f074ac7c0c8de16537c4fc5dfb6ef8941a804c6f47a7d5d
modular-macros/ocaml-macros
t090-acc7.ml
open Lib;; let x = true in let y = false in let z = false in let a = false in let b = false in let c = false in let d = false in let e = false in (); if not x then raise Not_found ;; * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 9 CONST1 10 PUSHCONST0 11 PUSHCONST0 12 PUSHCONST0 13 PUSHCONST0 14 PUSHCONST0 15 PUSHCONST0 16 PUSHCONST0 17 PUSHCONST0 18 ACC7 19 BOOLNOT 20 BRANCHIFNOT 27 22 GETGLOBAL Not_found 24 MAKEBLOCK1 0 26 RAISE 27 POP 8 29 ATOM0 30 SETGLOBAL T090 - acc7 32 STOP * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 SETGLOBAL Lib 9 CONST1 10 PUSHCONST0 11 PUSHCONST0 12 PUSHCONST0 13 PUSHCONST0 14 PUSHCONST0 15 PUSHCONST0 16 PUSHCONST0 17 PUSHCONST0 18 ACC7 19 BOOLNOT 20 BRANCHIFNOT 27 22 GETGLOBAL Not_found 24 MAKEBLOCK1 0 26 RAISE 27 POP 8 29 ATOM0 30 SETGLOBAL T090-acc7 32 STOP **)
null
https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/tool-ocaml/t090-acc7.ml
ocaml
open Lib;; let x = true in let y = false in let z = false in let a = false in let b = false in let c = false in let d = false in let e = false in (); if not x then raise Not_found ;; * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 9 CONST1 10 PUSHCONST0 11 PUSHCONST0 12 PUSHCONST0 13 PUSHCONST0 14 PUSHCONST0 15 PUSHCONST0 16 PUSHCONST0 17 PUSHCONST0 18 ACC7 19 BOOLNOT 20 BRANCHIFNOT 27 22 GETGLOBAL Not_found 24 MAKEBLOCK1 0 26 RAISE 27 POP 8 29 ATOM0 30 SETGLOBAL T090 - acc7 32 STOP * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 SETGLOBAL Lib 9 CONST1 10 PUSHCONST0 11 PUSHCONST0 12 PUSHCONST0 13 PUSHCONST0 14 PUSHCONST0 15 PUSHCONST0 16 PUSHCONST0 17 PUSHCONST0 18 ACC7 19 BOOLNOT 20 BRANCHIFNOT 27 22 GETGLOBAL Not_found 24 MAKEBLOCK1 0 26 RAISE 27 POP 8 29 ATOM0 30 SETGLOBAL T090-acc7 32 STOP **)
a49c3c36edf8229212d49b6a866260bdd87cfbb1141d573bddbc53952f0c9ba5
Toxaris/pts
Telescope.hs
module PTS.Syntax.Telescope ( Telescope , foldTelescope ) where import PTS.Syntax.Names type Telescope t = [([Name], t)] | a telescope in a binder with multiple arguments like this : -- -- > lambda (x1 : e1) (x2 x3 : e2) . e -- -- to a series of nested single argument binders: -- -- > lambda x1 : e1 . lambda x2 : e2 . lambda x3 : e2 . e foldTelescope :: (Name -> a -> b -> b) -> Telescope a -> b -> b foldTelescope mk [] body = body foldTelescope mk (([], _) : args) body = foldTelescope mk args body foldTelescope mk (((n : ns), t) : args) body = mk n t (foldTelescope mk ((ns, t) : args) body)
null
https://raw.githubusercontent.com/Toxaris/pts/1700024f47bc9d28528b68fc815d2421f5d25b84/src-lib/PTS/Syntax/Telescope.hs
haskell
> lambda (x1 : e1) (x2 x3 : e2) . e to a series of nested single argument binders: > lambda x1 : e1 . lambda x2 : e2 . lambda x3 : e2 . e
module PTS.Syntax.Telescope ( Telescope , foldTelescope ) where import PTS.Syntax.Names type Telescope t = [([Name], t)] | a telescope in a binder with multiple arguments like this : foldTelescope :: (Name -> a -> b -> b) -> Telescope a -> b -> b foldTelescope mk [] body = body foldTelescope mk (([], _) : args) body = foldTelescope mk args body foldTelescope mk (((n : ns), t) : args) body = mk n t (foldTelescope mk ((ns, t) : args) body)
fa6007b9cbd8e56786e8775be47154a5eb1cda8bf981b78a05c662805ffb825f
graninas/Functional-Design-and-Architecture
Domain.hs
module Andromeda.LogicControl.Domain where type Message = String type Key = String data LogicFailure = LogicFailure String deriving (Show, Eq, Ord)
null
https://raw.githubusercontent.com/graninas/Functional-Design-and-Architecture/f19c1fc5c28014545d4098edf8fc438d93e66048/Second-Edition-Manning-Publications/BookSamples/CH06/Section6p2/src/Andromeda/LogicControl/Domain.hs
haskell
module Andromeda.LogicControl.Domain where type Message = String type Key = String data LogicFailure = LogicFailure String deriving (Show, Eq, Ord)
822719f5c6f0319e8ec7a71c072aed1776d6b69e97c5caea468ca7ceb1a3b0c2
skanev/playground
71-tests.scm
(require rackunit rackunit/text-ui) (load "../71.scm") (define sicp-3.71-tests (test-suite "Tests for SICP exercise 3.71" (check-equal? (stream-take (ramanujan-numbers) 6) '(1729 4104 13832 20683 32832 39312)) )) (run-tests sicp-3.71-tests)
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/03/tests/71-tests.scm
scheme
(require rackunit rackunit/text-ui) (load "../71.scm") (define sicp-3.71-tests (test-suite "Tests for SICP exercise 3.71" (check-equal? (stream-take (ramanujan-numbers) 6) '(1729 4104 13832 20683 32832 39312)) )) (run-tests sicp-3.71-tests)
d8082ad53d467656421360135a8b0188828b75ccbe26a446b6a79d40f259965b
kadena-io/chainweaver
Legacy.hs
# LANGUAGE TemplateHaskell # module Frontend.UI.Dialogs.Receive.Legacy ( ReceiveFromLegacy (..) , HasReceiveFromLegacy (..) , NonBIP32TransferInfo (..) , HasNonBIP32TransferInfo (..) , uiReceiveFromLegacy , receiveFromLegacySubmitTransfer , receiveFromLegacySubmit ) where import Control.Applicative (liftA3) import Control.Lens (view, _1, _2, _3, (^.)) import Control.Error (hush) import Data.Decimal import Data.Either (isLeft) import Data.Bifunctor (first) import Data.Text (Text) import Data.Aeson ((.=), object,toJSON) import qualified Data.Aeson as Aeson import qualified Data.Text as T import qualified Data.Map as Map import qualified Data.HashMap.Lazy as HM import Language.Javascript.JSaddle.Types (MonadJSM) import Reflex import Reflex.Dom.Core import Kadena.SigningApi (DappCap (..)) import Pact.Types.PactValue (PactValue (..)) import Pact.Types.Exp (Literal (LString, LDecimal)) import Pact.Types.Capability (SigCapability (..)) import Pact.Types.Term (QualifiedName (..)) import Pact.Types.ChainMeta (PublicMeta (..), TTLSeconds) import Pact.Types.Runtime (GasLimit, GasPrice (..)) import qualified Pact.Types.Scheme as PactScheme import Common.Foundation import Frontend.UI.Widgets import Frontend.UI.Modal import Frontend.UI.DeploymentSettings (uiMetaData, defaultGASCapability) import Frontend.UI.Widgets.Helpers (dialogSectionHeading) import Frontend.UI.Dialogs.DeployConfirmation (CanSubmitTransaction, TransactionSubmitFeedback (..), submitTransactionWithFeedback) import Frontend.Crypto.Class (PactKey (..), HasCrypto, cryptoGenPubKeyFromPrivate) import Frontend.Wallet import Frontend.Log import Frontend.Network data NonBIP32TransferInfo = NonBIP32TransferInfo { _legacyTransferInfo_account :: AccountName , _legacyTransferInfo_amount :: Decimal , _legacyTransferInfo_pactKey :: PactKey } makePactLenses ''NonBIP32TransferInfo data ReceiveFromLegacy t conf = ReceiveFromLegacy { _receiveFromLegacy_conf :: conf , _receiveFromLegacy_ttl :: Dynamic t TTLSeconds , _receiveFromLegacy_gasLimit :: Dynamic t GasLimit , _receiveFromLegacy_gasPrice :: Dynamic t GasPrice , _receiveFromLegacy_transferInfo :: Dynamic t (Maybe NonBIP32TransferInfo) } makePactLenses ''ReceiveFromLegacy uiReceiveFromLegacyAccount :: ( MonadWidget t m , HasCrypto key (Performable m) ) => m (Dynamic t (Maybe NonBIP32TransferInfo)) uiReceiveFromLegacyAccount = do (_, mAccountName) <- uiAccountNameInput "Account Name" True Nothing never noValidation let onDeriveKey (_, onKey) = pure $ ffor onKey $ \case Left e -> PopoverState_Error $ T.takeWhile (/= ':') e Right _ -> PopoverState_Disabled uiInputPrivKey cfg = do inputE <- uiInputElement cfg onKey <- performEvent $ deriveKeyPair <$> _inputElement_input inputE pure (inputE, onKey) (_, onKeyPair) <- mkLabeledInput True "Private Key" ( uiInputWithPopover uiInputPrivKey (_inputElement_raw . fst) onDeriveKey ) def keyPair <- holdDyn Nothing $ hush <$> onKeyPair amount <- fmap hush . view _2 <$> mkLabeledInput True "Amount" uiAmountInput def pure $ (liftA3 . liftA3) NonBIP32TransferInfo mAccountName amount keyPair where deriveKeyPair :: (HasCrypto key m, MonadJSM m) => Text -> m (Either Text PactKey) deriveKeyPair = fmap (first T.pack) . cryptoGenPubKeyFromPrivate PactScheme.ED25519 uiReceiveFromLegacy :: ( MonadWidget t m , HasCrypto key (Performable m) , HasNetwork model t , HasNetworkCfg mConf t , Monoid mConf ) => model -> m (ReceiveFromLegacy t mConf) uiReceiveFromLegacy model = do dialogSectionHeading mempty "Sender Details" transferInfo0 <- divClass "group" uiReceiveFromLegacyAccount dialogSectionHeading mempty "Transaction Settings" (conf0, ttl0, gaslimit0, gasPrice) <- divClass "group" $ uiMetaData model Nothing Nothing pure $ ReceiveFromLegacy conf0 ttl0 gaslimit0 gasPrice transferInfo0 receiveFromLegacySubmitTransfer :: ( Monoid mConf , CanSubmitTransaction t m , HasCrypto key m , HasLogger model t , HasTransactionLogger m ) => model -> Event t () -> AccountName -> ChainId -> TTLSeconds -> GasLimit -> ([Either a NodeInfo], PublicMeta, NetworkName) -> NonBIP32TransferInfo -> Workflow t m (mConf, Event t ()) receiveFromLegacySubmitTransfer m onClose account chain ttl gasLimit netInfo transferInfo = let sender = _legacyTransferInfo_account transferInfo amount = _legacyTransferInfo_amount transferInfo code = T.unwords $ [ "(coin.transfer" , tshow $ unAccountName $ sender , tshow $ unAccountName account , tshow amount , ")" ] in receiveFromLegacySubmit m onClose account chain ttl gasLimit netInfo transferInfo code mempty receiveFromLegacySubmit :: ( Monoid mConf , CanSubmitTransaction t m , HasCrypto key m , HasLogger model t , HasTransactionLogger m ) => model -> Event t () -> AccountName -> ChainId -> TTLSeconds -> GasLimit -> ([Either a NodeInfo], PublicMeta, NetworkName) -> NonBIP32TransferInfo -> Text -> HM.HashMap Text Aeson.Value -> Workflow t m (mConf, Event t ()) receiveFromLegacySubmit m onClose account chain ttl gasLimit netInfo transferInfo code payload = Workflow $ do let sender = _legacyTransferInfo_account transferInfo senderKey = _legacyTransferInfo_pactKey transferInfo senderPubKey = _pactKey_publicKey senderKey amount = _legacyTransferInfo_amount transferInfo transferSigCap = SigCapability { _scName = QualifiedName { _qnQual = "coin" , _qnName = "TRANSFER" , _qnInfo = def } , _scArgs = [ PLiteral $ LString $ unAccountName sender , PLiteral $ LString $ unAccountName account , PLiteral $ LDecimal amount ] } pkCaps = Map.singleton senderPubKey [ _dappCap_cap defaultGASCapability , transferSigCap ] pm = (netInfo ^. _2) { _pmChainId = chain , _pmSender = unAccountName sender , _pmGasLimit = gasLimit , _pmTTL = ttl } cmd <- buildCmdWithPactKey senderKey Nothing (netInfo ^. _3) pm [KeyPair (_pactKey_publicKey senderKey) Nothing] [] code payload pkCaps txnSubFeedback <- elClass "div" "modal__main transaction_details" $ submitTransactionWithFeedback m cmd sender chain (netInfo ^. _1) let isDisabled = maybe True isLeft <$> _transactionSubmitFeedback_message txnSubFeedback done <- modalFooter $ uiButtonDyn (def & uiButtonCfg_class .~ "button_type_confirm" & uiButtonCfg_disabled .~ isDisabled) (text "Done") pure ( (mempty, done <> onClose) , never )
null
https://raw.githubusercontent.com/kadena-io/chainweaver/c7077869f7aca07697ef9e129a1948889e821e26/frontend/src/Frontend/UI/Dialogs/Receive/Legacy.hs
haskell
# LANGUAGE TemplateHaskell # module Frontend.UI.Dialogs.Receive.Legacy ( ReceiveFromLegacy (..) , HasReceiveFromLegacy (..) , NonBIP32TransferInfo (..) , HasNonBIP32TransferInfo (..) , uiReceiveFromLegacy , receiveFromLegacySubmitTransfer , receiveFromLegacySubmit ) where import Control.Applicative (liftA3) import Control.Lens (view, _1, _2, _3, (^.)) import Control.Error (hush) import Data.Decimal import Data.Either (isLeft) import Data.Bifunctor (first) import Data.Text (Text) import Data.Aeson ((.=), object,toJSON) import qualified Data.Aeson as Aeson import qualified Data.Text as T import qualified Data.Map as Map import qualified Data.HashMap.Lazy as HM import Language.Javascript.JSaddle.Types (MonadJSM) import Reflex import Reflex.Dom.Core import Kadena.SigningApi (DappCap (..)) import Pact.Types.PactValue (PactValue (..)) import Pact.Types.Exp (Literal (LString, LDecimal)) import Pact.Types.Capability (SigCapability (..)) import Pact.Types.Term (QualifiedName (..)) import Pact.Types.ChainMeta (PublicMeta (..), TTLSeconds) import Pact.Types.Runtime (GasLimit, GasPrice (..)) import qualified Pact.Types.Scheme as PactScheme import Common.Foundation import Frontend.UI.Widgets import Frontend.UI.Modal import Frontend.UI.DeploymentSettings (uiMetaData, defaultGASCapability) import Frontend.UI.Widgets.Helpers (dialogSectionHeading) import Frontend.UI.Dialogs.DeployConfirmation (CanSubmitTransaction, TransactionSubmitFeedback (..), submitTransactionWithFeedback) import Frontend.Crypto.Class (PactKey (..), HasCrypto, cryptoGenPubKeyFromPrivate) import Frontend.Wallet import Frontend.Log import Frontend.Network data NonBIP32TransferInfo = NonBIP32TransferInfo { _legacyTransferInfo_account :: AccountName , _legacyTransferInfo_amount :: Decimal , _legacyTransferInfo_pactKey :: PactKey } makePactLenses ''NonBIP32TransferInfo data ReceiveFromLegacy t conf = ReceiveFromLegacy { _receiveFromLegacy_conf :: conf , _receiveFromLegacy_ttl :: Dynamic t TTLSeconds , _receiveFromLegacy_gasLimit :: Dynamic t GasLimit , _receiveFromLegacy_gasPrice :: Dynamic t GasPrice , _receiveFromLegacy_transferInfo :: Dynamic t (Maybe NonBIP32TransferInfo) } makePactLenses ''ReceiveFromLegacy uiReceiveFromLegacyAccount :: ( MonadWidget t m , HasCrypto key (Performable m) ) => m (Dynamic t (Maybe NonBIP32TransferInfo)) uiReceiveFromLegacyAccount = do (_, mAccountName) <- uiAccountNameInput "Account Name" True Nothing never noValidation let onDeriveKey (_, onKey) = pure $ ffor onKey $ \case Left e -> PopoverState_Error $ T.takeWhile (/= ':') e Right _ -> PopoverState_Disabled uiInputPrivKey cfg = do inputE <- uiInputElement cfg onKey <- performEvent $ deriveKeyPair <$> _inputElement_input inputE pure (inputE, onKey) (_, onKeyPair) <- mkLabeledInput True "Private Key" ( uiInputWithPopover uiInputPrivKey (_inputElement_raw . fst) onDeriveKey ) def keyPair <- holdDyn Nothing $ hush <$> onKeyPair amount <- fmap hush . view _2 <$> mkLabeledInput True "Amount" uiAmountInput def pure $ (liftA3 . liftA3) NonBIP32TransferInfo mAccountName amount keyPair where deriveKeyPair :: (HasCrypto key m, MonadJSM m) => Text -> m (Either Text PactKey) deriveKeyPair = fmap (first T.pack) . cryptoGenPubKeyFromPrivate PactScheme.ED25519 uiReceiveFromLegacy :: ( MonadWidget t m , HasCrypto key (Performable m) , HasNetwork model t , HasNetworkCfg mConf t , Monoid mConf ) => model -> m (ReceiveFromLegacy t mConf) uiReceiveFromLegacy model = do dialogSectionHeading mempty "Sender Details" transferInfo0 <- divClass "group" uiReceiveFromLegacyAccount dialogSectionHeading mempty "Transaction Settings" (conf0, ttl0, gaslimit0, gasPrice) <- divClass "group" $ uiMetaData model Nothing Nothing pure $ ReceiveFromLegacy conf0 ttl0 gaslimit0 gasPrice transferInfo0 receiveFromLegacySubmitTransfer :: ( Monoid mConf , CanSubmitTransaction t m , HasCrypto key m , HasLogger model t , HasTransactionLogger m ) => model -> Event t () -> AccountName -> ChainId -> TTLSeconds -> GasLimit -> ([Either a NodeInfo], PublicMeta, NetworkName) -> NonBIP32TransferInfo -> Workflow t m (mConf, Event t ()) receiveFromLegacySubmitTransfer m onClose account chain ttl gasLimit netInfo transferInfo = let sender = _legacyTransferInfo_account transferInfo amount = _legacyTransferInfo_amount transferInfo code = T.unwords $ [ "(coin.transfer" , tshow $ unAccountName $ sender , tshow $ unAccountName account , tshow amount , ")" ] in receiveFromLegacySubmit m onClose account chain ttl gasLimit netInfo transferInfo code mempty receiveFromLegacySubmit :: ( Monoid mConf , CanSubmitTransaction t m , HasCrypto key m , HasLogger model t , HasTransactionLogger m ) => model -> Event t () -> AccountName -> ChainId -> TTLSeconds -> GasLimit -> ([Either a NodeInfo], PublicMeta, NetworkName) -> NonBIP32TransferInfo -> Text -> HM.HashMap Text Aeson.Value -> Workflow t m (mConf, Event t ()) receiveFromLegacySubmit m onClose account chain ttl gasLimit netInfo transferInfo code payload = Workflow $ do let sender = _legacyTransferInfo_account transferInfo senderKey = _legacyTransferInfo_pactKey transferInfo senderPubKey = _pactKey_publicKey senderKey amount = _legacyTransferInfo_amount transferInfo transferSigCap = SigCapability { _scName = QualifiedName { _qnQual = "coin" , _qnName = "TRANSFER" , _qnInfo = def } , _scArgs = [ PLiteral $ LString $ unAccountName sender , PLiteral $ LString $ unAccountName account , PLiteral $ LDecimal amount ] } pkCaps = Map.singleton senderPubKey [ _dappCap_cap defaultGASCapability , transferSigCap ] pm = (netInfo ^. _2) { _pmChainId = chain , _pmSender = unAccountName sender , _pmGasLimit = gasLimit , _pmTTL = ttl } cmd <- buildCmdWithPactKey senderKey Nothing (netInfo ^. _3) pm [KeyPair (_pactKey_publicKey senderKey) Nothing] [] code payload pkCaps txnSubFeedback <- elClass "div" "modal__main transaction_details" $ submitTransactionWithFeedback m cmd sender chain (netInfo ^. _1) let isDisabled = maybe True isLeft <$> _transactionSubmitFeedback_message txnSubFeedback done <- modalFooter $ uiButtonDyn (def & uiButtonCfg_class .~ "button_type_confirm" & uiButtonCfg_disabled .~ isDisabled) (text "Done") pure ( (mempty, done <> onClose) , never )
66a5d57de393493a33a518aa8053526e487acff57fed4e303a1d88cdd88e8cd4
alexandergunnarson/quantum
cpp.cljc
(ns quantum.compile.transpile.to.cpp)
null
https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/src/quantum/compile/transpile/to/cpp.cljc
clojure
(ns quantum.compile.transpile.to.cpp)
38e27918b4fc739ccedac8ad76120a033e9d2106d53d4100ece50fb9a5943fee
Eduap-com/WordMat
ratpow.lisp
ratpow version 0.3 4 June 2015 ;;; Copyright 2013 - 2015 ;;; Released under the LGPL () These functions operate on the * numerator * of a CRE ;;; to find the exponents in the denominator, use ratXXpow(ratdenom(...)) ratp_hipow -- highest power of the main variable in a CRE polynomial ratp_lopow -- lowest power of the main variable in a CRE polynomial ;;; ratp_coeffs -- list of powers and coefficients of the main variable ratp_dense_coeffs -- list of coefficients of the main variable , highest first ratp_dense_coeffs_lo -- list of coefficients of the main variable , lowest first To get a list of vars in a CRE , use showratvars ;;; ratp_hipow( expr, var ) => highest power of var in ratnumer(expr) ratp_hipow ( x^(5/2 ) + x^2 , x ) = > 2 ratp_hipow ( x^(5/2 ) + x^2 , sqrt(x ) ) = > 5 (defun $ratp_hipow (e v) (ratp_pow e v 'hipow)) ;;; ratp_lopow( expr, var ) => lowest power of var in ratnumer(expr) ratp_lopow ( x^(5/2 ) + x^3 , x ) = > 0 CRE is { x}^3 + { x^(1/2)}^5 * { x}^0 , where { } denotes kernels (defun $ratp_lopow (e v) (ratp_pow e v 'lopow)) ;;; ratp_coeffs( expr, var ) => list of powers/coefficients in ratnumer(expr) returned coefficients are in CRE form except for numbers ratp_coeffs ( 4*x^3 + x + sqrt(x ) , x ) = > [ [ 3,4],[1,1],[0,sqrt(x ) ] ] (defun $ratp_coeffs (e v) (ratp_pow e v 'sparse_coeffs)) ratp_dense_coeffs ( expr , var ) = > list of coefficients in ratnumer(expr ) , highest first returned coefficients are in CRE form except for numbers ratp_dense_coeffs ( 4*x^3 + x + sqrt(x ) , x ) = > [ 4,0,1,sqrt(x ) ] (defun $ratp_dense_coeffs (e v) (ratp_pow e v 'dense_coeffs)) ratp_dense_coeffs_lo ( expr , var ) = > list of coefficients in ratnumer(expr ) , lowest first returned coefficients are in CRE form except for numbers ratp_dense_coeffs_lo ( 4*x^3 + x + sqrt(x ) , x ) = > [ sqrt(x),1,0,4 ] (defun $ratp_dense_coeffs_lo (e v) (ratp_pow e v 'dense_coeffs_low)) (defun ratp_pow (e v func) (if (mbagp e) (simplify (cons (list (caar e)) (mapcar #'(lambda (i) (ratp_pow i v func)) (cdr e)))) (let* ((e ($rat (if ($taylorp e) ($ratdisrep e) e) v)) ; change main variable if necessary (mrat (car e)) (kernels (caddr mrat)) (gensyms (cadddr mrat)) (mainvar-gensym (nth (1- (length kernels)) gensyms)) (numerat (cadr e)) (res ()) (lis (if (or (pcoefp numerat) (not (eq (car numerat) mainvar-gensym))) (list 0 numerat) (cdr numerat)))) (cond ((eq func 'hipow) (car lis)) ((eq func 'lopow) (car (last lis 2))) (t (setq kernels (butlast kernels 1)) (setq mrat (list 'mrat 'simp kernels gensyms)) Putprop needed for pdisrep , but not part - rat ( mapc # ' ( lambda ( y z ) ( putprop y z ' disrep ) ) kernels ) (cond ((eq func 'sparse_coeffs) (do ((lis lis (cddr lis))) ((null lis) (cons '(mlist simp) (nreverse res))) (push (list '(mlist simp) (car lis) (part-rat mrat (cadr lis))) res))) ((memq func '(dense_coeffs dense_coeffs_low)) (do ((lis lis (cddr lis)) (pow (car lis) (1- pow))) ((null lis) (cons '(mlist simp) (if (eq func 'dense_coeffs_low) res (nreverse res)))) (while (> pow (car lis)) (push 0 res) (setq pow (1- pow))) (push (part-rat mrat (cadr lis)) res))))))))) (defun part-rat (mrat expr) (if (pcoefp expr) expr (list* mrat expr 1)))
null
https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/contrib/ratpow.lisp
lisp
Released under the LGPL () to find the exponents in the denominator, use ratXXpow(ratdenom(...)) ratp_coeffs -- list of powers and coefficients of the main variable ratp_hipow( expr, var ) => highest power of var in ratnumer(expr) ratp_lopow( expr, var ) => lowest power of var in ratnumer(expr) ratp_coeffs( expr, var ) => list of powers/coefficients in ratnumer(expr) change main variable if necessary
ratpow version 0.3 4 June 2015 Copyright 2013 - 2015 These functions operate on the * numerator * of a CRE ratp_hipow -- highest power of the main variable in a CRE polynomial ratp_lopow -- lowest power of the main variable in a CRE polynomial ratp_dense_coeffs -- list of coefficients of the main variable , highest first ratp_dense_coeffs_lo -- list of coefficients of the main variable , lowest first To get a list of vars in a CRE , use showratvars ratp_hipow ( x^(5/2 ) + x^2 , x ) = > 2 ratp_hipow ( x^(5/2 ) + x^2 , sqrt(x ) ) = > 5 (defun $ratp_hipow (e v) (ratp_pow e v 'hipow)) ratp_lopow ( x^(5/2 ) + x^3 , x ) = > 0 CRE is { x}^3 + { x^(1/2)}^5 * { x}^0 , where { } denotes kernels (defun $ratp_lopow (e v) (ratp_pow e v 'lopow)) returned coefficients are in CRE form except for numbers ratp_coeffs ( 4*x^3 + x + sqrt(x ) , x ) = > [ [ 3,4],[1,1],[0,sqrt(x ) ] ] (defun $ratp_coeffs (e v) (ratp_pow e v 'sparse_coeffs)) ratp_dense_coeffs ( expr , var ) = > list of coefficients in ratnumer(expr ) , highest first returned coefficients are in CRE form except for numbers ratp_dense_coeffs ( 4*x^3 + x + sqrt(x ) , x ) = > [ 4,0,1,sqrt(x ) ] (defun $ratp_dense_coeffs (e v) (ratp_pow e v 'dense_coeffs)) ratp_dense_coeffs_lo ( expr , var ) = > list of coefficients in ratnumer(expr ) , lowest first returned coefficients are in CRE form except for numbers ratp_dense_coeffs_lo ( 4*x^3 + x + sqrt(x ) , x ) = > [ sqrt(x),1,0,4 ] (defun $ratp_dense_coeffs_lo (e v) (ratp_pow e v 'dense_coeffs_low)) (defun ratp_pow (e v func) (if (mbagp e) (simplify (cons (list (caar e)) (mapcar #'(lambda (i) (ratp_pow i v func)) (cdr e)))) (mrat (car e)) (kernels (caddr mrat)) (gensyms (cadddr mrat)) (mainvar-gensym (nth (1- (length kernels)) gensyms)) (numerat (cadr e)) (res ()) (lis (if (or (pcoefp numerat) (not (eq (car numerat) mainvar-gensym))) (list 0 numerat) (cdr numerat)))) (cond ((eq func 'hipow) (car lis)) ((eq func 'lopow) (car (last lis 2))) (t (setq kernels (butlast kernels 1)) (setq mrat (list 'mrat 'simp kernels gensyms)) Putprop needed for pdisrep , but not part - rat ( mapc # ' ( lambda ( y z ) ( putprop y z ' disrep ) ) kernels ) (cond ((eq func 'sparse_coeffs) (do ((lis lis (cddr lis))) ((null lis) (cons '(mlist simp) (nreverse res))) (push (list '(mlist simp) (car lis) (part-rat mrat (cadr lis))) res))) ((memq func '(dense_coeffs dense_coeffs_low)) (do ((lis lis (cddr lis)) (pow (car lis) (1- pow))) ((null lis) (cons '(mlist simp) (if (eq func 'dense_coeffs_low) res (nreverse res)))) (while (> pow (car lis)) (push 0 res) (setq pow (1- pow))) (push (part-rat mrat (cadr lis)) res))))))))) (defun part-rat (mrat expr) (if (pcoefp expr) expr (list* mrat expr 1)))
993cf91865ae0e32fa78e8431f00409c4971cf4b9b1b4d9b78f690407fa6d07e
untangled-web/untangled-spec
assertions_spec.clj
(ns untangled-spec.assertions-spec (:require [clojure.spec :as s] [clojure.test :as t :refer [is]] [untangled-spec.assertions :as ae :refer [check-error check-error* parse-criteria]] [untangled-spec.contains :refer [*contains?]] [untangled-spec.core :refer [specification component behavior assertions]] [untangled-spec.impl.macros :as im] [untangled-spec.spec :as us] [untangled-spec.testing-helpers :as th]) (:import clojure.lang.ExceptionInfo)) (defn check-assertion [expected] (fn [actual] (and (->> actual first (= 'clojure.test/is)) (->> actual second (= expected))))) (defn test-triple->assertion [form] (ae/triple->assertion false (us/conform! ::ae/triple form))) (defn test-block->asserts [form] (ae/block->asserts false (us/conform! ::ae/block form))) (def test-regex #"a-simple-test-regex") (specification "check-error" (behavior "supports many syntaxes" (assertions (us/conform! ::ae/criteria 'ExceptionInfo) => [:sym 'ExceptionInfo] (us/conform! ::ae/criteria {:ex-type 'ExceptionInfo :fn even?, :regex test-regex}) => [:map {:ex-type 'ExceptionInfo :fn even? :regex test-regex}] (us/conform! ::ae/criteria ['ExceptionInfo]) => [:list {:ex-type 'ExceptionInfo}] (parse-criteria [:sym 'irr]) => {:ex-type 'irr} (parse-criteria [:w/e 'dont-care]) => 'dont-care (check-error "spec-msg1" (ex-info "foo" {}) {:ex-type ExceptionInfo}) =fn=> (*contains? {:type :pass}) (let [check #(-> % ex-data :ok)] (check-error "spec-msg2" (ex-info "foo" {:ok false}) {:fn check} '#(some fn))) =fn=> (*contains? {:type :fail :expected '#(some fn)}) (check-error "spec-msg3" (ex-info "foo" {}) {:regex #"oo"}) =fn=> (*contains? {:type :pass}))) (behavior "checks the exception is of the specified type or throws" (assertions (check-error* "msg1" (ex-info "foo" {}) clojure.lang.ExceptionInfo) =fn=> (*contains? {:type :pass :message "msg1"}) (check-error* "msg2" (ex-info "foo" {}) java.lang.Error) =fn=> (*contains? {:type :fail :extra "exception did not match type" :actual clojure.lang.ExceptionInfo :expected java.lang.Error}))) (behavior "checks the exception's message matches a regex or throws" (assertions (check-error* "msg3" (ex-info "Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn" {}) clojure.lang.ExceptionInfo #"(?i)cthulhu") =fn=> (*contains? {:type :pass}) (check-error* "msg4" (ex-info "kthxbye" {}) clojure.lang.ExceptionInfo #"cthulhu") =fn=> (*contains? {:type :fail :extra "exception's message did not match regex" :actual "kthxbye" :expected "cthulhu"}))) (behavior "checks the exception with the user's function" (let [cthulhu-bored (ex-info "Haskell 101" {:cthulhu :snores})] (assertions (check-error* "msg5" (ex-info "H.P. Lovecraft" {:cthulhu :rises}) clojure.lang.ExceptionInfo #"(?i)lovecraft" #(-> % ex-data :cthulhu (= :rises))) =fn=> (*contains? {:type :pass}) (check-error* "msg6" cthulhu-bored clojure.lang.ExceptionInfo #"Haskell" #(-> % ex-data :cthulhu (= :rises))) =fn=> (*contains? {:type :fail :actual cthulhu-bored :extra "checker function failed"}))))) (specification "triple->assertion" (behavior "checks equality with the => arrow" (assertions (test-triple->assertion '(left => right)) =fn=> (check-assertion '(= right left)))) (behavior "verifies actual with the =fn=> function" (assertions (test-triple->assertion '(left =fn=> right)) =fn=> (check-assertion '(exec right left)))) (behavior "verifies that actual threw an exception with the =throws=> arrow" (assertions (test-triple->assertion '(left =throws=> right)) =fn=> (check-assertion '(throws? false left right)))) (behavior "any other arrow, throws an ex-info" (assertions (test-triple->assertion '(left =bad-arrow=> right)) =throws=> (ExceptionInfo #"fails spec.*arrow")))) (specification "throws assertion arrow" (behavior "catches AssertionErrors" (let [f (fn [x] {:pre [(even? x)]} (inc x))] (is (thrown? AssertionError (f 1))) (is (= 3 (f 2))) (assertions (f 1) =throws=> (AssertionError #"even\? x") (f 6) => 7 (f 2) => 3)))) (defn get-exp-act [{exp :expected act :actual msg :message extra :extra} & [opt]] (case opt :all [act exp msg extra] :msg [act exp msg] :ae [act exp extra] [act exp])) (defmacro test-case [x & [opt]] `(binding [t/report identity] (get-exp-act ~(-> x test-triple->assertion) ~opt))) (specification "running assertions reports the correct data" (component "=>" (behavior "literals" (is (= [5 3] (test-case (5 => 3))))) (behavior "forms" (is (= [5 3 "(+ 3 2) => (+ 2 1)"] (test-case ((+ 3 2) => (+ 2 1)) :msg)))) (behavior "unexpected throw" (is (= ["clojure.lang.ExceptionInfo: bad {}" "(= \"good\" (throw (ex-info \"bad\" {})))" "(throw (ex-info \"bad\" {})) => good"] (mapv str (test-case ((throw (ex-info "bad" {})) => "good") :msg)))))) (component "=fn=>" (behavior "literals" (is (= [5 'even? "5 =fn=> even?"] (test-case (5 =fn=> even?) :msg)))) (behavior "lambda" (is (re-find #"even\?" (str (second (test-case (7 =fn=> #(even? %)))))))) (behavior "forms" (is (= [7 '(fn [x] (even? x))] (test-case ((+ 5 2) =fn=> (fn [x] (even? x))))))) (behavior "unexpected error" (is (= ["clojure.lang.ExceptionInfo: bad {}" "(exec even? (throw (ex-info \"bad\" {})))" "(throw (ex-info \"bad\" {})) =fn=> even?"] (mapv str (test-case ((throw (ex-info "bad" {})) =fn=> even?) :msg)))))) (component "=throws=>" (behavior "reports if the message didnt match the regex" (is (= ["foo", "asdf", "(throw (ex-info \"foo\" {})) =throws=> (clojure.lang.ExceptionInfo #\"asdf\")" "exception's message did not match regex"] (test-case ((throw (ex-info "foo" {})) =throws=> (clojure.lang.ExceptionInfo #"asdf")) :all)))) (behavior "reports if nothing was thrown" (is (= ["it to throw", "(+ 5 2) =throws=> (clojure.lang.ExceptionInfo #\"asdf\")" "Expected an error to be thrown!"] (-> ((+ 5 2) =throws=> (clojure.lang.ExceptionInfo #"asdf")) (test-case :all) rest))))) (component "block->asserts" (behavior "wraps triples in behavior do-reports" (let [reporting (th/locate `im/with-reporting (test-block->asserts '("string2" d => e)))] (is (= `(im/with-reporting {:type :behavior :string "string2"}) (take 2 reporting))))) (behavior "converts triples to assertions" (let [asserts (test-block->asserts '("string2" d => e))] (is (every? #{`t/is} (map first (drop 2 asserts)))))))) (specification "fix-conform for issue #31" (assertions (mapv (juxt :behavior (comp count :triples)) (ae/fix-conform (us/conform! ::ae/assertions '("foo" 1 => 2 "bar" 3 => 4, 5 => 6 "qux" 7 => 8, 9 => 10)))) => '[["foo" 1] ["bar" 2] ["qux" 2]]))
null
https://raw.githubusercontent.com/untangled-web/untangled-spec/0d44863f627ed7311677b438b88bd6d424249507/test/untangled_spec/assertions_spec.clj
clojure
(ns untangled-spec.assertions-spec (:require [clojure.spec :as s] [clojure.test :as t :refer [is]] [untangled-spec.assertions :as ae :refer [check-error check-error* parse-criteria]] [untangled-spec.contains :refer [*contains?]] [untangled-spec.core :refer [specification component behavior assertions]] [untangled-spec.impl.macros :as im] [untangled-spec.spec :as us] [untangled-spec.testing-helpers :as th]) (:import clojure.lang.ExceptionInfo)) (defn check-assertion [expected] (fn [actual] (and (->> actual first (= 'clojure.test/is)) (->> actual second (= expected))))) (defn test-triple->assertion [form] (ae/triple->assertion false (us/conform! ::ae/triple form))) (defn test-block->asserts [form] (ae/block->asserts false (us/conform! ::ae/block form))) (def test-regex #"a-simple-test-regex") (specification "check-error" (behavior "supports many syntaxes" (assertions (us/conform! ::ae/criteria 'ExceptionInfo) => [:sym 'ExceptionInfo] (us/conform! ::ae/criteria {:ex-type 'ExceptionInfo :fn even?, :regex test-regex}) => [:map {:ex-type 'ExceptionInfo :fn even? :regex test-regex}] (us/conform! ::ae/criteria ['ExceptionInfo]) => [:list {:ex-type 'ExceptionInfo}] (parse-criteria [:sym 'irr]) => {:ex-type 'irr} (parse-criteria [:w/e 'dont-care]) => 'dont-care (check-error "spec-msg1" (ex-info "foo" {}) {:ex-type ExceptionInfo}) =fn=> (*contains? {:type :pass}) (let [check #(-> % ex-data :ok)] (check-error "spec-msg2" (ex-info "foo" {:ok false}) {:fn check} '#(some fn))) =fn=> (*contains? {:type :fail :expected '#(some fn)}) (check-error "spec-msg3" (ex-info "foo" {}) {:regex #"oo"}) =fn=> (*contains? {:type :pass}))) (behavior "checks the exception is of the specified type or throws" (assertions (check-error* "msg1" (ex-info "foo" {}) clojure.lang.ExceptionInfo) =fn=> (*contains? {:type :pass :message "msg1"}) (check-error* "msg2" (ex-info "foo" {}) java.lang.Error) =fn=> (*contains? {:type :fail :extra "exception did not match type" :actual clojure.lang.ExceptionInfo :expected java.lang.Error}))) (behavior "checks the exception's message matches a regex or throws" (assertions (check-error* "msg3" (ex-info "Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn" {}) clojure.lang.ExceptionInfo #"(?i)cthulhu") =fn=> (*contains? {:type :pass}) (check-error* "msg4" (ex-info "kthxbye" {}) clojure.lang.ExceptionInfo #"cthulhu") =fn=> (*contains? {:type :fail :extra "exception's message did not match regex" :actual "kthxbye" :expected "cthulhu"}))) (behavior "checks the exception with the user's function" (let [cthulhu-bored (ex-info "Haskell 101" {:cthulhu :snores})] (assertions (check-error* "msg5" (ex-info "H.P. Lovecraft" {:cthulhu :rises}) clojure.lang.ExceptionInfo #"(?i)lovecraft" #(-> % ex-data :cthulhu (= :rises))) =fn=> (*contains? {:type :pass}) (check-error* "msg6" cthulhu-bored clojure.lang.ExceptionInfo #"Haskell" #(-> % ex-data :cthulhu (= :rises))) =fn=> (*contains? {:type :fail :actual cthulhu-bored :extra "checker function failed"}))))) (specification "triple->assertion" (behavior "checks equality with the => arrow" (assertions (test-triple->assertion '(left => right)) =fn=> (check-assertion '(= right left)))) (behavior "verifies actual with the =fn=> function" (assertions (test-triple->assertion '(left =fn=> right)) =fn=> (check-assertion '(exec right left)))) (behavior "verifies that actual threw an exception with the =throws=> arrow" (assertions (test-triple->assertion '(left =throws=> right)) =fn=> (check-assertion '(throws? false left right)))) (behavior "any other arrow, throws an ex-info" (assertions (test-triple->assertion '(left =bad-arrow=> right)) =throws=> (ExceptionInfo #"fails spec.*arrow")))) (specification "throws assertion arrow" (behavior "catches AssertionErrors" (let [f (fn [x] {:pre [(even? x)]} (inc x))] (is (thrown? AssertionError (f 1))) (is (= 3 (f 2))) (assertions (f 1) =throws=> (AssertionError #"even\? x") (f 6) => 7 (f 2) => 3)))) (defn get-exp-act [{exp :expected act :actual msg :message extra :extra} & [opt]] (case opt :all [act exp msg extra] :msg [act exp msg] :ae [act exp extra] [act exp])) (defmacro test-case [x & [opt]] `(binding [t/report identity] (get-exp-act ~(-> x test-triple->assertion) ~opt))) (specification "running assertions reports the correct data" (component "=>" (behavior "literals" (is (= [5 3] (test-case (5 => 3))))) (behavior "forms" (is (= [5 3 "(+ 3 2) => (+ 2 1)"] (test-case ((+ 3 2) => (+ 2 1)) :msg)))) (behavior "unexpected throw" (is (= ["clojure.lang.ExceptionInfo: bad {}" "(= \"good\" (throw (ex-info \"bad\" {})))" "(throw (ex-info \"bad\" {})) => good"] (mapv str (test-case ((throw (ex-info "bad" {})) => "good") :msg)))))) (component "=fn=>" (behavior "literals" (is (= [5 'even? "5 =fn=> even?"] (test-case (5 =fn=> even?) :msg)))) (behavior "lambda" (is (re-find #"even\?" (str (second (test-case (7 =fn=> #(even? %)))))))) (behavior "forms" (is (= [7 '(fn [x] (even? x))] (test-case ((+ 5 2) =fn=> (fn [x] (even? x))))))) (behavior "unexpected error" (is (= ["clojure.lang.ExceptionInfo: bad {}" "(exec even? (throw (ex-info \"bad\" {})))" "(throw (ex-info \"bad\" {})) =fn=> even?"] (mapv str (test-case ((throw (ex-info "bad" {})) =fn=> even?) :msg)))))) (component "=throws=>" (behavior "reports if the message didnt match the regex" (is (= ["foo", "asdf", "(throw (ex-info \"foo\" {})) =throws=> (clojure.lang.ExceptionInfo #\"asdf\")" "exception's message did not match regex"] (test-case ((throw (ex-info "foo" {})) =throws=> (clojure.lang.ExceptionInfo #"asdf")) :all)))) (behavior "reports if nothing was thrown" (is (= ["it to throw", "(+ 5 2) =throws=> (clojure.lang.ExceptionInfo #\"asdf\")" "Expected an error to be thrown!"] (-> ((+ 5 2) =throws=> (clojure.lang.ExceptionInfo #"asdf")) (test-case :all) rest))))) (component "block->asserts" (behavior "wraps triples in behavior do-reports" (let [reporting (th/locate `im/with-reporting (test-block->asserts '("string2" d => e)))] (is (= `(im/with-reporting {:type :behavior :string "string2"}) (take 2 reporting))))) (behavior "converts triples to assertions" (let [asserts (test-block->asserts '("string2" d => e))] (is (every? #{`t/is} (map first (drop 2 asserts)))))))) (specification "fix-conform for issue #31" (assertions (mapv (juxt :behavior (comp count :triples)) (ae/fix-conform (us/conform! ::ae/assertions '("foo" 1 => 2 "bar" 3 => 4, 5 => 6 "qux" 7 => 8, 9 => 10)))) => '[["foo" 1] ["bar" 2] ["qux" 2]]))
e7c770e4addd3df865fbc5efe4f0e371b2c58d20f904fd7aa519d7e18f598998
oakes/Nightcode
web.clj
(ns leiningen.new.web (:require [leiningen.new.templates :as t])) (defn web [name package-name] (let [render (t/renderer "web") package-name (t/sanitize (t/multi-segment (or package-name name))) main-ns (t/sanitize-ns package-name) data {:app-name name :name (t/project-name name) :namespace main-ns :path (t/name-to-path main-ns)}] (t/->files data ["boot.properties" (render "boot.properties" data)] ["build.boot" (render "build.boot" data)] ["README.md" (render "README.md" data)] [".gitignore" (render "gitignore" data)] ["src/clj/{{path}}.clj" (render "core.clj" data)] ["src/cljs/{{path}}.cljs" (render "core.cljs" data)] ["resources/public/index.html" (render "index.html" data)] ["resources/public/main.cljs.edn" (render "main.cljs.edn.txt" data)])))
null
https://raw.githubusercontent.com/oakes/Nightcode/2e112c59cddc5fdec96059a08912c73b880f9ae8/resources/leiningen/new/web.clj
clojure
(ns leiningen.new.web (:require [leiningen.new.templates :as t])) (defn web [name package-name] (let [render (t/renderer "web") package-name (t/sanitize (t/multi-segment (or package-name name))) main-ns (t/sanitize-ns package-name) data {:app-name name :name (t/project-name name) :namespace main-ns :path (t/name-to-path main-ns)}] (t/->files data ["boot.properties" (render "boot.properties" data)] ["build.boot" (render "build.boot" data)] ["README.md" (render "README.md" data)] [".gitignore" (render "gitignore" data)] ["src/clj/{{path}}.clj" (render "core.clj" data)] ["src/cljs/{{path}}.cljs" (render "core.cljs" data)] ["resources/public/index.html" (render "index.html" data)] ["resources/public/main.cljs.edn" (render "main.cljs.edn.txt" data)])))
ada1375f7c11c614e7bf3c65cc930f58ad31ccc02d341c1ecf9150c0e84d547e
Frama-C/Frama-C-snapshot
wpPropId.ml
(**************************************************************************) (* *) This file is part of WP plug - in of Frama - C. (* *) Copyright ( C ) 2007 - 2019 CEA ( Commissariat a l'energie atomique et aux energies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) open Cil_types open Cil_datatype (*----------------------------------------------------------------------------*) (* Property identification *) (*----------------------------------------------------------------------------*) * Beside the property identification , it can be found in different contexts * depending on which part of the computation is involved . * For instance , properties on loops are split in 2 parts : establishment and * preservation . * depending on which part of the computation is involved. * For instance, properties on loops are split in 2 parts : establishment and * preservation. *) type prop_kind = | PKTactic (** tactical sub-goal *) | PKCheck (** internal check *) | PKProp (** normal property *) | PKEstablished (** computation related to a loop property before the loop. *) | PKPreserved (** computation related to a loop property inside the loop. *) | PKPropLoop (** loop property used as hypothesis inside a loop. *) | PKVarDecr (** computation related to the decreasing of a variant in a loop *) | PKVarPos (** computation related to a loop variant being positive *) | PKAFctOut (** computation related to the function assigns on normal termination *) | PKAFctExit (** computation related to the function assigns on exit termination *) * precondition for function at stmt , property of the require . Many information that should come from the p_prop part of the prop_id , but in the case , it seems that it is hidden in a IPBlob property ! at stmt, property of the require. Many information that should come from the p_prop part of the prop_id, but in the PKPre case, it seems that it is hidden in a IPBlob property ! *) type prop_id = { p_kind : prop_kind ; p_prop : Property.t ; p_part : (int * int) option ; } let tactical ~gid = let ip = "Wp.Tactical." ^ gid in { p_kind = PKTactic ; p_prop = Property.(ip_other ip (OLGlob Cil_datatype.Location.unknown)); p_part = None } (* -------------------------------------------------------------------------- *) (* --- Category --- *) (* -------------------------------------------------------------------------- *) let kind_of_id p = p.p_kind let parts_of_id p = p.p_part let property_of_id p = p.p_prop let mk_part pid (k, n) = { pid with p_part = Some (k,n) } let source_of_id p = fst (Property.location p.p_prop) exception Found of int let num_of_bhv_from bhv (out, _) = match bhv.b_assigns with WritesAny -> Wp_parameters.fatal "no \\from in this behavior ???" | Writes l -> let add n (o, f) = match f with FromAny -> n | From _ -> if Logic_utils.is_same_identified_term out o then raise (Found n) else n+1 in try let _ = List.fold_left add 1 l in Wp_parameters.fatal "didn't found this \\from" with Found n -> n (*----------------------------------------------------------------------------*) (* Constructors *) (*----------------------------------------------------------------------------*) let mk_prop kind prop = { p_kind=kind ; p_prop=prop ; p_part=None } let mk_check prop = { p_kind=PKCheck ; p_prop=prop ; p_part=None } let mk_property prop = { p_kind=PKProp ; p_prop=prop ; p_part=None } let mk_annot_id kf stmt ca = Property.ip_of_code_annot_single kf stmt ca let mk_annot_ids kf stmt ca = Property.ip_of_code_annot kf stmt ca let mk_code_annot_ids kf s ca = List.map (mk_prop PKProp) (mk_annot_ids kf s ca) let mk_assert_id kf s ca = mk_prop PKProp (mk_annot_id kf s ca) let mk_loop_inv_id kf s ~established ca = let kind = if established then PKEstablished else PKPreserved in mk_prop kind (mk_annot_id kf s ca) let mk_inv_hyp_id kf s ca = mk_prop PKPropLoop (mk_annot_id kf s ca) let mk_var_decr_id kf s ca = mk_prop PKVarDecr (mk_annot_id kf s ca) let mk_var_pos_id kf s ca = mk_prop PKVarPos (mk_annot_id kf s ca) let mk_loop_from_id kf s ca from = let id = Property.ip_of_from kf (Kstmt s) (Property.Id_loop ca) from in mk_prop PKPropLoop (Extlib.the id) let mk_bhv_from_id kf ki a bhv from = let a = Datatype.String.Set.of_list a in let id = Property.ip_of_from kf ki (Property.Id_contract (a,bhv)) from in mk_prop PKProp (Extlib.the id) let get_kind_for_tk kf tkind = match tkind with | Normal -> if Cil2cfg.has_exit (Cil2cfg.get kf) then PKAFctOut else PKProp | Exits -> PKAFctExit | _ -> assert false let mk_fct_from_id kf bhv tkind from = let contract_info = Property.Id_contract(Datatype.String.Set.empty,bhv) in let id = Property.ip_of_from kf Kglobal contract_info from in let kind = get_kind_for_tk kf tkind in mk_prop kind (Extlib.the id) let mk_disj_bhv_id (kf,ki,active,disj) = mk_prop PKProp (Property.ip_of_disjoint kf ki active disj) let mk_compl_bhv_id (kf,ki,active,comp) = mk_prop PKProp (Property.ip_of_complete kf ki active comp) let mk_decrease_id (kf, s, x) = mk_prop PKProp (Property.ip_of_decreases kf s x) let mk_lemma_id l = mk_prop PKProp (LogicUsage.ip_lemma l) let mk_stmt_assigns_id kf s active b a = let active = Datatype.String.Set.of_list active in let b = Property.Id_contract (active,b) in let p = Property.ip_of_assigns kf (Kstmt s) b (Writes a) in Extlib.opt_map (mk_prop PKProp) p let mk_loop_assigns_id kf s ca a = let ca = Property.Id_loop ca in let p = Property.ip_of_assigns kf (Kstmt s) ca (Writes a) in Extlib.opt_map (mk_prop PKPropLoop) p let mk_fct_assigns_id kf b tkind a = let b = Property.Id_contract(Datatype.String.Set.empty,b) in let kind = get_kind_for_tk kf tkind in let p = Property.ip_of_assigns kf Kglobal b (Writes a) in Extlib.opt_map (mk_prop kind) p let mk_pre_id kf ki b p = mk_prop PKProp (Property.ip_of_requires kf ki b p) let mk_stmt_post_id kf s b p = mk_prop PKProp (Property.ip_of_ensures kf (Kstmt s) b p) let mk_fct_post_id kf b p = mk_prop PKProp (Property.ip_of_ensures kf Kglobal b p) let mk_call_pre_id called_kf s_call called_pre called_pre_p = let kind = PKPre (called_kf, s_call, called_pre) in mk_prop kind called_pre_p (*----------------------------------------------------------------------------*) let kind_order = function | PKProp -> 0 | PKPre _ -> 1 | PKEstablished -> 2 | PKPreserved -> 3 | PKVarPos -> 4 | PKVarDecr -> 5 | PKPropLoop -> 6 | PKAFctOut -> 7 | PKAFctExit -> 8 | PKCheck -> 9 | PKTactic -> 10 let compare_kind k1 k2 = match k1, k2 with PKPre (kf1, ki1, p1), PKPre (kf2, ki2, p2) -> let cmp = Kernel_function.compare kf1 kf2 in if cmp <> 0 then cmp else let cmp = Stmt.compare ki1 ki2 in if cmp <> 0 then cmp else Property.compare p1 p2 | _,_ -> Transitioning.Stdlib.compare (kind_order k1) (kind_order k2) let compare_prop_id pid1 pid2 = (* This order of comparison groups together prop_pids with same properties *) let p1 = property_of_id pid1 in let p2 = property_of_id pid2 in let cmp = Description.full_compare p1 p2 in if cmp <> 0 then cmp else let cmp = compare_kind pid2.p_kind pid1.p_kind in if cmp <> 0 then cmp else Transitioning.Stdlib.compare pid1.p_part pid2.p_part module PropId = Datatype.Make_with_collections( struct type t = prop_id include Datatype.Undefined let name = "WpAnnot.prop_id" let reprs = List.map (fun x -> { p_kind = PKProp; p_prop = x; p_part = None }) Property.reprs let hash pid = Property.hash pid.p_prop let compare = compare_prop_id let equal pid1 pid2 = compare_prop_id pid1 pid2 = 0 let copy = Datatype.undefined let rehash = Datatype.identity let internal_pretty_code = Datatype.undefined let pretty = Datatype.undefined let mem_project = Datatype.never_any_project let varname = Datatype.undefined end) (* -------------------------------------------------------------------------- *) --- --- (* -------------------------------------------------------------------------- *) module NameUniquify(D:Datatype.S_with_collections)(S:sig val name: string val basename: D.t -> string end) : sig val unique_basename: D.t -> string end = struct module NamesTbl = State_builder.Hashtbl(Datatype.String.Hashtbl)(Datatype.Int) (struct let name = S.name^"Names" let dependencies = [ ] let size = 97 end) module IndexTbl = State_builder.Hashtbl(D.Hashtbl)(Datatype.String) (struct let name = S.name^"Index" let dependencies = [ Ast.self; NamesTbl.self; Globals.Functions.self; Annotations.code_annot_state; Annotations.funspec_state; Annotations.global_state ] let size = 97 end) (** returns the name that should be returned by the function [get_prop_name_id] if the given property has [name] as basename. That name is reserved so that [get_prop_name_id prop] can never return an identical name. *) let reserve_name_id pid = let basename = S.basename pid in try let speed_up_start = NamesTbl.find basename in (* this basename is already reserved *) let n,unique_name = Extlib.make_unique_name NamesTbl.mem ~sep:"_" ~start:speed_up_start basename in NamesTbl.replace basename (succ n) ; (* to speed up Extlib.make_unique_name for next time *) unique_name first time that basename is reserved NamesTbl.add basename 2 ; basename (** returns a unique name identifying the property. This name is built from the basename of the property. *) let unique_basename pid = try IndexTbl.find pid first time we are asking for a name for that [ ip ] let unique_name = reserve_name_id pid in IndexTbl.add pid unique_name ; unique_name end module LegacyNames : sig val get_prop_id_name: prop_id -> string end = struct let base_id_prop_txt = Property.LegacyNames.get_prop_name_id let basename_of_prop_id p = match p.p_kind , p.p_prop with | (PKTactic | PKCheck | PKProp | PKPropLoop) , p -> base_id_prop_txt p | PKEstablished , p -> base_id_prop_txt p ^ "_established" | PKPreserved , p -> base_id_prop_txt p ^ "_preserved" | PKVarDecr , p -> base_id_prop_txt p ^ "_decrease" | PKVarPos , p -> base_id_prop_txt p ^ "_positive" | PKAFctOut , p -> base_id_prop_txt p ^ "_normal" | PKAFctExit , p -> base_id_prop_txt p ^ "_exit" | PKPre(_kf,stmt,pre) , _ -> let kf_name_of_stmt = Kernel_function.get_name (Kernel_function.find_englobing_kf stmt) in Printf.sprintf "%s_call_%s" kf_name_of_stmt (base_id_prop_txt pre) (** function used to normalize basename *) let normalize_basename s = (* truncates basename in order to limit length of file name *) let max_len = Wp_parameters.TruncPropIdFileName.get () in if max_len > 0 && String.length s > max_len then if max_len > 3 then (String.sub s 0 (max_len-3)) ^ "___" else String.sub s 0 max_len else s (** returns the normalized basename of the property. *) let get_prop_id_basename p = let basename = basename_of_prop_id p in let basename = match p.p_part with | None -> basename | Some(k,n) -> if n < 10 then Printf.sprintf "%s_part%d" basename (succ k) else if n < 100 then Printf.sprintf "%s_part%02d" basename (succ k) else if n < 1000 then Printf.sprintf "%s_part%03d" basename (succ k) else Printf.sprintf "%s_part%06d" basename (succ k) in normalize_basename basename module UniquifyPropId = NameUniquify(PropId)(struct let name = "WpProperty" let basename = get_prop_id_basename end) (** returns a unique name identifying the property. This name is built from the basename of the property. *) let get_prop_id_name pid = UniquifyPropId.unique_basename pid end (* -------------------------------------------------------------------------- *) (* --- Naming Properties --- *) (* -------------------------------------------------------------------------- *) module Names: sig val get_prop_id_name: prop_id -> string end = struct * Uniquify the first part of the prop_id module Uniquify1 = NameUniquify(Property)(struct let name = "Wp.WpPropId.Names." let basename ip = let truncate = max 20 (Wp_parameters.TruncPropIdFileName.get ()) in Property.Names.get_prop_basename ~truncate ip end) let get_ip ip = Uniquify1.unique_basename ip * Uniquify call - site for precondition check . So that precondition of the same call - site are grouped that precondition of the same call-site are grouped *) module CallSite = Datatype.Triple_with_collections (Kernel_function)(Kernel_function)(Stmt) (struct let module_name = "Wp.WpPropId.CallSite" end) module Uniquify_Stmt = NameUniquify(CallSite)(struct let name = "Wp.WpPropId.Names3." let basename (caller_kf,callee_kf,_stmt) = (Kernel_function.get_name caller_kf)^"_call_"^(Kernel_function.get_name callee_kf) end) let get_prop_id_base p = match p.p_kind , p.p_prop with | (PKTactic | PKCheck | PKProp | PKPropLoop) , p -> get_ip p | PKEstablished , p -> get_ip p ^ "_established" | PKPreserved , p -> get_ip p ^ "_preserved" | PKVarDecr , p -> get_ip p ^ "_decrease" | PKVarPos , p -> get_ip p ^ "_positive" | PKAFctOut , p -> get_ip p ^ "_normal" | PKAFctExit , p -> get_ip p ^ "_exit" | PKPre(callee_kf,stmt,pre) , _ -> let caller_kf = Kernel_function.find_englobing_kf stmt in let call_string = Uniquify_Stmt.unique_basename (caller_kf,callee_kf,stmt) in (** remove name of callee kernel function given by get_ip *) let ip_string = get_ip pre in let ip_string = Extlib.opt_conv ip_string (Extlib.string_del_prefix ((Kernel_function.get_name callee_kf)^"_") ip_string) in call_string^"_"^ip_string let get_prop_id_basename p = let basename = get_prop_id_base p in match p.p_part with | None -> basename | Some(k,n) -> if n < 10 then Printf.sprintf "%s_part%d" basename (succ k) else if n < 100 then Printf.sprintf "%s_part%02d" basename (succ k) else if n < 1000 then Printf.sprintf "%s_part%03d" basename (succ k) else Printf.sprintf "%s_part%06d" basename (succ k) module Uniquify2 = NameUniquify(PropId)(struct let name = "Wp.WpPropId.Names2." let basename = get_prop_id_basename end) let get_prop_id_name p = Uniquify2.unique_basename p end (* -------------------------------------------------------------------------- *) (* --- Naming Accessors --- *) (* -------------------------------------------------------------------------- *) let get_legacy = LegacyNames.get_prop_id_name * Legacy property PO name let get_propid = Names.get_prop_id_name (** Name related to a property PO *) let pp_propid fmt pid = Format.pp_print_string fmt (get_propid pid) let pp_names fmt l = match l with [] -> () | _ -> Format.fprintf fmt "_%a" (Wp_error.pp_string_list ~empty:"" ~sep:"_") l let ident_names names = List.filter (function "" -> true | _ as n -> '\"' <> (String.get n 0) ) names let code_annot_names ca = match ca.annot_content with | AAssert (_, Check, named_pred) -> "@check"::(ident_names named_pred.pred_name) | AAssert (_, Assert, named_pred) -> "@assert"::(ident_names named_pred.pred_name) | AInvariant (_,_,named_pred) -> "@invariant"::(ident_names named_pred.pred_name) | AVariant (term, _) -> "@variant"::(ident_names term.term_name) | AExtended(_,_,{ext_name}) -> [Printf.sprintf "@%s" ext_name] | _ -> [] (* TODO : add some more names ? *) (** This is used to give the name of the property that the user can give * to select it from the command line (-wp-prop option) *) let user_prop_names p = let open Property in match p with | IPPredicate {ip_kind; ip_pred} -> Format.asprintf "@@%a" Property.pretty_predicate_kind ip_kind :: ip_pred.ip_content.pred_name | IPExtended {ie_ext={ext_name}} -> [ Printf.sprintf "@%s" ext_name ] | IPCodeAnnot {ica_ca} -> code_annot_names ica_ca | IPComplete {ic_bhvs} -> let kind_name = "@complete_behaviors" in let name = Format.asprintf "complete_behaviors%a" pp_names ic_bhvs in kind_name::[name] | IPDisjoint {ic_bhvs} -> let kind_name = "@disjoint_behaviors" in let name = Format.asprintf "disjoint_behaviors%a" pp_names ic_bhvs in kind_name::[name] | IPAssigns {ias_froms} -> List.fold_left (fun acc (t,_) -> (ident_names t.it_content.term_name) @ acc) ["@assigns"] ias_froms | IPDecrease {id_ca=Some ca} -> "@decreases"::code_annot_names ca | IPDecrease _ -> [ "@decreases" ] | IPLemma {il_name = a; il_pred = l} -> let names = "@lemma"::a::(ident_names l.pred_name) in begin match LogicUsage.section_of_lemma a with | LogicUsage.Toplevel _ -> names | LogicUsage.Axiomatic ax -> ax.LogicUsage.ax_name::names end TODO | IPFrom _ | IPAllocation _ | IPAxiomatic _ | IPAxiom _ | IPBehavior _ | IPReachable _ | IPPropertyInstance _ | IPTypeInvariant _ | IPGlobalInvariant _ | IPOther _ -> [] let string_of_termination_kind = function Normal -> "post" | Exits -> "exits" | Breaks -> "breaks" | Continues -> "continues" | Returns -> "returns" let label_of_kind = function | PKTactic -> "Tactic" | PKCheck -> "Check" | PKProp -> "Property" | PKPropLoop -> "Invariant" (* should be assert false ??? *) | PKEstablished -> "Establishment" | PKPreserved -> "Preservation" | PKVarDecr -> "Decreasing" | PKVarPos -> "Positive" | PKAFctOut -> "Function assigns" | PKAFctExit -> "Exit assigns" | PKPre(kf,_,_) -> Printf.sprintf "Precondition for '%s'" (Kernel_function.get_name kf) let label_of_prop_id p = match p.p_part with | None -> label_of_kind p.p_kind | Some(k,n) -> Printf.sprintf "%s (%d/%d)" (label_of_kind p.p_kind) (succ k) n module Pretty = struct open Format let pp_part fmt p = match p.p_part with | None -> () | Some(k,n) -> fprintf fmt " (%d/%d)" (succ k) n let pp_subprop fmt p = match p.p_kind with | PKProp | PKTactic | PKCheck | PKPropLoop -> () | PKEstablished -> pp_print_string fmt " (established)" | PKPreserved -> pp_print_string fmt " (preserved)" | PKVarDecr -> pp_print_string fmt " (decrease)" | PKVarPos -> pp_print_string fmt " (positive)" | PKAFctOut -> pp_print_string fmt " (return)" | PKAFctExit -> pp_print_string fmt " (exit)" | PKPre(kf,_,_) -> fprintf fmt " (call '%s')" (Kernel_function.get_name kf) let pp_prop fmt p = Description.pp_localized ~kf:`Never ~ki:false ~kloc:false fmt p.p_prop let pp_local fmt p = begin pp_prop fmt p ; pp_subprop fmt p ; pp_part fmt p ; end end let pretty_local = Pretty.pp_local (* -------------------------------------------------------------------------- *) (* --- Hints --- *) (* -------------------------------------------------------------------------- *) type hints = { mutable required : string list ; mutable hints : string list ; } let add_hint hs x = if not (List.mem x hs.hints) then hs.hints <- x :: hs.hints let add_required hs x = if not (List.mem x hs.required) then hs.required <- x :: hs.required let stmt_hints hs s = List.iter (fun label -> match label with | Label(a,_,src) -> if src then add_hint hs a | Default _ -> add_hint hs "default" | Case(e,_) -> match Ctypes.get_int64 e with | Some k -> add_hint hs ("case-" ^ Int64.to_string k) | None -> () ) s.labels let kinstr_hints hs = function | Kstmt s -> stmt_hints hs s | Kglobal -> () let propid_hints hs p = let open Property in match p.p_kind , p.p_prop with | PKCheck , _ -> () | PKProp , IPAssigns {ias_kinstr=Kstmt _} -> add_required hs "stmt-assigns" | PKProp , IPAssigns {ias_kinstr=Kglobal} -> add_required hs "fct-assigns" | PKPropLoop , Property.IPAssigns _ -> add_required hs "loop-assigns" | PKPropLoop , _ -> add_required hs "invariant" | PKProp , _ -> add_required hs "property" | PKTactic , _ -> add_required hs "tactic" | PKEstablished , _ -> add_required hs "established" | PKPreserved , _ -> add_required hs "preserved" | PKVarDecr , _ -> add_required hs "decrease" | PKVarPos , _ -> add_required hs "positive" | PKAFctOut , _ -> add_required hs "return" | PKAFctExit , _ -> add_required hs "exit" | PKPre(kf,st,_) , _ -> add_required hs ("precond-" ^ Kernel_function.get_name kf) ; stmt_hints hs st let rec term_hints hs t = match t.term_node with | TLval(lv,_) -> lval_hints hs lv | TAddrOf(lv,_) -> lval_hints hs lv | TCastE(_,t) -> term_hints hs t | TBinOp((PlusPI|IndexPI|MinusPI),a,_) -> term_hints hs a | Tlet(_,t) -> term_hints hs t | _ -> () and lval_hints hs = function | TVar { lv_origin=Some { vorig_name=x } } | TVar { lv_name=x } -> add_hint hs x | TResult _ -> add_hint hs "result" | TMem t -> add_hint hs "*" ; term_hints hs t let assigns_hints hs froms = List.iter (fun ({it_content=t},_) -> term_hints hs t) froms let annot_hints hs = function | AAssert(bs,_,ipred) | AInvariant(bs,_,ipred) -> List.iter (add_hint hs) (ident_names ipred.pred_name) ; List.iter (add_hint hs) bs | AAssigns(bs,Writes froms) -> List.iter (add_hint hs) bs ; assigns_hints hs froms | AAllocation _ | AAssigns(_,WritesAny) | AStmtSpec _ | AVariant _ | APragma _ | AExtended _ -> () let property_hints hs = let open Property in function | IPAxiom {il_name; il_pred} | IPLemma {il_name; il_pred} -> List.iter (add_required hs) (il_name::il_pred.pred_name) | IPBehavior _ -> () | IPComplete {ic_bhvs} | IPDisjoint {ic_bhvs} -> List.iter (add_required hs) ic_bhvs | IPPredicate {ip_pred} -> List.iter (add_hint hs) ip_pred.ip_content.pred_name | IPExtended {ie_ext={ext_name}} -> List.iter (add_hint hs) [ext_name] | IPCodeAnnot {ica_ca} -> annot_hints hs ica_ca.annot_content | IPAssigns {ias_froms} -> assigns_hints hs ias_froms TODO | IPFrom _ | Property.IPDecrease _ | Property.IPPropertyInstance _ | IPReachable _ | Property.IPAxiomatic _ | Property.IPOther _ | IPTypeInvariant _ | Property.IPGlobalInvariant _ -> () let prop_id_keys p = begin let hs = { hints=[] ; required=[] } in let opt add f = function None -> () | Some x -> add hs (f x) in propid_hints hs p ; property_hints hs p.p_prop ; opt add_required Kernel_function.get_name (Property.get_kf p.p_prop) ; opt add_required (fun b -> if Cil.is_default_behavior b then "default" else b.b_name) (Property.get_behavior p.p_prop) ; opt add_hint (fun (k,_) -> Printf.sprintf "part-%d" k) p.p_part ; kinstr_hints hs (Property.get_kinstr p.p_prop) ; List.sort String.compare hs.required , List.sort String.compare hs.hints end (*----------------------------------------------------------------------------*) (* Pretty-Print *) (*----------------------------------------------------------------------------*) let pp_goal_kind fmt = function | PKTactic | PKCheck | PKProp | PKPropLoop | PKAFctOut | PKAFctExit | PKPre _ -> () | PKEstablished -> Format.pp_print_string fmt "Establishment of " | PKPreserved -> Format.pp_print_string fmt "Preservation of " | PKVarDecr -> Format.pp_print_string fmt "Decreasing of " | PKVarPos -> Format.pp_print_string fmt "Positivity of " let pp_goal_part fmt = function | None -> () | Some(k,n) -> Format.fprintf fmt " (%d/%d)" (succ k) n let pretty fmt pid = begin pp_goal_kind fmt pid.p_kind ; Description.pp_property fmt pid.p_prop ; pp_goal_part fmt pid.p_part ; end let pretty_context kf fmt pid = begin pp_goal_kind fmt pid.p_kind ; Description.pp_localized ~kf ~ki:true ~kloc:true fmt pid.p_prop ; pp_goal_part fmt pid.p_part ; end (*----------------------------------------------------------------------------*) Comparison (*----------------------------------------------------------------------------*) let is_check p = p.p_kind = PKCheck let is_tactic p = p.p_kind = PKTactic let is_assigns p = match property_of_id p with | Property.IPAssigns _ -> true | _ -> false let is_requires = let open Property in function | IPPredicate {ip_kind = PKRequires _} -> true | _ -> false let is_loop_preservation p = match p.p_kind with | PKPreserved -> begin match Property.get_kinstr p.p_prop with | Kglobal -> Wp_parameters.fatal "Loop Preservation ? (%a)" Property.pretty p.p_prop | Kstmt st -> Some st end | _ -> None let user_prop_pid pid = let p_prop = match pid.p_kind with | PKPre (_,_,p_prop) -> p_prop | _ -> property_of_id pid in user_prop_names p_prop let select_default pid = let names = user_prop_pid pid in not (List.mem "no_wp" names) let select_by_name asked_names pid = let names = user_prop_pid pid in if List.mem "no_wp" names then false else let is_minus s = try s.[0] = '-' with _ -> false in let is_plus s = try s.[0] = '+' with _ -> false in let remove_first s = String.sub s 1 ((String.length s) -1) in let eval acc asked = let is_minus,a = match acc with | None -> if is_minus asked then true,true else false,false | Some a -> (is_minus asked),a in let eval () = let asked = if is_minus || (is_plus asked) then remove_first asked else asked in List.mem asked names in Some (if is_minus then a && (not (eval ())) else a || (eval ())) in match List.fold_left eval None asked_names with | Some false -> false | _ -> true let select_call_pre s_call asked_pre pid = match pid.p_kind with | PKPre (_, p_stmt, p_prop) -> Stmt.equal s_call p_stmt && (match asked_pre with | None -> true | Some asked_pre -> Property.equal p_prop asked_pre) | _ -> false (*----------------------------------------------------------------------------*) (* About assigns identification *) (*----------------------------------------------------------------------------*) type a_kind = LoopAssigns | StmtAssigns type effect_source = FromCode | FromCall | FromReturn type assigns_desc = { a_label : Clabels.c_label ; a_stmt : Cil_types.stmt option ; a_kind : a_kind ; a_assigns : Cil_types.assigns ; } let mk_asm_assigns_desc s = { a_label = Clabels.stmt s ; a_stmt = Some s ; a_kind = StmtAssigns ; a_assigns = WritesAny ; } let mk_loop_assigns_desc s assigns = { a_label = Clabels.stmt s ; a_stmt = Some s ; a_kind = LoopAssigns ; a_assigns = Writes assigns } let mk_stmt_assigns_desc s assigns = { a_label = Clabels.stmt s ; a_stmt = Some s ; a_kind = StmtAssigns ; a_assigns = Writes assigns ; } let mk_init_assigns = { a_label = Clabels.init ; a_stmt = None ; a_kind = StmtAssigns ; a_assigns = WritesAny ; } (* (** kf assigns for normal path when there is an exit path *) let mk_fout_assigns_desc assigns = { a_label = Logic_const.pre_label ; (* a_fun = Assigns_FctOut ; *) a_kind = StmtAssigns ; a_assigns = Writes assigns ; } (** kf assigns for exit path *) let mk_exit_assigns_desc assigns = { a_label = Logic_const.pre_label ; (* a_fun = Assigns_FctExit ; *) a_kind = StmtAssigns ; a_assigns = Writes assigns ; } *) let mk_kf_assigns_desc assigns = { a_label = Clabels.pre ; a_stmt = None ; a_kind = StmtAssigns ; a_assigns = Writes assigns ; } let is_call_assigns = function | {a_stmt=Some {skind=Instr(Call _ | Local_init (_, ConsInit _, _)) } } -> true | _ -> false let pp_assigns_desc fmt a = Wp_error.pp_assigns fmt a.a_assigns (*----------------------------------------------------------------------------*) * * 2 kinds of annotations can be found : predicates and assigns . * because assigns properties can only be translated into predicates * by the memory model . * - Assigns properties are composed of the assigns list from , * and a label to know where to stop . * - Predicates are just the predicate type from . * 2 kinds of annotations can be found : predicates and assigns. * because assigns properties can only be translated into predicates * by the memory model. * - Assigns properties are composed of the assigns list from Cil, * and a label to know where to stop. * - Predicates are just the predicate type from Cil. *) (*----------------------------------------------------------------------------*) type pred_info = prop_id * Cil_types.predicate let mk_pred_info id p = (id, p) let pred_info_id (id, _) = id let pp_pred_of_pred_info fmt (_id, p) = Printer.pp_predicate fmt p let pp_pred_info fmt (id, p) = Format.fprintf fmt "(@[%a:@ %a@])" pp_propid id Printer.pp_predicate p type assigns_info = prop_id * assigns_desc let assigns_info_id (id,_) = id type assigns_full_info = AssignsLocations of assigns_info | AssignsAny of assigns_desc | NoAssignsInfo let empty_assigns_info = NoAssignsInfo let mk_assigns_info id a = AssignsLocations (id, a) let mk_stmt_any_assigns_info s = let a = { a_label = Clabels.stmt s ; a_stmt = Some s ; a_kind = StmtAssigns ; a_assigns = WritesAny ; } in AssignsAny a let mk_kf_any_assigns_info () = let a = { a_label = Clabels.pre ; a_stmt = None ; a_kind = StmtAssigns ; a_assigns = WritesAny ; } in AssignsAny a let mk_loop_any_assigns_info s = let a = { a_label = Clabels.stmt s ; a_stmt = Some s ; a_kind = LoopAssigns ; a_assigns = WritesAny ; } in AssignsAny a (* let pp_assigns_id (id, _a) = pp_propid id *) let pp_assign_info k fmt a = match a with | NoAssignsInfo -> () | AssignsAny a -> let pkind = match a.a_kind with | StmtAssigns -> "" | LoopAssigns -> "loop" in Format.fprintf fmt "%s(@@%a): %s assigns everything@." k Clabels.pretty a.a_label pkind | AssignsLocations (_,a) -> Format.fprintf fmt "%s(@@%a): %a@." k Clabels.pretty a.a_label pp_assigns_desc a let merge_assign_info a1 a2 = match a1,a2 with | NoAssignsInfo, a | a, NoAssignsInfo -> a | (AssignsLocations _ | AssignsAny _), (AssignsLocations _ | AssignsAny _) -> Wp_parameters.fatal "Several assigns ?" type axiom_info = prop_id * LogicUsage.logic_lemma let mk_axiom_info lemma = let id = mk_lemma_id lemma in (id, lemma) let pp_axiom_info fmt (id,thm) = Format.fprintf fmt "(@[%a:@ %a@])" pp_propid id Printer.pp_predicate thm.LogicUsage.lem_property (* -------------------------------------------------------------------------- *) (* --- Prop Splitter --- *) (* -------------------------------------------------------------------------- *) (* prop-id splitter *) let _split job pid goals = let n = Bag.length goals in if n <= 1 then Bag.iter (job pid) goals else let k = ref 0 in Bag.iter (fun g -> let pid_k = mk_part pid (!k,n) in incr k ; job pid_k g) goals (*----------------------------------------------------------------------------*) (** About proofs *) (*----------------------------------------------------------------------------*) let subproofs id = match id.p_kind with | PKCheck -> 0 | PKProp | PKTactic | PKPre _ | PKPropLoop -> 1 | PKEstablished | PKPreserved | PKVarDecr | PKVarPos | PKAFctExit | PKAFctOut -> 2 let subproof_idx id = match id.p_kind with 0/0 1/1 1/2 2/2 1/2 2/2 1/2 2/2 * find the outer loop in which the stmt is . let get_loop_stmt kf stmt = because we do n't have the cfg here , we can only use Cil information , * and then we can only recognize syntactic loops ... TODO : use the cfg ? * and then we can only recognize syntactic loops... TODO: use the cfg ? *) let rec is_in_blk b = List.exists is_in_stmt b.bstmts and is_in_stmt s = if s.sid = stmt.sid then true else match s.skind with | If (_, b1, b2,_) -> is_in_blk b1 || is_in_blk b2 | Switch (_, b, _, _) | Block b -> is_in_blk b | UnspecifiedSequence seq -> let b = Cil.block_from_unspecified_sequence seq in is_in_blk b | Loop (_, b, _, _, _) -> is_in_blk b | _ -> false and find_loop_in_blk blk = find_loop_in_stmts blk.bstmts and find_loop_in_stmts l = match l with | [] -> None | s::tl -> (match find_loop_in_stmt s with Some l -> Some l | None -> find_loop_in_stmts tl) and find_loop_in_stmt s = match s.skind with | (Loop _) -> if is_in_stmt s then Some s else None | If (_, b1, b2,_) -> (match find_loop_in_blk b1 with Some l -> Some l | None -> find_loop_in_blk b2) | Switch (_, b, _, _) | Block b -> find_loop_in_blk b | UnspecifiedSequence seq -> let b = Cil.block_from_unspecified_sequence seq in find_loop_in_blk b | _ -> None in let f = Kernel_function.get_definition kf in find_loop_in_blk f.sbody * Quite do n't understand what is going on here ... what is it supposed to do ? * [ 2011 - 07 - 07 - Anne ] * [2011-07-07-Anne] *) let get_induction p = let get_stmt = let open Property in function | IPDecrease {id_kf;id_kinstr=Kstmt stmt} -> Some (id_kf, stmt) | IPCodeAnnot {ica_kf;ica_stmt} -> Some (ica_kf, ica_stmt) | IPAssigns {ias_kf; ias_kinstr=Kstmt stmt} -> Some (ias_kf, stmt) | _ -> None in match p.p_kind with | PKCheck | PKAFctOut|PKAFctExit|PKPre _ | PKTactic -> None | PKProp -> let loop_stmt_opt = match get_stmt (property_of_id p) with | None -> None | Some (kf, s) -> get_loop_stmt kf s in loop_stmt_opt | PKPropLoop -> let open Property in let loop_stmt_opt = match property_of_id p with | IPCodeAnnot {ica_kf; ica_stmt; ica_ca = {annot_content = AInvariant(_, loop, _)}} -> if loop then (*loop invariant *) Some ica_stmt else (* invariant inside loop *) get_loop_stmt ica_kf ica_stmt | IPAssigns {ias_kinstr=Kstmt stmt; ias_bhv = Id_loop _} -> (* loop assigns *) Some stmt | _ -> None (* assert false ??? *) in loop_stmt_opt | PKEstablished|PKVarDecr|PKVarPos|PKPreserved -> (match get_stmt (property_of_id p) with | None -> None | Some (_, s) -> Some s)
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/wp/wpPropId.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ ---------------------------------------------------------------------------- Property identification ---------------------------------------------------------------------------- * tactical sub-goal * internal check * normal property * computation related to a loop property before the loop. * computation related to a loop property inside the loop. * loop property used as hypothesis inside a loop. * computation related to the decreasing of a variant in a loop * computation related to a loop variant being positive * computation related to the function assigns on normal termination * computation related to the function assigns on exit termination -------------------------------------------------------------------------- --- Category --- -------------------------------------------------------------------------- ---------------------------------------------------------------------------- Constructors ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- This order of comparison groups together prop_pids with same properties -------------------------------------------------------------------------- -------------------------------------------------------------------------- * returns the name that should be returned by the function [get_prop_name_id] if the given property has [name] as basename. That name is reserved so that [get_prop_name_id prop] can never return an identical name. this basename is already reserved to speed up Extlib.make_unique_name for next time * returns a unique name identifying the property. This name is built from the basename of the property. * function used to normalize basename truncates basename in order to limit length of file name * returns the normalized basename of the property. * returns a unique name identifying the property. This name is built from the basename of the property. -------------------------------------------------------------------------- --- Naming Properties --- -------------------------------------------------------------------------- * remove name of callee kernel function given by get_ip -------------------------------------------------------------------------- --- Naming Accessors --- -------------------------------------------------------------------------- * Name related to a property PO TODO : add some more names ? * This is used to give the name of the property that the user can give * to select it from the command line (-wp-prop option) should be assert false ??? -------------------------------------------------------------------------- --- Hints --- -------------------------------------------------------------------------- ---------------------------------------------------------------------------- Pretty-Print ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- About assigns identification ---------------------------------------------------------------------------- (** kf assigns for normal path when there is an exit path a_fun = Assigns_FctOut ; * kf assigns for exit path a_fun = Assigns_FctExit ; ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- let pp_assigns_id (id, _a) = pp_propid id -------------------------------------------------------------------------- --- Prop Splitter --- -------------------------------------------------------------------------- prop-id splitter ---------------------------------------------------------------------------- * About proofs ---------------------------------------------------------------------------- loop invariant invariant inside loop loop assigns assert false ???
This file is part of WP plug - in of Frama - C. Copyright ( C ) 2007 - 2019 CEA ( Commissariat a l'energie atomique et aux energies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Cil_types open Cil_datatype * Beside the property identification , it can be found in different contexts * depending on which part of the computation is involved . * For instance , properties on loops are split in 2 parts : establishment and * preservation . * depending on which part of the computation is involved. * For instance, properties on loops are split in 2 parts : establishment and * preservation. *) type prop_kind = * precondition for function at stmt , property of the require . Many information that should come from the p_prop part of the prop_id , but in the case , it seems that it is hidden in a IPBlob property ! at stmt, property of the require. Many information that should come from the p_prop part of the prop_id, but in the PKPre case, it seems that it is hidden in a IPBlob property ! *) type prop_id = { p_kind : prop_kind ; p_prop : Property.t ; p_part : (int * int) option ; } let tactical ~gid = let ip = "Wp.Tactical." ^ gid in { p_kind = PKTactic ; p_prop = Property.(ip_other ip (OLGlob Cil_datatype.Location.unknown)); p_part = None } let kind_of_id p = p.p_kind let parts_of_id p = p.p_part let property_of_id p = p.p_prop let mk_part pid (k, n) = { pid with p_part = Some (k,n) } let source_of_id p = fst (Property.location p.p_prop) exception Found of int let num_of_bhv_from bhv (out, _) = match bhv.b_assigns with WritesAny -> Wp_parameters.fatal "no \\from in this behavior ???" | Writes l -> let add n (o, f) = match f with FromAny -> n | From _ -> if Logic_utils.is_same_identified_term out o then raise (Found n) else n+1 in try let _ = List.fold_left add 1 l in Wp_parameters.fatal "didn't found this \\from" with Found n -> n let mk_prop kind prop = { p_kind=kind ; p_prop=prop ; p_part=None } let mk_check prop = { p_kind=PKCheck ; p_prop=prop ; p_part=None } let mk_property prop = { p_kind=PKProp ; p_prop=prop ; p_part=None } let mk_annot_id kf stmt ca = Property.ip_of_code_annot_single kf stmt ca let mk_annot_ids kf stmt ca = Property.ip_of_code_annot kf stmt ca let mk_code_annot_ids kf s ca = List.map (mk_prop PKProp) (mk_annot_ids kf s ca) let mk_assert_id kf s ca = mk_prop PKProp (mk_annot_id kf s ca) let mk_loop_inv_id kf s ~established ca = let kind = if established then PKEstablished else PKPreserved in mk_prop kind (mk_annot_id kf s ca) let mk_inv_hyp_id kf s ca = mk_prop PKPropLoop (mk_annot_id kf s ca) let mk_var_decr_id kf s ca = mk_prop PKVarDecr (mk_annot_id kf s ca) let mk_var_pos_id kf s ca = mk_prop PKVarPos (mk_annot_id kf s ca) let mk_loop_from_id kf s ca from = let id = Property.ip_of_from kf (Kstmt s) (Property.Id_loop ca) from in mk_prop PKPropLoop (Extlib.the id) let mk_bhv_from_id kf ki a bhv from = let a = Datatype.String.Set.of_list a in let id = Property.ip_of_from kf ki (Property.Id_contract (a,bhv)) from in mk_prop PKProp (Extlib.the id) let get_kind_for_tk kf tkind = match tkind with | Normal -> if Cil2cfg.has_exit (Cil2cfg.get kf) then PKAFctOut else PKProp | Exits -> PKAFctExit | _ -> assert false let mk_fct_from_id kf bhv tkind from = let contract_info = Property.Id_contract(Datatype.String.Set.empty,bhv) in let id = Property.ip_of_from kf Kglobal contract_info from in let kind = get_kind_for_tk kf tkind in mk_prop kind (Extlib.the id) let mk_disj_bhv_id (kf,ki,active,disj) = mk_prop PKProp (Property.ip_of_disjoint kf ki active disj) let mk_compl_bhv_id (kf,ki,active,comp) = mk_prop PKProp (Property.ip_of_complete kf ki active comp) let mk_decrease_id (kf, s, x) = mk_prop PKProp (Property.ip_of_decreases kf s x) let mk_lemma_id l = mk_prop PKProp (LogicUsage.ip_lemma l) let mk_stmt_assigns_id kf s active b a = let active = Datatype.String.Set.of_list active in let b = Property.Id_contract (active,b) in let p = Property.ip_of_assigns kf (Kstmt s) b (Writes a) in Extlib.opt_map (mk_prop PKProp) p let mk_loop_assigns_id kf s ca a = let ca = Property.Id_loop ca in let p = Property.ip_of_assigns kf (Kstmt s) ca (Writes a) in Extlib.opt_map (mk_prop PKPropLoop) p let mk_fct_assigns_id kf b tkind a = let b = Property.Id_contract(Datatype.String.Set.empty,b) in let kind = get_kind_for_tk kf tkind in let p = Property.ip_of_assigns kf Kglobal b (Writes a) in Extlib.opt_map (mk_prop kind) p let mk_pre_id kf ki b p = mk_prop PKProp (Property.ip_of_requires kf ki b p) let mk_stmt_post_id kf s b p = mk_prop PKProp (Property.ip_of_ensures kf (Kstmt s) b p) let mk_fct_post_id kf b p = mk_prop PKProp (Property.ip_of_ensures kf Kglobal b p) let mk_call_pre_id called_kf s_call called_pre called_pre_p = let kind = PKPre (called_kf, s_call, called_pre) in mk_prop kind called_pre_p let kind_order = function | PKProp -> 0 | PKPre _ -> 1 | PKEstablished -> 2 | PKPreserved -> 3 | PKVarPos -> 4 | PKVarDecr -> 5 | PKPropLoop -> 6 | PKAFctOut -> 7 | PKAFctExit -> 8 | PKCheck -> 9 | PKTactic -> 10 let compare_kind k1 k2 = match k1, k2 with PKPre (kf1, ki1, p1), PKPre (kf2, ki2, p2) -> let cmp = Kernel_function.compare kf1 kf2 in if cmp <> 0 then cmp else let cmp = Stmt.compare ki1 ki2 in if cmp <> 0 then cmp else Property.compare p1 p2 | _,_ -> Transitioning.Stdlib.compare (kind_order k1) (kind_order k2) let compare_prop_id pid1 pid2 = let p1 = property_of_id pid1 in let p2 = property_of_id pid2 in let cmp = Description.full_compare p1 p2 in if cmp <> 0 then cmp else let cmp = compare_kind pid2.p_kind pid1.p_kind in if cmp <> 0 then cmp else Transitioning.Stdlib.compare pid1.p_part pid2.p_part module PropId = Datatype.Make_with_collections( struct type t = prop_id include Datatype.Undefined let name = "WpAnnot.prop_id" let reprs = List.map (fun x -> { p_kind = PKProp; p_prop = x; p_part = None }) Property.reprs let hash pid = Property.hash pid.p_prop let compare = compare_prop_id let equal pid1 pid2 = compare_prop_id pid1 pid2 = 0 let copy = Datatype.undefined let rehash = Datatype.identity let internal_pretty_code = Datatype.undefined let pretty = Datatype.undefined let mem_project = Datatype.never_any_project let varname = Datatype.undefined end) --- --- module NameUniquify(D:Datatype.S_with_collections)(S:sig val name: string val basename: D.t -> string end) : sig val unique_basename: D.t -> string end = struct module NamesTbl = State_builder.Hashtbl(Datatype.String.Hashtbl)(Datatype.Int) (struct let name = S.name^"Names" let dependencies = [ ] let size = 97 end) module IndexTbl = State_builder.Hashtbl(D.Hashtbl)(Datatype.String) (struct let name = S.name^"Index" let dependencies = [ Ast.self; NamesTbl.self; Globals.Functions.self; Annotations.code_annot_state; Annotations.funspec_state; Annotations.global_state ] let size = 97 end) let reserve_name_id pid = let basename = S.basename pid in try let speed_up_start = NamesTbl.find basename in let n,unique_name = Extlib.make_unique_name NamesTbl.mem ~sep:"_" ~start:speed_up_start basename unique_name first time that basename is reserved NamesTbl.add basename 2 ; basename let unique_basename pid = try IndexTbl.find pid first time we are asking for a name for that [ ip ] let unique_name = reserve_name_id pid in IndexTbl.add pid unique_name ; unique_name end module LegacyNames : sig val get_prop_id_name: prop_id -> string end = struct let base_id_prop_txt = Property.LegacyNames.get_prop_name_id let basename_of_prop_id p = match p.p_kind , p.p_prop with | (PKTactic | PKCheck | PKProp | PKPropLoop) , p -> base_id_prop_txt p | PKEstablished , p -> base_id_prop_txt p ^ "_established" | PKPreserved , p -> base_id_prop_txt p ^ "_preserved" | PKVarDecr , p -> base_id_prop_txt p ^ "_decrease" | PKVarPos , p -> base_id_prop_txt p ^ "_positive" | PKAFctOut , p -> base_id_prop_txt p ^ "_normal" | PKAFctExit , p -> base_id_prop_txt p ^ "_exit" | PKPre(_kf,stmt,pre) , _ -> let kf_name_of_stmt = Kernel_function.get_name (Kernel_function.find_englobing_kf stmt) in Printf.sprintf "%s_call_%s" kf_name_of_stmt (base_id_prop_txt pre) let normalize_basename s = let max_len = Wp_parameters.TruncPropIdFileName.get () in if max_len > 0 && String.length s > max_len then if max_len > 3 then (String.sub s 0 (max_len-3)) ^ "___" else String.sub s 0 max_len else s let get_prop_id_basename p = let basename = basename_of_prop_id p in let basename = match p.p_part with | None -> basename | Some(k,n) -> if n < 10 then Printf.sprintf "%s_part%d" basename (succ k) else if n < 100 then Printf.sprintf "%s_part%02d" basename (succ k) else if n < 1000 then Printf.sprintf "%s_part%03d" basename (succ k) else Printf.sprintf "%s_part%06d" basename (succ k) in normalize_basename basename module UniquifyPropId = NameUniquify(PropId)(struct let name = "WpProperty" let basename = get_prop_id_basename end) let get_prop_id_name pid = UniquifyPropId.unique_basename pid end module Names: sig val get_prop_id_name: prop_id -> string end = struct * Uniquify the first part of the prop_id module Uniquify1 = NameUniquify(Property)(struct let name = "Wp.WpPropId.Names." let basename ip = let truncate = max 20 (Wp_parameters.TruncPropIdFileName.get ()) in Property.Names.get_prop_basename ~truncate ip end) let get_ip ip = Uniquify1.unique_basename ip * Uniquify call - site for precondition check . So that precondition of the same call - site are grouped that precondition of the same call-site are grouped *) module CallSite = Datatype.Triple_with_collections (Kernel_function)(Kernel_function)(Stmt) (struct let module_name = "Wp.WpPropId.CallSite" end) module Uniquify_Stmt = NameUniquify(CallSite)(struct let name = "Wp.WpPropId.Names3." let basename (caller_kf,callee_kf,_stmt) = (Kernel_function.get_name caller_kf)^"_call_"^(Kernel_function.get_name callee_kf) end) let get_prop_id_base p = match p.p_kind , p.p_prop with | (PKTactic | PKCheck | PKProp | PKPropLoop) , p -> get_ip p | PKEstablished , p -> get_ip p ^ "_established" | PKPreserved , p -> get_ip p ^ "_preserved" | PKVarDecr , p -> get_ip p ^ "_decrease" | PKVarPos , p -> get_ip p ^ "_positive" | PKAFctOut , p -> get_ip p ^ "_normal" | PKAFctExit , p -> get_ip p ^ "_exit" | PKPre(callee_kf,stmt,pre) , _ -> let caller_kf = Kernel_function.find_englobing_kf stmt in let call_string = Uniquify_Stmt.unique_basename (caller_kf,callee_kf,stmt) in let ip_string = get_ip pre in let ip_string = Extlib.opt_conv ip_string (Extlib.string_del_prefix ((Kernel_function.get_name callee_kf)^"_") ip_string) in call_string^"_"^ip_string let get_prop_id_basename p = let basename = get_prop_id_base p in match p.p_part with | None -> basename | Some(k,n) -> if n < 10 then Printf.sprintf "%s_part%d" basename (succ k) else if n < 100 then Printf.sprintf "%s_part%02d" basename (succ k) else if n < 1000 then Printf.sprintf "%s_part%03d" basename (succ k) else Printf.sprintf "%s_part%06d" basename (succ k) module Uniquify2 = NameUniquify(PropId)(struct let name = "Wp.WpPropId.Names2." let basename = get_prop_id_basename end) let get_prop_id_name p = Uniquify2.unique_basename p end let get_legacy = LegacyNames.get_prop_id_name * Legacy property PO name let get_propid = Names.get_prop_id_name let pp_propid fmt pid = Format.pp_print_string fmt (get_propid pid) let pp_names fmt l = match l with [] -> () | _ -> Format.fprintf fmt "_%a" (Wp_error.pp_string_list ~empty:"" ~sep:"_") l let ident_names names = List.filter (function "" -> true | _ as n -> '\"' <> (String.get n 0) ) names let code_annot_names ca = match ca.annot_content with | AAssert (_, Check, named_pred) -> "@check"::(ident_names named_pred.pred_name) | AAssert (_, Assert, named_pred) -> "@assert"::(ident_names named_pred.pred_name) | AInvariant (_,_,named_pred) -> "@invariant"::(ident_names named_pred.pred_name) | AVariant (term, _) -> "@variant"::(ident_names term.term_name) | AExtended(_,_,{ext_name}) -> [Printf.sprintf "@%s" ext_name] let user_prop_names p = let open Property in match p with | IPPredicate {ip_kind; ip_pred} -> Format.asprintf "@@%a" Property.pretty_predicate_kind ip_kind :: ip_pred.ip_content.pred_name | IPExtended {ie_ext={ext_name}} -> [ Printf.sprintf "@%s" ext_name ] | IPCodeAnnot {ica_ca} -> code_annot_names ica_ca | IPComplete {ic_bhvs} -> let kind_name = "@complete_behaviors" in let name = Format.asprintf "complete_behaviors%a" pp_names ic_bhvs in kind_name::[name] | IPDisjoint {ic_bhvs} -> let kind_name = "@disjoint_behaviors" in let name = Format.asprintf "disjoint_behaviors%a" pp_names ic_bhvs in kind_name::[name] | IPAssigns {ias_froms} -> List.fold_left (fun acc (t,_) -> (ident_names t.it_content.term_name) @ acc) ["@assigns"] ias_froms | IPDecrease {id_ca=Some ca} -> "@decreases"::code_annot_names ca | IPDecrease _ -> [ "@decreases" ] | IPLemma {il_name = a; il_pred = l} -> let names = "@lemma"::a::(ident_names l.pred_name) in begin match LogicUsage.section_of_lemma a with | LogicUsage.Toplevel _ -> names | LogicUsage.Axiomatic ax -> ax.LogicUsage.ax_name::names end TODO | IPFrom _ | IPAllocation _ | IPAxiomatic _ | IPAxiom _ | IPBehavior _ | IPReachable _ | IPPropertyInstance _ | IPTypeInvariant _ | IPGlobalInvariant _ | IPOther _ -> [] let string_of_termination_kind = function Normal -> "post" | Exits -> "exits" | Breaks -> "breaks" | Continues -> "continues" | Returns -> "returns" let label_of_kind = function | PKTactic -> "Tactic" | PKCheck -> "Check" | PKProp -> "Property" | PKEstablished -> "Establishment" | PKPreserved -> "Preservation" | PKVarDecr -> "Decreasing" | PKVarPos -> "Positive" | PKAFctOut -> "Function assigns" | PKAFctExit -> "Exit assigns" | PKPre(kf,_,_) -> Printf.sprintf "Precondition for '%s'" (Kernel_function.get_name kf) let label_of_prop_id p = match p.p_part with | None -> label_of_kind p.p_kind | Some(k,n) -> Printf.sprintf "%s (%d/%d)" (label_of_kind p.p_kind) (succ k) n module Pretty = struct open Format let pp_part fmt p = match p.p_part with | None -> () | Some(k,n) -> fprintf fmt " (%d/%d)" (succ k) n let pp_subprop fmt p = match p.p_kind with | PKProp | PKTactic | PKCheck | PKPropLoop -> () | PKEstablished -> pp_print_string fmt " (established)" | PKPreserved -> pp_print_string fmt " (preserved)" | PKVarDecr -> pp_print_string fmt " (decrease)" | PKVarPos -> pp_print_string fmt " (positive)" | PKAFctOut -> pp_print_string fmt " (return)" | PKAFctExit -> pp_print_string fmt " (exit)" | PKPre(kf,_,_) -> fprintf fmt " (call '%s')" (Kernel_function.get_name kf) let pp_prop fmt p = Description.pp_localized ~kf:`Never ~ki:false ~kloc:false fmt p.p_prop let pp_local fmt p = begin pp_prop fmt p ; pp_subprop fmt p ; pp_part fmt p ; end end let pretty_local = Pretty.pp_local type hints = { mutable required : string list ; mutable hints : string list ; } let add_hint hs x = if not (List.mem x hs.hints) then hs.hints <- x :: hs.hints let add_required hs x = if not (List.mem x hs.required) then hs.required <- x :: hs.required let stmt_hints hs s = List.iter (fun label -> match label with | Label(a,_,src) -> if src then add_hint hs a | Default _ -> add_hint hs "default" | Case(e,_) -> match Ctypes.get_int64 e with | Some k -> add_hint hs ("case-" ^ Int64.to_string k) | None -> () ) s.labels let kinstr_hints hs = function | Kstmt s -> stmt_hints hs s | Kglobal -> () let propid_hints hs p = let open Property in match p.p_kind , p.p_prop with | PKCheck , _ -> () | PKProp , IPAssigns {ias_kinstr=Kstmt _} -> add_required hs "stmt-assigns" | PKProp , IPAssigns {ias_kinstr=Kglobal} -> add_required hs "fct-assigns" | PKPropLoop , Property.IPAssigns _ -> add_required hs "loop-assigns" | PKPropLoop , _ -> add_required hs "invariant" | PKProp , _ -> add_required hs "property" | PKTactic , _ -> add_required hs "tactic" | PKEstablished , _ -> add_required hs "established" | PKPreserved , _ -> add_required hs "preserved" | PKVarDecr , _ -> add_required hs "decrease" | PKVarPos , _ -> add_required hs "positive" | PKAFctOut , _ -> add_required hs "return" | PKAFctExit , _ -> add_required hs "exit" | PKPre(kf,st,_) , _ -> add_required hs ("precond-" ^ Kernel_function.get_name kf) ; stmt_hints hs st let rec term_hints hs t = match t.term_node with | TLval(lv,_) -> lval_hints hs lv | TAddrOf(lv,_) -> lval_hints hs lv | TCastE(_,t) -> term_hints hs t | TBinOp((PlusPI|IndexPI|MinusPI),a,_) -> term_hints hs a | Tlet(_,t) -> term_hints hs t | _ -> () and lval_hints hs = function | TVar { lv_origin=Some { vorig_name=x } } | TVar { lv_name=x } -> add_hint hs x | TResult _ -> add_hint hs "result" | TMem t -> add_hint hs "*" ; term_hints hs t let assigns_hints hs froms = List.iter (fun ({it_content=t},_) -> term_hints hs t) froms let annot_hints hs = function | AAssert(bs,_,ipred) | AInvariant(bs,_,ipred) -> List.iter (add_hint hs) (ident_names ipred.pred_name) ; List.iter (add_hint hs) bs | AAssigns(bs,Writes froms) -> List.iter (add_hint hs) bs ; assigns_hints hs froms | AAllocation _ | AAssigns(_,WritesAny) | AStmtSpec _ | AVariant _ | APragma _ | AExtended _ -> () let property_hints hs = let open Property in function | IPAxiom {il_name; il_pred} | IPLemma {il_name; il_pred} -> List.iter (add_required hs) (il_name::il_pred.pred_name) | IPBehavior _ -> () | IPComplete {ic_bhvs} | IPDisjoint {ic_bhvs} -> List.iter (add_required hs) ic_bhvs | IPPredicate {ip_pred} -> List.iter (add_hint hs) ip_pred.ip_content.pred_name | IPExtended {ie_ext={ext_name}} -> List.iter (add_hint hs) [ext_name] | IPCodeAnnot {ica_ca} -> annot_hints hs ica_ca.annot_content | IPAssigns {ias_froms} -> assigns_hints hs ias_froms TODO | IPFrom _ | Property.IPDecrease _ | Property.IPPropertyInstance _ | IPReachable _ | Property.IPAxiomatic _ | Property.IPOther _ | IPTypeInvariant _ | Property.IPGlobalInvariant _ -> () let prop_id_keys p = begin let hs = { hints=[] ; required=[] } in let opt add f = function None -> () | Some x -> add hs (f x) in propid_hints hs p ; property_hints hs p.p_prop ; opt add_required Kernel_function.get_name (Property.get_kf p.p_prop) ; opt add_required (fun b -> if Cil.is_default_behavior b then "default" else b.b_name) (Property.get_behavior p.p_prop) ; opt add_hint (fun (k,_) -> Printf.sprintf "part-%d" k) p.p_part ; kinstr_hints hs (Property.get_kinstr p.p_prop) ; List.sort String.compare hs.required , List.sort String.compare hs.hints end let pp_goal_kind fmt = function | PKTactic | PKCheck | PKProp | PKPropLoop | PKAFctOut | PKAFctExit | PKPre _ -> () | PKEstablished -> Format.pp_print_string fmt "Establishment of " | PKPreserved -> Format.pp_print_string fmt "Preservation of " | PKVarDecr -> Format.pp_print_string fmt "Decreasing of " | PKVarPos -> Format.pp_print_string fmt "Positivity of " let pp_goal_part fmt = function | None -> () | Some(k,n) -> Format.fprintf fmt " (%d/%d)" (succ k) n let pretty fmt pid = begin pp_goal_kind fmt pid.p_kind ; Description.pp_property fmt pid.p_prop ; pp_goal_part fmt pid.p_part ; end let pretty_context kf fmt pid = begin pp_goal_kind fmt pid.p_kind ; Description.pp_localized ~kf ~ki:true ~kloc:true fmt pid.p_prop ; pp_goal_part fmt pid.p_part ; end Comparison let is_check p = p.p_kind = PKCheck let is_tactic p = p.p_kind = PKTactic let is_assigns p = match property_of_id p with | Property.IPAssigns _ -> true | _ -> false let is_requires = let open Property in function | IPPredicate {ip_kind = PKRequires _} -> true | _ -> false let is_loop_preservation p = match p.p_kind with | PKPreserved -> begin match Property.get_kinstr p.p_prop with | Kglobal -> Wp_parameters.fatal "Loop Preservation ? (%a)" Property.pretty p.p_prop | Kstmt st -> Some st end | _ -> None let user_prop_pid pid = let p_prop = match pid.p_kind with | PKPre (_,_,p_prop) -> p_prop | _ -> property_of_id pid in user_prop_names p_prop let select_default pid = let names = user_prop_pid pid in not (List.mem "no_wp" names) let select_by_name asked_names pid = let names = user_prop_pid pid in if List.mem "no_wp" names then false else let is_minus s = try s.[0] = '-' with _ -> false in let is_plus s = try s.[0] = '+' with _ -> false in let remove_first s = String.sub s 1 ((String.length s) -1) in let eval acc asked = let is_minus,a = match acc with | None -> if is_minus asked then true,true else false,false | Some a -> (is_minus asked),a in let eval () = let asked = if is_minus || (is_plus asked) then remove_first asked else asked in List.mem asked names in Some (if is_minus then a && (not (eval ())) else a || (eval ())) in match List.fold_left eval None asked_names with | Some false -> false | _ -> true let select_call_pre s_call asked_pre pid = match pid.p_kind with | PKPre (_, p_stmt, p_prop) -> Stmt.equal s_call p_stmt && (match asked_pre with | None -> true | Some asked_pre -> Property.equal p_prop asked_pre) | _ -> false type a_kind = LoopAssigns | StmtAssigns type effect_source = FromCode | FromCall | FromReturn type assigns_desc = { a_label : Clabels.c_label ; a_stmt : Cil_types.stmt option ; a_kind : a_kind ; a_assigns : Cil_types.assigns ; } let mk_asm_assigns_desc s = { a_label = Clabels.stmt s ; a_stmt = Some s ; a_kind = StmtAssigns ; a_assigns = WritesAny ; } let mk_loop_assigns_desc s assigns = { a_label = Clabels.stmt s ; a_stmt = Some s ; a_kind = LoopAssigns ; a_assigns = Writes assigns } let mk_stmt_assigns_desc s assigns = { a_label = Clabels.stmt s ; a_stmt = Some s ; a_kind = StmtAssigns ; a_assigns = Writes assigns ; } let mk_init_assigns = { a_label = Clabels.init ; a_stmt = None ; a_kind = StmtAssigns ; a_assigns = WritesAny ; } let mk_fout_assigns_desc assigns = { a_label = Logic_const.pre_label ; a_kind = StmtAssigns ; a_assigns = Writes assigns ; } let mk_exit_assigns_desc assigns = { a_label = Logic_const.pre_label ; a_kind = StmtAssigns ; a_assigns = Writes assigns ; } *) let mk_kf_assigns_desc assigns = { a_label = Clabels.pre ; a_stmt = None ; a_kind = StmtAssigns ; a_assigns = Writes assigns ; } let is_call_assigns = function | {a_stmt=Some {skind=Instr(Call _ | Local_init (_, ConsInit _, _)) } } -> true | _ -> false let pp_assigns_desc fmt a = Wp_error.pp_assigns fmt a.a_assigns * * 2 kinds of annotations can be found : predicates and assigns . * because assigns properties can only be translated into predicates * by the memory model . * - Assigns properties are composed of the assigns list from , * and a label to know where to stop . * - Predicates are just the predicate type from . * 2 kinds of annotations can be found : predicates and assigns. * because assigns properties can only be translated into predicates * by the memory model. * - Assigns properties are composed of the assigns list from Cil, * and a label to know where to stop. * - Predicates are just the predicate type from Cil. *) type pred_info = prop_id * Cil_types.predicate let mk_pred_info id p = (id, p) let pred_info_id (id, _) = id let pp_pred_of_pred_info fmt (_id, p) = Printer.pp_predicate fmt p let pp_pred_info fmt (id, p) = Format.fprintf fmt "(@[%a:@ %a@])" pp_propid id Printer.pp_predicate p type assigns_info = prop_id * assigns_desc let assigns_info_id (id,_) = id type assigns_full_info = AssignsLocations of assigns_info | AssignsAny of assigns_desc | NoAssignsInfo let empty_assigns_info = NoAssignsInfo let mk_assigns_info id a = AssignsLocations (id, a) let mk_stmt_any_assigns_info s = let a = { a_label = Clabels.stmt s ; a_stmt = Some s ; a_kind = StmtAssigns ; a_assigns = WritesAny ; } in AssignsAny a let mk_kf_any_assigns_info () = let a = { a_label = Clabels.pre ; a_stmt = None ; a_kind = StmtAssigns ; a_assigns = WritesAny ; } in AssignsAny a let mk_loop_any_assigns_info s = let a = { a_label = Clabels.stmt s ; a_stmt = Some s ; a_kind = LoopAssigns ; a_assigns = WritesAny ; } in AssignsAny a let pp_assign_info k fmt a = match a with | NoAssignsInfo -> () | AssignsAny a -> let pkind = match a.a_kind with | StmtAssigns -> "" | LoopAssigns -> "loop" in Format.fprintf fmt "%s(@@%a): %s assigns everything@." k Clabels.pretty a.a_label pkind | AssignsLocations (_,a) -> Format.fprintf fmt "%s(@@%a): %a@." k Clabels.pretty a.a_label pp_assigns_desc a let merge_assign_info a1 a2 = match a1,a2 with | NoAssignsInfo, a | a, NoAssignsInfo -> a | (AssignsLocations _ | AssignsAny _), (AssignsLocations _ | AssignsAny _) -> Wp_parameters.fatal "Several assigns ?" type axiom_info = prop_id * LogicUsage.logic_lemma let mk_axiom_info lemma = let id = mk_lemma_id lemma in (id, lemma) let pp_axiom_info fmt (id,thm) = Format.fprintf fmt "(@[%a:@ %a@])" pp_propid id Printer.pp_predicate thm.LogicUsage.lem_property let _split job pid goals = let n = Bag.length goals in if n <= 1 then Bag.iter (job pid) goals else let k = ref 0 in Bag.iter (fun g -> let pid_k = mk_part pid (!k,n) in incr k ; job pid_k g) goals let subproofs id = match id.p_kind with | PKCheck -> 0 | PKProp | PKTactic | PKPre _ | PKPropLoop -> 1 | PKEstablished | PKPreserved | PKVarDecr | PKVarPos | PKAFctExit | PKAFctOut -> 2 let subproof_idx id = match id.p_kind with 0/0 1/1 1/2 2/2 1/2 2/2 1/2 2/2 * find the outer loop in which the stmt is . let get_loop_stmt kf stmt = because we do n't have the cfg here , we can only use Cil information , * and then we can only recognize syntactic loops ... TODO : use the cfg ? * and then we can only recognize syntactic loops... TODO: use the cfg ? *) let rec is_in_blk b = List.exists is_in_stmt b.bstmts and is_in_stmt s = if s.sid = stmt.sid then true else match s.skind with | If (_, b1, b2,_) -> is_in_blk b1 || is_in_blk b2 | Switch (_, b, _, _) | Block b -> is_in_blk b | UnspecifiedSequence seq -> let b = Cil.block_from_unspecified_sequence seq in is_in_blk b | Loop (_, b, _, _, _) -> is_in_blk b | _ -> false and find_loop_in_blk blk = find_loop_in_stmts blk.bstmts and find_loop_in_stmts l = match l with | [] -> None | s::tl -> (match find_loop_in_stmt s with Some l -> Some l | None -> find_loop_in_stmts tl) and find_loop_in_stmt s = match s.skind with | (Loop _) -> if is_in_stmt s then Some s else None | If (_, b1, b2,_) -> (match find_loop_in_blk b1 with Some l -> Some l | None -> find_loop_in_blk b2) | Switch (_, b, _, _) | Block b -> find_loop_in_blk b | UnspecifiedSequence seq -> let b = Cil.block_from_unspecified_sequence seq in find_loop_in_blk b | _ -> None in let f = Kernel_function.get_definition kf in find_loop_in_blk f.sbody * Quite do n't understand what is going on here ... what is it supposed to do ? * [ 2011 - 07 - 07 - Anne ] * [2011-07-07-Anne] *) let get_induction p = let get_stmt = let open Property in function | IPDecrease {id_kf;id_kinstr=Kstmt stmt} -> Some (id_kf, stmt) | IPCodeAnnot {ica_kf;ica_stmt} -> Some (ica_kf, ica_stmt) | IPAssigns {ias_kf; ias_kinstr=Kstmt stmt} -> Some (ias_kf, stmt) | _ -> None in match p.p_kind with | PKCheck | PKAFctOut|PKAFctExit|PKPre _ | PKTactic -> None | PKProp -> let loop_stmt_opt = match get_stmt (property_of_id p) with | None -> None | Some (kf, s) -> get_loop_stmt kf s in loop_stmt_opt | PKPropLoop -> let open Property in let loop_stmt_opt = match property_of_id p with | IPCodeAnnot {ica_kf; ica_stmt; ica_ca = {annot_content = AInvariant(_, loop, _)}} -> | IPAssigns {ias_kinstr=Kstmt stmt; ias_bhv = Id_loop _} -> in loop_stmt_opt | PKEstablished|PKVarDecr|PKVarPos|PKPreserved -> (match get_stmt (property_of_id p) with | None -> None | Some (_, s) -> Some s)
9a1e82d6d966a2b513febe7fc8d3e231cb08aa382ce51abe082086fc55f6fdaa
electric-sql/vaxine
antidote_hooks.erl
%% ------------------------------------------------------------------- %% Copyright < 2013 - 2018 > < Technische Universität Kaiserslautern , Germany , France Universidade NOVA de Lisboa , Portugal Université catholique de Louvain ( UCL ) , Belgique , Portugal %% > %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either expressed or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% List of the contributors to the development of Antidote : see file . %% Description and complete License: see LICENSE file. %% ------------------------------------------------------------------- Pre - Commit hooks %% ------------------------ %% Pre-commit hooks are executed before an object is being updated. If %% pre-commit hook fails, the entire transaction is aborted. %% The commit hook function must be a function which take one argument which is %% of type update_object() and returns update_object(). %% The update operation corresponds to a data-type specific operation as defined in the respective CRDT specification . %% %% fun (update_object()) -> {ok, update_object()} | {error, Reason}. %% -type update_object() :: {{key(), bucket()}, crdt_type(), op()} %% The returned update_object() is used for updating the object. %% An example commit hook function is written in %% antidote_hooks.erl : test_increment_hook/1. %% Post-commit hooks %% ------------------------ %% Post commit hooks are executed after the transaction is successfully committed %% and before the reply is sent to the client. Currently if post commit hook is %% failed, it is ignored and transaction is still considered to be successfully %% committed and the client is notified of the success. %% An example commit hook function is written in %% antidote_hooks.erl: test_post_hook/1 %% An example of how to use these interfaces is given in %% riak_test/commit_hooks_test.erl -module(antidote_hooks). -include("antidote.hrl"). -include_lib("kernel/include/logger.hrl"). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -export([ register_pre_hook/3, register_post_hook/3, get_hooks/2, unregister_hook/2, execute_pre_commit_hook/3, execute_post_commit_hook/3 ]). -export([ test_commit_hook/1, test_increment_hook/1, test_post_hook/1 ]). -define(PREFIX_PRE, {commit_hooks, pre}). -define(PREFIX_POST, {commit_hooks, post}). -spec register_post_hook(bucket(), module_name(), function_name()) -> ok | {error, function_not_exported}. register_post_hook(Bucket, Module, Function) -> register_hook(?PREFIX_POST, Bucket, Module, Function). -spec register_pre_hook(bucket(), module_name(), function_name()) -> ok | {error, function_not_exported}. register_pre_hook(Bucket, Module, Function) -> register_hook(?PREFIX_PRE, Bucket, Module, Function). Overwrites the previous commit hook register_hook(Prefix, Bucket, Module, Function) -> case erlang:function_exported(Module, Function, 1) of true -> stable_meta_data_server:broadcast_meta_data({Prefix, Bucket}, {Module, Function}), ok; false -> {error, function_not_exported} end. -spec unregister_hook(pre_commit | post_commit, bucket()) -> ok. unregister_hook(pre_commit, Bucket) -> stable_meta_data_server:broadcast_meta_data({?PREFIX_PRE, Bucket}, undefined); unregister_hook(post_commit, Bucket) -> stable_meta_data_server:broadcast_meta_data({?PREFIX_POST, Bucket}, undefined). get_hooks(pre_commit, Bucket) -> R = stable_meta_data_server:read_meta_data({?PREFIX_PRE, Bucket}), case R of {ok, Hooks} -> Hooks; error -> undefined end; get_hooks(post_commit, Bucket) -> R = stable_meta_data_server:read_meta_data({?PREFIX_POST, Bucket}), case R of {ok, Hooks} -> Hooks; error -> undefined end. -spec execute_pre_commit_hook(term(), type(), op_param()) -> {term(), type(), op_param()} | {error, reason()}. execute_pre_commit_hook({Key, Bucket}, Type, Param) -> Hook = get_hooks(pre_commit, Bucket), case Hook of undefined -> {{Key, Bucket}, Type, Param}; {Module, Function} -> try Module:Function({{Key, Bucket}, Type, Param}) of {ok, Res} -> Res catch _:Reason -> {error, {pre_commit_hook, Reason}} end end; %% The following is kept to be backward compatible with the old %% interface where buckets are not used execute_pre_commit_hook(Key, Type, Param) -> {Key, Type, Param}. -spec execute_post_commit_hook(term(), type(), op_param()) -> {term(), type(), op_param()} | {error, reason()}. execute_post_commit_hook({Key, Bucket}, Type, Param) -> Hook = get_hooks(post_commit, Bucket), case Hook of undefined -> {{Key, Bucket}, Type, Param}; {Module, Function} -> try Module:Function({{Key, Bucket}, Type, Param}) of {ok, Res} -> Res catch _:Reason -> {error, {post_commit_hook, Reason}} end end; execute_post_commit_hook(Key, Type, Param) -> {Key, Type, Param}. %-ifdef(TEST). %% The following functions here provide commit hooks for the testing (test/commit_hook_SUITE). test_commit_hook(Object) -> ?LOG_INFO("Executing test commit hook"), {ok, Object}. test_increment_hook({{Key, Bucket}, antidote_crdt_counter_pn, {increment, 1}}) -> {ok, {{Key, Bucket}, antidote_crdt_counter_pn, {increment, 2}}}. test_post_hook({{Key, Bucket}, Type, OP}) -> {ok, _CT} = antidote:update_objects(ignore, [], [ {{Key, antidote_crdt_counter_pn, commitcount}, increment, 1} ]), {ok, {{Key, Bucket}, Type, OP}}. %-endif.
null
https://raw.githubusercontent.com/electric-sql/vaxine/872a83ea8d4935a52c7b850bb17ab099ee9c346b/apps/antidote/src/antidote_hooks.erl
erlang
------------------------------------------------------------------- > Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either expressed or implied. See the License for the specific language governing permissions and limitations under the License. Description and complete License: see LICENSE file. ------------------------------------------------------------------- ------------------------ Pre-commit hooks are executed before an object is being updated. If pre-commit hook fails, the entire transaction is aborted. of type update_object() and returns update_object(). The update operation corresponds to a data-type specific operation as defined fun (update_object()) -> {ok, update_object()} | {error, Reason}. -type update_object() :: {{key(), bucket()}, crdt_type(), op()} The returned update_object() is used for updating the object. An example commit hook function is written in antidote_hooks.erl : test_increment_hook/1. Post-commit hooks ------------------------ Post commit hooks are executed after the transaction is successfully committed and before the reply is sent to the client. Currently if post commit hook is failed, it is ignored and transaction is still considered to be successfully committed and the client is notified of the success. An example commit hook function is written in antidote_hooks.erl: test_post_hook/1 An example of how to use these interfaces is given in riak_test/commit_hooks_test.erl The following is kept to be backward compatible with the old interface where buckets are not used -ifdef(TEST). The following functions here provide commit hooks for the testing (test/commit_hook_SUITE). -endif.
Copyright < 2013 - 2018 > < Technische Universität Kaiserslautern , Germany , France Universidade NOVA de Lisboa , Portugal Université catholique de Louvain ( UCL ) , Belgique , Portugal This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY List of the contributors to the development of Antidote : see file . Pre - Commit hooks The commit hook function must be a function which take one argument which is in the respective CRDT specification . -module(antidote_hooks). -include("antidote.hrl"). -include_lib("kernel/include/logger.hrl"). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -export([ register_pre_hook/3, register_post_hook/3, get_hooks/2, unregister_hook/2, execute_pre_commit_hook/3, execute_post_commit_hook/3 ]). -export([ test_commit_hook/1, test_increment_hook/1, test_post_hook/1 ]). -define(PREFIX_PRE, {commit_hooks, pre}). -define(PREFIX_POST, {commit_hooks, post}). -spec register_post_hook(bucket(), module_name(), function_name()) -> ok | {error, function_not_exported}. register_post_hook(Bucket, Module, Function) -> register_hook(?PREFIX_POST, Bucket, Module, Function). -spec register_pre_hook(bucket(), module_name(), function_name()) -> ok | {error, function_not_exported}. register_pre_hook(Bucket, Module, Function) -> register_hook(?PREFIX_PRE, Bucket, Module, Function). Overwrites the previous commit hook register_hook(Prefix, Bucket, Module, Function) -> case erlang:function_exported(Module, Function, 1) of true -> stable_meta_data_server:broadcast_meta_data({Prefix, Bucket}, {Module, Function}), ok; false -> {error, function_not_exported} end. -spec unregister_hook(pre_commit | post_commit, bucket()) -> ok. unregister_hook(pre_commit, Bucket) -> stable_meta_data_server:broadcast_meta_data({?PREFIX_PRE, Bucket}, undefined); unregister_hook(post_commit, Bucket) -> stable_meta_data_server:broadcast_meta_data({?PREFIX_POST, Bucket}, undefined). get_hooks(pre_commit, Bucket) -> R = stable_meta_data_server:read_meta_data({?PREFIX_PRE, Bucket}), case R of {ok, Hooks} -> Hooks; error -> undefined end; get_hooks(post_commit, Bucket) -> R = stable_meta_data_server:read_meta_data({?PREFIX_POST, Bucket}), case R of {ok, Hooks} -> Hooks; error -> undefined end. -spec execute_pre_commit_hook(term(), type(), op_param()) -> {term(), type(), op_param()} | {error, reason()}. execute_pre_commit_hook({Key, Bucket}, Type, Param) -> Hook = get_hooks(pre_commit, Bucket), case Hook of undefined -> {{Key, Bucket}, Type, Param}; {Module, Function} -> try Module:Function({{Key, Bucket}, Type, Param}) of {ok, Res} -> Res catch _:Reason -> {error, {pre_commit_hook, Reason}} end end; execute_pre_commit_hook(Key, Type, Param) -> {Key, Type, Param}. -spec execute_post_commit_hook(term(), type(), op_param()) -> {term(), type(), op_param()} | {error, reason()}. execute_post_commit_hook({Key, Bucket}, Type, Param) -> Hook = get_hooks(post_commit, Bucket), case Hook of undefined -> {{Key, Bucket}, Type, Param}; {Module, Function} -> try Module:Function({{Key, Bucket}, Type, Param}) of {ok, Res} -> Res catch _:Reason -> {error, {post_commit_hook, Reason}} end end; execute_post_commit_hook(Key, Type, Param) -> {Key, Type, Param}. test_commit_hook(Object) -> ?LOG_INFO("Executing test commit hook"), {ok, Object}. test_increment_hook({{Key, Bucket}, antidote_crdt_counter_pn, {increment, 1}}) -> {ok, {{Key, Bucket}, antidote_crdt_counter_pn, {increment, 2}}}. test_post_hook({{Key, Bucket}, Type, OP}) -> {ok, _CT} = antidote:update_objects(ignore, [], [ {{Key, antidote_crdt_counter_pn, commitcount}, increment, 1} ]), {ok, {{Key, Bucket}, Type, OP}}.
e143296b8b57f565a8ab3690c0a4a936ad7b15af70ef84cf637eeffc63c49213
imdea-software/leap
Z3Symmetry.ml
(***********************************************************************) (* *) LEAP (* *) , IMDEA Software Institute (* *) (* *) Copyright 2011 IMDEA Software Institute (* *) 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. *) (* *) (***********************************************************************) let symmetry (fx:'a -> string) (f_spdom: 'b -> string) (f_dom:int -> string) (xs:'a list) (sp_dom:'b list) (dom:int) : string = if List.length xs > 0 && dom > 0 then begin let xs_str = List.map fx xs in let sp_dom_str = List.map f_spdom sp_dom in let (or_assert,_) = List.fold_left (fun (str,i) elem -> if i < dom then begin let sp_dom_assert = List.fold_left (fun str v -> str ^ "(= " ^elem^ " " ^v^ ") " ) "" sp_dom_str in let dom_assert = ref "" in for j = i downto 1 do dom_assert := !dom_assert ^ "(= " ^elem^ " " ^(f_dom j)^ ") " done; (str ^ " (or " ^ sp_dom_assert ^ !dom_assert ^ ")\n", i+1) end else begin (str, i) end ) ("",1) xs_str in if or_assert = "" then "" else "(assert (and\n" ^ or_assert ^ "))\n" end else ""
null
https://raw.githubusercontent.com/imdea-software/leap/5f946163c0f80ff9162db605a75b7ce2e27926ef/src/solvers/backend/query/z3/Z3Symmetry.ml
ocaml
********************************************************************* You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, either express or implied. See the License for the specific language governing permissions and limitations under the License. *********************************************************************
LEAP , IMDEA Software Institute Copyright 2011 IMDEA Software Institute Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , let symmetry (fx:'a -> string) (f_spdom: 'b -> string) (f_dom:int -> string) (xs:'a list) (sp_dom:'b list) (dom:int) : string = if List.length xs > 0 && dom > 0 then begin let xs_str = List.map fx xs in let sp_dom_str = List.map f_spdom sp_dom in let (or_assert,_) = List.fold_left (fun (str,i) elem -> if i < dom then begin let sp_dom_assert = List.fold_left (fun str v -> str ^ "(= " ^elem^ " " ^v^ ") " ) "" sp_dom_str in let dom_assert = ref "" in for j = i downto 1 do dom_assert := !dom_assert ^ "(= " ^elem^ " " ^(f_dom j)^ ") " done; (str ^ " (or " ^ sp_dom_assert ^ !dom_assert ^ ")\n", i+1) end else begin (str, i) end ) ("",1) xs_str in if or_assert = "" then "" else "(assert (and\n" ^ or_assert ^ "))\n" end else ""
7651423c4ba1ff0f197e34c73d4a7a278e8f034bb1c534a70edabd5583036cba
slindley/effect-handlers
OlegIteratees.hs
original implementation of iteratees . This example demonstrates that iteratees are algebraic computations and enumerators are effect handlers . It is a transcription of the code from Section 3 of 's FLOPS 2012 paper , Iteratees : Oleg Kiselyov's original implementation of iteratees. This example demonstrates that Oleg Kiselyov's iteratees are algebraic computations and enumerators are effect handlers. It is a transcription of the code from Section 3 of Oleg's FLOPS 2012 paper, Iteratees: -} {-# LANGUAGE BangPatterns #-} import Control.Monad type LChar = Maybe Char data I a = Done a | GetC (LChar -> I a) getC = GetC return instance Monad I where return = Done Done x >>= f = f x GetC k >>= f = GetC (k >=> f) getline :: I String getline = loop "" where loop acc = do w <- getC check acc w check acc (Just c) | c /= '\n' = loop (c:acc) check acc _ = return (reverse acc) eval :: String -> I a -> a eval "" (GetC k) = eval "" $ k Nothing eval (c:t) (GetC k) = eval t $ k (Just c) eval str (Done x) = x getlines :: I [String] getlines = loop [] where loop acc = getline >>= check acc check acc "" = return (reverse acc) check acc l = loop (l:acc) en_str :: String -> I a -> I a en_str "" i = i en_str (c:t) (GetC k) = en_str t $ k (Just c) en_str _ (Done x) = return x run :: I a -> a run (GetC k) = run $ k Nothing run (Done x) = x countI :: Char -> I Int countI c = count' 0 where count' :: Int -> I Int count' !n = do mc <- getC case mc of Nothing -> return n Just c' -> count' (if c==c' then n+1 else n) countH :: Char -> String -> Int countH c s = run (en_str s (countI c)) count :: Char -> String -> Int count c s = count' s 0 where count' :: String -> Int -> Int count' [] !n = n count' (c':cs) !n = count' cs (if c==c' then n+1 else n) test n = if n == 0 then "" else "abc" ++ test (n-1) main = print $ countH 'a' (test 100000000)
null
https://raw.githubusercontent.com/slindley/effect-handlers/39d0d09582d198dd6210177a0896db55d92529f4/Examples/OlegIteratees.hs
haskell
# LANGUAGE BangPatterns #
original implementation of iteratees . This example demonstrates that iteratees are algebraic computations and enumerators are effect handlers . It is a transcription of the code from Section 3 of 's FLOPS 2012 paper , Iteratees : Oleg Kiselyov's original implementation of iteratees. This example demonstrates that Oleg Kiselyov's iteratees are algebraic computations and enumerators are effect handlers. It is a transcription of the code from Section 3 of Oleg's FLOPS 2012 paper, Iteratees: -} import Control.Monad type LChar = Maybe Char data I a = Done a | GetC (LChar -> I a) getC = GetC return instance Monad I where return = Done Done x >>= f = f x GetC k >>= f = GetC (k >=> f) getline :: I String getline = loop "" where loop acc = do w <- getC check acc w check acc (Just c) | c /= '\n' = loop (c:acc) check acc _ = return (reverse acc) eval :: String -> I a -> a eval "" (GetC k) = eval "" $ k Nothing eval (c:t) (GetC k) = eval t $ k (Just c) eval str (Done x) = x getlines :: I [String] getlines = loop [] where loop acc = getline >>= check acc check acc "" = return (reverse acc) check acc l = loop (l:acc) en_str :: String -> I a -> I a en_str "" i = i en_str (c:t) (GetC k) = en_str t $ k (Just c) en_str _ (Done x) = return x run :: I a -> a run (GetC k) = run $ k Nothing run (Done x) = x countI :: Char -> I Int countI c = count' 0 where count' :: Int -> I Int count' !n = do mc <- getC case mc of Nothing -> return n Just c' -> count' (if c==c' then n+1 else n) countH :: Char -> String -> Int countH c s = run (en_str s (countI c)) count :: Char -> String -> Int count c s = count' s 0 where count' :: String -> Int -> Int count' [] !n = n count' (c':cs) !n = count' cs (if c==c' then n+1 else n) test n = if n == 0 then "" else "abc" ++ test (n-1) main = print $ countH 'a' (test 100000000)
bb151b53be0db322ffa7057b243b13d5542ccb7db6e47cc5f4473b3501086019
erikd/haskell-big-integer-experiment
Integer.hs
# LANGUAGE NoImplicitPrelude , MagicHash # # OPTIONS_GHC -fno - warn - orphans # * All * of this code was ripped from the GHC sources . We need this because the Integer we are compiling and testing is * not * the same as the Integer GHC already knows about . module Simple.Integer ( module Simple.GHC.Integer ) where import Simple.GHC.Integer import GHC.Base import Prelude hiding (Integer) instance Num Integer where (+) = plusInteger (-) = minusInteger (*) = minusInteger abs = absInteger signum = signumInteger fromInteger = error "Simple.Integer: fromInteger" instance Show Integer where show = hexShow hexShow :: Integer -> String hexShow i | eqInteger i (smallInteger 0#) = "0x0" | otherwise = signHex i : '0' : 'x' : reverse (inner (absInteger i)) where signHex x = if (ltInteger x (smallInteger 0#)) then '-' else '+' inner x | eqInteger x (smallInteger 0#) = [] | otherwise = let nibble = boxedIntFromInteger (andInteger x (smallInteger 15#)) in ("0123456789abcdef" !! nibble) : inner (quotInteger x (smallInteger 16#)) boxedIntFromInteger :: Integer -> Int boxedIntFromInteger i = I# (integerToInt i)
null
https://raw.githubusercontent.com/erikd/haskell-big-integer-experiment/7841ec3fcc5be219fa16963849bd12137112f8a9/Simple/Integer.hs
haskell
# LANGUAGE NoImplicitPrelude , MagicHash # # OPTIONS_GHC -fno - warn - orphans # * All * of this code was ripped from the GHC sources . We need this because the Integer we are compiling and testing is * not * the same as the Integer GHC already knows about . module Simple.Integer ( module Simple.GHC.Integer ) where import Simple.GHC.Integer import GHC.Base import Prelude hiding (Integer) instance Num Integer where (+) = plusInteger (-) = minusInteger (*) = minusInteger abs = absInteger signum = signumInteger fromInteger = error "Simple.Integer: fromInteger" instance Show Integer where show = hexShow hexShow :: Integer -> String hexShow i | eqInteger i (smallInteger 0#) = "0x0" | otherwise = signHex i : '0' : 'x' : reverse (inner (absInteger i)) where signHex x = if (ltInteger x (smallInteger 0#)) then '-' else '+' inner x | eqInteger x (smallInteger 0#) = [] | otherwise = let nibble = boxedIntFromInteger (andInteger x (smallInteger 15#)) in ("0123456789abcdef" !! nibble) : inner (quotInteger x (smallInteger 16#)) boxedIntFromInteger :: Integer -> Int boxedIntFromInteger i = I# (integerToInt i)
2e1fdbeb1d7213f0cd75a1514cbf47373f783edc2a1097a5b798b8d1db5b789e
min-ki/clojure-bootcamp
day4.clj
(ns aoc2018.day4 (:require [clojure.string :refer [split-lines]])) (def input (split-lines (slurp "resources/aoc2018/day4.txt"))) (def input-pattern #"\[(\d+)-(\d+)-(\d+)\s(\d+):(\d+)\]\s(.*)") (def guard-id-regex-pattern #"Guard #(\d+) begins shift") (defn get-guard-id [action] (last (re-matches guard-id-regex-pattern action))) (defn list->map [[year month day hour minutes action]] {:year year :month month :day day :hour hour :minutes minutes :action action}) (defn sort-by-date-asc [l] (sort-by (juxt :year :month :day :hour :minutes) l)) (defn get-repose-records [input] (->> input (map (partial re-matches input-pattern)) (map rest) (map list->map) (sort-by-date-asc))) (defn update-guard-sleep-time [result guard wake-up-time asleep-at] (-> result (update guard (fnil concat []) (range asleep-at wake-up-time)))) (defn get-guard-sleeps-info [repose-records] (->> repose-records (reduce (fn [[result current-guard asleep-at] repose-record] (let [{:keys [minutes action]} repose-record new-guard (get-guard-id action) wakes-up (= "wakes up" action) falls-asleep (= "falls asleep" action)] (cond 새로운 가드아이디를 설정해준다 . 잠이든 시간을 넣어준다 . wakes-up [(update-guard-sleep-time result current-guard (Integer/parseInt minutes) asleep-at) current-guard nil]))) [{} nil nil]) first)) (defn solve-part1 [repose-records] (let [[guard-id sleeps-info] (->> repose-records get-guard-sleeps-info (sort-by (fn [[_guard_id mins]] (count mins))) last) chosen-minute (first (last (sort-by second (frequencies sleeps-info))))] (* (Integer/parseInt guard-id) chosen-minute))) (defn solve-part2 [repose-records] (let [[guard-id [chosen-minute _chosen-frequency]] (->> repose-records get-guard-sleeps-info (map (fn [[guard-id mins]] [guard-id (last (sort-by second (frequencies mins)))])) (into {}) (sort-by (fn [[_guard-id [_chosen-minute chosen-frequency]]] chosen-frequency)) last)] (* (Integer/parseInt guard-id) chosen-minute))) (comment (->> input get-repose-records solve-part1) (->> input get-repose-records solve-part2))
null
https://raw.githubusercontent.com/min-ki/clojure-bootcamp/2d9e6ebcc46894fbea7672e07c2008e62fad4d81/src/aoc2018/day4.clj
clojure
(ns aoc2018.day4 (:require [clojure.string :refer [split-lines]])) (def input (split-lines (slurp "resources/aoc2018/day4.txt"))) (def input-pattern #"\[(\d+)-(\d+)-(\d+)\s(\d+):(\d+)\]\s(.*)") (def guard-id-regex-pattern #"Guard #(\d+) begins shift") (defn get-guard-id [action] (last (re-matches guard-id-regex-pattern action))) (defn list->map [[year month day hour minutes action]] {:year year :month month :day day :hour hour :minutes minutes :action action}) (defn sort-by-date-asc [l] (sort-by (juxt :year :month :day :hour :minutes) l)) (defn get-repose-records [input] (->> input (map (partial re-matches input-pattern)) (map rest) (map list->map) (sort-by-date-asc))) (defn update-guard-sleep-time [result guard wake-up-time asleep-at] (-> result (update guard (fnil concat []) (range asleep-at wake-up-time)))) (defn get-guard-sleeps-info [repose-records] (->> repose-records (reduce (fn [[result current-guard asleep-at] repose-record] (let [{:keys [minutes action]} repose-record new-guard (get-guard-id action) wakes-up (= "wakes up" action) falls-asleep (= "falls asleep" action)] (cond 새로운 가드아이디를 설정해준다 . 잠이든 시간을 넣어준다 . wakes-up [(update-guard-sleep-time result current-guard (Integer/parseInt minutes) asleep-at) current-guard nil]))) [{} nil nil]) first)) (defn solve-part1 [repose-records] (let [[guard-id sleeps-info] (->> repose-records get-guard-sleeps-info (sort-by (fn [[_guard_id mins]] (count mins))) last) chosen-minute (first (last (sort-by second (frequencies sleeps-info))))] (* (Integer/parseInt guard-id) chosen-minute))) (defn solve-part2 [repose-records] (let [[guard-id [chosen-minute _chosen-frequency]] (->> repose-records get-guard-sleeps-info (map (fn [[guard-id mins]] [guard-id (last (sort-by second (frequencies mins)))])) (into {}) (sort-by (fn [[_guard-id [_chosen-minute chosen-frequency]]] chosen-frequency)) last)] (* (Integer/parseInt guard-id) chosen-minute))) (comment (->> input get-repose-records solve-part1) (->> input get-repose-records solve-part2))
0728d65bd15586d8019d27b92518466a38889def116f6bb19d6a2d570592e366
chenyukang/eopl
check-modules.scm
(module check-modules (lib "eopl.ss" "eopl") (require "drscheme-init.scm") (require "lang.scm") (require "static-data-structures.scm") (require "checker.scm") (require "subtyping.scm") (provide type-of-program) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; type-of-program : Program -> Type Page : 286 (define type-of-program (lambda (pgm) (cases program pgm (a-program (module-defs body) (type-of body (add-module-defns-to-tenv module-defs (empty-tenv))))))) ;; add-module-defns-to-tenv : Listof(ModuleDefn) * Tenv -> Tenv Page : 286 (define add-module-defns-to-tenv (lambda (defns tenv) (if (null? defns) tenv (cases module-definition (car defns) (a-module-definition (m-name expected-iface m-body) (let ((actual-iface (interface-of m-body tenv))) (if (<:-iface actual-iface expected-iface tenv) (let ((new-tenv (extend-tenv-with-module m-name expected-iface tenv))) (add-module-defns-to-tenv (cdr defns) new-tenv)) (report-module-doesnt-satisfy-iface m-name expected-iface actual-iface)))))))) ;; interface-of : ModuleBody * Tenv -> Iface Page : 288 (define interface-of (lambda (m-body tenv) (cases module-body m-body (defns-module-body (defns) (simple-iface (defns-to-decls defns tenv))) ))) ;; defns-to-decls : Listof(Defn) * Tenv -> Listof(Decl) Page : 288 ;; Convert defns to a set of declarations for just the names defined in defns . Do this in the context of tenv . The tenv is extended ;; at every step, so we get the correct let* scoping ;; (define defns-to-decls (lambda (defns tenv) (if (null? defns) '() (cases definition (car defns) (val-defn (var-name exp) (let ((ty (type-of exp tenv))) (let ((new-env (extend-tenv var-name ty tenv))) (cons (val-decl var-name ty) (defns-to-decls (cdr defns) new-env))))))))) (define report-module-doesnt-satisfy-iface (lambda (m-name expected-type actual-type) (pretty-print (list 'error-in-defn-of-module: m-name 'expected-type: expected-type 'actual-type: actual-type)) (eopl:error 'type-of-module-defn))) )
null
https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/base/chapter8/simplemodules/check-modules.scm
scheme
type-of-program : Program -> Type add-module-defns-to-tenv : Listof(ModuleDefn) * Tenv -> Tenv interface-of : ModuleBody * Tenv -> Iface defns-to-decls : Listof(Defn) * Tenv -> Listof(Decl) at every step, so we get the correct let* scoping
(module check-modules (lib "eopl.ss" "eopl") (require "drscheme-init.scm") (require "lang.scm") (require "static-data-structures.scm") (require "checker.scm") (require "subtyping.scm") (provide type-of-program) Page : 286 (define type-of-program (lambda (pgm) (cases program pgm (a-program (module-defs body) (type-of body (add-module-defns-to-tenv module-defs (empty-tenv))))))) Page : 286 (define add-module-defns-to-tenv (lambda (defns tenv) (if (null? defns) tenv (cases module-definition (car defns) (a-module-definition (m-name expected-iface m-body) (let ((actual-iface (interface-of m-body tenv))) (if (<:-iface actual-iface expected-iface tenv) (let ((new-tenv (extend-tenv-with-module m-name expected-iface tenv))) (add-module-defns-to-tenv (cdr defns) new-tenv)) (report-module-doesnt-satisfy-iface m-name expected-iface actual-iface)))))))) Page : 288 (define interface-of (lambda (m-body tenv) (cases module-body m-body (defns-module-body (defns) (simple-iface (defns-to-decls defns tenv))) ))) Page : 288 Convert defns to a set of declarations for just the names defined in defns . Do this in the context of tenv . The tenv is extended (define defns-to-decls (lambda (defns tenv) (if (null? defns) '() (cases definition (car defns) (val-defn (var-name exp) (let ((ty (type-of exp tenv))) (let ((new-env (extend-tenv var-name ty tenv))) (cons (val-decl var-name ty) (defns-to-decls (cdr defns) new-env))))))))) (define report-module-doesnt-satisfy-iface (lambda (m-name expected-type actual-type) (pretty-print (list 'error-in-defn-of-module: m-name 'expected-type: expected-type 'actual-type: actual-type)) (eopl:error 'type-of-module-defn))) )
3db528a9170d6858a3889b5325991f34da4ba02ba5f653645246e6046975b969
madgen/exalog
RangeRestrictionSpec.hs
# LANGUAGE DataKinds # module Language.Exalog.RangeRestrictionSpec (spec) where import Protolude import Test.Hspec import qualified Fixture.RangeRestriction as RRes import qualified Fixture.DomainDependent as DDep import Language.Exalog.Annotation import qualified Language.Exalog.KnowledgeBase.Set as KB import Language.Exalog.Logger import Language.Exalog.RangeRestriction spec :: Spec spec = describe "Range restriction" $ do parallel $ describe "Checking" $ do it "programGood is range-restricted" $ runLoggerT vanillaEnv (checkRangeRestriction DDep.programGood) `shouldReturn` Just () it "programBad1 violates range restriction" $ runLoggerT vanillaEnv (checkRangeRestriction DDep.programBad1) `shouldReturn` Nothing it "programBad2 violates range restriction" $ runLoggerT vanillaEnv (checkRangeRestriction DDep.programBad2) `shouldReturn` Nothing describe "Repair" $ it "programSimple can be repaired" $ do let input = (RRes.prSimple, mempty :: KB.Set ('ARename 'ABase)) let output = (RRes.prSimpleRepaired, mempty :: KB.Set 'ABase) runLoggerT vanillaEnv (fixRangeRestriction input) `shouldReturn` Just output
null
https://raw.githubusercontent.com/madgen/exalog/7d169b066c5c08f2b8e44f5e078df264731ac177/test/Language/Exalog/RangeRestrictionSpec.hs
haskell
# LANGUAGE DataKinds # module Language.Exalog.RangeRestrictionSpec (spec) where import Protolude import Test.Hspec import qualified Fixture.RangeRestriction as RRes import qualified Fixture.DomainDependent as DDep import Language.Exalog.Annotation import qualified Language.Exalog.KnowledgeBase.Set as KB import Language.Exalog.Logger import Language.Exalog.RangeRestriction spec :: Spec spec = describe "Range restriction" $ do parallel $ describe "Checking" $ do it "programGood is range-restricted" $ runLoggerT vanillaEnv (checkRangeRestriction DDep.programGood) `shouldReturn` Just () it "programBad1 violates range restriction" $ runLoggerT vanillaEnv (checkRangeRestriction DDep.programBad1) `shouldReturn` Nothing it "programBad2 violates range restriction" $ runLoggerT vanillaEnv (checkRangeRestriction DDep.programBad2) `shouldReturn` Nothing describe "Repair" $ it "programSimple can be repaired" $ do let input = (RRes.prSimple, mempty :: KB.Set ('ARename 'ABase)) let output = (RRes.prSimpleRepaired, mempty :: KB.Set 'ABase) runLoggerT vanillaEnv (fixRangeRestriction input) `shouldReturn` Just output
7b93b8e95a3583a90f5f720946beaf879f3c164915efc4cb269a22930d379443
nkpart/kit
FlaggedFile.hs
module Kit.FlaggedFile ( FlaggedFile, flaggedFile, flaggedFilePath, flaggedFileFlags ) where import Kit.AbsolutePath as AF data FlaggedFile = FlaggedFile { flaggedFileAbsolutePath :: AbsolutePath, flaggedFileFlags :: String } deriving (Eq, Show) flaggedFile :: String -> AbsolutePath -> FlaggedFile flaggedFile a b = FlaggedFile b a flaggedFilePath :: FlaggedFile -> FilePath flaggedFilePath = AF.filePath . flaggedFileAbsolutePath
null
https://raw.githubusercontent.com/nkpart/kit/ed217ddbc90688350e52156503cca092c9bf8300/Kit/FlaggedFile.hs
haskell
module Kit.FlaggedFile ( FlaggedFile, flaggedFile, flaggedFilePath, flaggedFileFlags ) where import Kit.AbsolutePath as AF data FlaggedFile = FlaggedFile { flaggedFileAbsolutePath :: AbsolutePath, flaggedFileFlags :: String } deriving (Eq, Show) flaggedFile :: String -> AbsolutePath -> FlaggedFile flaggedFile a b = FlaggedFile b a flaggedFilePath :: FlaggedFile -> FilePath flaggedFilePath = AF.filePath . flaggedFileAbsolutePath
757b0e3cfd530dd69862feec3ca5da7eb59391b7cd820a8697a84a8edf2d4c43
goblint/analyzer
violationZ3.z3.ml
open Violation module WP (Node: MyARG.Node): Feasibility with module Node = Node = struct module Node = Node open Z3 open GoblintCil let cfg = [ ("model", "true"); ("unsat_core", "true"); (* TODO: do these do anything? are these necessary? *) (* ("smt.core.minimize", "true"); *) (* ("sat.core.minimize", "true"); *) ] let ctx = mk_context cfg type var = varinfo module Var = CilType.Varinfo module type Env = sig type t val empty: t val get_const: t -> var -> Expr.expr val freshen: t -> var -> t end module Env: Env = struct module VarMap = Map.Make (Var) type t = Expr.expr VarMap.t let empty = VarMap.empty let get_name x = x.vname let get_const m x = match VarMap.find_opt x m with | Some x -> x | None -> Arithmetic.Integer.mk_const_s ctx (get_name x) let sort = Arithmetic.Integer.mk_sort ctx let freshen env x = VarMap.add x (Expr.mk_fresh_const ctx (get_name x) sort) env end let bool_to_int expr = Boolean.mk_ite ctx expr (Arithmetic.Integer.mk_numeral_i ctx 1) (Arithmetic.Integer.mk_numeral_i ctx 0) let int_to_bool expr = Boolean.mk_distinct ctx [expr; Arithmetic.Integer.mk_numeral_i ctx 0] let rec exp_to_expr env = function | Const (CInt (i, _, _)) -> Arithmetic.Integer.mk_numeral_s ctx (Z.to_string i) | Lval (Var v, NoOffset) -> Env.get_const env v | BinOp (PlusA, e1, e2, TInt _) -> Arithmetic.mk_add ctx [exp_to_expr env e1; exp_to_expr env e2] | BinOp (MinusA, e1, e2, TInt _) -> Arithmetic.mk_sub ctx [exp_to_expr env e1; exp_to_expr env e2] | BinOp (Mult, e1, e2, TInt _) -> Arithmetic.mk_mul ctx [exp_to_expr env e1; exp_to_expr env e2] | BinOp (Eq, e1, e2, TInt _) -> bool_to_int (Boolean.mk_eq ctx (exp_to_expr env e1) (exp_to_expr env e2)) | BinOp (Ne, e1, e2, TInt _) -> bool_to_int (Boolean.mk_distinct ctx [exp_to_expr env e1; exp_to_expr env e2]) | BinOp (Gt, e1, e2, TInt _) -> bool_to_int (Arithmetic.mk_gt ctx (exp_to_expr env e1) (exp_to_expr env e2)) | BinOp (Lt, e1, e2, TInt _) -> bool_to_int (Arithmetic.mk_lt ctx (exp_to_expr env e1) (exp_to_expr env e2)) | BinOp (Ge, e1, e2, TInt _) -> bool_to_int (Arithmetic.mk_ge ctx (exp_to_expr env e1) (exp_to_expr env e2)) | BinOp (Le, e1, e2, TInt _) -> bool_to_int (Arithmetic.mk_le ctx (exp_to_expr env e1) (exp_to_expr env e2)) | UnOp (LNot, e, TInt _) -> bool_to_int (Boolean.mk_not ctx (int_to_bool (exp_to_expr env e))) | e -> failwith @@ Pretty.sprint ~width:max_int @@ Pretty.dprintf "exp_to_expr: %a" Cil.d_exp e let get_arg_vname i = Goblintutil.create_var (Cil.makeVarinfo false ("_arg" ^ string_of_int i) Cil.intType) (* TODO: correct type in general *) let return_vname = Goblintutil.create_var (Cil.makeVarinfo false "_return" Cil.intType) (* TODO: correct type in general *) let wp_assert env (from_node, (edge: MyARG.inline_edge), _) = match edge with | MyARG.CFGEdge (MyCFG.Assign ((Var v, NoOffset), e)) -> let env' = Env.freshen env v in (env', [Boolean.mk_eq ctx (Env.get_const env v) (exp_to_expr env' e)]) | MyARG.CFGEdge (MyCFG.Test (e, true)) -> (env, [Boolean.mk_distinct ctx [exp_to_expr env e; Arithmetic.Integer.mk_numeral_i ctx 0]]) | MyARG.CFGEdge (MyCFG.Test (e, false)) -> (env, [Boolean.mk_eq ctx (exp_to_expr env e) (Arithmetic.Integer.mk_numeral_i ctx 0)]) | MyARG.CFGEdge (MyCFG.Entry fd) -> let env' = List.fold_left (fun acc formal -> Env.freshen acc formal ) env fd.sformals in let eqs = List.mapi (fun i formal -> let arg_vname = get_arg_vname i in Boolean.mk_eq ctx (Env.get_const env formal) (Env.get_const env' arg_vname) ) fd.sformals in (env', eqs) | MyARG.InlineEntry (_, _, args) -> let env' = BatList.fold_lefti (fun acc i arg -> let arg_vname = get_arg_vname i in Env.freshen acc arg_vname ) env args in let eqs = List.mapi (fun i arg -> let arg_vname = get_arg_vname i in Boolean.mk_eq ctx (Env.get_const env arg_vname) (exp_to_expr env' arg) ) args in (env', eqs) | MyARG.CFGEdge (MyCFG.Ret (None, fd)) -> (env, []) | MyARG.CFGEdge (MyCFG.Ret (Some e, fd)) -> let env' = Env.freshen env return_vname in (env', [Boolean.mk_eq ctx (Env.get_const env return_vname) (exp_to_expr env' e)]) | MyARG.InlineReturn (None, _, _) -> (env, []) | MyARG.InlineReturn (Some (Var v, NoOffset), _, _) -> let env' = Env.freshen env v in (env', [Boolean.mk_eq ctx (Env.get_const env v) (Env.get_const env' return_vname)]) | _ -> (* (env, Boolean.mk_true ctx) *) failwith @@ Pretty.sprint ~width:max_int @@ Pretty.dprintf "wp_assert: %a" MyARG.pretty_inline_edge edge let const_get_symbol (expr: Expr.expr): Symbol.symbol = assert (Expr.is_const expr); let func_decl = Expr.get_func_decl expr in FuncDecl.get_name func_decl type result = | Feasible | Infeasible of (Node.t * MyARG.inline_edge * Node.t) list | Unknown let wp_path path = let solver = Solver.mk_simple_solver ctx in let rec iter_wp revpath i env = match revpath with | [] -> Feasible | step :: revpath' -> let (env', asserts) = wp_assert env step in begin match asserts with | [] -> iter_wp revpath' (i - 1) env' | [expr] -> do_assert revpath' i env' expr | exprs -> let expr = Boolean.mk_and ctx exprs in do_assert revpath' i env' expr end and do_assert revpath' i env' expr = Printf.printf "%d: %s\n" i (Expr.to_string expr); let track_const = Boolean.mk_const ctx (Symbol.mk_int ctx i) in Solver.assert_and_track solver expr track_const; let status = Solver.check solver [] in Printf.printf "%d: %s\n" i (Solver.string_of_status status); match Solver.check solver [] with | Solver.SATISFIABLE -> Printf.printf "%d: %s\n" i (Model.to_string (BatOption.get @@ Solver.get_model solver)); iter_wp revpath' (i - 1) env' | Solver.UNSATISFIABLE -> (* TODO: this doesn't exist in Z3 API? *) let extract_track expr = assert (Expr.is_const expr); let symbol = const_get_symbol expr in assert (Symbol.is_int_symbol symbol); Symbol.get_int symbol in let unsat_core = Solver.get_unsat_core solver in let unsat_core_is = unsat_core |> List.map extract_track |> List.sort compare in unsat_core_is |> List.map string_of_int |> String.concat " " |> print_endline; let (mini, maxi) = BatList.min_max unsat_core_is in let unsat_path = BatList.filteri (fun i _ -> mini <= i && i <= maxi) path in (* TODO: optimize subpath *) Infeasible unsat_path | Solver.UNKNOWN -> Unknown in iter_wp (List.rev path) (List.length path - 1) Env.empty let check_path = wp_path end
null
https://raw.githubusercontent.com/goblint/analyzer/2f29b8b20f1985022a0850d9396926f8f2fda6a8/src/witness/z3/violationZ3.z3.ml
ocaml
TODO: do these do anything? are these necessary? ("smt.core.minimize", "true"); ("sat.core.minimize", "true"); TODO: correct type in general TODO: correct type in general (env, Boolean.mk_true ctx) TODO: this doesn't exist in Z3 API? TODO: optimize subpath
open Violation module WP (Node: MyARG.Node): Feasibility with module Node = Node = struct module Node = Node open Z3 open GoblintCil let cfg = [ ("model", "true"); ("unsat_core", "true"); ] let ctx = mk_context cfg type var = varinfo module Var = CilType.Varinfo module type Env = sig type t val empty: t val get_const: t -> var -> Expr.expr val freshen: t -> var -> t end module Env: Env = struct module VarMap = Map.Make (Var) type t = Expr.expr VarMap.t let empty = VarMap.empty let get_name x = x.vname let get_const m x = match VarMap.find_opt x m with | Some x -> x | None -> Arithmetic.Integer.mk_const_s ctx (get_name x) let sort = Arithmetic.Integer.mk_sort ctx let freshen env x = VarMap.add x (Expr.mk_fresh_const ctx (get_name x) sort) env end let bool_to_int expr = Boolean.mk_ite ctx expr (Arithmetic.Integer.mk_numeral_i ctx 1) (Arithmetic.Integer.mk_numeral_i ctx 0) let int_to_bool expr = Boolean.mk_distinct ctx [expr; Arithmetic.Integer.mk_numeral_i ctx 0] let rec exp_to_expr env = function | Const (CInt (i, _, _)) -> Arithmetic.Integer.mk_numeral_s ctx (Z.to_string i) | Lval (Var v, NoOffset) -> Env.get_const env v | BinOp (PlusA, e1, e2, TInt _) -> Arithmetic.mk_add ctx [exp_to_expr env e1; exp_to_expr env e2] | BinOp (MinusA, e1, e2, TInt _) -> Arithmetic.mk_sub ctx [exp_to_expr env e1; exp_to_expr env e2] | BinOp (Mult, e1, e2, TInt _) -> Arithmetic.mk_mul ctx [exp_to_expr env e1; exp_to_expr env e2] | BinOp (Eq, e1, e2, TInt _) -> bool_to_int (Boolean.mk_eq ctx (exp_to_expr env e1) (exp_to_expr env e2)) | BinOp (Ne, e1, e2, TInt _) -> bool_to_int (Boolean.mk_distinct ctx [exp_to_expr env e1; exp_to_expr env e2]) | BinOp (Gt, e1, e2, TInt _) -> bool_to_int (Arithmetic.mk_gt ctx (exp_to_expr env e1) (exp_to_expr env e2)) | BinOp (Lt, e1, e2, TInt _) -> bool_to_int (Arithmetic.mk_lt ctx (exp_to_expr env e1) (exp_to_expr env e2)) | BinOp (Ge, e1, e2, TInt _) -> bool_to_int (Arithmetic.mk_ge ctx (exp_to_expr env e1) (exp_to_expr env e2)) | BinOp (Le, e1, e2, TInt _) -> bool_to_int (Arithmetic.mk_le ctx (exp_to_expr env e1) (exp_to_expr env e2)) | UnOp (LNot, e, TInt _) -> bool_to_int (Boolean.mk_not ctx (int_to_bool (exp_to_expr env e))) | e -> failwith @@ Pretty.sprint ~width:max_int @@ Pretty.dprintf "exp_to_expr: %a" Cil.d_exp e let wp_assert env (from_node, (edge: MyARG.inline_edge), _) = match edge with | MyARG.CFGEdge (MyCFG.Assign ((Var v, NoOffset), e)) -> let env' = Env.freshen env v in (env', [Boolean.mk_eq ctx (Env.get_const env v) (exp_to_expr env' e)]) | MyARG.CFGEdge (MyCFG.Test (e, true)) -> (env, [Boolean.mk_distinct ctx [exp_to_expr env e; Arithmetic.Integer.mk_numeral_i ctx 0]]) | MyARG.CFGEdge (MyCFG.Test (e, false)) -> (env, [Boolean.mk_eq ctx (exp_to_expr env e) (Arithmetic.Integer.mk_numeral_i ctx 0)]) | MyARG.CFGEdge (MyCFG.Entry fd) -> let env' = List.fold_left (fun acc formal -> Env.freshen acc formal ) env fd.sformals in let eqs = List.mapi (fun i formal -> let arg_vname = get_arg_vname i in Boolean.mk_eq ctx (Env.get_const env formal) (Env.get_const env' arg_vname) ) fd.sformals in (env', eqs) | MyARG.InlineEntry (_, _, args) -> let env' = BatList.fold_lefti (fun acc i arg -> let arg_vname = get_arg_vname i in Env.freshen acc arg_vname ) env args in let eqs = List.mapi (fun i arg -> let arg_vname = get_arg_vname i in Boolean.mk_eq ctx (Env.get_const env arg_vname) (exp_to_expr env' arg) ) args in (env', eqs) | MyARG.CFGEdge (MyCFG.Ret (None, fd)) -> (env, []) | MyARG.CFGEdge (MyCFG.Ret (Some e, fd)) -> let env' = Env.freshen env return_vname in (env', [Boolean.mk_eq ctx (Env.get_const env return_vname) (exp_to_expr env' e)]) | MyARG.InlineReturn (None, _, _) -> (env, []) | MyARG.InlineReturn (Some (Var v, NoOffset), _, _) -> let env' = Env.freshen env v in (env', [Boolean.mk_eq ctx (Env.get_const env v) (Env.get_const env' return_vname)]) | _ -> failwith @@ Pretty.sprint ~width:max_int @@ Pretty.dprintf "wp_assert: %a" MyARG.pretty_inline_edge edge let const_get_symbol (expr: Expr.expr): Symbol.symbol = assert (Expr.is_const expr); let func_decl = Expr.get_func_decl expr in FuncDecl.get_name func_decl type result = | Feasible | Infeasible of (Node.t * MyARG.inline_edge * Node.t) list | Unknown let wp_path path = let solver = Solver.mk_simple_solver ctx in let rec iter_wp revpath i env = match revpath with | [] -> Feasible | step :: revpath' -> let (env', asserts) = wp_assert env step in begin match asserts with | [] -> iter_wp revpath' (i - 1) env' | [expr] -> do_assert revpath' i env' expr | exprs -> let expr = Boolean.mk_and ctx exprs in do_assert revpath' i env' expr end and do_assert revpath' i env' expr = Printf.printf "%d: %s\n" i (Expr.to_string expr); let track_const = Boolean.mk_const ctx (Symbol.mk_int ctx i) in Solver.assert_and_track solver expr track_const; let status = Solver.check solver [] in Printf.printf "%d: %s\n" i (Solver.string_of_status status); match Solver.check solver [] with | Solver.SATISFIABLE -> Printf.printf "%d: %s\n" i (Model.to_string (BatOption.get @@ Solver.get_model solver)); iter_wp revpath' (i - 1) env' | Solver.UNSATISFIABLE -> let extract_track expr = assert (Expr.is_const expr); let symbol = const_get_symbol expr in assert (Symbol.is_int_symbol symbol); Symbol.get_int symbol in let unsat_core = Solver.get_unsat_core solver in let unsat_core_is = unsat_core |> List.map extract_track |> List.sort compare in unsat_core_is |> List.map string_of_int |> String.concat " " |> print_endline; let (mini, maxi) = BatList.min_max unsat_core_is in Infeasible unsat_path | Solver.UNKNOWN -> Unknown in iter_wp (List.rev path) (List.length path - 1) Env.empty let check_path = wp_path end
1aaa506c3daea783c7d0d4a07dee4a11fc19d4130ac321d301e5b421e8677e66
flipstone/orville
Where.hs
| Module : Database . Orville . PostgreSQL.Internal . Where Copyright : Flipstone Technology Partners 2016 - 2018 License : MIT Module : Database.Orville.PostgreSQL.Internal.Where Copyright : Flipstone Technology Partners 2016-2018 License : MIT -} # LANGUAGE FlexibleContexts # # LANGUAGE ExistentialQuantification # module Database.Orville.PostgreSQL.Internal.Where ( WhereCondition(..) , (.==) , (.<>) , (.>) , (.>=) , (.<) , (.<=) , (.<-) , (%==) , whereConditionValues , whereAnd , whereOr , whereIn , whereLike , whereLikeInsensitive , whereNotIn , whereQualified , whereRaw , isNull , isNotNull , whereClause , whereValues , whereToSql ) where import qualified Data.List as List import Database.HDBC import Database.Orville.PostgreSQL.Internal.Expr import qualified Database.Orville.PostgreSQL.Internal.Expr.WhereExpr as E import Database.Orville.PostgreSQL.Internal.FieldDefinition import Database.Orville.PostgreSQL.Internal.QueryKey import Database.Orville.PostgreSQL.Internal.Types It would be nice to match the SqlValues in these with the types from the corresponding FieldDefinitions . However , this would require adding an Eq constraint for List.nub on the .<- operation , which I 'm not willing to do at this moment . Alternately , we could eliminate storing the entire FieldDefinition here , thereby removing the need for ExistentialQuantification . Currently the field definition is being used in the QueryKeyable instances for WhereCondition for calls to qkOp an friends . Replacing FieldDefinition with just the field name here would be nice . We would probably want a fully - fledged FieldName type whech could provide the appropriate QueryKeyable instance . That then raises questions about the ergonomics users creating FieldDefinition values without requiring OverloadedStrings to be turned on . It would be nice to match the SqlValues in these with the types from the corresponding FieldDefinitions. However, this would require adding an Eq constraint for List.nub on the .<- operation, which I'm not willing to do at this moment. Alternately, we could eliminate storing the entire FieldDefinition here, thereby removing the need for ExistentialQuantification. Currently the field definition is being used in the QueryKeyable instances for WhereCondition for calls to qkOp an friends. Replacing FieldDefinition with just the field name here would be nice. We would probably want a fully-fledged FieldName type whech could provide the appropriate QueryKeyable instance. That then raises questions about the ergonomics users creating FieldDefinition values without requiring OverloadedStrings to be turned on. -} data WhereCondition = WhereConditionExpr E.WhereExpr | Or [WhereCondition] | And [WhereCondition] | forall a b c. Qualified (TableDefinition a b c) WhereCondition instance QueryKeyable WhereCondition where queryKey (WhereConditionExpr (Expr (Right form))) = queryKey form queryKey (WhereConditionExpr (Expr (Left raw))) = QKField $ rawExprToSql raw queryKey (Or conds) = qkOp "OR" conds queryKey (And conds) = qkOp "And" conds queryKey (Qualified _ cond) = queryKey cond (.==) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .== a = WhereConditionExpr . expr $ nameForm E..== sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<>) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .<> a = WhereConditionExpr . expr $ nameForm E..<> sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.>) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .> a = WhereConditionExpr . expr $ nameForm E..> sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.>=) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .>= a = WhereConditionExpr . expr $ nameForm E..>= sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .< a = WhereConditionExpr . expr $ nameForm E..< sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<=) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .<= a = WhereConditionExpr . expr $ nameForm E..<= sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<-) :: FieldDefinition nullability a -> [a] -> WhereCondition fieldDef .<- as = whereIn fieldDef as (%==) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef %== a = WhereConditionExpr . expr $ nameForm E.%== sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a whereConditionSql :: WhereCondition -> String whereConditionSql cond = internalWhereConditionSql Nothing cond internalWhereConditionSql :: Maybe (TableDefinition a b c) -> WhereCondition -> String internalWhereConditionSql mbTableDef whereCondition = case whereCondition of Or [] -> "FALSE" Or conds -> let condsSql = map innerCondSql conds in List.intercalate " OR " condsSql And [] -> "TRUE" And conds -> let condsSql = map innerCondSql conds in List.intercalate " AND " condsSql WhereConditionExpr expression -> case mbTableDef of Just tableDef -> rawExprToSql . generateSql $ expression `qualified` (tableName tableDef) Nothing -> rawExprToSql . generateSql $ expression Qualified tableDef cond -> internalWhereConditionSql (Just tableDef) cond where innerCondSql c = let sql = internalWhereConditionSql mbTableDef c in "(" ++ sql ++ ")" whereConditionValues :: WhereCondition -> [SqlValue] whereConditionValues (WhereConditionExpr (Expr (Right form))) = E.whereValues [form] whereConditionValues (WhereConditionExpr (Expr (Left _))) = [] whereConditionValues (Or conds) = concatMap whereConditionValues conds whereConditionValues (And conds) = concatMap whereConditionValues conds whereConditionValues (Qualified _ cond) = whereConditionValues cond whereAnd :: [WhereCondition] -> WhereCondition whereAnd = And whereOr :: [WhereCondition] -> WhereCondition whereOr = Or whereIn :: FieldDefinition nullability a -> [a] -> WhereCondition whereIn fieldDef values = WhereConditionExpr . expr $ E.whereIn (fieldToNameForm fieldDef) (map (fieldToSqlValue fieldDef) values) whereLike :: FieldDefinition nullability a -> String -> WhereCondition whereLike fieldDef raw = WhereConditionExpr . expr $ E.whereLike (fieldToNameForm fieldDef) (toSql raw) whereLikeInsensitive :: FieldDefinition nullability a -> String -> WhereCondition whereLikeInsensitive fieldDef raw = WhereConditionExpr . expr $ E.whereLikeInsensitive (fieldToNameForm fieldDef) (toSql raw) whereNotIn :: FieldDefinition nullability a -> [a] -> WhereCondition whereNotIn fieldDef values = WhereConditionExpr . expr $ E.whereNotIn (fieldToNameForm fieldDef) (map (fieldToSqlValue fieldDef) values) whereQualified :: TableDefinition a b c -> WhereCondition -> WhereCondition whereQualified tableDef cond = Qualified tableDef cond whereRaw :: String -> [SqlValue] -> WhereCondition whereRaw str values = WhereConditionExpr . expr $ E.whereRaw str values isNull :: FieldDefinition Nullable a -> WhereCondition isNull = WhereConditionExpr . expr . E.whereNull . fieldToNameForm isNotNull :: FieldDefinition Nullable a -> WhereCondition isNotNull = WhereConditionExpr . expr . E.whereNotNull . fieldToNameForm whereClause :: [WhereCondition] -> String whereClause [] = "" whereClause conds = "WHERE " ++ whereConditionSql (whereAnd conds) whereValues :: [WhereCondition] -> [SqlValue] whereValues = List.concatMap whereConditionValues whereToSql :: [WhereCondition] -> (String, [SqlValue]) whereToSql conds = (whereClause conds, whereValues conds)
null
https://raw.githubusercontent.com/flipstone/orville/97824b2abbf34aa9ea495767691fbd06647342ff/orville-postgresql/src/Database/Orville/PostgreSQL/Internal/Where.hs
haskell
| Module : Database . Orville . PostgreSQL.Internal . Where Copyright : Flipstone Technology Partners 2016 - 2018 License : MIT Module : Database.Orville.PostgreSQL.Internal.Where Copyright : Flipstone Technology Partners 2016-2018 License : MIT -} # LANGUAGE FlexibleContexts # # LANGUAGE ExistentialQuantification # module Database.Orville.PostgreSQL.Internal.Where ( WhereCondition(..) , (.==) , (.<>) , (.>) , (.>=) , (.<) , (.<=) , (.<-) , (%==) , whereConditionValues , whereAnd , whereOr , whereIn , whereLike , whereLikeInsensitive , whereNotIn , whereQualified , whereRaw , isNull , isNotNull , whereClause , whereValues , whereToSql ) where import qualified Data.List as List import Database.HDBC import Database.Orville.PostgreSQL.Internal.Expr import qualified Database.Orville.PostgreSQL.Internal.Expr.WhereExpr as E import Database.Orville.PostgreSQL.Internal.FieldDefinition import Database.Orville.PostgreSQL.Internal.QueryKey import Database.Orville.PostgreSQL.Internal.Types It would be nice to match the SqlValues in these with the types from the corresponding FieldDefinitions . However , this would require adding an Eq constraint for List.nub on the .<- operation , which I 'm not willing to do at this moment . Alternately , we could eliminate storing the entire FieldDefinition here , thereby removing the need for ExistentialQuantification . Currently the field definition is being used in the QueryKeyable instances for WhereCondition for calls to qkOp an friends . Replacing FieldDefinition with just the field name here would be nice . We would probably want a fully - fledged FieldName type whech could provide the appropriate QueryKeyable instance . That then raises questions about the ergonomics users creating FieldDefinition values without requiring OverloadedStrings to be turned on . It would be nice to match the SqlValues in these with the types from the corresponding FieldDefinitions. However, this would require adding an Eq constraint for List.nub on the .<- operation, which I'm not willing to do at this moment. Alternately, we could eliminate storing the entire FieldDefinition here, thereby removing the need for ExistentialQuantification. Currently the field definition is being used in the QueryKeyable instances for WhereCondition for calls to qkOp an friends. Replacing FieldDefinition with just the field name here would be nice. We would probably want a fully-fledged FieldName type whech could provide the appropriate QueryKeyable instance. That then raises questions about the ergonomics users creating FieldDefinition values without requiring OverloadedStrings to be turned on. -} data WhereCondition = WhereConditionExpr E.WhereExpr | Or [WhereCondition] | And [WhereCondition] | forall a b c. Qualified (TableDefinition a b c) WhereCondition instance QueryKeyable WhereCondition where queryKey (WhereConditionExpr (Expr (Right form))) = queryKey form queryKey (WhereConditionExpr (Expr (Left raw))) = QKField $ rawExprToSql raw queryKey (Or conds) = qkOp "OR" conds queryKey (And conds) = qkOp "And" conds queryKey (Qualified _ cond) = queryKey cond (.==) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .== a = WhereConditionExpr . expr $ nameForm E..== sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<>) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .<> a = WhereConditionExpr . expr $ nameForm E..<> sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.>) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .> a = WhereConditionExpr . expr $ nameForm E..> sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.>=) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .>= a = WhereConditionExpr . expr $ nameForm E..>= sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .< a = WhereConditionExpr . expr $ nameForm E..< sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<=) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef .<= a = WhereConditionExpr . expr $ nameForm E..<= sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a (.<-) :: FieldDefinition nullability a -> [a] -> WhereCondition fieldDef .<- as = whereIn fieldDef as (%==) :: FieldDefinition nullability a -> a -> WhereCondition fieldDef %== a = WhereConditionExpr . expr $ nameForm E.%== sqlValue where nameForm = fieldToNameForm fieldDef sqlValue = fieldToSqlValue fieldDef a whereConditionSql :: WhereCondition -> String whereConditionSql cond = internalWhereConditionSql Nothing cond internalWhereConditionSql :: Maybe (TableDefinition a b c) -> WhereCondition -> String internalWhereConditionSql mbTableDef whereCondition = case whereCondition of Or [] -> "FALSE" Or conds -> let condsSql = map innerCondSql conds in List.intercalate " OR " condsSql And [] -> "TRUE" And conds -> let condsSql = map innerCondSql conds in List.intercalate " AND " condsSql WhereConditionExpr expression -> case mbTableDef of Just tableDef -> rawExprToSql . generateSql $ expression `qualified` (tableName tableDef) Nothing -> rawExprToSql . generateSql $ expression Qualified tableDef cond -> internalWhereConditionSql (Just tableDef) cond where innerCondSql c = let sql = internalWhereConditionSql mbTableDef c in "(" ++ sql ++ ")" whereConditionValues :: WhereCondition -> [SqlValue] whereConditionValues (WhereConditionExpr (Expr (Right form))) = E.whereValues [form] whereConditionValues (WhereConditionExpr (Expr (Left _))) = [] whereConditionValues (Or conds) = concatMap whereConditionValues conds whereConditionValues (And conds) = concatMap whereConditionValues conds whereConditionValues (Qualified _ cond) = whereConditionValues cond whereAnd :: [WhereCondition] -> WhereCondition whereAnd = And whereOr :: [WhereCondition] -> WhereCondition whereOr = Or whereIn :: FieldDefinition nullability a -> [a] -> WhereCondition whereIn fieldDef values = WhereConditionExpr . expr $ E.whereIn (fieldToNameForm fieldDef) (map (fieldToSqlValue fieldDef) values) whereLike :: FieldDefinition nullability a -> String -> WhereCondition whereLike fieldDef raw = WhereConditionExpr . expr $ E.whereLike (fieldToNameForm fieldDef) (toSql raw) whereLikeInsensitive :: FieldDefinition nullability a -> String -> WhereCondition whereLikeInsensitive fieldDef raw = WhereConditionExpr . expr $ E.whereLikeInsensitive (fieldToNameForm fieldDef) (toSql raw) whereNotIn :: FieldDefinition nullability a -> [a] -> WhereCondition whereNotIn fieldDef values = WhereConditionExpr . expr $ E.whereNotIn (fieldToNameForm fieldDef) (map (fieldToSqlValue fieldDef) values) whereQualified :: TableDefinition a b c -> WhereCondition -> WhereCondition whereQualified tableDef cond = Qualified tableDef cond whereRaw :: String -> [SqlValue] -> WhereCondition whereRaw str values = WhereConditionExpr . expr $ E.whereRaw str values isNull :: FieldDefinition Nullable a -> WhereCondition isNull = WhereConditionExpr . expr . E.whereNull . fieldToNameForm isNotNull :: FieldDefinition Nullable a -> WhereCondition isNotNull = WhereConditionExpr . expr . E.whereNotNull . fieldToNameForm whereClause :: [WhereCondition] -> String whereClause [] = "" whereClause conds = "WHERE " ++ whereConditionSql (whereAnd conds) whereValues :: [WhereCondition] -> [SqlValue] whereValues = List.concatMap whereConditionValues whereToSql :: [WhereCondition] -> (String, [SqlValue]) whereToSql conds = (whereClause conds, whereValues conds)
f362e405520c1280ba5c6d4ff515598dc88e030fe5d70f7a4d0cc10a20a3e71f
ChesleyTan/ascii-chat
package.mli
open Cv type package val get_timestamp: unit -> int val pack: image -> string -> int -> int -> package val unpack: package -> (image * string * int * int) val serialize: package -> string val deserialize: string -> package val encrypt: string -> string val decrypt: string -> string val get_encryption_key: unit -> string val set_encryption_key: string -> unit val generate_encryption_key: string -> unit val is_encryption_key_set: unit -> bool
null
https://raw.githubusercontent.com/ChesleyTan/ascii-chat/f2670c4a9d8b8e555d6b42741b314257db942c30/src/package.mli
ocaml
open Cv type package val get_timestamp: unit -> int val pack: image -> string -> int -> int -> package val unpack: package -> (image * string * int * int) val serialize: package -> string val deserialize: string -> package val encrypt: string -> string val decrypt: string -> string val get_encryption_key: unit -> string val set_encryption_key: string -> unit val generate_encryption_key: string -> unit val is_encryption_key_set: unit -> bool
731e9f6dfa0c9d6c636059ee320a74055cfac3ec0dd3a50d1b83c475e521c1f7
jonasseglare/geex
try_block.clj
(ns geex.java.try-block (:require [clojure.spec.alpha :as spec])) (spec/def ::body fn?) (spec/def ::finally fn?) (spec/def ::type class?) (spec/def ::catch (spec/keys :req-un [::type ::body])) (spec/def ::catches (spec/* ::catch)) (spec/def ::try-block (spec/keys :req-un [::body] :opt-un [::catches ::finally])) (defn validate [x] (when (not (spec/valid? ::try-block x)) (throw (ex-info (str "Not a valid try-block: " (spec/explain-str ::try-block x)) {:block x}))) x)
null
https://raw.githubusercontent.com/jonasseglare/geex/f1a48c14c983c054c91fb221b91f42de5fa8eee0/src/clj/geex/java/try_block.clj
clojure
(ns geex.java.try-block (:require [clojure.spec.alpha :as spec])) (spec/def ::body fn?) (spec/def ::finally fn?) (spec/def ::type class?) (spec/def ::catch (spec/keys :req-un [::type ::body])) (spec/def ::catches (spec/* ::catch)) (spec/def ::try-block (spec/keys :req-un [::body] :opt-un [::catches ::finally])) (defn validate [x] (when (not (spec/valid? ::try-block x)) (throw (ex-info (str "Not a valid try-block: " (spec/explain-str ::try-block x)) {:block x}))) x)
30344769bf671b7cb4554b54e5fb489311de3029b7ceb5eab5f0455f7ef737ea
rd--/hsc3
dbAmp.help.hs
dbAmp ; linear db motion is exponential amplitude decay fSinOsc ar 800 0 * dbAmp (line kr (-24) (-48) 10 RemoveSynth) -- ; there is a non - UGen variant dbAmp (-26::Double) == 0.05011872336272722
null
https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/dbAmp.help.hs
haskell
; there is a non - UGen variant
dbAmp ; linear db motion is exponential amplitude decay fSinOsc ar 800 0 * dbAmp (line kr (-24) (-48) 10 RemoveSynth) dbAmp (-26::Double) == 0.05011872336272722
e6fb4a1eb37250cc2420c7dd26ab79ce12a606cf5638882c16e57c3acd50b3a9
eugeneia/erlangen
agent-test.lisp
;;;; Basic tests for agents. (defpackage erlangen.agent-test (:use :cl :erlangen.agent :erlangen.conditions :erlangen.mailbox) (:export :run-tests :basic-message-benchmark)) (in-package :erlangen.agent-test) (defmacro with-pseudo-agent ((var &key (mailbox-size '*default-mailbox-size*)) &body body) `(let* ((,var (erlangen.agent::make-agent% :mailbox (make-mailbox ,mailbox-size))) (erlangen.agent::*agent* ,var)) ,@body)) (defun test-send-receive () (with-pseudo-agent (p) (let ((relay (spawn (lambda () (send (receive) p))))) (spawn (lambda () (send :hello relay)))) (assert (eq :hello (receive :timeout 1)) nil "SEND/RECEIVE failed.") (let ((timeout (spawn (lambda () (receive :timeout 1/10)) :attach :monitor))) (destructuring-bind (agent exit . error) (receive :timeout 2/10) (assert (and (eq agent timeout) (eq exit :exit) (typep error 'timeout)) nil "RECEIVE (timeout) misbehaves."))))) (defun test-monitor-kill () (with-pseudo-agent (p) (let ((monitored (spawn (lambda () (receive)) :attach :monitor))) (exit :kill monitored) (assert (equal `(,monitored :exit . :kill) (receive :timeout 1)) nil "Monitor received corrupted message.")))) (defun test-link () (with-pseudo-agent (p) (let ((parent (spawn (lambda () (spawn (lambda () (+ 1 2 3)) :attach :link) (receive)) :attach :monitor))) (assert (equal `(,parent :exit :ok 6) (receive :timeout 1)) nil "Monitor received corrupt message.")))) (defun test-send-error-killed () (with-pseudo-agent (p) (let ((agent (spawn (lambda () (receive))))) (exit :kill agent) (send :test agent) (handler-case (exit :test agent) (error (error) (error "EXIT to exited agent signals: ~a" error)))))) (defun run-tests () (test-send-receive) (test-monitor-kill) (test-link) (test-send-error-killed) :ok) (defun ping-pong-bench (n-messages &optional (timeout 60)) (lambda () (let ((start (get-internal-real-time)) (n/2 (/ n-messages 2)) (incrementer (spawn (lambda () (loop do (destructuring-bind (a . i) (receive) (send (1+ i) a))))))) (spawn (lambda () (send (cons (agent) 0) incrementer) (loop for i = (receive) while (< i n/2) do (send (cons (agent) i) incrementer))) :attach :monitor) (unwind-protect (destructuring-bind (spammer status result) (receive :timeout timeout) (declare (ignore spammer result)) (let ((seconds (/ (- (get-internal-real-time) start) internal-time-units-per-second))) (assert (eq status :ok) nil "SPAMMER exited abnormally.") seconds)) (exit :kill incrementer))))) (defun basic-message-benchmark (&key (n-messages 1000000) (n-pairs 1) (timeout 60)) (check-type n-messages (integer 1)) (check-type n-pairs (integer 1)) (with-pseudo-agent (p) (loop repeat n-pairs do (spawn (ping-pong-bench n-messages timeout) :attach :monitor)) (let ((total-messages (* n-pairs n-messages)) (seconds (loop repeat n-pairs for (agent status seconds) = (receive) do (assert (eq status :ok) nil "~a exited abnormally." agent) maximize seconds))) (format t "Sent ~f million messages in ~f seconds.~%" (/ total-messages 1e6) seconds) (format t "That’s ~f messages per second.~%" (/ total-messages seconds)))))
null
https://raw.githubusercontent.com/eugeneia/erlangen/204166b33833c49841617bbc6ecfaf4dd77cf6d8/test/agent-test.lisp
lisp
Basic tests for agents.
(defpackage erlangen.agent-test (:use :cl :erlangen.agent :erlangen.conditions :erlangen.mailbox) (:export :run-tests :basic-message-benchmark)) (in-package :erlangen.agent-test) (defmacro with-pseudo-agent ((var &key (mailbox-size '*default-mailbox-size*)) &body body) `(let* ((,var (erlangen.agent::make-agent% :mailbox (make-mailbox ,mailbox-size))) (erlangen.agent::*agent* ,var)) ,@body)) (defun test-send-receive () (with-pseudo-agent (p) (let ((relay (spawn (lambda () (send (receive) p))))) (spawn (lambda () (send :hello relay)))) (assert (eq :hello (receive :timeout 1)) nil "SEND/RECEIVE failed.") (let ((timeout (spawn (lambda () (receive :timeout 1/10)) :attach :monitor))) (destructuring-bind (agent exit . error) (receive :timeout 2/10) (assert (and (eq agent timeout) (eq exit :exit) (typep error 'timeout)) nil "RECEIVE (timeout) misbehaves."))))) (defun test-monitor-kill () (with-pseudo-agent (p) (let ((monitored (spawn (lambda () (receive)) :attach :monitor))) (exit :kill monitored) (assert (equal `(,monitored :exit . :kill) (receive :timeout 1)) nil "Monitor received corrupted message.")))) (defun test-link () (with-pseudo-agent (p) (let ((parent (spawn (lambda () (spawn (lambda () (+ 1 2 3)) :attach :link) (receive)) :attach :monitor))) (assert (equal `(,parent :exit :ok 6) (receive :timeout 1)) nil "Monitor received corrupt message.")))) (defun test-send-error-killed () (with-pseudo-agent (p) (let ((agent (spawn (lambda () (receive))))) (exit :kill agent) (send :test agent) (handler-case (exit :test agent) (error (error) (error "EXIT to exited agent signals: ~a" error)))))) (defun run-tests () (test-send-receive) (test-monitor-kill) (test-link) (test-send-error-killed) :ok) (defun ping-pong-bench (n-messages &optional (timeout 60)) (lambda () (let ((start (get-internal-real-time)) (n/2 (/ n-messages 2)) (incrementer (spawn (lambda () (loop do (destructuring-bind (a . i) (receive) (send (1+ i) a))))))) (spawn (lambda () (send (cons (agent) 0) incrementer) (loop for i = (receive) while (< i n/2) do (send (cons (agent) i) incrementer))) :attach :monitor) (unwind-protect (destructuring-bind (spammer status result) (receive :timeout timeout) (declare (ignore spammer result)) (let ((seconds (/ (- (get-internal-real-time) start) internal-time-units-per-second))) (assert (eq status :ok) nil "SPAMMER exited abnormally.") seconds)) (exit :kill incrementer))))) (defun basic-message-benchmark (&key (n-messages 1000000) (n-pairs 1) (timeout 60)) (check-type n-messages (integer 1)) (check-type n-pairs (integer 1)) (with-pseudo-agent (p) (loop repeat n-pairs do (spawn (ping-pong-bench n-messages timeout) :attach :monitor)) (let ((total-messages (* n-pairs n-messages)) (seconds (loop repeat n-pairs for (agent status seconds) = (receive) do (assert (eq status :ok) nil "~a exited abnormally." agent) maximize seconds))) (format t "Sent ~f million messages in ~f seconds.~%" (/ total-messages 1e6) seconds) (format t "That’s ~f messages per second.~%" (/ total-messages seconds)))))
f596053a4de761f6ce3b38f5fdd9a323cff6dcd3fe420b285cb5e7765918d262
esl/MongooseIM
mod_mam.erl
%%============================================================================== Copyright 2016 Erlang Solutions Ltd. %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%============================================================================== -module(mod_mam). -behaviour(gen_mod). -behaviour(mongoose_module_metrics). -include("mod_mam.hrl"). -include("mongoose_config_spec.hrl"). -type module_opts() :: gen_mod:module_opts(). -type module_map() :: gen_mod_deps:module_map(). %% ---------------------------------------------------------------------- %% Datetime types Microseconds from 01.01.1970 -type unix_timestamp() :: non_neg_integer(). %% ---------------------------------------------------------------------- %% Other types -type archive_behaviour() :: roster | always | never. -type message_id() :: non_neg_integer(). -type archive_id() :: non_neg_integer(). -type borders() :: #mam_borders{}. -type message_row() :: #{id := message_id(), jid := jid:jid(), packet := exml:element()}. -type lookup_result() :: {TotalCount :: non_neg_integer() | undefined, Offset :: non_neg_integer() | undefined, MessageRows :: [message_row()]}. -type lookup_result_map() :: #{total_count := TotalCount :: non_neg_integer() | undefined, offset := Offset :: non_neg_integer() | undefined, messages := MessageRows :: [message_row()], is_complete => boolean()}. %% Internal types -type iterator_fun() :: fun(() -> {'ok', {_, _}}). -type rewriter_fun() :: fun((JID :: jid:literal_jid()) -> jid:literal_jid()). -type restore_option() :: {rewrite_jids, rewriter_fun() | [{binary(), binary()}]} | new_message_ids. -type preference() :: {DefaultMode :: archive_behaviour(), AlwaysJIDs :: [jid:literal_jid()], NeverJIDs :: [jid:literal_jid()]}. -type archive_message_params() :: #{message_id := message_id(), archive_id := archive_id(), local_jid := jid:jid(), remote_jid := jid:jid(), source_jid := jid:jid(), origin_id := binary() | none, direction := atom(), packet := exml:element(), %% Only in mod_mam_muc_rdbms_arch:retract_message/2 sender_id => archive_id()}. -export_type([rewriter_fun/0, borders/0, preference/0, archive_behaviour/0, iterator_fun/0, unix_timestamp/0, archive_id/0, lookup_result/0, lookup_result_map/0, message_row/0, message_id/0, restore_option/0, archive_message_params/0, mam_type/0 ]). -export([start/2, stop/1, config_spec/0, supported_features/0, deps/2, config_metrics/1]). -export([remove_unused_backend_opts/1]). %%-------------------------------------------------------------------- %% API %%-------------------------------------------------------------------- -spec supported_features() -> [atom()]. supported_features() -> [dynamic_domains]. -spec start(mongooseim:host_type(), module_opts()) -> any(). start(_HostType, _Opts) -> ok. -spec stop(mongooseim:host_type()) -> any(). stop(_HostType) -> ok. -spec config_spec() -> mongoose_config_spec:config_section(). config_spec() -> Items = maps:merge(common_config_items(), root_config_items()), #section{ items = Items#{<<"pm">> => pm_config_spec(), <<"muc">> => muc_config_spec(), <<"riak">> => riak_config_spec()}, defaults = #{<<"backend">> => rdbms, <<"no_stanzaid_element">> => false, <<"is_archivable_message">> => mod_mam_utils, <<"send_message">> => mod_mam_utils, <<"archive_chat_markers">> => false, <<"message_retraction">> => true, <<"full_text_search">> => true, <<"cache_users">> => true, <<"default_result_limit">> => 50, <<"max_result_limit">> => 50, <<"enforce_simple_queries">> => false}, process = fun ?MODULE:remove_unused_backend_opts/1 }. remove_unused_backend_opts(Opts = #{backend := riak}) -> Opts; remove_unused_backend_opts(Opts) -> maps:remove(riak, Opts). pm_config_spec() -> #section{items = maps:merge(common_config_items(), pm_config_items()), defaults = #{<<"archive_groupchats">> => false, <<"same_mam_id_for_peers">> => false}}. muc_config_spec() -> #section{items = maps:merge(common_config_items(), muc_config_items()), defaults = #{<<"host">> => mod_muc:default_host()}}. root_config_items() -> Cache = mongoose_user_cache:config_spec(), AsyncWriter = async_config_spec(), #{<<"cache">> => Cache#section{include = always}, <<"async_writer">> => AsyncWriter#section{include = always}}. common_config_items() -> #{%% General options <<"backend">> => #option{type = atom, validate = {enum, [rdbms, riak, cassandra, elasticsearch]}}, <<"no_stanzaid_element">> => #option{type = boolean}, <<"is_archivable_message">> => #option{type = atom, validate = module}, <<"send_message">> => #option{type = atom, validate = module}, <<"archive_chat_markers">> => #option{type = boolean}, <<"message_retraction">> => #option{type = boolean}, %% Common backend options <<"user_prefs_store">> => #option{type = atom, validate = {enum, [rdbms, cassandra, mnesia]}}, <<"full_text_search">> => #option{type = boolean}, %% RDBMS-specific options <<"cache_users">> => #option{type = boolean}, %% Low-level options <<"default_result_limit">> => #option{type = integer, validate = non_negative}, <<"enforce_simple_queries">> => #option{type = boolean}, <<"delete_domain_limit">> => #option{type = int_or_infinity, validate = positive}, <<"max_result_limit">> => #option{type = integer, validate = non_negative}, <<"db_jid_format">> => #option{type = atom, validate = module}, <<"db_message_format">> => #option{type = atom, validate = module}, <<"extra_fin_element">> => #option{type = atom, validate = module}, <<"extra_lookup_params">> => #option{type = atom, validate = module} }. pm_config_items() -> #{<<"async_writer">> => async_config_spec(), <<"archive_groupchats">> => #option{type = boolean}, <<"same_mam_id_for_peers">> => #option{type = boolean}}. muc_config_items() -> #{<<"async_writer">> => async_config_spec(), <<"host">> => #option{type = string, validate = subdomain_template, process = fun mongoose_subdomain_utils:make_subdomain_pattern/1}}. async_config_spec() -> #section{ items = #{<<"enabled">> => #option{type = boolean}, <<"flush_interval">> => #option{type = integer, validate = non_negative}, <<"batch_size">> => #option{type = integer, validate = non_negative}, <<"pool_size">> => #option{type = integer, validate = non_negative}}, defaults = #{<<"enabled">> => true, <<"flush_interval">> => 2000, <<"batch_size">> => 30, <<"pool_size">> => 4 * erlang:system_info(schedulers_online)} }. riak_config_spec() -> #section{ items = #{<<"search_index">> => #option{type = binary, validate = non_empty}, <<"bucket_type">> => #option{type = binary, validate = non_empty}}, defaults = #{<<"search_index">> => <<"mam">>, <<"bucket_type">> => <<"mam_yz">>}, include = always }. -spec deps(mongooseim:host_type(), module_opts()) -> gen_mod_deps:deps(). deps(_HostType, Opts) -> DepsWithPm = handle_nested_opts(pm, Opts, #{}), DepsWithPmAndMuc = handle_nested_opts(muc, Opts, DepsWithPm), [{DepMod, DepOpts, hard} || {DepMod, DepOpts} <- maps:to_list(DepsWithPmAndMuc)]. %%-------------------------------------------------------------------- %% Helpers %%-------------------------------------------------------------------- -type mam_type() :: pm | muc. -type mam_backend() :: rdbms | riak | cassandra | elasticsearch. -spec handle_nested_opts(mam_type(), module_opts(), module_map()) -> module_map(). handle_nested_opts(Key, RootOpts, Deps) -> case maps:find(Key, RootOpts) of error -> Deps; {ok, Opts} -> FullOpts = maps:merge(maps:without([pm, muc], RootOpts), Opts), parse_opts(Key, FullOpts, Deps) end. -spec parse_opts(mam_type(), module_opts(), module_map()) -> module_map(). parse_opts(Type, Opts, Deps) -> Opts are merged root options with options inside pm or muc section CoreMod = mam_type_to_core_mod(Type), CoreModOpts = maps:with(valid_core_mod_opts(CoreMod), Opts), WithCoreDeps = add_dep(CoreMod, CoreModOpts, Deps), {Backend, BackendOpts} = maps:take(backend, Opts), WithPrefs = add_prefs_store_module(Backend, Type, Opts, WithCoreDeps), parse_backend_opts(Backend, Type, BackendOpts, WithPrefs). -spec mam_type_to_core_mod(mam_type()) -> module(). mam_type_to_core_mod(pm) -> mod_mam_pm; mam_type_to_core_mod(muc) -> mod_mam_muc. Get a list of options to pass into the two modules . They do n't have to be defined in pm or muc sections , the root section is enough . -spec valid_core_mod_opts(module()) -> [atom()]. valid_core_mod_opts(mod_mam_pm) -> [archive_groupchats, same_mam_id_for_peers] ++ common_opts(); valid_core_mod_opts(mod_mam_muc) -> [host] ++ common_opts(). common_opts() -> [async_writer, is_archivable_message, send_message, archive_chat_markers, extra_fin_element, extra_lookup_params, full_text_search, message_retraction, default_result_limit, max_result_limit, enforce_simple_queries, no_stanzaid_element]. -spec add_prefs_store_module(mam_backend(), mam_type(), module_opts(), module_map()) -> module_map(). add_prefs_store_module(Backend, Type, #{user_prefs_store := Store}, Deps) -> PrefsModule = prefs_module(Backend, Store), add_dep(PrefsModule, #{Type => true}, Deps); add_prefs_store_module(_Backend, _Type, _Opts, Deps) -> Deps. -spec parse_backend_opts(mam_backend(), mam_type(), module_opts(), module_map()) -> module_map(). parse_backend_opts(cassandra, Type, Opts, Deps) -> Opts1 = maps:with([db_message_format], Opts), add_dep(cassandra_arch_module(Type), maps:merge(arch_defaults(), Opts1), Deps); parse_backend_opts(riak, Type, Opts, Deps) -> Opts1 = maps:with([db_message_format, riak], Opts), add_dep(mod_mam_riak_timed_arch_yz, maps:merge(arch_defaults(), Opts1#{Type => true}), Deps); parse_backend_opts(rdbms, Type, Opts, Deps) -> lists:foldl(fun(OptionGroup, DepsIn) -> add_rdbms_deps(OptionGroup, Type, Opts, DepsIn) end, Deps, [basic, user_cache, async_writer]); parse_backend_opts(elasticsearch, Type, _Opts, Deps0) -> add_dep(elasticsearch_arch_module(Type), Deps0). -spec add_rdbms_deps(basic | user_cache | async_writer, mam_type(), module_opts(), module_map()) -> module_map(). add_rdbms_deps(basic, Type, Opts, Deps) -> Opts1 = maps:with([db_message_format, db_jid_format, delete_domain_limit], Opts), Deps1 = add_dep(rdbms_arch_module(Type), maps:merge(rdbms_arch_defaults(Type), Opts1), Deps), add_dep(mod_mam_rdbms_user, user_db_types(Type), Deps1); add_rdbms_deps(user_cache, Type, #{cache_users := true, cache := CacheOpts}, Deps) -> Deps1 = case gen_mod:get_opt(module, CacheOpts, internal) of internal -> Deps; mod_cache_users -> add_dep(mod_cache_users, Deps) end, add_dep(mod_mam_cache_user, CacheOpts#{Type => true}, Deps1); add_rdbms_deps(async_writer, Type, #{async_writer := AsyncOpts = #{enabled := true}}, Deps) -> Deps1 = add_dep(rdbms_arch_module(Type), #{no_writer => true}, Deps), add_dep(rdbms_async_arch_module(Type), AsyncOpts, Deps1); add_rdbms_deps(_, _Type, _Opts, Deps) -> Deps. muc backend requires both pm and muc user DB to populate sender_id column -spec user_db_types(mam_type()) -> module_opts(). user_db_types(pm) -> #{pm => true}; user_db_types(muc) -> #{pm => true, muc => true}. cassandra_arch_module(pm) -> mod_mam_cassandra_arch; cassandra_arch_module(muc) -> mod_mam_muc_cassandra_arch. arch_defaults() -> #{db_message_format => mam_message_xml}. rdbms_arch_defaults(pm) -> maps:merge(rdbms_arch_defaults(), #{db_jid_format => mam_jid_mini}); rdbms_arch_defaults(muc) -> maps:merge(rdbms_arch_defaults(), #{db_jid_format => mam_jid_rfc}). rdbms_arch_defaults() -> #{db_message_format => mam_message_compressed_eterm, no_writer => false, delete_domain_limit => infinity}. rdbms_arch_module(pm) -> mod_mam_rdbms_arch; rdbms_arch_module(muc) -> mod_mam_muc_rdbms_arch. rdbms_async_arch_module(pm) -> mod_mam_rdbms_arch_async; rdbms_async_arch_module(muc) -> mod_mam_muc_rdbms_arch_async. elasticsearch_arch_module(pm) -> mod_mam_elasticsearch_arch; elasticsearch_arch_module(muc) -> mod_mam_muc_elasticsearch_arch. prefs_module(rdbms, rdbms) -> mod_mam_rdbms_prefs; prefs_module(cassandra, cassandra) -> mod_mam_cassandra_prefs; prefs_module(_, mnesia) -> mod_mam_mnesia_prefs; prefs_module(Backend, PrefsStore) -> error(#{what => invalid_mam_user_prefs_store, backend => Backend, user_prefs_store => PrefsStore}). -spec add_dep(module(), module_map()) -> module_map(). add_dep(Dep, Deps) -> add_dep(Dep, #{}, Deps). -spec add_dep(module(), module_opts(), module_map()) -> module_map(). add_dep(Dep, Opts, Deps) -> PrevOpts = maps:get(Dep, Deps, #{}), NewOpts = maps:merge(PrevOpts, Opts), maps:put(Dep, NewOpts, Deps). config_metrics(Host) -> mongoose_module_metrics:opts_for_module(Host, ?MODULE, [backend]).
null
https://raw.githubusercontent.com/esl/MongooseIM/dda03c16c83f5ea9f5c9b87c3b36c989813b9250/src/mam/mod_mam.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. ============================================================================== ---------------------------------------------------------------------- Datetime types ---------------------------------------------------------------------- Other types Internal types Only in mod_mam_muc_rdbms_arch:retract_message/2 -------------------------------------------------------------------- API -------------------------------------------------------------------- General options Common backend options RDBMS-specific options Low-level options -------------------------------------------------------------------- Helpers --------------------------------------------------------------------
Copyright 2016 Erlang Solutions Ltd. Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(mod_mam). -behaviour(gen_mod). -behaviour(mongoose_module_metrics). -include("mod_mam.hrl"). -include("mongoose_config_spec.hrl"). -type module_opts() :: gen_mod:module_opts(). -type module_map() :: gen_mod_deps:module_map(). Microseconds from 01.01.1970 -type unix_timestamp() :: non_neg_integer(). -type archive_behaviour() :: roster | always | never. -type message_id() :: non_neg_integer(). -type archive_id() :: non_neg_integer(). -type borders() :: #mam_borders{}. -type message_row() :: #{id := message_id(), jid := jid:jid(), packet := exml:element()}. -type lookup_result() :: {TotalCount :: non_neg_integer() | undefined, Offset :: non_neg_integer() | undefined, MessageRows :: [message_row()]}. -type lookup_result_map() :: #{total_count := TotalCount :: non_neg_integer() | undefined, offset := Offset :: non_neg_integer() | undefined, messages := MessageRows :: [message_row()], is_complete => boolean()}. -type iterator_fun() :: fun(() -> {'ok', {_, _}}). -type rewriter_fun() :: fun((JID :: jid:literal_jid()) -> jid:literal_jid()). -type restore_option() :: {rewrite_jids, rewriter_fun() | [{binary(), binary()}]} | new_message_ids. -type preference() :: {DefaultMode :: archive_behaviour(), AlwaysJIDs :: [jid:literal_jid()], NeverJIDs :: [jid:literal_jid()]}. -type archive_message_params() :: #{message_id := message_id(), archive_id := archive_id(), local_jid := jid:jid(), remote_jid := jid:jid(), source_jid := jid:jid(), origin_id := binary() | none, direction := atom(), packet := exml:element(), sender_id => archive_id()}. -export_type([rewriter_fun/0, borders/0, preference/0, archive_behaviour/0, iterator_fun/0, unix_timestamp/0, archive_id/0, lookup_result/0, lookup_result_map/0, message_row/0, message_id/0, restore_option/0, archive_message_params/0, mam_type/0 ]). -export([start/2, stop/1, config_spec/0, supported_features/0, deps/2, config_metrics/1]). -export([remove_unused_backend_opts/1]). -spec supported_features() -> [atom()]. supported_features() -> [dynamic_domains]. -spec start(mongooseim:host_type(), module_opts()) -> any(). start(_HostType, _Opts) -> ok. -spec stop(mongooseim:host_type()) -> any(). stop(_HostType) -> ok. -spec config_spec() -> mongoose_config_spec:config_section(). config_spec() -> Items = maps:merge(common_config_items(), root_config_items()), #section{ items = Items#{<<"pm">> => pm_config_spec(), <<"muc">> => muc_config_spec(), <<"riak">> => riak_config_spec()}, defaults = #{<<"backend">> => rdbms, <<"no_stanzaid_element">> => false, <<"is_archivable_message">> => mod_mam_utils, <<"send_message">> => mod_mam_utils, <<"archive_chat_markers">> => false, <<"message_retraction">> => true, <<"full_text_search">> => true, <<"cache_users">> => true, <<"default_result_limit">> => 50, <<"max_result_limit">> => 50, <<"enforce_simple_queries">> => false}, process = fun ?MODULE:remove_unused_backend_opts/1 }. remove_unused_backend_opts(Opts = #{backend := riak}) -> Opts; remove_unused_backend_opts(Opts) -> maps:remove(riak, Opts). pm_config_spec() -> #section{items = maps:merge(common_config_items(), pm_config_items()), defaults = #{<<"archive_groupchats">> => false, <<"same_mam_id_for_peers">> => false}}. muc_config_spec() -> #section{items = maps:merge(common_config_items(), muc_config_items()), defaults = #{<<"host">> => mod_muc:default_host()}}. root_config_items() -> Cache = mongoose_user_cache:config_spec(), AsyncWriter = async_config_spec(), #{<<"cache">> => Cache#section{include = always}, <<"async_writer">> => AsyncWriter#section{include = always}}. common_config_items() -> <<"backend">> => #option{type = atom, validate = {enum, [rdbms, riak, cassandra, elasticsearch]}}, <<"no_stanzaid_element">> => #option{type = boolean}, <<"is_archivable_message">> => #option{type = atom, validate = module}, <<"send_message">> => #option{type = atom, validate = module}, <<"archive_chat_markers">> => #option{type = boolean}, <<"message_retraction">> => #option{type = boolean}, <<"user_prefs_store">> => #option{type = atom, validate = {enum, [rdbms, cassandra, mnesia]}}, <<"full_text_search">> => #option{type = boolean}, <<"cache_users">> => #option{type = boolean}, <<"default_result_limit">> => #option{type = integer, validate = non_negative}, <<"enforce_simple_queries">> => #option{type = boolean}, <<"delete_domain_limit">> => #option{type = int_or_infinity, validate = positive}, <<"max_result_limit">> => #option{type = integer, validate = non_negative}, <<"db_jid_format">> => #option{type = atom, validate = module}, <<"db_message_format">> => #option{type = atom, validate = module}, <<"extra_fin_element">> => #option{type = atom, validate = module}, <<"extra_lookup_params">> => #option{type = atom, validate = module} }. pm_config_items() -> #{<<"async_writer">> => async_config_spec(), <<"archive_groupchats">> => #option{type = boolean}, <<"same_mam_id_for_peers">> => #option{type = boolean}}. muc_config_items() -> #{<<"async_writer">> => async_config_spec(), <<"host">> => #option{type = string, validate = subdomain_template, process = fun mongoose_subdomain_utils:make_subdomain_pattern/1}}. async_config_spec() -> #section{ items = #{<<"enabled">> => #option{type = boolean}, <<"flush_interval">> => #option{type = integer, validate = non_negative}, <<"batch_size">> => #option{type = integer, validate = non_negative}, <<"pool_size">> => #option{type = integer, validate = non_negative}}, defaults = #{<<"enabled">> => true, <<"flush_interval">> => 2000, <<"batch_size">> => 30, <<"pool_size">> => 4 * erlang:system_info(schedulers_online)} }. riak_config_spec() -> #section{ items = #{<<"search_index">> => #option{type = binary, validate = non_empty}, <<"bucket_type">> => #option{type = binary, validate = non_empty}}, defaults = #{<<"search_index">> => <<"mam">>, <<"bucket_type">> => <<"mam_yz">>}, include = always }. -spec deps(mongooseim:host_type(), module_opts()) -> gen_mod_deps:deps(). deps(_HostType, Opts) -> DepsWithPm = handle_nested_opts(pm, Opts, #{}), DepsWithPmAndMuc = handle_nested_opts(muc, Opts, DepsWithPm), [{DepMod, DepOpts, hard} || {DepMod, DepOpts} <- maps:to_list(DepsWithPmAndMuc)]. -type mam_type() :: pm | muc. -type mam_backend() :: rdbms | riak | cassandra | elasticsearch. -spec handle_nested_opts(mam_type(), module_opts(), module_map()) -> module_map(). handle_nested_opts(Key, RootOpts, Deps) -> case maps:find(Key, RootOpts) of error -> Deps; {ok, Opts} -> FullOpts = maps:merge(maps:without([pm, muc], RootOpts), Opts), parse_opts(Key, FullOpts, Deps) end. -spec parse_opts(mam_type(), module_opts(), module_map()) -> module_map(). parse_opts(Type, Opts, Deps) -> Opts are merged root options with options inside pm or muc section CoreMod = mam_type_to_core_mod(Type), CoreModOpts = maps:with(valid_core_mod_opts(CoreMod), Opts), WithCoreDeps = add_dep(CoreMod, CoreModOpts, Deps), {Backend, BackendOpts} = maps:take(backend, Opts), WithPrefs = add_prefs_store_module(Backend, Type, Opts, WithCoreDeps), parse_backend_opts(Backend, Type, BackendOpts, WithPrefs). -spec mam_type_to_core_mod(mam_type()) -> module(). mam_type_to_core_mod(pm) -> mod_mam_pm; mam_type_to_core_mod(muc) -> mod_mam_muc. Get a list of options to pass into the two modules . They do n't have to be defined in pm or muc sections , the root section is enough . -spec valid_core_mod_opts(module()) -> [atom()]. valid_core_mod_opts(mod_mam_pm) -> [archive_groupchats, same_mam_id_for_peers] ++ common_opts(); valid_core_mod_opts(mod_mam_muc) -> [host] ++ common_opts(). common_opts() -> [async_writer, is_archivable_message, send_message, archive_chat_markers, extra_fin_element, extra_lookup_params, full_text_search, message_retraction, default_result_limit, max_result_limit, enforce_simple_queries, no_stanzaid_element]. -spec add_prefs_store_module(mam_backend(), mam_type(), module_opts(), module_map()) -> module_map(). add_prefs_store_module(Backend, Type, #{user_prefs_store := Store}, Deps) -> PrefsModule = prefs_module(Backend, Store), add_dep(PrefsModule, #{Type => true}, Deps); add_prefs_store_module(_Backend, _Type, _Opts, Deps) -> Deps. -spec parse_backend_opts(mam_backend(), mam_type(), module_opts(), module_map()) -> module_map(). parse_backend_opts(cassandra, Type, Opts, Deps) -> Opts1 = maps:with([db_message_format], Opts), add_dep(cassandra_arch_module(Type), maps:merge(arch_defaults(), Opts1), Deps); parse_backend_opts(riak, Type, Opts, Deps) -> Opts1 = maps:with([db_message_format, riak], Opts), add_dep(mod_mam_riak_timed_arch_yz, maps:merge(arch_defaults(), Opts1#{Type => true}), Deps); parse_backend_opts(rdbms, Type, Opts, Deps) -> lists:foldl(fun(OptionGroup, DepsIn) -> add_rdbms_deps(OptionGroup, Type, Opts, DepsIn) end, Deps, [basic, user_cache, async_writer]); parse_backend_opts(elasticsearch, Type, _Opts, Deps0) -> add_dep(elasticsearch_arch_module(Type), Deps0). -spec add_rdbms_deps(basic | user_cache | async_writer, mam_type(), module_opts(), module_map()) -> module_map(). add_rdbms_deps(basic, Type, Opts, Deps) -> Opts1 = maps:with([db_message_format, db_jid_format, delete_domain_limit], Opts), Deps1 = add_dep(rdbms_arch_module(Type), maps:merge(rdbms_arch_defaults(Type), Opts1), Deps), add_dep(mod_mam_rdbms_user, user_db_types(Type), Deps1); add_rdbms_deps(user_cache, Type, #{cache_users := true, cache := CacheOpts}, Deps) -> Deps1 = case gen_mod:get_opt(module, CacheOpts, internal) of internal -> Deps; mod_cache_users -> add_dep(mod_cache_users, Deps) end, add_dep(mod_mam_cache_user, CacheOpts#{Type => true}, Deps1); add_rdbms_deps(async_writer, Type, #{async_writer := AsyncOpts = #{enabled := true}}, Deps) -> Deps1 = add_dep(rdbms_arch_module(Type), #{no_writer => true}, Deps), add_dep(rdbms_async_arch_module(Type), AsyncOpts, Deps1); add_rdbms_deps(_, _Type, _Opts, Deps) -> Deps. muc backend requires both pm and muc user DB to populate sender_id column -spec user_db_types(mam_type()) -> module_opts(). user_db_types(pm) -> #{pm => true}; user_db_types(muc) -> #{pm => true, muc => true}. cassandra_arch_module(pm) -> mod_mam_cassandra_arch; cassandra_arch_module(muc) -> mod_mam_muc_cassandra_arch. arch_defaults() -> #{db_message_format => mam_message_xml}. rdbms_arch_defaults(pm) -> maps:merge(rdbms_arch_defaults(), #{db_jid_format => mam_jid_mini}); rdbms_arch_defaults(muc) -> maps:merge(rdbms_arch_defaults(), #{db_jid_format => mam_jid_rfc}). rdbms_arch_defaults() -> #{db_message_format => mam_message_compressed_eterm, no_writer => false, delete_domain_limit => infinity}. rdbms_arch_module(pm) -> mod_mam_rdbms_arch; rdbms_arch_module(muc) -> mod_mam_muc_rdbms_arch. rdbms_async_arch_module(pm) -> mod_mam_rdbms_arch_async; rdbms_async_arch_module(muc) -> mod_mam_muc_rdbms_arch_async. elasticsearch_arch_module(pm) -> mod_mam_elasticsearch_arch; elasticsearch_arch_module(muc) -> mod_mam_muc_elasticsearch_arch. prefs_module(rdbms, rdbms) -> mod_mam_rdbms_prefs; prefs_module(cassandra, cassandra) -> mod_mam_cassandra_prefs; prefs_module(_, mnesia) -> mod_mam_mnesia_prefs; prefs_module(Backend, PrefsStore) -> error(#{what => invalid_mam_user_prefs_store, backend => Backend, user_prefs_store => PrefsStore}). -spec add_dep(module(), module_map()) -> module_map(). add_dep(Dep, Deps) -> add_dep(Dep, #{}, Deps). -spec add_dep(module(), module_opts(), module_map()) -> module_map(). add_dep(Dep, Opts, Deps) -> PrevOpts = maps:get(Dep, Deps, #{}), NewOpts = maps:merge(PrevOpts, Opts), maps:put(Dep, NewOpts, Deps). config_metrics(Host) -> mongoose_module_metrics:opts_for_module(Host, ?MODULE, [backend]).
7972cd21ca8b042ebbc78fa2e4cd64d919aaf4bdf6c617c343ae7cf9ebc5a289
s-expressionists/Concrete-Syntax-Tree
unparse.lisp
(cl:in-package #:concrete-syntax-tree-lambda-list-test) (defgeneric unparse (tree)) (defmethod unparse ((tree cst::lambda-list-type)) (reduce #'append (mapcar #'unparse (cst::children tree)))) (defmethod unparse ((tree cst::parameter-group)) (mapcar #'unparse (cst::parameters tree))) (defmethod unparse ((tree cst::lambda-list-keyword)) (cst::name tree)) (defmethod unparse ((tree cst::simple-variable)) (cst::name tree)) (defmethod unparse ((tree cst::ordinary-optional-parameter)) (list (cst::name tree) (cst::form tree) (cst::supplied-p tree))) (defmethod unparse ((tree cst::ordinary-key-parameter)) (list (list (cst::keyword tree) (cst::name tree)) (cst::form tree) (cst::supplied-p tree))) (defmethod unparse ((tree cst::aux-parameter)) (list (cst::name tree) (cst::form tree))) (defmethod unparse ((tree cst::generic-function-optional-parameter)) (cst::name tree)) (defmethod unparse ((tree cst::generic-function-key-parameter)) (list (list (cst::keyword tree) (cst::name tree)))) (defmethod unparse ((tree cst::specialized-required-parameter)) (list (cst::name tree) (cst::specializer tree)))
null
https://raw.githubusercontent.com/s-expressionists/Concrete-Syntax-Tree/a56a5246fbaa90b98a29368c011a6616f2bcb482/Lambda-list/Test/unparse.lisp
lisp
(cl:in-package #:concrete-syntax-tree-lambda-list-test) (defgeneric unparse (tree)) (defmethod unparse ((tree cst::lambda-list-type)) (reduce #'append (mapcar #'unparse (cst::children tree)))) (defmethod unparse ((tree cst::parameter-group)) (mapcar #'unparse (cst::parameters tree))) (defmethod unparse ((tree cst::lambda-list-keyword)) (cst::name tree)) (defmethod unparse ((tree cst::simple-variable)) (cst::name tree)) (defmethod unparse ((tree cst::ordinary-optional-parameter)) (list (cst::name tree) (cst::form tree) (cst::supplied-p tree))) (defmethod unparse ((tree cst::ordinary-key-parameter)) (list (list (cst::keyword tree) (cst::name tree)) (cst::form tree) (cst::supplied-p tree))) (defmethod unparse ((tree cst::aux-parameter)) (list (cst::name tree) (cst::form tree))) (defmethod unparse ((tree cst::generic-function-optional-parameter)) (cst::name tree)) (defmethod unparse ((tree cst::generic-function-key-parameter)) (list (list (cst::keyword tree) (cst::name tree)))) (defmethod unparse ((tree cst::specialized-required-parameter)) (list (cst::name tree) (cst::specializer tree)))
de45d6bd80d9572643cd4eb6699750ef24f2448c8107df6428633db5bb019a27
mrphlip/aoc
03.hs
# OPTIONS_GHC -Wno - tabs # import Data.Bits import Data.List import Control.Exception import Utils getInput :: IO (Int, [Integer]) getInput = do dat <- readFile "03.txt" return $ parseInput dat parseInput :: String -> (Int, [Integer]) parseInput dat = if all ((==bitlen).length) ls then (bitlen, map (readBaseN 2) ls) else error "not all strings are the same length" where ls = lines dat bitlen = length $ head ls mostCommon :: Int -> [Integer] -> Bool mostCommon pos xs = countSet * 2 >= countAll where countAll = genericLength xs countSet = genericLength $ filter (flip testBit pos) xs mostCommons :: Int -> [Integer] -> Integer mostCommons bitlen xs = foldl1 (.|.) [bit i | i<-[0..bitlen-1], mostCommon i xs] doSelect :: Bool -> Int -> [Integer] -> Integer doSelect invert bitlen xs = worker (bitlen - 1) xs where worker :: Int -> [Integer] -> Integer worker _ [] = error "No result found" worker _ [x] = x worker pos xs = worker (pos - 1) $ filter ((==sel).flip testBit pos) xs where sel = mostCommon pos xs `xor` invert partA bitlen xs = (gamma, epsilon) where gamma = mostCommons bitlen xs epsilon = complement gamma .&. (bit bitlen - 1) partB bitlen xs = (o2, co2) where o2 = doSelect False bitlen xs co2 = doSelect True bitlen xs tests :: IO () tests = do check $ partA bitlen values == (22, 9) check $ partB bitlen values == (23, 10) where (bitlen, values) = parseInput "00100\n11110\n10110\n10111\n10101\n01111\n00111\n11100\n10000\n11001\n00010\n01010" check True = return () check False = throwIO $ AssertionFailed "test failed" main :: IO () main = do tests (bitlen, values) <- getInput print $ uncurry (*) $ partA bitlen values print $ uncurry (*) $ partB bitlen values
null
https://raw.githubusercontent.com/mrphlip/aoc/2b853e9d7e9ec65ce72ce64b6df1b6253d4730fe/2021/03.hs
haskell
# OPTIONS_GHC -Wno - tabs # import Data.Bits import Data.List import Control.Exception import Utils getInput :: IO (Int, [Integer]) getInput = do dat <- readFile "03.txt" return $ parseInput dat parseInput :: String -> (Int, [Integer]) parseInput dat = if all ((==bitlen).length) ls then (bitlen, map (readBaseN 2) ls) else error "not all strings are the same length" where ls = lines dat bitlen = length $ head ls mostCommon :: Int -> [Integer] -> Bool mostCommon pos xs = countSet * 2 >= countAll where countAll = genericLength xs countSet = genericLength $ filter (flip testBit pos) xs mostCommons :: Int -> [Integer] -> Integer mostCommons bitlen xs = foldl1 (.|.) [bit i | i<-[0..bitlen-1], mostCommon i xs] doSelect :: Bool -> Int -> [Integer] -> Integer doSelect invert bitlen xs = worker (bitlen - 1) xs where worker :: Int -> [Integer] -> Integer worker _ [] = error "No result found" worker _ [x] = x worker pos xs = worker (pos - 1) $ filter ((==sel).flip testBit pos) xs where sel = mostCommon pos xs `xor` invert partA bitlen xs = (gamma, epsilon) where gamma = mostCommons bitlen xs epsilon = complement gamma .&. (bit bitlen - 1) partB bitlen xs = (o2, co2) where o2 = doSelect False bitlen xs co2 = doSelect True bitlen xs tests :: IO () tests = do check $ partA bitlen values == (22, 9) check $ partB bitlen values == (23, 10) where (bitlen, values) = parseInput "00100\n11110\n10110\n10111\n10101\n01111\n00111\n11100\n10000\n11001\n00010\n01010" check True = return () check False = throwIO $ AssertionFailed "test failed" main :: IO () main = do tests (bitlen, values) <- getInput print $ uncurry (*) $ partA bitlen values print $ uncurry (*) $ partB bitlen values
1c4088e6ee2c423b749b49d9d151f695ccdb47f5a0d74ee94732bada75271767
AbstractMachinesLab/caramel
omd_utils.mli
(***********************************************************************) omd : frontend in OCaml ( c ) 2013/2014 by < > (* Licence : ISC *) (* -support-policy/isc-license/ *) (***********************************************************************) val debug : bool (** Equals [true] if the environment variable DEBUG is set, or if the environment variable OMD_DEBUG is set to a string that is not ["false"]. *) val trackfix : bool exception Error of string val raise : exn -> 'a (** Same as [Pervasives.raise] except if [debug] equals true, in which case it prints a trace on stderr before raising the exception. *) val warn : ?we:bool -> string -> unit (** [warn we x] prints a warning with the message [x] if [we] is true, else raises [Omd_utils.Error x]. *) module StringSet : sig include Set.S with type elt = string val of_list : elt list -> t end (** Set of [string]. Cf. documentation of {!Set.S} *) type 'a split = 'a list -> 'a split_action (** Type of a split function *) and 'a split_action = (** Don't split yet *) | Continue * Do n't split yet but continue with those two lists instead of default | Continue_with of 'a list * 'a list (** Do split with this split scheme *) | Split of 'a list * 'a list (** Type of a split action *) val fsplit_rev : ?excl:('a list -> bool) -> f:'a split -> 'a list -> ('a list * 'a list) option * [ fsplit_rev ? excl ~f l ] returns [ Some(x , y ) ] where [ x ] is the * * reversed * * list of the consecutive elements of [ l ] that obey the split function [ f ] . Note that [ f ] is applied to a list of elements and not just an element , so that [ f ] can look farther in the list when applied . [ f l ] returns [ Continue ] if there 're more elements to consume , [ Continue_with(left , right ) ] if there 's more elements to consume but we want to choose what goes to the left part and what remains to process ( right part ) , and returns [ , right ) ] if the splitting is decided . When [ f ] is applied to an empty list , if it returns [ Continue ] then the result will be [ None ] . If [ excl ] is given , then [ excl ] is applied before [ f ] is , to check if the splitting should be stopped right away . When the split fails , it returns [ None ] . **reversed** list of the consecutive elements of [l] that obey the split function [f]. Note that [f] is applied to a list of elements and not just an element, so that [f] can look farther in the list when applied. [f l] returns [Continue] if there're more elements to consume, [Continue_with(left,right)] if there's more elements to consume but we want to choose what goes to the left part and what remains to process (right part), and returns [Split(left,right)] if the splitting is decided. When [f] is applied to an empty list, if it returns [Continue] then the result will be [None]. If [excl] is given, then [excl] is applied before [f] is, to check if the splitting should be stopped right away. When the split fails, it returns [None]. *) val fsplit : ?excl:('a list -> bool) -> f:'a split -> 'a list -> ('a list * 'a list) option (** [fsplit ?excl ~f l] returns [Some(List.rev x, y)] if [fsplit ?excl ~f l] returns [Some(x,y)], else it returns [None]. *) val id_of_string : < mangle : string -> string; .. > -> string -> string (** [id_of_string ids id] returns a mangled version of [id], using the method [ids#mangle]. If you don't need mangling, you may use [object method mangle x = x end] for [ids]. However, the name [ids] also means that your object should have knowledge of all IDs it has issued, in order to avoid collision. This is why [id_of_string] asks for an object rather than "just a function". *) val htmlentities : ?md:bool -> string -> string (** [htmlentities s] returns a new string in which html-significant characters have been converted to html entities. For instance, "<Foo&Bar>" is converted to "&lt;Foo&amp;Bar&gt;". *) val minimalize_blanks : string -> string * [ minimalize_blanks s ] returns a copy of [ s ] in which the first and last characters are never blank , and two consecutive blanks never happen . characters are never blank, and two consecutive blanks never happen. *) val eat : ('a -> bool) -> 'a list -> 'a list * [ eat f l ] returns [ l ] where elements satisfying [ f ] have been removed , but it stops removing as soon as one element does n't satisfy [ f ] . but it stops removing as soon as one element doesn't satisfy [f]. *) val extract_html_attributes : string -> (string * string) list * Takes some HTML and returns the list of attributes of the first HTML tag . Notes : * Does n't check the validity of HTML tags or attributes . * Does n't support backslash escaping . * Attribute names are delimited by the space and equal characters . * Attribute values are either delimited by the double quote or the simple quote character . HTML tag. Notes: * Doesn't check the validity of HTML tags or attributes. * Doesn't support backslash escaping. * Attribute names are delimited by the space and equal characters. * Attribute values are either delimited by the double quote or the simple quote character. *) val extract_inner_html : string -> string (** Takes an HTML node and returns the contents of the node. If it's not given a node, it returns something rubbish. *) val html_void_elements : StringSet.t (** HTML void elements *) val ( @ ) : 'a list -> 'a list -> 'a list * Tail - recursive version of [ Pervasives.(@ ) ] .
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/omd/src/omd_utils.mli
ocaml
********************************************************************* Licence : ISC -support-policy/isc-license/ ********************************************************************* * Equals [true] if the environment variable DEBUG is set, or if the environment variable OMD_DEBUG is set to a string that is not ["false"]. * Same as [Pervasives.raise] except if [debug] equals true, in which case it prints a trace on stderr before raising the exception. * [warn we x] prints a warning with the message [x] if [we] is true, else raises [Omd_utils.Error x]. * Set of [string]. Cf. documentation of {!Set.S} * Type of a split function * Don't split yet * Do split with this split scheme * Type of a split action * [fsplit ?excl ~f l] returns [Some(List.rev x, y)] if [fsplit ?excl ~f l] returns [Some(x,y)], else it returns [None]. * [id_of_string ids id] returns a mangled version of [id], using the method [ids#mangle]. If you don't need mangling, you may use [object method mangle x = x end] for [ids]. However, the name [ids] also means that your object should have knowledge of all IDs it has issued, in order to avoid collision. This is why [id_of_string] asks for an object rather than "just a function". * [htmlentities s] returns a new string in which html-significant characters have been converted to html entities. For instance, "<Foo&Bar>" is converted to "&lt;Foo&amp;Bar&gt;". * Takes an HTML node and returns the contents of the node. If it's not given a node, it returns something rubbish. * HTML void elements
omd : frontend in OCaml ( c ) 2013/2014 by < > val debug : bool val trackfix : bool exception Error of string val raise : exn -> 'a val warn : ?we:bool -> string -> unit module StringSet : sig include Set.S with type elt = string val of_list : elt list -> t end type 'a split = 'a list -> 'a split_action and 'a split_action = | Continue * Do n't split yet but continue with those two lists instead of default | Continue_with of 'a list * 'a list | Split of 'a list * 'a list val fsplit_rev : ?excl:('a list -> bool) -> f:'a split -> 'a list -> ('a list * 'a list) option * [ fsplit_rev ? excl ~f l ] returns [ Some(x , y ) ] where [ x ] is the * * reversed * * list of the consecutive elements of [ l ] that obey the split function [ f ] . Note that [ f ] is applied to a list of elements and not just an element , so that [ f ] can look farther in the list when applied . [ f l ] returns [ Continue ] if there 're more elements to consume , [ Continue_with(left , right ) ] if there 's more elements to consume but we want to choose what goes to the left part and what remains to process ( right part ) , and returns [ , right ) ] if the splitting is decided . When [ f ] is applied to an empty list , if it returns [ Continue ] then the result will be [ None ] . If [ excl ] is given , then [ excl ] is applied before [ f ] is , to check if the splitting should be stopped right away . When the split fails , it returns [ None ] . **reversed** list of the consecutive elements of [l] that obey the split function [f]. Note that [f] is applied to a list of elements and not just an element, so that [f] can look farther in the list when applied. [f l] returns [Continue] if there're more elements to consume, [Continue_with(left,right)] if there's more elements to consume but we want to choose what goes to the left part and what remains to process (right part), and returns [Split(left,right)] if the splitting is decided. When [f] is applied to an empty list, if it returns [Continue] then the result will be [None]. If [excl] is given, then [excl] is applied before [f] is, to check if the splitting should be stopped right away. When the split fails, it returns [None]. *) val fsplit : ?excl:('a list -> bool) -> f:'a split -> 'a list -> ('a list * 'a list) option val id_of_string : < mangle : string -> string; .. > -> string -> string val htmlentities : ?md:bool -> string -> string val minimalize_blanks : string -> string * [ minimalize_blanks s ] returns a copy of [ s ] in which the first and last characters are never blank , and two consecutive blanks never happen . characters are never blank, and two consecutive blanks never happen. *) val eat : ('a -> bool) -> 'a list -> 'a list * [ eat f l ] returns [ l ] where elements satisfying [ f ] have been removed , but it stops removing as soon as one element does n't satisfy [ f ] . but it stops removing as soon as one element doesn't satisfy [f]. *) val extract_html_attributes : string -> (string * string) list * Takes some HTML and returns the list of attributes of the first HTML tag . Notes : * Does n't check the validity of HTML tags or attributes . * Does n't support backslash escaping . * Attribute names are delimited by the space and equal characters . * Attribute values are either delimited by the double quote or the simple quote character . HTML tag. Notes: * Doesn't check the validity of HTML tags or attributes. * Doesn't support backslash escaping. * Attribute names are delimited by the space and equal characters. * Attribute values are either delimited by the double quote or the simple quote character. *) val extract_inner_html : string -> string val html_void_elements : StringSet.t val ( @ ) : 'a list -> 'a list -> 'a list * Tail - recursive version of [ Pervasives.(@ ) ] .
203dde0acc1d4e0ba888c8ebcc36f0c351705a58644d02b960743da28e69f352
mfoemmel/erlang-otp
ssh_ssh.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2005 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% %% %%% Description: THIS MODULE IS DEPRECATD AND SHOULD BE REMOVED IN R14 -module(ssh_ssh). -export([connect/1, connect/2, connect/3]). -deprecated({connect, 1, next_major_release}). -deprecated({connect, 2, next_major_release}). -deprecated({connect, 3, next_major_release}). -include("ssh.hrl"). -include("ssh_connect.hrl"). -define(default_timeout, 10000). %%% Backwards compatibility connect(A) -> connect(A, []). connect(Host, Opts) when is_list(Host) -> connect(Host, 22, Opts); connect(CM, Opts) -> Timeout = proplists:get_value(connect_timeout, Opts, ?default_timeout), session(CM, Timeout). connect(Host, Port, Opts) -> case ssh:connect(Host, Port, Opts) of {ok, CM} -> session(CM, proplists:get_value(connect_timeout, Opts, ?default_timeout)); Error -> Error end. session(CM, Timeout) -> case ssh_connection:session_channel(CM, Timeout) of {ok, ChannelId} -> Args = [{channel_cb, ssh_shell}, {init_args,[CM, ChannelId]}, {cm, CM}, {channel_id, ChannelId}], {ok, State} = ssh_channel:init([Args]), ssh_channel:enter_loop(State); Error -> Error end.
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/ssh/src/ssh_ssh.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% Description: THIS MODULE IS DEPRECATD AND SHOULD BE REMOVED IN R14 Backwards compatibility
Copyright Ericsson AB 2005 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(ssh_ssh). -export([connect/1, connect/2, connect/3]). -deprecated({connect, 1, next_major_release}). -deprecated({connect, 2, next_major_release}). -deprecated({connect, 3, next_major_release}). -include("ssh.hrl"). -include("ssh_connect.hrl"). -define(default_timeout, 10000). connect(A) -> connect(A, []). connect(Host, Opts) when is_list(Host) -> connect(Host, 22, Opts); connect(CM, Opts) -> Timeout = proplists:get_value(connect_timeout, Opts, ?default_timeout), session(CM, Timeout). connect(Host, Port, Opts) -> case ssh:connect(Host, Port, Opts) of {ok, CM} -> session(CM, proplists:get_value(connect_timeout, Opts, ?default_timeout)); Error -> Error end. session(CM, Timeout) -> case ssh_connection:session_channel(CM, Timeout) of {ok, ChannelId} -> Args = [{channel_cb, ssh_shell}, {init_args,[CM, ChannelId]}, {cm, CM}, {channel_id, ChannelId}], {ok, State} = ssh_channel:init([Args]), ssh_channel:enter_loop(State); Error -> Error end.
4099eb9f6f303ac45e31ea2bb720418852c9ca8d230543f62cf45dae1b00261d
sdiehl/elliptic-curve
Generate.hs
module Generate.Edwards.Generate ( prettyGenerate ) where import Protolude hiding (toLower) import Data.Text (toLower) import Text.PrettyPrint.Leijen.Text import Generate.Edwards.Types import Generate.Generate import Generate.Pretty ------------------------------------------------------------------------------- -- Generate ------------------------------------------------------------------------------- prettyImports :: Doc prettyImports = "module Generate.Edwards.Parameters" <$$> indent 2 ( "( curves" <$$> ") where" ) <> prettyBreak <$$> "import Generate.Edwards.Types" prettyCurves :: [Curve] -> Doc prettyCurves curves = prettySection "Curves" <$$> "curves :: [Curve]" <$$> "curves =" <$$> indent 2 ( "[ " <> hcat (punctuate "\n, " (map prettyCurves' curves)) <$$> "]" ) where prettyCurves' :: Curve -> Doc prettyCurves' = pretty . toLower . name prettyParameters :: [Curve] -> Doc prettyParameters curves = prettySection "Parameters" <$$> vcat (punctuate prettyBreak (map prettyParameters' curves)) where prettyParameters' :: Curve -> Doc prettyParameters' (Curve name Types{..} Parameters{..}) = pretty (toLower name) <+> ":: Curve" <$$> pretty (toLower name) <+> "= Curve" <$$> indent 2 ( "{ name =" <+> prettyText name <$$> ", types = Types" <$$> indent 2 ( "{ curve =" <+> prettyText curve <$$> ", field =" <+> prettyField field <$$> "}" ) <$$> ", parameters = Parameters" <$$> indent 2 ( "{ a =" <+> prettyElement a <$$> ", d =" <+> prettyElement d <$$> ", h =" <+> prettyNatural h <$$> ", q =" <+> prettyNatural q <$$> ", r =" <+> prettyNatural r <$$> ", x =" <+> prettyElement x <$$> ", y =" <+> prettyElement y <$$> "}" ) <$$> "}" ) prettyGenerate :: [Curve] -> Doc prettyGenerate curves = prettyImports <> prettyBreak <$$> prettyCurves curves <> prettyBreak <$$> prettyParameters curves <> prettyBreak
null
https://raw.githubusercontent.com/sdiehl/elliptic-curve/445e196a550e36e0f25bd4d9d6a38676b4cf2be8/generate/Generate/Edwards/Generate.hs
haskell
----------------------------------------------------------------------------- Generate -----------------------------------------------------------------------------
module Generate.Edwards.Generate ( prettyGenerate ) where import Protolude hiding (toLower) import Data.Text (toLower) import Text.PrettyPrint.Leijen.Text import Generate.Edwards.Types import Generate.Generate import Generate.Pretty prettyImports :: Doc prettyImports = "module Generate.Edwards.Parameters" <$$> indent 2 ( "( curves" <$$> ") where" ) <> prettyBreak <$$> "import Generate.Edwards.Types" prettyCurves :: [Curve] -> Doc prettyCurves curves = prettySection "Curves" <$$> "curves :: [Curve]" <$$> "curves =" <$$> indent 2 ( "[ " <> hcat (punctuate "\n, " (map prettyCurves' curves)) <$$> "]" ) where prettyCurves' :: Curve -> Doc prettyCurves' = pretty . toLower . name prettyParameters :: [Curve] -> Doc prettyParameters curves = prettySection "Parameters" <$$> vcat (punctuate prettyBreak (map prettyParameters' curves)) where prettyParameters' :: Curve -> Doc prettyParameters' (Curve name Types{..} Parameters{..}) = pretty (toLower name) <+> ":: Curve" <$$> pretty (toLower name) <+> "= Curve" <$$> indent 2 ( "{ name =" <+> prettyText name <$$> ", types = Types" <$$> indent 2 ( "{ curve =" <+> prettyText curve <$$> ", field =" <+> prettyField field <$$> "}" ) <$$> ", parameters = Parameters" <$$> indent 2 ( "{ a =" <+> prettyElement a <$$> ", d =" <+> prettyElement d <$$> ", h =" <+> prettyNatural h <$$> ", q =" <+> prettyNatural q <$$> ", r =" <+> prettyNatural r <$$> ", x =" <+> prettyElement x <$$> ", y =" <+> prettyElement y <$$> "}" ) <$$> "}" ) prettyGenerate :: [Curve] -> Doc prettyGenerate curves = prettyImports <> prettyBreak <$$> prettyCurves curves <> prettyBreak <$$> prettyParameters curves <> prettyBreak
6e69e4ce15f436b20c8c9ab1f3c155228ec3e7b19c3cba2221003f78e4c154e7
softlab-ntua/bencherl
linear_2D.erl
Copyright ( C ) 2003 - 2014 % This file is part of the Ceylan Erlang library . % % This library is free software: you can redistribute it and/or modify % it under the terms of the GNU Lesser General Public License or the GNU General Public License , as they are published by the Free Software Foundation , either version 3 of these Licenses , or ( at your option ) % any later version. % You can also redistribute it and/or modify it under the terms of the Mozilla Public License , version 1.1 or later . % % This library is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License and the GNU General Public License % for more details. % You should have received a copy of the GNU Lesser General Public License , of the GNU General Public License and of the Mozilla Public License % along with this library. % If not, see </> and % </>. % Author : ( ) Creation date : Monday , February 15 , 2010 . Gathering of various two dimensional linear facilities . % % See linear_2D_test.erl for the corresponding test. % -module(linear_2D). % Operations on points: % -export([ get_origin/0, are_close/2, is_within/3, is_within_square/3, square_distance/2, distance/2, cross_product/2, roundify/1, get_integer_center/2, get_center/2, translate/2 ]). % Operations on vectors: % -export([ vectorize/2, square_magnitude/1, magnitude/1, scale/2, make_unit/1, normal_left/1, normal_right/1, dot_product/2 ]). % Operations on lines: % -export([ get_line/2, intersect/2, get_abscissa_for_ordinate/2 ]). Operations related to angles : % -export([ is_strictly_on_the_right/3, is_obtuse/1, abs_angle_rad/3, angle_rad/3, abs_angle_deg/3, angle_deg/3 ]). Operations on set of points : % -export([ compute_smallest_enclosing_rectangle/1, compute_max_overall_distance/1, compute_convex_hull/1 ]). % Textual conversions: % -export([ to_string/1, to_string/2 ]). % Only useful for tests: % -export([ find_pivot/1, sort_by_angle/2 ]). % For epsilon: -include("math_utils.hrl"). -type point() :: { linear:coordinate(), linear:coordinate() }. -type integer_point() :: { linear:integer_coordinate(), linear:integer_coordinate() }. { Width , } : -type dimensions() :: { linear:integer_coordinate(), linear:integer_coordinate() }. % Vectors could/should be aliased to points: -type vector() :: { linear:coordinate(), linear:coordinate() }. -type integer_vector() :: { linear:integer_coordinate(), linear:integer_coordinate() }. A line , whose equation A.x+B.y+C=0 , can be defined by its three coefficients % {A,B,C}. % -type line() :: { number(), number(), number() }. -type shape() :: 'circle' | 'rectangle' | 'square' | 'triangle' | 'polygon'. -export_type([ point/0, integer_point/0, dimensions/0, vector/0, integer_vector/0, line/0, shape/0 ]). Point section . % Returns the origin of this referential. % -spec get_origin() -> point(). get_origin() -> { 0, 0 }. Returns whether the two specified points are close , i.e. if they could be % considered as representing the same point (equality operator on points). % -spec are_close( point(), point() ) -> boolean(). are_close( _P1={X1,Y1}, _P2={X2,Y2} ) -> math_utils:are_close( X1, X2 ) andalso math_utils:are_close( Y1, Y2 ). % Tells whether point P is within a distance D from point C, using some margin % to overcome numerical errors. % -spec is_within( point(), point(), number() ) -> boolean(). is_within( P, C, D ) -> " Taylor series " , square(epsilon ) is negligible here : square_distance( P, C ) < D * ( D + ?epsilon ). Tells whether point P is within a square distance SquareD from point C. % -spec is_within_square( point(), point(), number() ) -> boolean(). is_within_square( P, C, SquareD ) -> square_distance( P, C ) < SquareD. Returns the square of the distance between the two specified points . % % For comparison purposes, computing the square root is useless. % % Could rely on vectorize and square_magnitude as well. % -spec square_distance( point(), point() ) -> linear:square_distance(). square_distance( {X1,Y1}, {X2,Y2} ) -> XDiff = X2-X1, YDiff = Y2-Y1, XDiff*XDiff + YDiff*YDiff. Returns the distance between the two specified points . % % For comparison purposes, computing the square root is useless. % % Could rely on vectorize and magnitude as well. % -spec distance( point(), point() ) -> linear:distance(). distance( P1, P2 ) -> math:sqrt( square_distance( P1, P2 ) ). Returns the cross - product of the two specified 2D points , i.e. the magnitude % of the vector that would result from a regular 3D cross product of the input % vectors, taking their Z values implicitly as 0. -spec cross_product( point(), point() ) -> number(). cross_product( {X1,Y1}, {X2,Y2} ) -> X1*Y2 - Y1*X2. % Returns a point (or vector) whose coordinates have been rounded to nearest % integer. % -spec roundify( point() ) -> integer_point(). roundify( {X,Y} ) -> { erlang:round(X), erlang:round(Y) }. Returns a vertex corresponding the middle of the two specified vertices , % returned with integer coordinates. % -spec get_integer_center( point(), point() ) -> integer_point(). get_integer_center( P1, P2 ) -> roundify( get_center( P1, P2 ) ). Returns a vertex corresponding the middle of the two specified vertices , % returned with possibly floating-point coordinates. % -spec get_center( point(), point() ) -> point(). get_center( {X1,Y1}, {X2,Y2} ) -> { (X1+X2)/2, (Y1+Y2)/2 }. % Returns a point corresponding to the specified point P translated by the % specified vector V. % -spec translate( point(), vector() ) -> point(). translate( _P={X,Y}, _V={Vx,Vy} ) -> { X+Vx, Y+Vy }. % Section for sets of points. % Computes the smallest rectangle that encloses the specified list of points. % Returns { TopLeft , BottomRight } . % -spec compute_smallest_enclosing_rectangle( [ point() ] ) -> { point(), point() }. compute_smallest_enclosing_rectangle( Points ) -> compute_smallest_enclosing_rectangle( Points, undefined, undefined ). % Helper: compute_smallest_enclosing_rectangle( _Points=[], TopLeft, BottomRight ) -> { TopLeft, BottomRight }; compute_smallest_enclosing_rectangle( [ _Points=P | Others ], undefined, undefined ) -> First found initializes best , knowing at least two points are expected : compute_smallest_enclosing_rectangle( Others, _TopLeft=P, _BottomRight=P ); compute_smallest_enclosing_rectangle( [ _Points={ X, Y } | Others ], { Xt, Yt }, { Xb, Yb } ) -> Xmin = erlang:min( X, Xt ), Ymin = erlang:min( Y, Yt ), Xmax = erlang:max( X, Xb ), Ymax = erlang:max( Y, Yb ), compute_smallest_enclosing_rectangle( Others, { Xmin, Ymin }, { Xmax, Ymax } ). Computes the maximum distance between two points in the specified list of % points. % % Returns {P1,P2,square_distance(P1,P2)} so that (square) distance is maximal. % We ensure that each internal edge is examined only once: when the distance % between a given vertex V and all other vertices have been computed, V is removed from the list and a new mAximum is searched within this subset . % Here there is only one vertex left : % -spec compute_max_overall_distance( [ point() ] ) -> { point(), point(), linear:square_distance() }. compute_max_overall_distance( Points ) when length( Points ) < 2 -> throw( { no_computable_overall_distance, Points } ); compute_max_overall_distance( Points ) -> compute_max_overall_distance( Points, undefined ). % Helper. compute_max_overall_distance( _Points=[ _H ], Longest ) -> Longest; % Here we have not compute a distance yet: compute_max_overall_distance( _Points=[ H | Others ], undefined ) -> FirstEntry = compute_max_distance_between( H, Others ), compute_max_overall_distance( Others, _FirstBest=FirstEntry ); At least one other vertex remains , and at least one distance was computed : compute_max_overall_distance( _Points=[ H | Others ], Best={ _V1, _V2, LongestSquareDistance } ) -> case compute_max_distance_between( H, Others ) of NewBest={ _H, _PmaxForH, LongestSquareDistanceFromH } when LongestSquareDistanceFromH > LongestSquareDistance -> % We have a new winner: compute_max_overall_distance( Others, NewBest ); _Other -> Here LongestSquareDistance is not beaten : compute_max_overall_distance( Others, Best ) end. % Computes the maximum distance between a point (P) and a list of other points. % Returns { P , , LongestSquareDistance } with LongestSquareDistance being the distance between P and , being chosen so that LongestSquareDistance % is maximal. % As there must have been at least one point in the list , exists here % (never undefined): -spec compute_max_distance_between( point(), [ point() ] ) -> { point(), point(), linear:square_distance() }. compute_max_distance_between( _P, [] ) -> throw( no_computable_max_distance ); compute_max_distance_between( P, Points ) -> compute_max_distance_between( P, Points, undefined ). compute_max_distance_between( P, _Points=[], {Pmax,LongestSquareDistance} ) -> {P,Pmax,LongestSquareDistance}; compute_max_distance_between( P, _Points=[ Pnew | OtherPoints ], undefined ) -> First point examined is at first by construction the first best : compute_max_distance_between( P, OtherPoints, { Pnew, linear_2D:square_distance( P, Pnew ) } ); compute_max_distance_between( P, _Points=[ Pnew | OtherPoints ], Best={ _Pmax, LongestSquareDistance } ) -> case linear_2D:square_distance( P, Pnew ) of SquareDistance when SquareDistance > LongestSquareDistance -> % We have a new winner: compute_max_distance_between( P, OtherPoints, { Pnew, SquareDistance } ); _LesserSquareDistance -> % Previous best not beaten, let's keep it: compute_max_distance_between( P, OtherPoints, Best ) end. % Sorting by angle section. % Finds the pivot, i.e. the leftmost point with the highest ordinate. % % The point list is supposed not having duplicates. % % Returns {Pivot,PivotLessList} where PivotLessList is the (unordered) input % list, without the Pivot. % -spec find_pivot( [ point() ] ) -> { point(), [ point() ] }. find_pivot( _PointList = [ FirstPivot | Others ] ) -> First found is the first pivot : find_pivot( Others, FirstPivot, _NewList=[] ). % Helper: find_pivot( [], Pivot, NewList ) -> { Pivot, NewList }; % Higher than the pivot, thus not wanted as pivot: find_pivot( [ Point={_X,Y} | Others ], Pivot={ _Xp, Yp }, NewList ) when Y<Yp -> find_pivot( Others, Pivot, [ Point | NewList ] ); % Lower than the pivot, thus wanted: find_pivot( [ Point={_X,Y} | Others ], PreviousPivot={ _Xp, Yp }, NewList ) when Y>Yp -> find_pivot( Others, Point, [ PreviousPivot | NewList ] ); % Same level as the pivot, but at its right, thus not wanted: find_pivot( [ Point={X,_Y} | Others ], Pivot={ Xp, _Y }, NewList ) when X>Xp -> find_pivot( Others, Pivot, [ Point | NewList ] ); % Same level as the pivot, but at its left, thus wanted: find_pivot( [ Point={X,_Yp} | Others ], PreviousPivot={ Xp, _Yp }, NewList ) when X<Xp -> find_pivot( Others, Point, [ PreviousPivot | NewList ] ); % Duplicated pivot, abnormal: find_pivot( [ Pivot | _Others ], Pivot, _NewList ) -> throw( { duplicate_pivot, Pivot } ). % Returns a list containing the points sorted according to an increasing angle % between the abscissa axis and the vector from the pivot that each point. % % Note: all points having the same abscissa as the pivot, except the highest % one, will be removed from the returned list. % -spec sort_by_angle( point(), [ point() ] ) -> [ point() ]. sort_by_angle( Pivot, Points ) -> sort_by_angle( Pivot, Points, _LeftPoints=[], _MiddlePoint=undefined, _RightPoints=[] ). % Helper. % LeftPoints and RightPoints are lists of { Angle , Point } pairs . % -spec sort_by_angle( point(), [ point() ], [ { number(), point() } ], 'undefined', [ { number(), point() } ] ) -> [ point() ]; ( point(), [ point() ], [ { number(), point() } ], point(), [ { number(), point() } ] ) -> [ point() ]. sort_by_angle( _Pivot, _Points=[], LeftPoints, undefined, RightPoints ) -> %io:format( "sort_by_angle: no middle point found.~n" ), % Not having a middle point to integrate here: L = lists:keysort( _Index=1, LeftPoints ) ++ lists:keysort( _Index=1, RightPoints ), %io:format( "Full list: ~w.~n", [ L ] ), reverse_and_drop_angle( L, [] ); sort_by_angle( _Pivot, _Points=[], LeftPoints, MiddlePoint, RightPoints ) -> io : format ( " sort_by_angle : at least one middle point found.~n " ) , L = lists:keysort( _Index=1, LeftPoints ) ++ [ {dummy,MiddlePoint} | lists:keysort( _Index=1, RightPoints ) ], reverse_and_drop_angle( L, [] ); % Note that Y<=Yp by definition of the pivot, hence Y-Yp<=0: sort_by_angle( Pivot={Xp,Yp}, [ Point={X,Y} | T ], LeftPoints, MiddlePoint, RightPoints ) -> case X-Xp of 0 -> % Here we are just above the pivot, tan(Pi/2) is infinite. case MiddlePoint of undefined -> First found is first best : sort_by_angle( Pivot, T, LeftPoints, Point, RightPoints ); { _Xm, Ym } -> case Y < Ym of true -> % This point is above the previous highest middle % point, previous middle point can be dropped on the % floor: sort_by_angle( Pivot, T, LeftPoints, Point, RightPoints ); false -> % The current point can be dropped on the floor, as % it is below the highest middle point: sort_by_angle( Pivot, T, LeftPoints, MiddlePoint, RightPoints ) end end; DeltaX when DeltaX > 0 -> % This is a point on the right of the pivot, stores the tangent of % the angle the vector defined by the pivot and that point makes % with the abscissa axis: sort_by_angle( Pivot, T, LeftPoints, MiddlePoint, [ { (Y-Yp) / DeltaX, Point } | RightPoints ] ); NegativeDeltaX -> % This is a point on the left of the pivot: sort_by_angle( Pivot, T, [ { (Y-Yp) / NegativeDeltaX, Point } | LeftPoints ], MiddlePoint, RightPoints ) end. % Helper: reverse_and_drop_angle( [], Acc ) -> Acc; reverse_and_drop_angle( [ {_Tangent,Point} | T ], Acc ) -> reverse_and_drop_angle( T, [ Point | Acc ] ). % Vector section. Returns a vector V made from the specified two points : V = P2 - P1 . % -spec vectorize( point(), point() ) -> vector(). vectorize( _P1={X1,Y1}, _P2={X2,Y2} ) -> { X2-X1, Y2-Y1 }. % Returns the square of the magnitude of the specified vector. % -spec square_magnitude( vector() ) -> linear:square_distance(). square_magnitude( _V={X,Y} ) -> X*X + Y*Y. % Returns the magnitude of the specified vector. % -spec magnitude( vector() ) -> linear:distance(). magnitude( V ) -> math:sqrt( square_magnitude(V) ). % Scales specified vector of specified factor. -spec scale( vector(), number() ) -> vector(). scale( _V={X,Y}, Factor ) -> { Factor*X, Factor*Y }. Returns the specified vector with an unit length ( magnitude of 1 ): % % (epsilon-based test for null vectors with floating-point coordinates could % be done here). % -spec make_unit( vector() ) -> vector(). make_unit( {0,0} ) -> throw( cannot_make_null_vector_unit ); make_unit( V ) -> scale( V, 1 / magnitude(V) ). % Returns a (non-unit) vector which is normal to specified vector V, and is on % the left of V in the standard basis. % -spec normal_left( vector() ) -> vector(). normal_left( _V={X,Y} ) -> { -Y, X }. % Returns a (non-unit) vector which is normal to specified vector V, and is on % the right of V in the standard basis. % -spec normal_right( vector() ) -> vector(). normal_right( _V={X,Y} ) -> { Y, -X }. Returns the dot product of the two specified vectors . -spec dot_product( vector(), vector() ) -> number(). dot_product( _V1={X1,Y1}, _V2={X2,Y2} ) -> X1*X2 + Y1*Y2. % Line section. Returns the three coefficients { A , B , C } for the line passing by point P and being perpendicular to vector V , whose equation A.x+B.y+C=0 . % -spec get_line( point(), point() ) -> line(). get_line( _P={Xp,Yp}, _V={Vx,Vy} ) -> % Here we know that: % P is on the line: A.Xp+B.Yp+C=0 (I) % Let M be (X,Y). If M is on the line, the PM.V=0 (null dot product), thus: % (X-Xp)*Vx+(Y-Yp)*Vy=0 (II) % We want to determine A, B and C: ( II ) is : Vx . X + Vy*Y - ( Xp . Vx+Yp . Vy ) = 0 thus : A=Vx, B=Vy, C = - ( Xp*Vx + Yp*Vy ), { A, B, C }. Returns the intersection of the two specified lines , if it is a point , otherwise the atom no_point ( the intersection can be void , if the lines are % parallel but different, or a full line, if they are the same line). % First line has for equation a.x+b.y+c=0 , second has for equation u.x+v.y+w=0 . % -spec intersect( line(), line() ) -> 'no_point' | point(). intersect( _D1={A,B,C}, _D2={U,V,W} ) -> We will try to substitute y , as determined from first equation , into the second one : case B of 0 -> Thus A.X = -C case A of 0 -> % Either empty or the same: no_point; _ -> X = -C/A, case V of 0 -> no_point; _ -> Y= -(W+U*X) / V, {X,Y} end end; _ -> General case : Y = - ( C+A.X)/B ( I ) , will be replaced in second % equation: case U of 0 -> % Thus Y: Y= -W/V, Now X from first : case A of 0 -> no_point; _ -> X= - (B*Y+C)/A, {X,Y} end; _ -> General case , substituing ( I ) in second equation we have : % (B.U-V.A).X = V.C-B.D case B*U-V*A of 0 -> no_point; Denom -> X = (V*C-B*W) / Denom, Y = - (C+A*X) / B, {X,Y} end end end. % Returns the abscissa of a point on line L having Y for ordinate. % % Line L must not have for equation Y=constant (i.e. its A parameter must not be % null). % -spec get_abscissa_for_ordinate( line(), linear:coordinate() ) -> linear:coordinate(). get_abscissa_for_ordinate( _L={A,B,C}, Y ) -> % For y=K, x=-(C+BK)/A -(C+B*Y) / A. % Angle section. % Returns true iff P is strictly on the right of the oriented segment going from P1 to P2 . % -spec is_strictly_on_the_right( point(), point(), point() ) -> boolean(). is_strictly_on_the_right( P, P1, P2 ) -> Vec_P1P2 = vectorize( P1, P2 ), RightNormal = normal_right( Vec_P1P2 ), Vec_P1P = vectorize( P1, P ), DotProduct = dot_product( Vec_P1P, RightNormal ), DotProduct > 0. % Returns whether specified angle (in degrees, canonical form) is obtuse. % -spec is_obtuse( unit_utils:int_degrees() ) -> boolean(). is_obtuse( AngleInDegrees ) -> AngleInDegrees > 90 andalso AngleInDegrees < 180. % Returns the angle, in radians, between the vector AB and AC. % Note : with this function we can not tell whether one vector is ahead of the % other, i.e. if we should use the returned angle or its opposite to go from AB % to AC. % -spec abs_angle_rad( point(), point(), point() ) -> unit_utils:radians(). abs_angle_rad( A, B, C ) -> AB = vectorize( A, B ), M1 = magnitude(AB), case math_utils:is_null(M1) of true -> throw( { degenerate_angle, { A, B } } ); _ -> ok end, AC = vectorize( A, C ), M2 = magnitude( AC ), case math_utils:is_null( M2 ) of true -> throw( { degenerate_angle,{ A, C } } ); _ -> ok end, io : format ( " AB=~w , AC=~w , M1=~f , M2=~f.~n " , [ AB , AC , M1,M2 ] ) , math:acos( dot_product( AB, AC ) / ( magnitude( AB ) * magnitude( AC ) ) ). % Returns the signed (oriented) angle, in radians, between the vector AB and AC. % % Note: with this function we can tell that we must rotate counter-clockwise of % the returned angle to go from AB to AC. % -spec angle_rad( point(), point(), point() ) -> unit_utils:radians(). angle_rad( A, B, C ) -> { X1, Y1 } = vectorize( A, B ), { X2, Y2 } = vectorize( A, C ), math:atan2( Y2, X2 ) - math:atan2( Y1, X1 ). % Returns the angle, in canonical degrees, between the vector AB and AC. % Note : with this function we can not tell whether one vector is ahead of the % other, i.e. if we should use the returned angle or its opposite to go from AB % to AC. % -spec abs_angle_deg( point(), point(), point() ) -> unit_utils:int_degrees(). abs_angle_deg( A, B, C ) -> math_utils:canonify( math_utils:radian_to_degree( abs_angle_rad( A, B, C ) ) ). % Returns the signed (oriented) angle, in canonical degrees, between the vector % AB and AC. % % Note: with this function we can tell that we must rotate counter-clockwise of % the returned angle to go from AB to AC. % -spec angle_deg( point(), point(), point() ) -> unit_utils:int_degrees(). angle_deg( A, B, C ) -> math_utils:canonify( math_utils:radian_to_degree( angle_rad( A, B, C ) ) ). % Convex hull section. % Computes the convex hull corresponding to the specified list of points. % % Returns the list of points that defines the hull. % -spec compute_convex_hull( [point()] ) -> [point()]. compute_convex_hull( Points ) -> { Pivot, RemainingPoints } = find_pivot( Points ), case length(RemainingPoints) of Len when Len < 2 -> throw( not_enough_points_for_convex_hull ); _Other -> We have at least 2 points in addition to the pivot . %io:format( "Pivot is ~w, remaining points: ~w.~n", [ Pivot , RemainingPoints ] ) , [ P1, P2 | T ] = sort_by_angle( Pivot, RemainingPoints ), % Initially only the pivot is known to belong to the convex hull. We had P1 , next to be validated against P2 . % We also add the pivot to the end of the NextPoints list , so that % the hull can be closed. compute_graham_scan_hull( _ToValidate=[ P1, Pivot ], _NewPoint=P2, _NextPoints=( T++ [Pivot] ) ) end. Computes the scan for the specified list of points , expected to be % already sorted by increasing angle between the abscissa axis and the vector % from the pivot to each of these points (i.e. in increasing order of the angle % they and the point P make with the x-axis, in counter-clockwise order). % % See: % % Returns the corresponding convex hull, in clock-wise order. % -spec compute_graham_scan_hull( [ point() ], point(), [ point() ] ) -> [ point() ]. compute_graham_scan_hull( ToValidate, _Pivot, _NextPoints=[] ) -> % Last new point is by construction always to pivot. %io:format( "compute_graham_scan_hull: " % "exhausted input points, returning: ~w.~n", [ ToValidate ] ), ToValidate; compute_graham_scan_hull( ToValidate=[ P2, P1 | T ], NewPoint, NextPoints=[ Next | OtherNext ] ) -> Should P2 be on the line defined by P1 and NewPoint , then P2 will be % considered as not being on the left: in the convex hull, only necessary % points will be kept, i.e. no point on the boundary of the hull will be % kept. % % Note: The test seems to be wrongly negated; however it is correct as % actually we describe the algorithm as seen if represented in a basis whose % ordinates are increasing when going from the top to the bottom (i.e. like % when rendered on a classical GUI, the Y axis going then downward). % case is_strictly_on_the_right( P2, P1, NewPoint ) of false -> %io:format( "compute_graham_scan_hull: point ~w is on the right of " % "segment from ~w to ~w, keeping ~w.~n", [ P2 , P1 , NewPoint , P2 ] ) , Here , the point P2 is on the right of the segment going from P1 to the Next point , thus P2 can be kept and we can continue with the % next points: compute_graham_scan_hull( [ NewPoint | ToValidate ], Next, OtherNext ); true -> %io:format( "compute_graham_scan_hull: point ~w is on the left of " % "segment from ~w to ~w, eliminating ~w.~n", [ P2 , P1 , NewPoint , P2 ] ) , Here , the point P2 is on the left of ( or in ) the segment going from P1 to the Next point , thus P2 is to be discarded , and will have to check predecessor(s ) of P2 against the Next point . % compute_graham_scan_hull( [ P1 | T ], NewPoint, NextPoints ) end; Note however that the first point examined after the pivot ( FP1 ) may have to be discarded because of the second . If we just removed FP1 , then the ToValidate list would just contain the pivot , thus triggering a function clause . In that case we just have to replace FP1 by the next(FP1)=P2 here , and thus ToValidate will always contain at least two elements : This clause matches whenever we just removed the first point in the list examined after the pivot . So the first parameter ( ToValidate ) is just a list with one element , the pivot , that was added to close the hull . As we have no % intermediate point, we accept directly the next point (Next), knowing it will % be checked at the next recursion: compute_graham_scan_hull ( [ Pivot ] , NewPoint , [ Next | OtherNext ] ) - > compute_graham_scan_hull ( [ NewPoint , Pivot ] , Next , OtherNext ) . % A bit faster as we know L is actually [ Pivot ]: % compute_graham_scan_hull( L, NewPoint, [ Next | OtherNext ] ) -> compute_graham_scan_hull( [ NewPoint | L ], Next, OtherNext ). % Textual conversion section. % Returns a precise textual representation of specified point. % -spec to_string( point() ) -> string(). to_string( { X, Y } ) -> io_lib:format( "{ ~w, ~w }", [ X, Y ] ). % Returns a human-friendly, approximated textual representation of specified % point, based on specified print-out precision (number of digits after the % comma). % -spec to_string( point(), basic_utils:count() ) -> string(). to_string( { X, Y }, DigitCountAfterComma ) -> % We want to avoid displaying larger texts for coordinates, like 0.10000000000000009 : %XRounded = math_utils:round_after( X, DigitCountAfterComma ), YRounded = : round_after ( Y , DigitCountAfterComma ) , %text_utils:format( "{ ~.*w, ~.*w }", [ Precision, X, Precision, Y ] ). XString = case is_float( X ) of true -> text_utils:format( "~.*f", [ DigitCountAfterComma, X ] ); false -> % Integer: text_utils:format( "~B", [ X ] ) end, YString = case is_float( Y ) of true -> text_utils:format( "~.*f", [ DigitCountAfterComma, Y ] ); false -> % Integer: text_utils:format( "~B", [ Y ] ) end, text_utils:format( "{ ~s, ~s }", [ XString, YString ] ).
null
https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/sim-diasca/common/src/maths/linear_2D.erl
erlang
This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License or any later version. You can also redistribute it and/or modify it under the terms of the This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the for more details. along with this library. If not, see </> and </>. See linear_2D_test.erl for the corresponding test. Operations on points: Operations on vectors: Operations on lines: Textual conversions: Only useful for tests: For epsilon: Vectors could/should be aliased to points: {A,B,C}. Returns the origin of this referential. considered as representing the same point (equality operator on points). Tells whether point P is within a distance D from point C, using some margin to overcome numerical errors. For comparison purposes, computing the square root is useless. Could rely on vectorize and square_magnitude as well. For comparison purposes, computing the square root is useless. Could rely on vectorize and magnitude as well. of the vector that would result from a regular 3D cross product of the input vectors, taking their Z values implicitly as 0. Returns a point (or vector) whose coordinates have been rounded to nearest integer. returned with integer coordinates. returned with possibly floating-point coordinates. Returns a point corresponding to the specified point P translated by the specified vector V. Section for sets of points. Computes the smallest rectangle that encloses the specified list of points. Helper: points. Returns {P1,P2,square_distance(P1,P2)} so that (square) distance is maximal. We ensure that each internal edge is examined only once: when the distance between a given vertex V and all other vertices have been computed, V is Helper. Here we have not compute a distance yet: We have a new winner: Computes the maximum distance between a point (P) and a list of other points. is maximal. (never undefined): We have a new winner: Previous best not beaten, let's keep it: Sorting by angle section. Finds the pivot, i.e. the leftmost point with the highest ordinate. The point list is supposed not having duplicates. Returns {Pivot,PivotLessList} where PivotLessList is the (unordered) input list, without the Pivot. Helper: Higher than the pivot, thus not wanted as pivot: Lower than the pivot, thus wanted: Same level as the pivot, but at its right, thus not wanted: Same level as the pivot, but at its left, thus wanted: Duplicated pivot, abnormal: Returns a list containing the points sorted according to an increasing angle between the abscissa axis and the vector from the pivot that each point. Note: all points having the same abscissa as the pivot, except the highest one, will be removed from the returned list. Helper. io:format( "sort_by_angle: no middle point found.~n" ), Not having a middle point to integrate here: io:format( "Full list: ~w.~n", [ L ] ), Note that Y<=Yp by definition of the pivot, hence Y-Yp<=0: Here we are just above the pivot, tan(Pi/2) is infinite. This point is above the previous highest middle point, previous middle point can be dropped on the floor: The current point can be dropped on the floor, as it is below the highest middle point: This is a point on the right of the pivot, stores the tangent of the angle the vector defined by the pivot and that point makes with the abscissa axis: This is a point on the left of the pivot: Helper: Vector section. Returns the square of the magnitude of the specified vector. Returns the magnitude of the specified vector. Scales specified vector of specified factor. (epsilon-based test for null vectors with floating-point coordinates could be done here). Returns a (non-unit) vector which is normal to specified vector V, and is on the left of V in the standard basis. Returns a (non-unit) vector which is normal to specified vector V, and is on the right of V in the standard basis. Line section. Here we know that: P is on the line: A.Xp+B.Yp+C=0 (I) Let M be (X,Y). If M is on the line, the PM.V=0 (null dot product), thus: (X-Xp)*Vx+(Y-Yp)*Vy=0 (II) We want to determine A, B and C: parallel but different, or a full line, if they are the same line). Either empty or the same: equation: Thus Y: (B.U-V.A).X = V.C-B.D Returns the abscissa of a point on line L having Y for ordinate. Line L must not have for equation Y=constant (i.e. its A parameter must not be null). For y=K, x=-(C+BK)/A Angle section. Returns true iff P is strictly on the right of the oriented segment going from Returns whether specified angle (in degrees, canonical form) is obtuse. Returns the angle, in radians, between the vector AB and AC. other, i.e. if we should use the returned angle or its opposite to go from AB to AC. Returns the signed (oriented) angle, in radians, between the vector AB and AC. Note: with this function we can tell that we must rotate counter-clockwise of the returned angle to go from AB to AC. Returns the angle, in canonical degrees, between the vector AB and AC. other, i.e. if we should use the returned angle or its opposite to go from AB to AC. Returns the signed (oriented) angle, in canonical degrees, between the vector AB and AC. Note: with this function we can tell that we must rotate counter-clockwise of the returned angle to go from AB to AC. Convex hull section. Computes the convex hull corresponding to the specified list of points. Returns the list of points that defines the hull. io:format( "Pivot is ~w, remaining points: ~w.~n", Initially only the pivot is known to belong to the convex hull. the hull can be closed. already sorted by increasing angle between the abscissa axis and the vector from the pivot to each of these points (i.e. in increasing order of the angle they and the point P make with the x-axis, in counter-clockwise order). See: Returns the corresponding convex hull, in clock-wise order. Last new point is by construction always to pivot. io:format( "compute_graham_scan_hull: " "exhausted input points, returning: ~w.~n", [ ToValidate ] ), considered as not being on the left: in the convex hull, only necessary points will be kept, i.e. no point on the boundary of the hull will be kept. Note: The test seems to be wrongly negated; however it is correct as actually we describe the algorithm as seen if represented in a basis whose ordinates are increasing when going from the top to the bottom (i.e. like when rendered on a classical GUI, the Y axis going then downward). io:format( "compute_graham_scan_hull: point ~w is on the right of " "segment from ~w to ~w, keeping ~w.~n", next points: io:format( "compute_graham_scan_hull: point ~w is on the left of " "segment from ~w to ~w, eliminating ~w.~n", intermediate point, we accept directly the next point (Next), knowing it will be checked at the next recursion: A bit faster as we know L is actually [ Pivot ]: Textual conversion section. Returns a precise textual representation of specified point. Returns a human-friendly, approximated textual representation of specified point, based on specified print-out precision (number of digits after the comma). We want to avoid displaying larger texts for coordinates, like XRounded = math_utils:round_after( X, DigitCountAfterComma ), text_utils:format( "{ ~.*w, ~.*w }", [ Precision, X, Precision, Y ] ). Integer: Integer:
Copyright ( C ) 2003 - 2014 This file is part of the Ceylan Erlang library . the GNU General Public License , as they are published by the Free Software Foundation , either version 3 of these Licenses , or ( at your option ) Mozilla Public License , version 1.1 or later . GNU Lesser General Public License and the GNU General Public License You should have received a copy of the GNU Lesser General Public License , of the GNU General Public License and of the Mozilla Public License Author : ( ) Creation date : Monday , February 15 , 2010 . Gathering of various two dimensional linear facilities . -module(linear_2D). -export([ get_origin/0, are_close/2, is_within/3, is_within_square/3, square_distance/2, distance/2, cross_product/2, roundify/1, get_integer_center/2, get_center/2, translate/2 ]). -export([ vectorize/2, square_magnitude/1, magnitude/1, scale/2, make_unit/1, normal_left/1, normal_right/1, dot_product/2 ]). -export([ get_line/2, intersect/2, get_abscissa_for_ordinate/2 ]). Operations related to angles : -export([ is_strictly_on_the_right/3, is_obtuse/1, abs_angle_rad/3, angle_rad/3, abs_angle_deg/3, angle_deg/3 ]). Operations on set of points : -export([ compute_smallest_enclosing_rectangle/1, compute_max_overall_distance/1, compute_convex_hull/1 ]). -export([ to_string/1, to_string/2 ]). -export([ find_pivot/1, sort_by_angle/2 ]). -include("math_utils.hrl"). -type point() :: { linear:coordinate(), linear:coordinate() }. -type integer_point() :: { linear:integer_coordinate(), linear:integer_coordinate() }. { Width , } : -type dimensions() :: { linear:integer_coordinate(), linear:integer_coordinate() }. -type vector() :: { linear:coordinate(), linear:coordinate() }. -type integer_vector() :: { linear:integer_coordinate(), linear:integer_coordinate() }. A line , whose equation A.x+B.y+C=0 , can be defined by its three coefficients -type line() :: { number(), number(), number() }. -type shape() :: 'circle' | 'rectangle' | 'square' | 'triangle' | 'polygon'. -export_type([ point/0, integer_point/0, dimensions/0, vector/0, integer_vector/0, line/0, shape/0 ]). Point section . -spec get_origin() -> point(). get_origin() -> { 0, 0 }. Returns whether the two specified points are close , i.e. if they could be -spec are_close( point(), point() ) -> boolean(). are_close( _P1={X1,Y1}, _P2={X2,Y2} ) -> math_utils:are_close( X1, X2 ) andalso math_utils:are_close( Y1, Y2 ). -spec is_within( point(), point(), number() ) -> boolean(). is_within( P, C, D ) -> " Taylor series " , square(epsilon ) is negligible here : square_distance( P, C ) < D * ( D + ?epsilon ). Tells whether point P is within a square distance SquareD from point C. -spec is_within_square( point(), point(), number() ) -> boolean(). is_within_square( P, C, SquareD ) -> square_distance( P, C ) < SquareD. Returns the square of the distance between the two specified points . -spec square_distance( point(), point() ) -> linear:square_distance(). square_distance( {X1,Y1}, {X2,Y2} ) -> XDiff = X2-X1, YDiff = Y2-Y1, XDiff*XDiff + YDiff*YDiff. Returns the distance between the two specified points . -spec distance( point(), point() ) -> linear:distance(). distance( P1, P2 ) -> math:sqrt( square_distance( P1, P2 ) ). Returns the cross - product of the two specified 2D points , i.e. the magnitude -spec cross_product( point(), point() ) -> number(). cross_product( {X1,Y1}, {X2,Y2} ) -> X1*Y2 - Y1*X2. -spec roundify( point() ) -> integer_point(). roundify( {X,Y} ) -> { erlang:round(X), erlang:round(Y) }. Returns a vertex corresponding the middle of the two specified vertices , -spec get_integer_center( point(), point() ) -> integer_point(). get_integer_center( P1, P2 ) -> roundify( get_center( P1, P2 ) ). Returns a vertex corresponding the middle of the two specified vertices , -spec get_center( point(), point() ) -> point(). get_center( {X1,Y1}, {X2,Y2} ) -> { (X1+X2)/2, (Y1+Y2)/2 }. -spec translate( point(), vector() ) -> point(). translate( _P={X,Y}, _V={Vx,Vy} ) -> { X+Vx, Y+Vy }. Returns { TopLeft , BottomRight } . -spec compute_smallest_enclosing_rectangle( [ point() ] ) -> { point(), point() }. compute_smallest_enclosing_rectangle( Points ) -> compute_smallest_enclosing_rectangle( Points, undefined, undefined ). compute_smallest_enclosing_rectangle( _Points=[], TopLeft, BottomRight ) -> { TopLeft, BottomRight }; compute_smallest_enclosing_rectangle( [ _Points=P | Others ], undefined, undefined ) -> First found initializes best , knowing at least two points are expected : compute_smallest_enclosing_rectangle( Others, _TopLeft=P, _BottomRight=P ); compute_smallest_enclosing_rectangle( [ _Points={ X, Y } | Others ], { Xt, Yt }, { Xb, Yb } ) -> Xmin = erlang:min( X, Xt ), Ymin = erlang:min( Y, Yt ), Xmax = erlang:max( X, Xb ), Ymax = erlang:max( Y, Yb ), compute_smallest_enclosing_rectangle( Others, { Xmin, Ymin }, { Xmax, Ymax } ). Computes the maximum distance between two points in the specified list of removed from the list and a new mAximum is searched within this subset . Here there is only one vertex left : -spec compute_max_overall_distance( [ point() ] ) -> { point(), point(), linear:square_distance() }. compute_max_overall_distance( Points ) when length( Points ) < 2 -> throw( { no_computable_overall_distance, Points } ); compute_max_overall_distance( Points ) -> compute_max_overall_distance( Points, undefined ). compute_max_overall_distance( _Points=[ _H ], Longest ) -> Longest; compute_max_overall_distance( _Points=[ H | Others ], undefined ) -> FirstEntry = compute_max_distance_between( H, Others ), compute_max_overall_distance( Others, _FirstBest=FirstEntry ); At least one other vertex remains , and at least one distance was computed : compute_max_overall_distance( _Points=[ H | Others ], Best={ _V1, _V2, LongestSquareDistance } ) -> case compute_max_distance_between( H, Others ) of NewBest={ _H, _PmaxForH, LongestSquareDistanceFromH } when LongestSquareDistanceFromH > LongestSquareDistance -> compute_max_overall_distance( Others, NewBest ); _Other -> Here LongestSquareDistance is not beaten : compute_max_overall_distance( Others, Best ) end. Returns { P , , LongestSquareDistance } with LongestSquareDistance being the distance between P and , being chosen so that LongestSquareDistance As there must have been at least one point in the list , exists here -spec compute_max_distance_between( point(), [ point() ] ) -> { point(), point(), linear:square_distance() }. compute_max_distance_between( _P, [] ) -> throw( no_computable_max_distance ); compute_max_distance_between( P, Points ) -> compute_max_distance_between( P, Points, undefined ). compute_max_distance_between( P, _Points=[], {Pmax,LongestSquareDistance} ) -> {P,Pmax,LongestSquareDistance}; compute_max_distance_between( P, _Points=[ Pnew | OtherPoints ], undefined ) -> First point examined is at first by construction the first best : compute_max_distance_between( P, OtherPoints, { Pnew, linear_2D:square_distance( P, Pnew ) } ); compute_max_distance_between( P, _Points=[ Pnew | OtherPoints ], Best={ _Pmax, LongestSquareDistance } ) -> case linear_2D:square_distance( P, Pnew ) of SquareDistance when SquareDistance > LongestSquareDistance -> compute_max_distance_between( P, OtherPoints, { Pnew, SquareDistance } ); _LesserSquareDistance -> compute_max_distance_between( P, OtherPoints, Best ) end. -spec find_pivot( [ point() ] ) -> { point(), [ point() ] }. find_pivot( _PointList = [ FirstPivot | Others ] ) -> First found is the first pivot : find_pivot( Others, FirstPivot, _NewList=[] ). find_pivot( [], Pivot, NewList ) -> { Pivot, NewList }; find_pivot( [ Point={_X,Y} | Others ], Pivot={ _Xp, Yp }, NewList ) when Y<Yp -> find_pivot( Others, Pivot, [ Point | NewList ] ); find_pivot( [ Point={_X,Y} | Others ], PreviousPivot={ _Xp, Yp }, NewList ) when Y>Yp -> find_pivot( Others, Point, [ PreviousPivot | NewList ] ); find_pivot( [ Point={X,_Y} | Others ], Pivot={ Xp, _Y }, NewList ) when X>Xp -> find_pivot( Others, Pivot, [ Point | NewList ] ); find_pivot( [ Point={X,_Yp} | Others ], PreviousPivot={ Xp, _Yp }, NewList ) when X<Xp -> find_pivot( Others, Point, [ PreviousPivot | NewList ] ); find_pivot( [ Pivot | _Others ], Pivot, _NewList ) -> throw( { duplicate_pivot, Pivot } ). -spec sort_by_angle( point(), [ point() ] ) -> [ point() ]. sort_by_angle( Pivot, Points ) -> sort_by_angle( Pivot, Points, _LeftPoints=[], _MiddlePoint=undefined, _RightPoints=[] ). LeftPoints and RightPoints are lists of { Angle , Point } pairs . -spec sort_by_angle( point(), [ point() ], [ { number(), point() } ], 'undefined', [ { number(), point() } ] ) -> [ point() ]; ( point(), [ point() ], [ { number(), point() } ], point(), [ { number(), point() } ] ) -> [ point() ]. sort_by_angle( _Pivot, _Points=[], LeftPoints, undefined, RightPoints ) -> L = lists:keysort( _Index=1, LeftPoints ) ++ lists:keysort( _Index=1, RightPoints ), reverse_and_drop_angle( L, [] ); sort_by_angle( _Pivot, _Points=[], LeftPoints, MiddlePoint, RightPoints ) -> io : format ( " sort_by_angle : at least one middle point found.~n " ) , L = lists:keysort( _Index=1, LeftPoints ) ++ [ {dummy,MiddlePoint} | lists:keysort( _Index=1, RightPoints ) ], reverse_and_drop_angle( L, [] ); sort_by_angle( Pivot={Xp,Yp}, [ Point={X,Y} | T ], LeftPoints, MiddlePoint, RightPoints ) -> case X-Xp of 0 -> case MiddlePoint of undefined -> First found is first best : sort_by_angle( Pivot, T, LeftPoints, Point, RightPoints ); { _Xm, Ym } -> case Y < Ym of true -> sort_by_angle( Pivot, T, LeftPoints, Point, RightPoints ); false -> sort_by_angle( Pivot, T, LeftPoints, MiddlePoint, RightPoints ) end end; DeltaX when DeltaX > 0 -> sort_by_angle( Pivot, T, LeftPoints, MiddlePoint, [ { (Y-Yp) / DeltaX, Point } | RightPoints ] ); NegativeDeltaX -> sort_by_angle( Pivot, T, [ { (Y-Yp) / NegativeDeltaX, Point } | LeftPoints ], MiddlePoint, RightPoints ) end. reverse_and_drop_angle( [], Acc ) -> Acc; reverse_and_drop_angle( [ {_Tangent,Point} | T ], Acc ) -> reverse_and_drop_angle( T, [ Point | Acc ] ). Returns a vector V made from the specified two points : V = P2 - P1 . -spec vectorize( point(), point() ) -> vector(). vectorize( _P1={X1,Y1}, _P2={X2,Y2} ) -> { X2-X1, Y2-Y1 }. -spec square_magnitude( vector() ) -> linear:square_distance(). square_magnitude( _V={X,Y} ) -> X*X + Y*Y. -spec magnitude( vector() ) -> linear:distance(). magnitude( V ) -> math:sqrt( square_magnitude(V) ). -spec scale( vector(), number() ) -> vector(). scale( _V={X,Y}, Factor ) -> { Factor*X, Factor*Y }. Returns the specified vector with an unit length ( magnitude of 1 ): -spec make_unit( vector() ) -> vector(). make_unit( {0,0} ) -> throw( cannot_make_null_vector_unit ); make_unit( V ) -> scale( V, 1 / magnitude(V) ). -spec normal_left( vector() ) -> vector(). normal_left( _V={X,Y} ) -> { -Y, X }. -spec normal_right( vector() ) -> vector(). normal_right( _V={X,Y} ) -> { Y, -X }. Returns the dot product of the two specified vectors . -spec dot_product( vector(), vector() ) -> number(). dot_product( _V1={X1,Y1}, _V2={X2,Y2} ) -> X1*X2 + Y1*Y2. Returns the three coefficients { A , B , C } for the line passing by point P and being perpendicular to vector V , whose equation A.x+B.y+C=0 . -spec get_line( point(), point() ) -> line(). get_line( _P={Xp,Yp}, _V={Vx,Vy} ) -> ( II ) is : Vx . X + Vy*Y - ( Xp . Vx+Yp . Vy ) = 0 thus : A=Vx, B=Vy, C = - ( Xp*Vx + Yp*Vy ), { A, B, C }. Returns the intersection of the two specified lines , if it is a point , otherwise the atom no_point ( the intersection can be void , if the lines are First line has for equation a.x+b.y+c=0 , second has for equation u.x+v.y+w=0 . -spec intersect( line(), line() ) -> 'no_point' | point(). intersect( _D1={A,B,C}, _D2={U,V,W} ) -> We will try to substitute y , as determined from first equation , into the second one : case B of 0 -> Thus A.X = -C case A of 0 -> no_point; _ -> X = -C/A, case V of 0 -> no_point; _ -> Y= -(W+U*X) / V, {X,Y} end end; _ -> General case : Y = - ( C+A.X)/B ( I ) , will be replaced in second case U of 0 -> Y= -W/V, Now X from first : case A of 0 -> no_point; _ -> X= - (B*Y+C)/A, {X,Y} end; _ -> General case , substituing ( I ) in second equation we have : case B*U-V*A of 0 -> no_point; Denom -> X = (V*C-B*W) / Denom, Y = - (C+A*X) / B, {X,Y} end end end. -spec get_abscissa_for_ordinate( line(), linear:coordinate() ) -> linear:coordinate(). get_abscissa_for_ordinate( _L={A,B,C}, Y ) -> -(C+B*Y) / A. P1 to P2 . -spec is_strictly_on_the_right( point(), point(), point() ) -> boolean(). is_strictly_on_the_right( P, P1, P2 ) -> Vec_P1P2 = vectorize( P1, P2 ), RightNormal = normal_right( Vec_P1P2 ), Vec_P1P = vectorize( P1, P ), DotProduct = dot_product( Vec_P1P, RightNormal ), DotProduct > 0. -spec is_obtuse( unit_utils:int_degrees() ) -> boolean(). is_obtuse( AngleInDegrees ) -> AngleInDegrees > 90 andalso AngleInDegrees < 180. Note : with this function we can not tell whether one vector is ahead of the -spec abs_angle_rad( point(), point(), point() ) -> unit_utils:radians(). abs_angle_rad( A, B, C ) -> AB = vectorize( A, B ), M1 = magnitude(AB), case math_utils:is_null(M1) of true -> throw( { degenerate_angle, { A, B } } ); _ -> ok end, AC = vectorize( A, C ), M2 = magnitude( AC ), case math_utils:is_null( M2 ) of true -> throw( { degenerate_angle,{ A, C } } ); _ -> ok end, io : format ( " AB=~w , AC=~w , M1=~f , M2=~f.~n " , [ AB , AC , M1,M2 ] ) , math:acos( dot_product( AB, AC ) / ( magnitude( AB ) * magnitude( AC ) ) ). -spec angle_rad( point(), point(), point() ) -> unit_utils:radians(). angle_rad( A, B, C ) -> { X1, Y1 } = vectorize( A, B ), { X2, Y2 } = vectorize( A, C ), math:atan2( Y2, X2 ) - math:atan2( Y1, X1 ). Note : with this function we can not tell whether one vector is ahead of the -spec abs_angle_deg( point(), point(), point() ) -> unit_utils:int_degrees(). abs_angle_deg( A, B, C ) -> math_utils:canonify( math_utils:radian_to_degree( abs_angle_rad( A, B, C ) ) ). -spec angle_deg( point(), point(), point() ) -> unit_utils:int_degrees(). angle_deg( A, B, C ) -> math_utils:canonify( math_utils:radian_to_degree( angle_rad( A, B, C ) ) ). -spec compute_convex_hull( [point()] ) -> [point()]. compute_convex_hull( Points ) -> { Pivot, RemainingPoints } = find_pivot( Points ), case length(RemainingPoints) of Len when Len < 2 -> throw( not_enough_points_for_convex_hull ); _Other -> We have at least 2 points in addition to the pivot . [ Pivot , RemainingPoints ] ) , [ P1, P2 | T ] = sort_by_angle( Pivot, RemainingPoints ), We had P1 , next to be validated against P2 . We also add the pivot to the end of the NextPoints list , so that compute_graham_scan_hull( _ToValidate=[ P1, Pivot ], _NewPoint=P2, _NextPoints=( T++ [Pivot] ) ) end. Computes the scan for the specified list of points , expected to be -spec compute_graham_scan_hull( [ point() ], point(), [ point() ] ) -> [ point() ]. compute_graham_scan_hull( ToValidate, _Pivot, _NextPoints=[] ) -> ToValidate; compute_graham_scan_hull( ToValidate=[ P2, P1 | T ], NewPoint, NextPoints=[ Next | OtherNext ] ) -> Should P2 be on the line defined by P1 and NewPoint , then P2 will be case is_strictly_on_the_right( P2, P1, NewPoint ) of false -> [ P2 , P1 , NewPoint , P2 ] ) , Here , the point P2 is on the right of the segment going from P1 to the Next point , thus P2 can be kept and we can continue with the compute_graham_scan_hull( [ NewPoint | ToValidate ], Next, OtherNext ); true -> [ P2 , P1 , NewPoint , P2 ] ) , Here , the point P2 is on the left of ( or in ) the segment going from P1 to the Next point , thus P2 is to be discarded , and will have to check predecessor(s ) of P2 against the Next point . compute_graham_scan_hull( [ P1 | T ], NewPoint, NextPoints ) end; Note however that the first point examined after the pivot ( FP1 ) may have to be discarded because of the second . If we just removed FP1 , then the ToValidate list would just contain the pivot , thus triggering a function clause . In that case we just have to replace FP1 by the next(FP1)=P2 here , and thus ToValidate will always contain at least two elements : This clause matches whenever we just removed the first point in the list examined after the pivot . So the first parameter ( ToValidate ) is just a list with one element , the pivot , that was added to close the hull . As we have no compute_graham_scan_hull ( [ Pivot ] , NewPoint , [ Next | OtherNext ] ) - > compute_graham_scan_hull ( [ NewPoint , Pivot ] , Next , OtherNext ) . compute_graham_scan_hull( L, NewPoint, [ Next | OtherNext ] ) -> compute_graham_scan_hull( [ NewPoint | L ], Next, OtherNext ). -spec to_string( point() ) -> string(). to_string( { X, Y } ) -> io_lib:format( "{ ~w, ~w }", [ X, Y ] ). -spec to_string( point(), basic_utils:count() ) -> string(). to_string( { X, Y }, DigitCountAfterComma ) -> 0.10000000000000009 : YRounded = : round_after ( Y , DigitCountAfterComma ) , XString = case is_float( X ) of true -> text_utils:format( "~.*f", [ DigitCountAfterComma, X ] ); false -> text_utils:format( "~B", [ X ] ) end, YString = case is_float( Y ) of true -> text_utils:format( "~.*f", [ DigitCountAfterComma, Y ] ); false -> text_utils:format( "~B", [ Y ] ) end, text_utils:format( "{ ~s, ~s }", [ XString, YString ] ).
103d0c3b59623a14788c9d234e6506ab78154d9fb9b3957386f11785185232d8
learnuidev/reagent-reposh-realworld
auth.cljs
(ns app.auth (:require [reagent.core :as r] [reitit.frontend.easy :as rfe] [app.api :refer [api-uri]] [clojure.string :as s] [ajax.core :refer [GET POST PUT json-request-format json-response-format]])) ;; Local Storage testing (comment "Saving value into local storage" (.setItem js/localStorage "auth-user-token" "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTM4ODM2LCJ1c2VybmFtZSI6ImxlYXJudWlkZXYzQGZvby5jb20iLCJleHAiOjE2MTcxNjEwNzN9.O_cIsa66SQN26s3ap-F5oOQvp_zTpF4COH_HJDBK_cA")) (comment "Getting auth value from local storage - will be used to make auth requests" (.getItem js/localStorage "auth-user-token")) (comment "Removing value" (.removeItem js/localStorage "auth-user-token")) ;; ================= Auth State =================== ;; ================================================ (defonce auth-state (r/atom nil)) (defonce error-state (r/atom nil)) (comment @auth-state (s/join ", " ["error a", "error b"])) (defn auth-success! [{{:keys [token] :as user} :user}] (.setItem js/localStorage "auth-user-token" token) (reset! auth-state user) (when (seq @error-state) (reset! error-state nil)) (rfe/push-state :routes/home)) (defn auth-error! [{{:keys [errors]} :response}] (reset! error-state errors)) ;; ================= Register =================== ;; ================================================ (defn register! [input] (POST (str api-uri "/users") {:params {:user input} :handler auth-success! :format (json-request-format) :response-format (json-response-format {:keywords? true}) :error-handler auth-error!})) (comment (register! {:username "" :email "" :password ""})) ;; ================= Login ======================== ;; ================================================ (defn login! [input] ;; {:email "" :password} (POST (str api-uri "/users/login") {:params {:user input} :handler auth-success! :format (json-request-format) :response-format (json-response-format {:keywords? true}) :error-handler auth-error!})) (comment (login! {:email "" :password ""})) ;; ================= Me ======================== (defn get-auth-header [] (let [token (.getItem js/localStorage "auth-user-token")] [:Authorization (str "Token " token)])) ;; ================================================ ;; (defn get-me-success! [{user :user}] (reset! auth-state user)) (defn get-me-error! [error] (js/console.log "ERROR")) (defn me [] (GET (str api-uri "/user") {:handler get-me-success! :headers (get-auth-header) :response-format (json-response-format {:keywords? true}) :error-handler get-me-error!})) ;; save-user (def example-user {:email "" :password "" :username "" :image "" :bio ""}) (defn save-user! [user] ;; {:email "" :password} (PUT (str api-uri "/user") {:params {:user user} :handler get-me-success! :error-handler get-me-error! :headers (get-auth-header) :format (json-request-format) :response-format (json-response-format {:keywords? true})})) (comment (save-user! {:image "www.learnuidev123.com" :bio "I make videos on Clojure and ClojureScript"})) (comment (me))
null
https://raw.githubusercontent.com/learnuidev/reagent-reposh-realworld/b6b77159ca0c38f47a858fb47fde66ad1155ba47/src/app/auth.cljs
clojure
Local Storage testing ================= Auth State =================== ================================================ ================= Register =================== ================================================ ================= Login ======================== ================================================ {:email "" :password} ================= Me ======================== ================================================ save-user {:email "" :password}
(ns app.auth (:require [reagent.core :as r] [reitit.frontend.easy :as rfe] [app.api :refer [api-uri]] [clojure.string :as s] [ajax.core :refer [GET POST PUT json-request-format json-response-format]])) (comment "Saving value into local storage" (.setItem js/localStorage "auth-user-token" "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTM4ODM2LCJ1c2VybmFtZSI6ImxlYXJudWlkZXYzQGZvby5jb20iLCJleHAiOjE2MTcxNjEwNzN9.O_cIsa66SQN26s3ap-F5oOQvp_zTpF4COH_HJDBK_cA")) (comment "Getting auth value from local storage - will be used to make auth requests" (.getItem js/localStorage "auth-user-token")) (comment "Removing value" (.removeItem js/localStorage "auth-user-token")) (defonce auth-state (r/atom nil)) (defonce error-state (r/atom nil)) (comment @auth-state (s/join ", " ["error a", "error b"])) (defn auth-success! [{{:keys [token] :as user} :user}] (.setItem js/localStorage "auth-user-token" token) (reset! auth-state user) (when (seq @error-state) (reset! error-state nil)) (rfe/push-state :routes/home)) (defn auth-error! [{{:keys [errors]} :response}] (reset! error-state errors)) (defn register! [input] (POST (str api-uri "/users") {:params {:user input} :handler auth-success! :format (json-request-format) :response-format (json-response-format {:keywords? true}) :error-handler auth-error!})) (comment (register! {:username "" :email "" :password ""})) (POST (str api-uri "/users/login") {:params {:user input} :handler auth-success! :format (json-request-format) :response-format (json-response-format {:keywords? true}) :error-handler auth-error!})) (comment (login! {:email "" :password ""})) (defn get-auth-header [] (let [token (.getItem js/localStorage "auth-user-token")] [:Authorization (str "Token " token)])) (defn get-me-success! [{user :user}] (reset! auth-state user)) (defn get-me-error! [error] (js/console.log "ERROR")) (defn me [] (GET (str api-uri "/user") {:handler get-me-success! :headers (get-auth-header) :response-format (json-response-format {:keywords? true}) :error-handler get-me-error!})) (def example-user {:email "" :password "" :username "" :image "" :bio ""}) (PUT (str api-uri "/user") {:params {:user user} :handler get-me-success! :error-handler get-me-error! :headers (get-auth-header) :format (json-request-format) :response-format (json-response-format {:keywords? true})})) (comment (save-user! {:image "www.learnuidev123.com" :bio "I make videos on Clojure and ClojureScript"})) (comment (me))
1b2058615deb1840123d169565cf23a0abddd22e96571a88cdf80960e6c866ac
urbit/urbit-hob
Property.hs
module Title.Tests.Property ( tests ) where import Data.Word (Word8, Word16, Word32, Word64) import Test.Hspec import Test.QuickCheck import Urbit.Ob.Co (Patp) import qualified Urbit.Ob.Co as Co import qualified Urbit.Ob.Title as Title galaxies :: Gen Patp galaxies = fmap (Co.patp . fromIntegral) (arbitrary :: Gen Word8) stars :: Gen Patp stars = do star <- arbitrary `suchThat` (> (0xFF :: Word16)) return (Co.patp (fromIntegral star)) planets :: Gen Patp planets = do planet <- arbitrary `suchThat` (> (0xFFFF :: Word32)) return (Co.patp (fromIntegral planet)) moons :: Gen Patp moons = do moon <- arbitrary `suchThat` (> (0xFFFFFFFF :: Word64)) return (Co.patp (fromIntegral moon)) tests :: Spec tests = describe "clan" $ do it "identifies galaxies correctly" $ forAll galaxies $ \x -> Title.clan x == Title.Galaxy it "identifies stars correctly" $ forAll stars $ \x -> Title.clan x == Title.Star it "identifies planets correctly" $ forAll planets $ \x -> Title.clan x == Title.Planet it "identifies moons correctly" $ forAll moons $ \x -> Title.clan x == Title.Moon
null
https://raw.githubusercontent.com/urbit/urbit-hob/3d4da34523ba8e5ea192744c861fead076c0f8e8/test/Title/Tests/Property.hs
haskell
module Title.Tests.Property ( tests ) where import Data.Word (Word8, Word16, Word32, Word64) import Test.Hspec import Test.QuickCheck import Urbit.Ob.Co (Patp) import qualified Urbit.Ob.Co as Co import qualified Urbit.Ob.Title as Title galaxies :: Gen Patp galaxies = fmap (Co.patp . fromIntegral) (arbitrary :: Gen Word8) stars :: Gen Patp stars = do star <- arbitrary `suchThat` (> (0xFF :: Word16)) return (Co.patp (fromIntegral star)) planets :: Gen Patp planets = do planet <- arbitrary `suchThat` (> (0xFFFF :: Word32)) return (Co.patp (fromIntegral planet)) moons :: Gen Patp moons = do moon <- arbitrary `suchThat` (> (0xFFFFFFFF :: Word64)) return (Co.patp (fromIntegral moon)) tests :: Spec tests = describe "clan" $ do it "identifies galaxies correctly" $ forAll galaxies $ \x -> Title.clan x == Title.Galaxy it "identifies stars correctly" $ forAll stars $ \x -> Title.clan x == Title.Star it "identifies planets correctly" $ forAll planets $ \x -> Title.clan x == Title.Planet it "identifies moons correctly" $ forAll moons $ \x -> Title.clan x == Title.Moon
dfcd837086811cfc17e31e1458bea5ea7cbd268935064a7414ded600eafe151f
gossiperl/gossiperl
gossiperl_encryption.erl
Copyright ( c ) 2014 < > %% %% Permission is hereby granted, free of charge, to any person obtaining a copy %% of this software and associated documentation files (the "Software"), to deal in the Software without restriction , including without limitation the rights %% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is %% furnished to do so, subject to the following conditions: %% %% The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . %% THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE %% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , %% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN %% THE SOFTWARE. -module(gossiperl_encryption). -behaviour(gen_server). -export([start_link/1, stop/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, code_change/3, terminate/2]). -include("gossiperl.hrl"). start_link(Config) -> gen_server:start_link({local, ?ENCRYPTION(Config)}, ?MODULE, [Config], []). init([Config]) -> {ok, { encryption, Config#overlayConfig{ symmetric_key = erlsha2:sha256( Config#overlayConfig.symmetric_key ) } }}. stop() -> gen_server:cast(?MODULE, stop). terminate(_Reason, _LoopData) -> {ok}. handle_cast(stop, LoopData) -> {noreply, LoopData}. handle_info({ update_config, NewConfig = #overlayConfig{} }, {encryption, _Config}) -> gossiperl_log:notice("[~p] Reconfiguring encryption component with ~p.", [ NewConfig#overlayConfig.name, NewConfig ]), {noreply, {encryption, NewConfig#overlayConfig{ symmetric_key = erlsha2:sha256( NewConfig#overlayConfig.symmetric_key ) }}}; handle_info(_Info, LoopData) -> {noreply, LoopData}. %% @doc Encrypt Msg and deliver to a caller. handle_call({ encrypt, Msg }, From, { encryption, Config }) -> IV = crypto:next_iv( aes_cbc, Msg ), Encrypted = crypto:block_encrypt( aes_cbc256, Config#overlayConfig.symmetric_key, IV, <<IV/binary, (?AES_PAD( Msg ))/binary>> ), gen_server:reply( From, { ok, Encrypted } ), {noreply, { encryption, Config }}; %% @doc Decrypt Msg and deliver to a caller, forward given state. handle_call({ decrypt, <<IV:16/binary, Msg/binary>> }, From, { encryption, Config }) -> try Decrypted = crypto:block_decrypt( aes_cbc256, Config#overlayConfig.symmetric_key, IV, Msg ), gen_server:reply( From, { ok, Decrypted } ) catch _Error:_Reason -> gen_server:reply( From, { error, decryption_failed } ) end, {noreply, { encryption, Config }}; handle_call({ decrypt, _ }, From, { encryption, Config }) -> gen_server:reply( From, { error, decryption_failed } ), {noreply, { encryption, Config }}; handle_call(_Msg, _From, LoopData) -> {reply, ok, LoopData}. code_change(_OldVsn, State, _Extra) -> {ok, State}.
null
https://raw.githubusercontent.com/gossiperl/gossiperl/0e7a3806bdec94016ba12f069d1699037c477c29/src/gossiperl_encryption.erl
erlang
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal to use, copy, modify, merge, publish, distribute, sublicense, and/or sell furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @doc Encrypt Msg and deliver to a caller. @doc Decrypt Msg and deliver to a caller, forward given state.
Copyright ( c ) 2014 < > in the Software without restriction , including without limitation the rights copies of the Software , and to permit persons to whom the Software is all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , -module(gossiperl_encryption). -behaviour(gen_server). -export([start_link/1, stop/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, code_change/3, terminate/2]). -include("gossiperl.hrl"). start_link(Config) -> gen_server:start_link({local, ?ENCRYPTION(Config)}, ?MODULE, [Config], []). init([Config]) -> {ok, { encryption, Config#overlayConfig{ symmetric_key = erlsha2:sha256( Config#overlayConfig.symmetric_key ) } }}. stop() -> gen_server:cast(?MODULE, stop). terminate(_Reason, _LoopData) -> {ok}. handle_cast(stop, LoopData) -> {noreply, LoopData}. handle_info({ update_config, NewConfig = #overlayConfig{} }, {encryption, _Config}) -> gossiperl_log:notice("[~p] Reconfiguring encryption component with ~p.", [ NewConfig#overlayConfig.name, NewConfig ]), {noreply, {encryption, NewConfig#overlayConfig{ symmetric_key = erlsha2:sha256( NewConfig#overlayConfig.symmetric_key ) }}}; handle_info(_Info, LoopData) -> {noreply, LoopData}. handle_call({ encrypt, Msg }, From, { encryption, Config }) -> IV = crypto:next_iv( aes_cbc, Msg ), Encrypted = crypto:block_encrypt( aes_cbc256, Config#overlayConfig.symmetric_key, IV, <<IV/binary, (?AES_PAD( Msg ))/binary>> ), gen_server:reply( From, { ok, Encrypted } ), {noreply, { encryption, Config }}; handle_call({ decrypt, <<IV:16/binary, Msg/binary>> }, From, { encryption, Config }) -> try Decrypted = crypto:block_decrypt( aes_cbc256, Config#overlayConfig.symmetric_key, IV, Msg ), gen_server:reply( From, { ok, Decrypted } ) catch _Error:_Reason -> gen_server:reply( From, { error, decryption_failed } ) end, {noreply, { encryption, Config }}; handle_call({ decrypt, _ }, From, { encryption, Config }) -> gen_server:reply( From, { error, decryption_failed } ), {noreply, { encryption, Config }}; handle_call(_Msg, _From, LoopData) -> {reply, ok, LoopData}. code_change(_OldVsn, State, _Extra) -> {ok, State}.
a3de5aa57c6209aced7e50efe7bcacf637445ce2a3227e86f1af546865a71586
slipstream/SlipStreamServer
credential_lifecycle_test.clj
(ns com.sixsq.slipstream.ssclj.resources.credential-lifecycle-test (:require [clojure.test :refer [are deftest is use-fixtures]] [com.sixsq.slipstream.ssclj.app.params :as p] [com.sixsq.slipstream.ssclj.resources.common.utils :as u] [com.sixsq.slipstream.ssclj.resources.credential :as credential] [com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu] [peridot.core :refer :all])) (use-fixtures :each ltu/with-test-server-fixture) (def base-uri (str p/service-context credential/resource-url)) (deftest bad-methods (let [resource-uri (str p/service-context (u/new-resource-id credential/resource-url))] (ltu/verify-405-status [[base-uri :options] [base-uri :delete] [resource-uri :options] [resource-uri :post]])))
null
https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/cimi/test/com/sixsq/slipstream/ssclj/resources/credential_lifecycle_test.clj
clojure
(ns com.sixsq.slipstream.ssclj.resources.credential-lifecycle-test (:require [clojure.test :refer [are deftest is use-fixtures]] [com.sixsq.slipstream.ssclj.app.params :as p] [com.sixsq.slipstream.ssclj.resources.common.utils :as u] [com.sixsq.slipstream.ssclj.resources.credential :as credential] [com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu] [peridot.core :refer :all])) (use-fixtures :each ltu/with-test-server-fixture) (def base-uri (str p/service-context credential/resource-url)) (deftest bad-methods (let [resource-uri (str p/service-context (u/new-resource-id credential/resource-url))] (ltu/verify-405-status [[base-uri :options] [base-uri :delete] [resource-uri :options] [resource-uri :post]])))
3d503285b5488337c7152eefe99970172d53611699b28599356ea01192bb284c
a-nikolaev/wanderers
trade.ml
Wanderers - open world adventure game . Copyright ( C ) 2013 - 2014 . 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 < / > . Copyright (C) 2013-2014 Alexey Nikolaev. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. *) open Base open Item let comp_price mult b = if b.Cnt.item.barcode = Coll.coin_barcode then b.Cnt.item.price * b.Cnt.amount else let x = (mult *. float (b.Cnt.item.price * b.Cnt.amount)) in (if mult >= 1.0 then ceil x |> int_of_float else max 1 (round x)) let comp_price_ls mult ls = List.fold_left (fun acc b -> acc + comp_price mult b) 0 ls let comp_price_cnt mult cnt = Cnt.fold (fun acc _ b -> acc + comp_price mult b) 0 cnt (* Barcode Map *) module M = Map.Make (struct type t = barcode let compare = compare end) let opt_get bc m = try Some (M.find bc m) with Not_found -> None let get bc m = try M.find bc m with Not_found -> 0 let put bc v m = M.add bc (get bc m + v) m let put_bunch b m = put b.Cnt.item.barcode b.Cnt.amount m let take bc v m = let vv = get bc m - v in if vv < 0 then failwith "Trade: take" else if vv = 0 then M.remove bc m else M.add bc vv m let put_bunch b m = put b.Cnt.item.barcode b.Cnt.amount m let take_bunch b m = take b.Cnt.item.barcode b.Cnt.amount m (* Trader *) type trader = { skill: float; stuff: int M.t; kb: Item.t M.t } let trader_empty = {skill = 1.5; stuff = M.empty; kb = M.empty} let trader_init money = let coin = Item.Coll.coin in let rec additem attempts_left ls money = if attempts_left > 0 && money > 0 then ( let obj = Item.Coll.random None in let price = Item.decompose obj |> Resource.numeric in if price <= money then additem attempts_left (Cnt.({item = obj; amount = 1})::ls) (money - price) else additem (attempts_left - 1) ls money ) else (ls, money) in let money_keep = money/2 in let money_stuff = money - money_keep in let ls, money_left = additem 5 [] money_stuff in let money = money_keep + money_left in (* put money *) let sf = let b = Cnt.({item = coin; amount = money}) in if money > 0 then put_bunch b M.empty else M.empty in let kb = M.add Coll.coin_barcode coin M.empty in (* put stuff *) let sf, kb = List.fold_left (fun (sf,kb) b -> (put_bunch b sf, M.add b.Cnt.item.barcode b.Cnt.item kb)) (sf, kb) ls in {skill = 1.5; stuff = sf; kb = kb} let price_buy tr ls = comp_price (1.0 /. tr.skill) ls let price_sell tr ls = comp_price tr.skill ls let price_buy_ls tr ls = comp_price_ls (1.0 /. tr.skill) ls let price_sell_ls tr ls = comp_price_ls tr.skill ls let price_buy_cnt tr ls = comp_price_cnt (1.0 /. tr.skill) ls let price_sell_cnt tr ls = comp_price_cnt tr.skill ls let print_trader tr = let print b = Printf.printf "\t%s; Amount = %i\n" (Item.string_of_item b.Item.Cnt.item) b.Item.Cnt.amount in M.iter (fun bc am -> let b = Item.Cnt.({item = M.find bc tr.kb; amount = am}) in print b ) tr.stuff; Printf.printf "\n%!" let extract bc tr = match get bc tr.stuff, opt_get bc tr.kb with | n, _ when n <= 0 -> None | _, None -> failwith "Trade: extract: error" | n, Some item -> let sf = take bc n tr.stuff in Some (Cnt.({item; amount = n}), {tr with stuff = sf}) let exchange sell buy tr= let sf = List.fold_left (fun sf b -> take_bunch b sf) tr.stuff sell in let sf = List.fold_left (fun sf b -> put_bunch b sf) sf buy in let kb = List.fold_left (fun kb b -> M.add b.Cnt.item.barcode b.Cnt.item kb) tr.kb buy in {tr with stuff = sf; kb} let decompose_useless tr = let coin_bc = Coll.coin_barcode in let count prop = M.fold (fun bc amount acc -> match opt_get bc tr.kb with | Some item -> if prop bc item then acc + amount * item.price else acc | _ -> acc ) tr.stuff 0 in let tot_money = count (fun bc _ -> bc = coin_bc) in let tot_stuff = count (fun bc _ -> bc <> coin_bc) in let tot = tot_money + tot_stuff in if tot > 0 then ( let prob_decompose = (0.5 *. float (tot_stuff - tot_money) /. float tot) |> max 0.0 in let prob_keep = 1.0 -. prob_decompose in Printf.printf " prob_keep = % g\n% ! " ; Printf.printf "prob_keep = %g\n%!" prob_keep; *) let sf = M.fold ( fun bc amount acc_sf -> let new_am = (prob_keep *. float amount) |> round_prob in let drop_am = amount - new_am in let sf = if new_am > 0 then acc_sf |> put bc new_am else acc_sf in if drop_am > 0 then let price = match opt_get bc tr.kb with Some item -> item.price | _ -> failwith "Trade: decompose_useless" in sf |> put coin_bc (price*drop_am) else sf ) tr.stuff M.empty in {tr with stuff = sf} ) else tr let barter_no_decomposition sell buy tr = let p_buy = price_buy_ls tr buy in let p_sell = price_sell_ls tr sell in if p_buy >= p_sell then Some (tr |> exchange sell buy) else None let barter sell buy tr = let p_buy = price_buy_ls tr buy in let p_sell = price_sell_ls tr sell in if p_buy >= p_sell then Some (tr |> exchange sell buy |> decompose_useless) else None let make_offer_ls price_cap num prop tr = (* Printf.printf "price cap = %i\n%!" price_cap; *) let coins_num = get Coll.coin_barcode tr.stuff in let coins_bunch = match coins_num, opt_get Coll.coin_barcode tr.kb with | x, Some coin -> Some Cnt.({item = coin; amount = min x price_cap}) | _ -> None in let pick probability ((init_ls, init_sf, init_n) as init_acc) = M.fold ( fun bc amount (ls, sf, n) -> if n > 0 then match opt_get bc tr.kb with | Some item -> if prop item && Random.float 1.0 <= probability item then let amount = match item.Item.stackable with | Some n -> min n amount | None -> 1 in (Cnt.({item; amount}) :: ls, take bc 1 sf, n-1) else (ls, sf, n) | None -> failwith "Trade: make_offer_ls: unknown item" else (ls, sf, n) ) init_sf init_acc in let factor = 2.0 in let inv_factor = 1.0 /. factor in let sf_no_coins = take Coll.coin_barcode coins_num tr.stuff in let ls, sf, n = [], sf_no_coins, num in 1 let ls, sf, n = pick (fun item -> let ratio = float item.price /. float price_cap in if ratio <= 1.0 then 0.0 +. factor *. ratio else 0.0 ) (ls, sf, n) in 2 let ls, sf, n = if n > 0 then pick (fun item -> let ratio = float item.price /. float price_cap in if ratio <= inv_factor then 0.25 +. factor *. 0.75 *. ratio else 0.0 ) (ls, sf, n) else (ls, sf, n) in 3 let ls, sf, n = if n > 0 then pick (fun item -> 1.0) (ls, sf, n) else (ls, sf, n) in (coins_bunch, ls) module UC = Common.Unit.Core let make_default_offer_ls core tr = let price_cap = UC.decompose core |> Resource.numeric in make_offer_ls price_cap 10 (fun _ -> true) tr let move_money_from_tr_to_core (core, tr) = let coin = Item.Coll.coin in match extract coin.Item.barcode tr with | Some (u_money_bunch, u_tr) -> let u_core = ( match Inv.put_somewhere_bunch u_money_bunch (UC.get_inv core) with | Item.Cnt.MoveBunchSuccess inv' -> UC.upd_inv inv' core | _ -> core ) in (u_core, u_tr) | None -> (core, tr)
null
https://raw.githubusercontent.com/a-nikolaev/wanderers/054c1cdc6dd833d8938357e6d898def510531d67/src/trade.ml
ocaml
Barcode Map Trader put money put stuff Printf.printf "price cap = %i\n%!" price_cap;
Wanderers - open world adventure game . Copyright ( C ) 2013 - 2014 . 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 < / > . Copyright (C) 2013-2014 Alexey Nikolaev. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. *) open Base open Item let comp_price mult b = if b.Cnt.item.barcode = Coll.coin_barcode then b.Cnt.item.price * b.Cnt.amount else let x = (mult *. float (b.Cnt.item.price * b.Cnt.amount)) in (if mult >= 1.0 then ceil x |> int_of_float else max 1 (round x)) let comp_price_ls mult ls = List.fold_left (fun acc b -> acc + comp_price mult b) 0 ls let comp_price_cnt mult cnt = Cnt.fold (fun acc _ b -> acc + comp_price mult b) 0 cnt module M = Map.Make (struct type t = barcode let compare = compare end) let opt_get bc m = try Some (M.find bc m) with Not_found -> None let get bc m = try M.find bc m with Not_found -> 0 let put bc v m = M.add bc (get bc m + v) m let put_bunch b m = put b.Cnt.item.barcode b.Cnt.amount m let take bc v m = let vv = get bc m - v in if vv < 0 then failwith "Trade: take" else if vv = 0 then M.remove bc m else M.add bc vv m let put_bunch b m = put b.Cnt.item.barcode b.Cnt.amount m let take_bunch b m = take b.Cnt.item.barcode b.Cnt.amount m type trader = { skill: float; stuff: int M.t; kb: Item.t M.t } let trader_empty = {skill = 1.5; stuff = M.empty; kb = M.empty} let trader_init money = let coin = Item.Coll.coin in let rec additem attempts_left ls money = if attempts_left > 0 && money > 0 then ( let obj = Item.Coll.random None in let price = Item.decompose obj |> Resource.numeric in if price <= money then additem attempts_left (Cnt.({item = obj; amount = 1})::ls) (money - price) else additem (attempts_left - 1) ls money ) else (ls, money) in let money_keep = money/2 in let money_stuff = money - money_keep in let ls, money_left = additem 5 [] money_stuff in let money = money_keep + money_left in let sf = let b = Cnt.({item = coin; amount = money}) in if money > 0 then put_bunch b M.empty else M.empty in let kb = M.add Coll.coin_barcode coin M.empty in let sf, kb = List.fold_left (fun (sf,kb) b -> (put_bunch b sf, M.add b.Cnt.item.barcode b.Cnt.item kb)) (sf, kb) ls in {skill = 1.5; stuff = sf; kb = kb} let price_buy tr ls = comp_price (1.0 /. tr.skill) ls let price_sell tr ls = comp_price tr.skill ls let price_buy_ls tr ls = comp_price_ls (1.0 /. tr.skill) ls let price_sell_ls tr ls = comp_price_ls tr.skill ls let price_buy_cnt tr ls = comp_price_cnt (1.0 /. tr.skill) ls let price_sell_cnt tr ls = comp_price_cnt tr.skill ls let print_trader tr = let print b = Printf.printf "\t%s; Amount = %i\n" (Item.string_of_item b.Item.Cnt.item) b.Item.Cnt.amount in M.iter (fun bc am -> let b = Item.Cnt.({item = M.find bc tr.kb; amount = am}) in print b ) tr.stuff; Printf.printf "\n%!" let extract bc tr = match get bc tr.stuff, opt_get bc tr.kb with | n, _ when n <= 0 -> None | _, None -> failwith "Trade: extract: error" | n, Some item -> let sf = take bc n tr.stuff in Some (Cnt.({item; amount = n}), {tr with stuff = sf}) let exchange sell buy tr= let sf = List.fold_left (fun sf b -> take_bunch b sf) tr.stuff sell in let sf = List.fold_left (fun sf b -> put_bunch b sf) sf buy in let kb = List.fold_left (fun kb b -> M.add b.Cnt.item.barcode b.Cnt.item kb) tr.kb buy in {tr with stuff = sf; kb} let decompose_useless tr = let coin_bc = Coll.coin_barcode in let count prop = M.fold (fun bc amount acc -> match opt_get bc tr.kb with | Some item -> if prop bc item then acc + amount * item.price else acc | _ -> acc ) tr.stuff 0 in let tot_money = count (fun bc _ -> bc = coin_bc) in let tot_stuff = count (fun bc _ -> bc <> coin_bc) in let tot = tot_money + tot_stuff in if tot > 0 then ( let prob_decompose = (0.5 *. float (tot_stuff - tot_money) /. float tot) |> max 0.0 in let prob_keep = 1.0 -. prob_decompose in Printf.printf " prob_keep = % g\n% ! " ; Printf.printf "prob_keep = %g\n%!" prob_keep; *) let sf = M.fold ( fun bc amount acc_sf -> let new_am = (prob_keep *. float amount) |> round_prob in let drop_am = amount - new_am in let sf = if new_am > 0 then acc_sf |> put bc new_am else acc_sf in if drop_am > 0 then let price = match opt_get bc tr.kb with Some item -> item.price | _ -> failwith "Trade: decompose_useless" in sf |> put coin_bc (price*drop_am) else sf ) tr.stuff M.empty in {tr with stuff = sf} ) else tr let barter_no_decomposition sell buy tr = let p_buy = price_buy_ls tr buy in let p_sell = price_sell_ls tr sell in if p_buy >= p_sell then Some (tr |> exchange sell buy) else None let barter sell buy tr = let p_buy = price_buy_ls tr buy in let p_sell = price_sell_ls tr sell in if p_buy >= p_sell then Some (tr |> exchange sell buy |> decompose_useless) else None let make_offer_ls price_cap num prop tr = let coins_num = get Coll.coin_barcode tr.stuff in let coins_bunch = match coins_num, opt_get Coll.coin_barcode tr.kb with | x, Some coin -> Some Cnt.({item = coin; amount = min x price_cap}) | _ -> None in let pick probability ((init_ls, init_sf, init_n) as init_acc) = M.fold ( fun bc amount (ls, sf, n) -> if n > 0 then match opt_get bc tr.kb with | Some item -> if prop item && Random.float 1.0 <= probability item then let amount = match item.Item.stackable with | Some n -> min n amount | None -> 1 in (Cnt.({item; amount}) :: ls, take bc 1 sf, n-1) else (ls, sf, n) | None -> failwith "Trade: make_offer_ls: unknown item" else (ls, sf, n) ) init_sf init_acc in let factor = 2.0 in let inv_factor = 1.0 /. factor in let sf_no_coins = take Coll.coin_barcode coins_num tr.stuff in let ls, sf, n = [], sf_no_coins, num in 1 let ls, sf, n = pick (fun item -> let ratio = float item.price /. float price_cap in if ratio <= 1.0 then 0.0 +. factor *. ratio else 0.0 ) (ls, sf, n) in 2 let ls, sf, n = if n > 0 then pick (fun item -> let ratio = float item.price /. float price_cap in if ratio <= inv_factor then 0.25 +. factor *. 0.75 *. ratio else 0.0 ) (ls, sf, n) else (ls, sf, n) in 3 let ls, sf, n = if n > 0 then pick (fun item -> 1.0) (ls, sf, n) else (ls, sf, n) in (coins_bunch, ls) module UC = Common.Unit.Core let make_default_offer_ls core tr = let price_cap = UC.decompose core |> Resource.numeric in make_offer_ls price_cap 10 (fun _ -> true) tr let move_money_from_tr_to_core (core, tr) = let coin = Item.Coll.coin in match extract coin.Item.barcode tr with | Some (u_money_bunch, u_tr) -> let u_core = ( match Inv.put_somewhere_bunch u_money_bunch (UC.get_inv core) with | Item.Cnt.MoveBunchSuccess inv' -> UC.upd_inv inv' core | _ -> core ) in (u_core, u_tr) | None -> (core, tr)
ff60fb434ce7d15081916885b8fd5f2f3cae5ffea855d24e21a9e31d558d94fa
lambdageek/centrinel
InferenceResult.hs
-- | A concrete monad transformer that is an instance of ' Centrinel . Control . Monad . Class . ' # language GeneralizedNewtypeDeriving # module Centrinel.Control.Monad.InferenceResult ( InferenceResultT (..) , runInferenceResultT ) where import Control.Monad.Reader (runReaderT, ReaderT, asks) import qualified Control.Monad.Trans.Reader as Reader import Control.Monad.Trans.Class (MonadTrans(..)) import qualified Data.Map as Map import qualified Language.C.Data.Ident as C import qualified Language.C.Analysis.SemRep as C import qualified Language.C.Analysis.TravMonad as CM import Language.C.Analysis.TravMonad.Instances () import Centrinel.Control.Monad.Class.RegionResult import Centrinel.Region.Region (RegionScheme(..)) import Centrinel.RegionInferenceResult (RegionInferenceResult) import Data.Assoc newtype InferenceResultT m a = InferenceResultT { unInferenceResultT :: ReaderT (Map.Map C.Ident C.TypeDef, RegionInferenceResult) m a } deriving (Functor, Applicative, Monad) instance CM.MonadCError m => CM.MonadCError (InferenceResultT m) where throwTravError = InferenceResultT . lift . CM.throwTravError catchTravError (InferenceResultT c) handler = InferenceResultT (CM.catchTravError c (unInferenceResultT . handler)) recordError = InferenceResultT . lift . CM.recordError getErrors = InferenceResultT $ lift $ CM.getErrors instance CM.MonadName m => CM.MonadName (InferenceResultT m) where genName = lift CM.genName instance CM.MonadSymtab m => CM.MonadSymtab (InferenceResultT m) where getDefTable = lift CM.getDefTable withDefTable = lift . CM.withDefTable instance Monad m => RegionResultMonad (InferenceResultT m) where rrStructTagRegion sr = InferenceResultT $ asks (certain . Map.lookup sr . Data.Assoc.getAssocMap . snd) where certain Nothing = PolyRS certain (Just a) = a rrLookupTypedef ident = InferenceResultT $ asks (certain . Map.lookup ident . fst) where certain Nothing = error "cannot get Nothing from rrLookupTypedef" certain (Just a) = a instance CM.MonadTrav m => CM.MonadTrav (InferenceResultT m) where handleDecl = lift . CM.handleDecl instance MonadTrans InferenceResultT where lift = InferenceResultT . lift runInferenceResultT :: InferenceResultT m a -> Map.Map C.Ident C.TypeDef -> RegionInferenceResult -> m a runInferenceResultT comp = curry (runReaderT (unInferenceResultT comp))
null
https://raw.githubusercontent.com/lambdageek/centrinel/412b620b77c6cb569811fec845b89d04585c1332/src/Centrinel/Control/Monad/InferenceResult.hs
haskell
| A concrete monad transformer that is an instance of
' Centrinel . Control . Monad . Class . ' # language GeneralizedNewtypeDeriving # module Centrinel.Control.Monad.InferenceResult ( InferenceResultT (..) , runInferenceResultT ) where import Control.Monad.Reader (runReaderT, ReaderT, asks) import qualified Control.Monad.Trans.Reader as Reader import Control.Monad.Trans.Class (MonadTrans(..)) import qualified Data.Map as Map import qualified Language.C.Data.Ident as C import qualified Language.C.Analysis.SemRep as C import qualified Language.C.Analysis.TravMonad as CM import Language.C.Analysis.TravMonad.Instances () import Centrinel.Control.Monad.Class.RegionResult import Centrinel.Region.Region (RegionScheme(..)) import Centrinel.RegionInferenceResult (RegionInferenceResult) import Data.Assoc newtype InferenceResultT m a = InferenceResultT { unInferenceResultT :: ReaderT (Map.Map C.Ident C.TypeDef, RegionInferenceResult) m a } deriving (Functor, Applicative, Monad) instance CM.MonadCError m => CM.MonadCError (InferenceResultT m) where throwTravError = InferenceResultT . lift . CM.throwTravError catchTravError (InferenceResultT c) handler = InferenceResultT (CM.catchTravError c (unInferenceResultT . handler)) recordError = InferenceResultT . lift . CM.recordError getErrors = InferenceResultT $ lift $ CM.getErrors instance CM.MonadName m => CM.MonadName (InferenceResultT m) where genName = lift CM.genName instance CM.MonadSymtab m => CM.MonadSymtab (InferenceResultT m) where getDefTable = lift CM.getDefTable withDefTable = lift . CM.withDefTable instance Monad m => RegionResultMonad (InferenceResultT m) where rrStructTagRegion sr = InferenceResultT $ asks (certain . Map.lookup sr . Data.Assoc.getAssocMap . snd) where certain Nothing = PolyRS certain (Just a) = a rrLookupTypedef ident = InferenceResultT $ asks (certain . Map.lookup ident . fst) where certain Nothing = error "cannot get Nothing from rrLookupTypedef" certain (Just a) = a instance CM.MonadTrav m => CM.MonadTrav (InferenceResultT m) where handleDecl = lift . CM.handleDecl instance MonadTrans InferenceResultT where lift = InferenceResultT . lift runInferenceResultT :: InferenceResultT m a -> Map.Map C.Ident C.TypeDef -> RegionInferenceResult -> m a runInferenceResultT comp = curry (runReaderT (unInferenceResultT comp))
7f77f8d9a7f365f3143d16cf5e1d0431bcb8bcc7cba25d695bfa30a33bbca3d0
inria-parkas/sundialsml
dochtml.ml
(***********************************************************************) (* *) (* OCaml interface to Sundials *) (* *) ( ) , ( ) , and ( LIENS ) (* *) Copyright 2021 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed (* under a New BSD License, refer to the file LICENSE. *) (* *) (***********************************************************************) [@@@ocaml.warning "-7"] * Custom tags for the ocamldoc comments : @sundials link to Sundials documentation @profiler link to Sundials Profiler module documentation @context link to Sundials Context module documentation @cvode link to Sundials CVODE documentation @cvodes link to Sundials CVODES documentation @cvodes_quad link to Sundials CVODES Quadrature documentation @cvodes_sens link to Sundials CVODES Sensitivity documentation @cvodes_adj link to Sundials CVODES Adjoint documentation @arkode link to Sundials ARKODE documentation @arkode_ark link to Sundials ARKODE ARKStep documentation @arkode_erk link to Sundials ARKODE ERKStep documentation @arkode_mri link to Sundials ARKODE MRIStep documentation @arkode_bt link to Sundials ARKODE Butcher Table documentation @arkode_user link to Sundials ARKODE User - supplied functions documentation @arkode_precond link to Sundials ARKODE Preconditioners documentation @arkode_innerstepper link to Sundials ARKODE Innerstepper documentation @arkode_coupling link to Sundials ARKODE Coupling documentation @ida link to Sundials IDA documentation @idas link to Sundials IDAS documentation @idas_quad link to Sundials IDAS Quadrature documentation @idas_sens link to Sundials IDAS Sensitivity documentation @idas_adj link to Sundials IDAS Adjoint documentation @kinsol link to Sundials KINSOL documentation @nvector link to Sundials NVECTOR documentation @matrix link to Sundials MATRIX documentation @matrix_data link to Sundials MATRIX data - specific documentation @linsol link to Sundials Linear Solver documentation @linsol_module link to Sundials Linear Solver module documentation @nonlinsol link to Sundials Nonlinear Solver documentation @nonlinsol_module link to Sundials Nonlinear Solver module documentation @nodoc No link is possible Custom tags for the ocamldoc comments: @sundials link to Sundials documentation @profiler link to Sundials Profiler module documentation @context link to Sundials Context module documentation @cvode link to Sundials CVODE documentation @cvodes link to Sundials CVODES documentation @cvodes_quad link to Sundials CVODES Quadrature documentation @cvodes_sens link to Sundials CVODES Sensitivity documentation @cvodes_adj link to Sundials CVODES Adjoint documentation @arkode link to Sundials ARKODE documentation @arkode_ark link to Sundials ARKODE ARKStep documentation @arkode_erk link to Sundials ARKODE ERKStep documentation @arkode_mri link to Sundials ARKODE MRIStep documentation @arkode_bt link to Sundials ARKODE Butcher Table documentation @arkode_user link to Sundials ARKODE User-supplied functions documentation @arkode_precond link to Sundials ARKODE Preconditioners documentation @arkode_innerstepper link to Sundials ARKODE Innerstepper documentation @arkode_coupling link to Sundials ARKODE Coupling documentation @ida link to Sundials IDA documentation @idas link to Sundials IDAS documentation @idas_quad link to Sundials IDAS Quadrature documentation @idas_sens link to Sundials IDAS Sensitivity documentation @idas_adj link to Sundials IDAS Adjoint documentation @kinsol link to Sundials KINSOL documentation @nvector link to Sundials NVECTOR documentation @matrix link to Sundials MATRIX documentation @matrix_data link to Sundials MATRIX data-specific documentation @linsol link to Sundials Linear Solver documentation @linsol_module link to Sundials Linear Solver module documentation @nonlinsol link to Sundials Nonlinear Solver documentation @nonlinsol_module link to Sundials Nonlinear Solver module documentation @nodoc No link is possible *) let sundials_doc_root = ref SUNDIALS_DOC_ROOT let mathjax_url = ref MATHJAX_URL (* directory containing MathJax.js *) let bp = Printf.bprintf let bs = Buffer.add_string type custom_type = Simple of (string -> string) | Full of (Buffer.t -> Odoc_info.text -> unit) let sundials_link div_class doc_root page anchor title = Printf.sprintf "<li class=\"sundials %s\">\ <span class=\"seesundials\">See Sundials: </span>\ <a href=\"%s%s%s\">%s</a></li>" div_class doc_root page anchor title module Generator (G : Odoc_html.Html_generator) = struct class html = object(self) inherit G.html as super val rex = Str.regexp "<\\([^#>]*\\)\\(#[^)]*\\)?> \\(.*\\)" val variables = [ ("version", let major, minor, patch, _binding = Sundials_configuration.version in Printf.sprintf "%d.%d.%d" major minor patch) ] method private split_text ?(page="Usage/index.html") (t:Odoc_info.text) = let s = Odoc_info.text_string_of_text t in if not (Str.string_match rex s 0) then let first_word = List.hd (Str.split (Str.regexp " +") s) in (page, "#c." ^ first_word, s) else let page = Str.matched_group 1 s and anchor = try Str.matched_group 2 s with Not_found -> "" and title = Str.matched_group 3 s in (page, anchor, title) method private html_of_missing t = let (_page, _anchor, title) = self#split_text t in Printf.sprintf "<li class=\"sundials nodoc\">\ <span class=\"seesundials\">See Sundials: </span>%s\ </li>" title method private html_of_sundials t = let (page, anchor, title) = self#split_text t in sundials_link "sundials" (!sundials_doc_root ^ "sundials/") page anchor title method private html_of_profiler t = let (page, anchor, title) = self#split_text ~page:"Profiling_link.html" t in sundials_link "sundials" (!sundials_doc_root ^ "sundials/") page anchor title method private html_of_context t = let (page, anchor, title) = self#split_text ~page:"SUNContext_link.html" t in sundials_link "sundials" (!sundials_doc_root ^ "sundials/") page anchor title method private html_of_cvode t = let (page, anchor, title) = self#split_text t in sundials_link "cvode" (!sundials_doc_root ^ "cvode/") page anchor title method private html_of_cvodes t = let (page, anchor, title) = self#split_text ~page:"Usage/SIM.html" t in sundials_link "cvodes" (!sundials_doc_root ^ "cvodes/") page anchor title method private html_of_cvodes_quad t = let (page, anchor, title) = self#split_text ~page:"Usage/SIM.html" t in sundials_link "cvodes" (!sundials_doc_root ^ "cvodes/") page anchor title method private html_of_cvodes_sens t = let (page, anchor, title) = self#split_text ~page:"Usage/FSA.html" t in sundials_link "cvodes" (!sundials_doc_root ^ "cvodes/") page anchor title method private html_of_cvodes_adj t = let (page, anchor, title) = self#split_text ~page:"Usage/ADJ.html" t in sundials_link "cvodes" (!sundials_doc_root ^ "cvodes/") page anchor title method private html_of_arkode t = let (page, anchor, title) = self#split_text t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_ark t = let (page, anchor, title) = self#split_text ~page:"Usage/ARKStep_c_interface/User_callable.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_erk t = let (page, anchor, title) = self#split_text ~page:"Usage/ERKStep_c_interface/User_callable.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_mri t = let (page, anchor, title) = self#split_text ~page:"Usage/MRIStep_c_interface/User_callable.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_bt t = let (page, anchor, title) = self#split_text ~page:"ARKodeButcherTable_link.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_user t = let (page, anchor, title) = self#split_text ~page:"Usage/User_supplied.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_precond t = let (page, anchor, title) = self#split_text ~page:"Usage/ARKStep_c_interface/Preconditioners.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_innerstepper t = let (page, anchor, title) = self#split_text ~page:"Usage/MRIStep_c_interface/Custom_Inner_Stepper/Description.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_coupling t = let (page, anchor, title) = self#split_text ~page:"Usage/MRIStep_c_interface/MRIStepCoupling.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_ida t = let (page, anchor, title) = self#split_text t in sundials_link "ida" (!sundials_doc_root ^ "ida/") page anchor title method private html_of_idas t = let (page, anchor, title) = self#split_text ~page:"Usage/SIM.html" t in sundials_link "idas" (!sundials_doc_root ^ "idas/") page anchor title method private html_of_idas_quad t = let (page, anchor, title) = self#split_text ~page:"Usage/SIM.html" t in sundials_link "idas" (!sundials_doc_root ^ "idas/") page anchor title method private html_of_idas_sens t = let (page, anchor, title) = self#split_text ~page:"Usage/FSA.html" t in sundials_link "idas" (!sundials_doc_root ^ "idas/") page anchor title method private html_of_idas_adj t = let (page, anchor, title) = self#split_text ~page:"Usage/ADJ.html" t in sundials_link "idas" (!sundials_doc_root ^ "idas/") page anchor title method private html_of_kinsol t = let (page, anchor, title) = self#split_text t in sundials_link "kinsol" (!sundials_doc_root ^ "kinsol/") page anchor title method private html_of_nvector t = let (page, anchor, title) = self#split_text ~page:"NVector_links.html" t in sundials_link "nvector" (!sundials_doc_root ^ "nvectors/") page anchor title method private html_of_matrix t = let (page, anchor, title) = self#split_text ~page:"SUNMatrix_API_link.html" t in sundials_link "matrix" (!sundials_doc_root ^ "sunmatrix/") page anchor title method private html_of_matrix_data t = let (page, anchor, title) = self#split_text ~page:"SUNMatrix_links.html" t in sundials_link "matrix" (!sundials_doc_root ^ "sunmatrix/") page anchor title method private html_of_linsol t = let (page, anchor, title) = self#split_text ~page:"SUNLinSol_API_link.html" t in sundials_link "linsol" (!sundials_doc_root ^ "sunlinsol/") page anchor title method private html_of_linsol_module t = let (page, anchor, title) = self#split_text ~page:"SUNLinSol_links.html" t in sundials_link "linsol" (!sundials_doc_root ^ "sunlinsol/") page anchor title method private html_of_nonlinsol t = let (page, anchor, title) = self#split_text ~page:"SUNNonlinSol_API_link.html" t in sundials_link "nonlinsol" (!sundials_doc_root ^ "sunnonlinsol/") page anchor title method private html_of_nonlinsol_module t = let (page, anchor, title) = self#split_text ~page:"SUNNonlinSol_links.html" t in sundials_link "nonlinsol" (!sundials_doc_root ^ "sunnonlinsol/") page anchor title val divrex = Str.regexp " *\\(open\\|close\\) *\\(.*\\)" method private html_of_div s = let baddiv s = (Odoc_info.warning (Printf.sprintf "div must be followed by 'open' or 'close', not '%s'!" s); "") in if not (Str.string_match divrex s 0) then baddiv s else match Str.matched_group 1 s with | "open" -> let attrs = try Str.matched_group 2 s with Not_found -> "" in Printf.sprintf "<div %s>" attrs | "close" -> "</div>" | s -> baddiv s method private html_of_var s = let var = Str.replace_first (Str.regexp " +$") "" (Str.replace_first (Str.regexp "^ +") "" s) in try List.assoc var variables with Not_found -> (Odoc_info.warning (Printf.sprintf "Variable '%s' is not defined." var); "") method private html_of_img s = Printf.sprintf "<a href=\"%s\"><img src=\"%s\"></a>" s s method private html_of_openfile s = let var = Str.replace_first (Str.regexp " +$") "" (Str.replace_first (Str.regexp "^ +") "" s) in Printf.sprintf "<a href=\"%s\">%s</a>" var var method private html_of_cconst s = let var = Str.replace_first (Str.regexp " +$") "" (Str.replace_first (Str.regexp "^ +") "" s) in Printf.sprintf "<span class=\"cconst\">(%s)</span>" var method private html_of_color s = let ss = Str.bounded_split (Str.regexp "[ \t\n]+") s 2 in match ss with | [x] -> (Odoc_info.warning (Printf.sprintf "No color given ('%s')." x); x) | [color; text] -> Printf.sprintf "<span style=\"color: %s;\">%s</span>" color text | _ -> assert false method html_of_raised_exceptions b l = match l with [] -> () | (s, t) :: [] -> bs b "<div class=\"raisedexceptions\">"; bp b "<span class=\"raises\">%s</span> <code>%s</code> " Odoc_messages.raises s; self#html_of_text b t; bs b "</div>\n" | _ -> bs b "<div class=\"raisedexceptions\">"; bp b "<span class=\"raises\">%s</span><ul>" Odoc_messages.raises; List.iter (fun (ex, desc) -> bp b "<li><code>%s</code> " ex ; self#html_of_text b desc; bs b "</li>\n" ) l; bs b "</ul></div>\n" method html_of_author_list b l = match l with [] -> () | _ -> bp b "<div class=\"authors\">"; bp b "<b>%s:</b> " Odoc_messages.authors; self#html_of_text b [Odoc_info.Raw (String.concat ", " l)]; bs b "</div>\n" val mutable custom_functions = ([] : (string * custom_type) list) method private html_of_warning b t = bs b "<div class=\"warningbox\">"; self#html_of_text b t; bs b "</div>" method private html_of_custom_text b tag text = try match List.assoc tag custom_functions, text with | (Simple f, [Odoc_info.Raw s]) -> Buffer.add_string b (f s) | (Simple _, _) -> Odoc_info.warning (Printf.sprintf "custom tags (%s) must be followed by plain text." tag) | (Full f, _) -> f b text with Not_found -> Odoc_info.warning (Odoc_messages.tag_not_handled tag) (* Import MathJax (/) to render mathematics in function comments. *) method init_style = super#init_style; style <- style ^ "<script type=\"text/x-mathjax-config\">\n" ^ " MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$']]}});\n" ^ "</script>" ^ "<script type=\"text/javascript\"\n" ^ Printf.sprintf " src=\"%s/MathJax.js?config=TeX-AMS-MML_HTMLorMML\">\n" !mathjax_url ^ "</script>\n" method html_of_Latex b s = Buffer.add_string b s initializer tag_functions <- ("sundials", self#html_of_sundials) :: tag_functions; tag_functions <- ("profiler", self#html_of_profiler) :: tag_functions; tag_functions <- ("context", self#html_of_context) :: tag_functions; tag_functions <- ("cvode", self#html_of_cvode) :: tag_functions; tag_functions <- ("cvodes", self#html_of_cvodes) :: tag_functions; tag_functions <- ("cvodes_quad", self#html_of_cvodes_quad) :: tag_functions; tag_functions <- ("cvodes_sens", self#html_of_cvodes_sens) :: tag_functions; tag_functions <- ("cvodes_adj", self#html_of_cvodes_adj) :: tag_functions; tag_functions <- ("arkode", self#html_of_arkode) :: tag_functions; tag_functions <- ("arkode_ark", self#html_of_arkode_ark) :: tag_functions; tag_functions <- ("arkode_erk", self#html_of_arkode_erk) :: tag_functions; tag_functions <- ("arkode_mri", self#html_of_arkode_mri) :: tag_functions; tag_functions <- ("arkode_bt", self#html_of_arkode_bt) :: tag_functions; tag_functions <- ("arkode_user",self#html_of_arkode_user) :: tag_functions; tag_functions <- ("arkode_precond",self#html_of_arkode_precond) :: tag_functions; tag_functions <- ("arkode_innerstepper",self#html_of_arkode_innerstepper) :: tag_functions; tag_functions <- ("arkode_coupling",self#html_of_arkode_coupling) :: tag_functions; tag_functions <- ("ida", self#html_of_ida) :: tag_functions; tag_functions <- ("idas", self#html_of_idas) :: tag_functions; tag_functions <- ("idas_quad", self#html_of_idas_quad) :: tag_functions; tag_functions <- ("idas_sens", self#html_of_idas_sens) :: tag_functions; tag_functions <- ("idas_adj", self#html_of_idas_adj) :: tag_functions; tag_functions <- ("kinsol", self#html_of_kinsol) :: tag_functions; tag_functions <- ("nvector", self#html_of_nvector) :: tag_functions; tag_functions <- ("matrix", self#html_of_matrix) :: tag_functions; tag_functions <- ("matrix_data", self#html_of_matrix_data) :: tag_functions; tag_functions <- ("linsol", self#html_of_linsol) :: tag_functions; tag_functions <- ("linsol_module", self#html_of_linsol_module) :: tag_functions; tag_functions <- ("nonlinsol", self#html_of_nonlinsol) :: tag_functions; tag_functions <- ("nonlinsol_module", self#html_of_nonlinsol_module) :: tag_functions; tag_functions <- ("nodoc", self#html_of_missing) :: tag_functions; custom_functions <- ("div", Simple self#html_of_div) :: ("var", Simple self#html_of_var) :: ("color", Simple self#html_of_color) :: ("img", Simple self#html_of_img) :: ("cconst", Simple self#html_of_cconst) :: ("openfile", Simple self#html_of_openfile) :: ("warning", Full self#html_of_warning) :: custom_functions end end let _ = Odoc_html.charset := "utf-8" let option_sundials_doc_root = ("-sundials-doc-root", Arg.String (fun d -> sundials_doc_root := d), "<dir> specify the root url for the Sundials documentation.") let option_mathjax_url = ("-mathjax", Arg.String (fun d -> mathjax_url := d), "<url> specify the root url for MathJax.") let _ = Odoc_args.add_option option_sundials_doc_root; Odoc_args.add_option option_mathjax_url; Odoc_args.extend_html_generator (module Generator : Odoc_gen.Html_functor)
null
https://raw.githubusercontent.com/inria-parkas/sundialsml/a72ebfc84b55470ed97fbb0b45d700deebfc1664/doc/dochtml.ml
ocaml
********************************************************************* OCaml interface to Sundials under a New BSD License, refer to the file LICENSE. ********************************************************************* directory containing MathJax.js Import MathJax (/) to render mathematics in function comments.
( ) , ( ) , and ( LIENS ) Copyright 2021 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed [@@@ocaml.warning "-7"] * Custom tags for the ocamldoc comments : @sundials link to Sundials documentation @profiler link to Sundials Profiler module documentation @context link to Sundials Context module documentation @cvode link to Sundials CVODE documentation @cvodes link to Sundials CVODES documentation @cvodes_quad link to Sundials CVODES Quadrature documentation @cvodes_sens link to Sundials CVODES Sensitivity documentation @cvodes_adj link to Sundials CVODES Adjoint documentation @arkode link to Sundials ARKODE documentation @arkode_ark link to Sundials ARKODE ARKStep documentation @arkode_erk link to Sundials ARKODE ERKStep documentation @arkode_mri link to Sundials ARKODE MRIStep documentation @arkode_bt link to Sundials ARKODE Butcher Table documentation @arkode_user link to Sundials ARKODE User - supplied functions documentation @arkode_precond link to Sundials ARKODE Preconditioners documentation @arkode_innerstepper link to Sundials ARKODE Innerstepper documentation @arkode_coupling link to Sundials ARKODE Coupling documentation @ida link to Sundials IDA documentation @idas link to Sundials IDAS documentation @idas_quad link to Sundials IDAS Quadrature documentation @idas_sens link to Sundials IDAS Sensitivity documentation @idas_adj link to Sundials IDAS Adjoint documentation @kinsol link to Sundials KINSOL documentation @nvector link to Sundials NVECTOR documentation @matrix link to Sundials MATRIX documentation @matrix_data link to Sundials MATRIX data - specific documentation @linsol link to Sundials Linear Solver documentation @linsol_module link to Sundials Linear Solver module documentation @nonlinsol link to Sundials Nonlinear Solver documentation @nonlinsol_module link to Sundials Nonlinear Solver module documentation @nodoc No link is possible Custom tags for the ocamldoc comments: @sundials link to Sundials documentation @profiler link to Sundials Profiler module documentation @context link to Sundials Context module documentation @cvode link to Sundials CVODE documentation @cvodes link to Sundials CVODES documentation @cvodes_quad link to Sundials CVODES Quadrature documentation @cvodes_sens link to Sundials CVODES Sensitivity documentation @cvodes_adj link to Sundials CVODES Adjoint documentation @arkode link to Sundials ARKODE documentation @arkode_ark link to Sundials ARKODE ARKStep documentation @arkode_erk link to Sundials ARKODE ERKStep documentation @arkode_mri link to Sundials ARKODE MRIStep documentation @arkode_bt link to Sundials ARKODE Butcher Table documentation @arkode_user link to Sundials ARKODE User-supplied functions documentation @arkode_precond link to Sundials ARKODE Preconditioners documentation @arkode_innerstepper link to Sundials ARKODE Innerstepper documentation @arkode_coupling link to Sundials ARKODE Coupling documentation @ida link to Sundials IDA documentation @idas link to Sundials IDAS documentation @idas_quad link to Sundials IDAS Quadrature documentation @idas_sens link to Sundials IDAS Sensitivity documentation @idas_adj link to Sundials IDAS Adjoint documentation @kinsol link to Sundials KINSOL documentation @nvector link to Sundials NVECTOR documentation @matrix link to Sundials MATRIX documentation @matrix_data link to Sundials MATRIX data-specific documentation @linsol link to Sundials Linear Solver documentation @linsol_module link to Sundials Linear Solver module documentation @nonlinsol link to Sundials Nonlinear Solver documentation @nonlinsol_module link to Sundials Nonlinear Solver module documentation @nodoc No link is possible *) let sundials_doc_root = ref SUNDIALS_DOC_ROOT let bp = Printf.bprintf let bs = Buffer.add_string type custom_type = Simple of (string -> string) | Full of (Buffer.t -> Odoc_info.text -> unit) let sundials_link div_class doc_root page anchor title = Printf.sprintf "<li class=\"sundials %s\">\ <span class=\"seesundials\">See Sundials: </span>\ <a href=\"%s%s%s\">%s</a></li>" div_class doc_root page anchor title module Generator (G : Odoc_html.Html_generator) = struct class html = object(self) inherit G.html as super val rex = Str.regexp "<\\([^#>]*\\)\\(#[^)]*\\)?> \\(.*\\)" val variables = [ ("version", let major, minor, patch, _binding = Sundials_configuration.version in Printf.sprintf "%d.%d.%d" major minor patch) ] method private split_text ?(page="Usage/index.html") (t:Odoc_info.text) = let s = Odoc_info.text_string_of_text t in if not (Str.string_match rex s 0) then let first_word = List.hd (Str.split (Str.regexp " +") s) in (page, "#c." ^ first_word, s) else let page = Str.matched_group 1 s and anchor = try Str.matched_group 2 s with Not_found -> "" and title = Str.matched_group 3 s in (page, anchor, title) method private html_of_missing t = let (_page, _anchor, title) = self#split_text t in Printf.sprintf "<li class=\"sundials nodoc\">\ <span class=\"seesundials\">See Sundials: </span>%s\ </li>" title method private html_of_sundials t = let (page, anchor, title) = self#split_text t in sundials_link "sundials" (!sundials_doc_root ^ "sundials/") page anchor title method private html_of_profiler t = let (page, anchor, title) = self#split_text ~page:"Profiling_link.html" t in sundials_link "sundials" (!sundials_doc_root ^ "sundials/") page anchor title method private html_of_context t = let (page, anchor, title) = self#split_text ~page:"SUNContext_link.html" t in sundials_link "sundials" (!sundials_doc_root ^ "sundials/") page anchor title method private html_of_cvode t = let (page, anchor, title) = self#split_text t in sundials_link "cvode" (!sundials_doc_root ^ "cvode/") page anchor title method private html_of_cvodes t = let (page, anchor, title) = self#split_text ~page:"Usage/SIM.html" t in sundials_link "cvodes" (!sundials_doc_root ^ "cvodes/") page anchor title method private html_of_cvodes_quad t = let (page, anchor, title) = self#split_text ~page:"Usage/SIM.html" t in sundials_link "cvodes" (!sundials_doc_root ^ "cvodes/") page anchor title method private html_of_cvodes_sens t = let (page, anchor, title) = self#split_text ~page:"Usage/FSA.html" t in sundials_link "cvodes" (!sundials_doc_root ^ "cvodes/") page anchor title method private html_of_cvodes_adj t = let (page, anchor, title) = self#split_text ~page:"Usage/ADJ.html" t in sundials_link "cvodes" (!sundials_doc_root ^ "cvodes/") page anchor title method private html_of_arkode t = let (page, anchor, title) = self#split_text t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_ark t = let (page, anchor, title) = self#split_text ~page:"Usage/ARKStep_c_interface/User_callable.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_erk t = let (page, anchor, title) = self#split_text ~page:"Usage/ERKStep_c_interface/User_callable.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_mri t = let (page, anchor, title) = self#split_text ~page:"Usage/MRIStep_c_interface/User_callable.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_bt t = let (page, anchor, title) = self#split_text ~page:"ARKodeButcherTable_link.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_user t = let (page, anchor, title) = self#split_text ~page:"Usage/User_supplied.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_precond t = let (page, anchor, title) = self#split_text ~page:"Usage/ARKStep_c_interface/Preconditioners.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_innerstepper t = let (page, anchor, title) = self#split_text ~page:"Usage/MRIStep_c_interface/Custom_Inner_Stepper/Description.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_arkode_coupling t = let (page, anchor, title) = self#split_text ~page:"Usage/MRIStep_c_interface/MRIStepCoupling.html" t in sundials_link "arkode" (!sundials_doc_root ^ "arkode/") page anchor title method private html_of_ida t = let (page, anchor, title) = self#split_text t in sundials_link "ida" (!sundials_doc_root ^ "ida/") page anchor title method private html_of_idas t = let (page, anchor, title) = self#split_text ~page:"Usage/SIM.html" t in sundials_link "idas" (!sundials_doc_root ^ "idas/") page anchor title method private html_of_idas_quad t = let (page, anchor, title) = self#split_text ~page:"Usage/SIM.html" t in sundials_link "idas" (!sundials_doc_root ^ "idas/") page anchor title method private html_of_idas_sens t = let (page, anchor, title) = self#split_text ~page:"Usage/FSA.html" t in sundials_link "idas" (!sundials_doc_root ^ "idas/") page anchor title method private html_of_idas_adj t = let (page, anchor, title) = self#split_text ~page:"Usage/ADJ.html" t in sundials_link "idas" (!sundials_doc_root ^ "idas/") page anchor title method private html_of_kinsol t = let (page, anchor, title) = self#split_text t in sundials_link "kinsol" (!sundials_doc_root ^ "kinsol/") page anchor title method private html_of_nvector t = let (page, anchor, title) = self#split_text ~page:"NVector_links.html" t in sundials_link "nvector" (!sundials_doc_root ^ "nvectors/") page anchor title method private html_of_matrix t = let (page, anchor, title) = self#split_text ~page:"SUNMatrix_API_link.html" t in sundials_link "matrix" (!sundials_doc_root ^ "sunmatrix/") page anchor title method private html_of_matrix_data t = let (page, anchor, title) = self#split_text ~page:"SUNMatrix_links.html" t in sundials_link "matrix" (!sundials_doc_root ^ "sunmatrix/") page anchor title method private html_of_linsol t = let (page, anchor, title) = self#split_text ~page:"SUNLinSol_API_link.html" t in sundials_link "linsol" (!sundials_doc_root ^ "sunlinsol/") page anchor title method private html_of_linsol_module t = let (page, anchor, title) = self#split_text ~page:"SUNLinSol_links.html" t in sundials_link "linsol" (!sundials_doc_root ^ "sunlinsol/") page anchor title method private html_of_nonlinsol t = let (page, anchor, title) = self#split_text ~page:"SUNNonlinSol_API_link.html" t in sundials_link "nonlinsol" (!sundials_doc_root ^ "sunnonlinsol/") page anchor title method private html_of_nonlinsol_module t = let (page, anchor, title) = self#split_text ~page:"SUNNonlinSol_links.html" t in sundials_link "nonlinsol" (!sundials_doc_root ^ "sunnonlinsol/") page anchor title val divrex = Str.regexp " *\\(open\\|close\\) *\\(.*\\)" method private html_of_div s = let baddiv s = (Odoc_info.warning (Printf.sprintf "div must be followed by 'open' or 'close', not '%s'!" s); "") in if not (Str.string_match divrex s 0) then baddiv s else match Str.matched_group 1 s with | "open" -> let attrs = try Str.matched_group 2 s with Not_found -> "" in Printf.sprintf "<div %s>" attrs | "close" -> "</div>" | s -> baddiv s method private html_of_var s = let var = Str.replace_first (Str.regexp " +$") "" (Str.replace_first (Str.regexp "^ +") "" s) in try List.assoc var variables with Not_found -> (Odoc_info.warning (Printf.sprintf "Variable '%s' is not defined." var); "") method private html_of_img s = Printf.sprintf "<a href=\"%s\"><img src=\"%s\"></a>" s s method private html_of_openfile s = let var = Str.replace_first (Str.regexp " +$") "" (Str.replace_first (Str.regexp "^ +") "" s) in Printf.sprintf "<a href=\"%s\">%s</a>" var var method private html_of_cconst s = let var = Str.replace_first (Str.regexp " +$") "" (Str.replace_first (Str.regexp "^ +") "" s) in Printf.sprintf "<span class=\"cconst\">(%s)</span>" var method private html_of_color s = let ss = Str.bounded_split (Str.regexp "[ \t\n]+") s 2 in match ss with | [x] -> (Odoc_info.warning (Printf.sprintf "No color given ('%s')." x); x) | [color; text] -> Printf.sprintf "<span style=\"color: %s;\">%s</span>" color text | _ -> assert false method html_of_raised_exceptions b l = match l with [] -> () | (s, t) :: [] -> bs b "<div class=\"raisedexceptions\">"; bp b "<span class=\"raises\">%s</span> <code>%s</code> " Odoc_messages.raises s; self#html_of_text b t; bs b "</div>\n" | _ -> bs b "<div class=\"raisedexceptions\">"; bp b "<span class=\"raises\">%s</span><ul>" Odoc_messages.raises; List.iter (fun (ex, desc) -> bp b "<li><code>%s</code> " ex ; self#html_of_text b desc; bs b "</li>\n" ) l; bs b "</ul></div>\n" method html_of_author_list b l = match l with [] -> () | _ -> bp b "<div class=\"authors\">"; bp b "<b>%s:</b> " Odoc_messages.authors; self#html_of_text b [Odoc_info.Raw (String.concat ", " l)]; bs b "</div>\n" val mutable custom_functions = ([] : (string * custom_type) list) method private html_of_warning b t = bs b "<div class=\"warningbox\">"; self#html_of_text b t; bs b "</div>" method private html_of_custom_text b tag text = try match List.assoc tag custom_functions, text with | (Simple f, [Odoc_info.Raw s]) -> Buffer.add_string b (f s) | (Simple _, _) -> Odoc_info.warning (Printf.sprintf "custom tags (%s) must be followed by plain text." tag) | (Full f, _) -> f b text with Not_found -> Odoc_info.warning (Odoc_messages.tag_not_handled tag) method init_style = super#init_style; style <- style ^ "<script type=\"text/x-mathjax-config\">\n" ^ " MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$']]}});\n" ^ "</script>" ^ "<script type=\"text/javascript\"\n" ^ Printf.sprintf " src=\"%s/MathJax.js?config=TeX-AMS-MML_HTMLorMML\">\n" !mathjax_url ^ "</script>\n" method html_of_Latex b s = Buffer.add_string b s initializer tag_functions <- ("sundials", self#html_of_sundials) :: tag_functions; tag_functions <- ("profiler", self#html_of_profiler) :: tag_functions; tag_functions <- ("context", self#html_of_context) :: tag_functions; tag_functions <- ("cvode", self#html_of_cvode) :: tag_functions; tag_functions <- ("cvodes", self#html_of_cvodes) :: tag_functions; tag_functions <- ("cvodes_quad", self#html_of_cvodes_quad) :: tag_functions; tag_functions <- ("cvodes_sens", self#html_of_cvodes_sens) :: tag_functions; tag_functions <- ("cvodes_adj", self#html_of_cvodes_adj) :: tag_functions; tag_functions <- ("arkode", self#html_of_arkode) :: tag_functions; tag_functions <- ("arkode_ark", self#html_of_arkode_ark) :: tag_functions; tag_functions <- ("arkode_erk", self#html_of_arkode_erk) :: tag_functions; tag_functions <- ("arkode_mri", self#html_of_arkode_mri) :: tag_functions; tag_functions <- ("arkode_bt", self#html_of_arkode_bt) :: tag_functions; tag_functions <- ("arkode_user",self#html_of_arkode_user) :: tag_functions; tag_functions <- ("arkode_precond",self#html_of_arkode_precond) :: tag_functions; tag_functions <- ("arkode_innerstepper",self#html_of_arkode_innerstepper) :: tag_functions; tag_functions <- ("arkode_coupling",self#html_of_arkode_coupling) :: tag_functions; tag_functions <- ("ida", self#html_of_ida) :: tag_functions; tag_functions <- ("idas", self#html_of_idas) :: tag_functions; tag_functions <- ("idas_quad", self#html_of_idas_quad) :: tag_functions; tag_functions <- ("idas_sens", self#html_of_idas_sens) :: tag_functions; tag_functions <- ("idas_adj", self#html_of_idas_adj) :: tag_functions; tag_functions <- ("kinsol", self#html_of_kinsol) :: tag_functions; tag_functions <- ("nvector", self#html_of_nvector) :: tag_functions; tag_functions <- ("matrix", self#html_of_matrix) :: tag_functions; tag_functions <- ("matrix_data", self#html_of_matrix_data) :: tag_functions; tag_functions <- ("linsol", self#html_of_linsol) :: tag_functions; tag_functions <- ("linsol_module", self#html_of_linsol_module) :: tag_functions; tag_functions <- ("nonlinsol", self#html_of_nonlinsol) :: tag_functions; tag_functions <- ("nonlinsol_module", self#html_of_nonlinsol_module) :: tag_functions; tag_functions <- ("nodoc", self#html_of_missing) :: tag_functions; custom_functions <- ("div", Simple self#html_of_div) :: ("var", Simple self#html_of_var) :: ("color", Simple self#html_of_color) :: ("img", Simple self#html_of_img) :: ("cconst", Simple self#html_of_cconst) :: ("openfile", Simple self#html_of_openfile) :: ("warning", Full self#html_of_warning) :: custom_functions end end let _ = Odoc_html.charset := "utf-8" let option_sundials_doc_root = ("-sundials-doc-root", Arg.String (fun d -> sundials_doc_root := d), "<dir> specify the root url for the Sundials documentation.") let option_mathjax_url = ("-mathjax", Arg.String (fun d -> mathjax_url := d), "<url> specify the root url for MathJax.") let _ = Odoc_args.add_option option_sundials_doc_root; Odoc_args.add_option option_mathjax_url; Odoc_args.extend_html_generator (module Generator : Odoc_gen.Html_functor)
fbca2a7bc411c5fff8a679344844760c459e06d82f4859649b18a0a49bbaacd0
djblue/portal
main.clj
(ns portal.main (:require [clojure.edn :as edn] [clojure.java.io :as io] [portal.api :as p]) (:import [java.io PushbackReader])) (defn- lazy-fn [symbol] (fn [& args] (apply (requiring-resolve symbol) args))) (def ^:private read-json (lazy-fn 'portal.runtime.json/read-stream)) (def ^:private read-yaml (lazy-fn 'clj-yaml.core/parse-string)) (def ^:private transit-read (lazy-fn 'cognitect.transit/read)) (def ^:private transit-reader (lazy-fn 'cognitect.transit/reader)) (defn- read-transit [in] (transit-read (transit-reader in :json))) (defn- read-edn [reader] (with-open [in (PushbackReader. reader)] (edn/read in))) (defn -main [& args] (let [[input-format] args in (case input-format "json" (-> System/in io/reader read-json) "yaml" (-> System/in io/reader slurp read-yaml) "edn" (-> System/in io/reader read-edn) "transit" (-> System/in read-transit))] (reset! (p/open) in) (.addShutdownHook (Runtime/getRuntime) (Thread. #(p/close))) (println "Press CTRL+C to exit") @(promise)))
null
https://raw.githubusercontent.com/djblue/portal/435dfe172e4cec31d95ee17c8688750a61101907/src/portal/main.clj
clojure
(ns portal.main (:require [clojure.edn :as edn] [clojure.java.io :as io] [portal.api :as p]) (:import [java.io PushbackReader])) (defn- lazy-fn [symbol] (fn [& args] (apply (requiring-resolve symbol) args))) (def ^:private read-json (lazy-fn 'portal.runtime.json/read-stream)) (def ^:private read-yaml (lazy-fn 'clj-yaml.core/parse-string)) (def ^:private transit-read (lazy-fn 'cognitect.transit/read)) (def ^:private transit-reader (lazy-fn 'cognitect.transit/reader)) (defn- read-transit [in] (transit-read (transit-reader in :json))) (defn- read-edn [reader] (with-open [in (PushbackReader. reader)] (edn/read in))) (defn -main [& args] (let [[input-format] args in (case input-format "json" (-> System/in io/reader read-json) "yaml" (-> System/in io/reader slurp read-yaml) "edn" (-> System/in io/reader read-edn) "transit" (-> System/in read-transit))] (reset! (p/open) in) (.addShutdownHook (Runtime/getRuntime) (Thread. #(p/close))) (println "Press CTRL+C to exit") @(promise)))
605fc6118eec098b4c7abb6602230a5f8d4e559a3b773d640f269ce822aef7e3
viebel/klipse-repl
eval.clj
(ns klipse-repl.eval (:require [clojure.string :as string] [gadjett.core :refer [dbg]] [clojure.test :refer [with-test is]])) (defn repl-init "Initialize repl in user namespace and make standard repl requires." [{:keys [cool-forms]}] (in-ns 'user) (require '[klipse-repl.eval :refer [doc]]) (require '[clojure.repl :refer (source apropos dir pst find-doc)]) (require '[clojure.java.javadoc :refer (javadoc)]) (require '[clojure.pprint :refer (pp pprint)]) (when cool-forms (require '[gadjett.core :refer [dbg dbgdef]]) (require '[klipse-repl.deps :refer [refresh-classpath add-deps]]) (require '[klipse-repl.classpath :refer [classpath]]) (println " Debugging: (dbg an-expression)") (println " (dbgdef an-expression)") (println " Classpath: (classpath)") (println " (refresh-classpath)") (println " (add-deps deps-coordinates)"))) (defn ns-unmap-in-current-ns [name] (ns-unmap (symbol (str *ns*)) name)) (comment (ns-unmap-in-current-ns 'foo)) (with-test (defn eval-defn [[_ func-name :as form]] (try (let [func-exists? (resolve func-name) created-or-updated (if func-exists? "Updated" "Created") res (eval form)] (symbol (str created-or-updated " function " (:name (meta res)) " " (:arglists (meta res))))) (catch Exception e (println "an exception occured" e) (eval form)))) (is (do (ns-unmap-in-current-ns 'foo) (= (eval-defn '(defn foo [])) (symbol "Function foo created"))) )) (defn eval-def [form] (deref (eval form))) (comment (symbol (str *ns*))) (with-test (defn custom-eval [x] (if (seq? x) (cond (= 'defn (first x)) (eval-defn x) (= 'def (first x)) (eval-def x) :else (eval x)) (eval x))) (is (= (custom-eval '(def foo 42)) 42)) (is (= (do (ns-unmap-in-current-ns 'foo) (custom-eval '(defn foo []))) (symbol "Function foo created"))) (is (= (do (ns-unmap-in-current-ns 'foo) (custom-eval '(defn foo [])) (custom-eval '(defn foo []))) (symbol (->> "Function foo updated"))))) (defn safe-resolve [s] (some-> s symbol (-> resolve (try (catch Throwable e nil))))) (def safe-meta (comp meta safe-resolve)) (defn resolve-meta [var-str] (or (safe-meta var-str) (when-let [ns' (some-> var-str symbol find-ns)] (assoc (meta ns') :ns var-str)))) (defn url-for [ns name] (cond (.startsWith (str ns) "clojure.") (cond-> "/" ns (str ns) name (str "/" (string/replace name #"\?$" "_q"))) :else nil)) (defn doc-url [var-str] (when-let [{:keys [ns name]} (resolve-meta var-str)] (url-for (str ns) (str name)))) (defn online-doc [var-str] (when-let [url (doc-url var-str)] (do (println "-------------------------") (println "Online doc:" url)))) (defmacro doc "Prints documentation for a var or special form given its name, or for a spec if given a keyword" [var] `(do (clojure.repl/doc ~var) (online-doc ~(str var)))) (comment (doc mape) (doc-url "clojure.string/replace") (resolve-meta "clojure.string/replace"))
null
https://raw.githubusercontent.com/viebel/klipse-repl/8acc1ffaee520c991f834af5a0827286884aa8c9/src/klipse_repl/eval.clj
clojure
(ns klipse-repl.eval (:require [clojure.string :as string] [gadjett.core :refer [dbg]] [clojure.test :refer [with-test is]])) (defn repl-init "Initialize repl in user namespace and make standard repl requires." [{:keys [cool-forms]}] (in-ns 'user) (require '[klipse-repl.eval :refer [doc]]) (require '[clojure.repl :refer (source apropos dir pst find-doc)]) (require '[clojure.java.javadoc :refer (javadoc)]) (require '[clojure.pprint :refer (pp pprint)]) (when cool-forms (require '[gadjett.core :refer [dbg dbgdef]]) (require '[klipse-repl.deps :refer [refresh-classpath add-deps]]) (require '[klipse-repl.classpath :refer [classpath]]) (println " Debugging: (dbg an-expression)") (println " (dbgdef an-expression)") (println " Classpath: (classpath)") (println " (refresh-classpath)") (println " (add-deps deps-coordinates)"))) (defn ns-unmap-in-current-ns [name] (ns-unmap (symbol (str *ns*)) name)) (comment (ns-unmap-in-current-ns 'foo)) (with-test (defn eval-defn [[_ func-name :as form]] (try (let [func-exists? (resolve func-name) created-or-updated (if func-exists? "Updated" "Created") res (eval form)] (symbol (str created-or-updated " function " (:name (meta res)) " " (:arglists (meta res))))) (catch Exception e (println "an exception occured" e) (eval form)))) (is (do (ns-unmap-in-current-ns 'foo) (= (eval-defn '(defn foo [])) (symbol "Function foo created"))) )) (defn eval-def [form] (deref (eval form))) (comment (symbol (str *ns*))) (with-test (defn custom-eval [x] (if (seq? x) (cond (= 'defn (first x)) (eval-defn x) (= 'def (first x)) (eval-def x) :else (eval x)) (eval x))) (is (= (custom-eval '(def foo 42)) 42)) (is (= (do (ns-unmap-in-current-ns 'foo) (custom-eval '(defn foo []))) (symbol "Function foo created"))) (is (= (do (ns-unmap-in-current-ns 'foo) (custom-eval '(defn foo [])) (custom-eval '(defn foo []))) (symbol (->> "Function foo updated"))))) (defn safe-resolve [s] (some-> s symbol (-> resolve (try (catch Throwable e nil))))) (def safe-meta (comp meta safe-resolve)) (defn resolve-meta [var-str] (or (safe-meta var-str) (when-let [ns' (some-> var-str symbol find-ns)] (assoc (meta ns') :ns var-str)))) (defn url-for [ns name] (cond (.startsWith (str ns) "clojure.") (cond-> "/" ns (str ns) name (str "/" (string/replace name #"\?$" "_q"))) :else nil)) (defn doc-url [var-str] (when-let [{:keys [ns name]} (resolve-meta var-str)] (url-for (str ns) (str name)))) (defn online-doc [var-str] (when-let [url (doc-url var-str)] (do (println "-------------------------") (println "Online doc:" url)))) (defmacro doc "Prints documentation for a var or special form given its name, or for a spec if given a keyword" [var] `(do (clojure.repl/doc ~var) (online-doc ~(str var)))) (comment (doc mape) (doc-url "clojure.string/replace") (resolve-meta "clojure.string/replace"))
9afb13e56c1f79e84c1aeaff55c7e044328c50ae25b79014edd1291842e6455f
kahua/Kahua
spvr.scm
-*- coding : utf-8 ; mode : scheme -*- ;; test supervisor scripts. ;; this test isn't for modules, but for actual scripts. (use gauche.test) (use gauche.process) (use gauche.net) (use file.util) (use text.tree) (use sxml.ssax) (use sxml.sxpath) (use kahua.config) (use kahua.gsid) (use kahua.test.util) (test-start "supervisor script") (define *site* "_site") (define-constant *prompt* "kahua> ") (sys-system #`"rm -rf ,|*site*|") (kahua-site-create *site*) (for-each make-directory* (list #`",|*site*|/app/lister" #`",|*site*|/app/greeting" #`",|*site*|/app/hello" #`",|*site*|/app/ss1" #`",|*site*|/app/ss2")) (copy-file "../plugins/allow-module.scm" #`",|*site*|/plugins/allow-module.scm") (for-each (apply$ (lambda (m d) (copy-file #`",|m|.kahua" #`",|*site*|/app/,|d|/,|d|.kahua"))) '(("lister" "lister") ("greeting" "greeting") ("hello-world" "hello") ("sharedstate" "ss1") ("sharedstate" "ss2"))) (define *spvr* #f) (define *gsid* #f) (define *app-servers* #`",|*site*|/app-servers") (kahua-common-init *site* #f) ;; some utilities (define (send-message out header body) (write header out) (newline out) (write body out) (newline out) (flush out)) (define (receive-message in) (let* ((header (read in)) (body (read in))) (values header body))) (define (send&receive header body receiver) (call-with-client-socket (make-client-socket (supervisor-sockaddr (kahua-sockbase))) (lambda (in out) (send-message out header body) (call-with-values (cut receive-message in) receiver)))) ;; prepare app-servers file (with-output-to-file *app-servers* (lambda () (write '((hello :run-by-default 1) (greeting :run-by-default 0) (lister :run-by-default 0))))) ;;----------------------------------------------------------- (test-section "basic functionality") (test* "start" #t (receive (p prompt) (kahua:invoke&wait `("../src/kahua-spvr" "--test" "-S" ,*site* "-i") :prompt *prompt*) (set! *spvr* p) (let1 path #`",|*site*|/socket/kahua" (and (string=? *prompt* (string-incomplete->complete prompt)) (file-exists? path) (or (eq? (file-type path) 'socket) (eq? (file-type path) 'fifo)))))) (test* "listener" #t (let ((out (process-input *spvr*)) (in (process-output *spvr*))) (write '(is-a? *spvr* <kahua-spvr>) out) (newline out) (flush out) (read in))) ;; result ;;----------------------------------------------------------- (test* "greeting service via kahua-server (start)" #t (let* ((out (process-input *spvr*)) (in (process-output *spvr*)) ) (read in) ;; prompt (write '(begin (run-worker *spvr* 'greeting) #t) out) (newline out) (flush out) (read in))) ;; result (test* "hello-world session initiation" #f ;; non-sense (send&receive '(("x-kahua-worker" "greeting")) "greeting" (lambda (header body) (receive (stat-gsid cont-gsid) (get-gsid-from-header header) (set! *gsid* (list stat-gsid cont-gsid)) (and (string? stat-gsid) (string? cont-gsid) body))))) ;;----------------------------------------------------------- (test-section "spvr protocol") (test* "ls" '(hello greeting) (send&receive '(("x-kahua-worker" "spvr")) '(ls) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body)))) (test* "types" '(hello greeting lister) (send&receive '(("x-kahua-worker" "spvr")) '(types) (lambda (header body) body))) (test* "kill" '(greeting) (send&receive '(("x-kahua-worker" "spvr")) '(kill hello) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body)))) (with-output-to-file *app-servers* (lambda () (write '()))) (test* "reload" '() (send&receive '(("x-kahua-worker" "spvr")) '(reload) (lambda (header body) body))) (test* "types after reload" '() (send&receive '(("x-kahua-worker" "spvr")) '(types) (lambda (header body) body))) (with-output-to-file *app-servers* (lambda () (write '(a b)))) (test* "reload malformed" #f (send&receive '(("x-kahua-worker" "spvr")) '(reload) (lambda (header body) body))) (with-output-to-file *app-servers* (lambda () (write '((lister :run-by-default 0))))) (test* "reload again" '(lister) (send&receive '(("x-kahua-worker" "spvr")) '(reload) (lambda (header body) body))) (with-output-to-file *app-servers* (lambda () (write '((lister :run-by-default 2))))) (test* "reload and check kicked" '(greeting lister lister) (begin (send&receive '(("x-kahua-worker" "spvr")) '(reload) (lambda (header body) body)) (send&receive `(("x-kahua-worker" "spvr")) '(ls) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body))))) (test* "run" '(lister) (send&receive '(("x-kahua-worker" "spvr")) '(run lister) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body)))) (test* "run" '(greeting lister lister lister) (send&receive '(("x-kahua-worker" "spvr")) '(ls) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body)))) ;;----------------------------------------------------------- (test-section "sharing state") (with-output-to-file *app-servers* (lambda () (write '((ss1 :run-by-default 1) (ss2 :run-by-default 1))))) (test* "start ss1&ss2" '(ss1 ss2) (begin (send&receive '(("x-kahua-worker" "spvr")) '(kill *) (lambda _ #f)) (send&receive '(("x-kahua-worker" "spvr")) '(reload) (lambda _ #f)) (send&receive '(("x-kahua-worker" "spvr")) '(ls) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body))))) (let () (define *sgsid* #f) (define (get-ss-li body) ((sxpath '(// li)) (call-with-input-string (tree->string body) (cut ssax:xml->sxml <> '())))) (test* "show ss1" () (send&receive '(("x-kahua-worker" "ss1")) '() (lambda (header body) (receive (sgsid cgsid) (get-gsid-from-header header) (set! *sgsid* sgsid)) (get-ss-li body)))) (test* "set ss1" '((li "foo=bar")) (send&receive `(("x-kahua-worker" "ss1") ("x-kahua-cgsid" "set") ("x-kahua-sgsid" ,*sgsid*) ("x-kahua-path-info" ("kahua.cgi" "set" "foo" "bar"))) '() (lambda (header body) (get-ss-li body)))) (test* "show ss2" '((li "foo=bar")) (send&receive `(("x-kahua-worker" "ss2") ("x-kahua-sgsid" ,*sgsid*)) '() (lambda (header body) (get-ss-li body)))) (test* "set ss2" '((li "foo=baz")) (send&receive `(("x-kahua-worker" "ss2") ("x-kahua-cgsid" "set") ("x-kahua-sgsid" ,*sgsid*) ("x-kahua-path-info" ("kahua.cgi" "set" "foo" "baz"))) '() (lambda (header body) (get-ss-li body)))) (test* "set/show ss1" '((li "boo=bee") (li "foo=baz")) (send&receive `(("x-kahua-worker" "ss1") ("x-kahua-cgsid" "set") ("x-kahua-sgsid" ,*sgsid*) ("x-kahua-path-info" ("kahua.cgi" "set" "boo" "bee"))) '() (lambda (header body) (get-ss-li body)))) (test* "show ss2" '((li "boo=bee") (li "foo=baz")) (send&receive `(("x-kahua-worker" "ss2") ("x-kahua-sgsid" ,*sgsid*)) '() (lambda (header body) (get-ss-li body)))) ) ;; ----------------------------------------------------------- (test* "shutdown" '() (begin (process-send-signal *spvr* SIGTERM) (process-wait *spvr*) (directory-list #`",|*site*|/socket" :children? #t))) (test-end)
null
https://raw.githubusercontent.com/kahua/Kahua/41fa415511c54beab4922820989faf7ea71d2818/test/spvr.scm
scheme
mode : scheme -*- test supervisor scripts. this test isn't for modules, but for actual scripts. some utilities prepare app-servers file ----------------------------------------------------------- result ----------------------------------------------------------- prompt result non-sense ----------------------------------------------------------- ----------------------------------------------------------- -----------------------------------------------------------
(use gauche.test) (use gauche.process) (use gauche.net) (use file.util) (use text.tree) (use sxml.ssax) (use sxml.sxpath) (use kahua.config) (use kahua.gsid) (use kahua.test.util) (test-start "supervisor script") (define *site* "_site") (define-constant *prompt* "kahua> ") (sys-system #`"rm -rf ,|*site*|") (kahua-site-create *site*) (for-each make-directory* (list #`",|*site*|/app/lister" #`",|*site*|/app/greeting" #`",|*site*|/app/hello" #`",|*site*|/app/ss1" #`",|*site*|/app/ss2")) (copy-file "../plugins/allow-module.scm" #`",|*site*|/plugins/allow-module.scm") (for-each (apply$ (lambda (m d) (copy-file #`",|m|.kahua" #`",|*site*|/app/,|d|/,|d|.kahua"))) '(("lister" "lister") ("greeting" "greeting") ("hello-world" "hello") ("sharedstate" "ss1") ("sharedstate" "ss2"))) (define *spvr* #f) (define *gsid* #f) (define *app-servers* #`",|*site*|/app-servers") (kahua-common-init *site* #f) (define (send-message out header body) (write header out) (newline out) (write body out) (newline out) (flush out)) (define (receive-message in) (let* ((header (read in)) (body (read in))) (values header body))) (define (send&receive header body receiver) (call-with-client-socket (make-client-socket (supervisor-sockaddr (kahua-sockbase))) (lambda (in out) (send-message out header body) (call-with-values (cut receive-message in) receiver)))) (with-output-to-file *app-servers* (lambda () (write '((hello :run-by-default 1) (greeting :run-by-default 0) (lister :run-by-default 0))))) (test-section "basic functionality") (test* "start" #t (receive (p prompt) (kahua:invoke&wait `("../src/kahua-spvr" "--test" "-S" ,*site* "-i") :prompt *prompt*) (set! *spvr* p) (let1 path #`",|*site*|/socket/kahua" (and (string=? *prompt* (string-incomplete->complete prompt)) (file-exists? path) (or (eq? (file-type path) 'socket) (eq? (file-type path) 'fifo)))))) (test* "listener" #t (let ((out (process-input *spvr*)) (in (process-output *spvr*))) (write '(is-a? *spvr* <kahua-spvr>) out) (newline out) (flush out) (test* "greeting service via kahua-server (start)" #t (let* ((out (process-input *spvr*)) (in (process-output *spvr*)) ) (write '(begin (run-worker *spvr* 'greeting) #t) out) (newline out) (flush out) (send&receive '(("x-kahua-worker" "greeting")) "greeting" (lambda (header body) (receive (stat-gsid cont-gsid) (get-gsid-from-header header) (set! *gsid* (list stat-gsid cont-gsid)) (and (string? stat-gsid) (string? cont-gsid) body))))) (test-section "spvr protocol") (test* "ls" '(hello greeting) (send&receive '(("x-kahua-worker" "spvr")) '(ls) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body)))) (test* "types" '(hello greeting lister) (send&receive '(("x-kahua-worker" "spvr")) '(types) (lambda (header body) body))) (test* "kill" '(greeting) (send&receive '(("x-kahua-worker" "spvr")) '(kill hello) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body)))) (with-output-to-file *app-servers* (lambda () (write '()))) (test* "reload" '() (send&receive '(("x-kahua-worker" "spvr")) '(reload) (lambda (header body) body))) (test* "types after reload" '() (send&receive '(("x-kahua-worker" "spvr")) '(types) (lambda (header body) body))) (with-output-to-file *app-servers* (lambda () (write '(a b)))) (test* "reload malformed" #f (send&receive '(("x-kahua-worker" "spvr")) '(reload) (lambda (header body) body))) (with-output-to-file *app-servers* (lambda () (write '((lister :run-by-default 0))))) (test* "reload again" '(lister) (send&receive '(("x-kahua-worker" "spvr")) '(reload) (lambda (header body) body))) (with-output-to-file *app-servers* (lambda () (write '((lister :run-by-default 2))))) (test* "reload and check kicked" '(greeting lister lister) (begin (send&receive '(("x-kahua-worker" "spvr")) '(reload) (lambda (header body) body)) (send&receive `(("x-kahua-worker" "spvr")) '(ls) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body))))) (test* "run" '(lister) (send&receive '(("x-kahua-worker" "spvr")) '(run lister) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body)))) (test* "run" '(greeting lister lister lister) (send&receive '(("x-kahua-worker" "spvr")) '(ls) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body)))) (test-section "sharing state") (with-output-to-file *app-servers* (lambda () (write '((ss1 :run-by-default 1) (ss2 :run-by-default 1))))) (test* "start ss1&ss2" '(ss1 ss2) (begin (send&receive '(("x-kahua-worker" "spvr")) '(kill *) (lambda _ #f)) (send&receive '(("x-kahua-worker" "spvr")) '(reload) (lambda _ #f)) (send&receive '(("x-kahua-worker" "spvr")) '(ls) (lambda (header body) (map (cut get-keyword :worker-type <> #f) body))))) (let () (define *sgsid* #f) (define (get-ss-li body) ((sxpath '(// li)) (call-with-input-string (tree->string body) (cut ssax:xml->sxml <> '())))) (test* "show ss1" () (send&receive '(("x-kahua-worker" "ss1")) '() (lambda (header body) (receive (sgsid cgsid) (get-gsid-from-header header) (set! *sgsid* sgsid)) (get-ss-li body)))) (test* "set ss1" '((li "foo=bar")) (send&receive `(("x-kahua-worker" "ss1") ("x-kahua-cgsid" "set") ("x-kahua-sgsid" ,*sgsid*) ("x-kahua-path-info" ("kahua.cgi" "set" "foo" "bar"))) '() (lambda (header body) (get-ss-li body)))) (test* "show ss2" '((li "foo=bar")) (send&receive `(("x-kahua-worker" "ss2") ("x-kahua-sgsid" ,*sgsid*)) '() (lambda (header body) (get-ss-li body)))) (test* "set ss2" '((li "foo=baz")) (send&receive `(("x-kahua-worker" "ss2") ("x-kahua-cgsid" "set") ("x-kahua-sgsid" ,*sgsid*) ("x-kahua-path-info" ("kahua.cgi" "set" "foo" "baz"))) '() (lambda (header body) (get-ss-li body)))) (test* "set/show ss1" '((li "boo=bee") (li "foo=baz")) (send&receive `(("x-kahua-worker" "ss1") ("x-kahua-cgsid" "set") ("x-kahua-sgsid" ,*sgsid*) ("x-kahua-path-info" ("kahua.cgi" "set" "boo" "bee"))) '() (lambda (header body) (get-ss-li body)))) (test* "show ss2" '((li "boo=bee") (li "foo=baz")) (send&receive `(("x-kahua-worker" "ss2") ("x-kahua-sgsid" ,*sgsid*)) '() (lambda (header body) (get-ss-li body)))) ) (test* "shutdown" '() (begin (process-send-signal *spvr* SIGTERM) (process-wait *spvr*) (directory-list #`",|*site*|/socket" :children? #t))) (test-end)
e7a45c3fa89e70e453654099cd9b19bc4029591d28add6b23df1a828fe59ad20
ocsigen/eliomlang
eliom_unwrap.ml
Ocsigen * * Copyright ( C ) 2011 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2011 Pierre Chambart * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) TODO : implement with WeakMap when standardised : class type [ ' a,'b ] weakMap = object method get : ' a - > ' b Js.optdef Js.meth method set : ' a - > ' b - > unit Js.meth method has : ' a - > bool Js.t Js.meth end let weakMap : ( ' a,'b ) weakMap = Js.Unsafe.global##_WeakMap let map : ( Obj.t , Obj.t ) weakMap weakMap ( ) let get_obj_copy map o = Js . Optdef.to_option ( ) ) let set_obj_copy map o c = map##set(o , c ) class type ['a,'b] weakMap = object method get : 'a -> 'b Js.optdef Js.meth method set : 'a -> 'b -> unit Js.meth method has : 'a -> bool Js.t Js.meth end let weakMap : ('a,'b) weakMap Js.t Js.constr = Js.Unsafe.global##_WeakMap let map : (Obj.t,Obj.t) weakMap Js.t = jsnew weakMap () let get_obj_copy map o = Js.Optdef.to_option ( map##get(o) ) let set_obj_copy map o c = map##set(o,c) *) (* let section = Lwt_log_js.Section.make "eliom.unwrap" *) (* let log_section = section *) let _ = Lwt_log_js . Section.set_level section Lwt_log_js . Info let option_map f = function | None -> None | Some x -> Some (f x) module Mark : sig type t end = struct type t = string end (* XXX must be the same as in Ocsigen_wrap *) type unwrap_id = int let id_of_int x = x type unwrapper = { id : unwrap_id; mutable umark : Mark.t; } let unwrap_table : (Obj.t -> Obj.t option) Js.js_array Js.t = new%js Js.array_empty (* table containing all the unwrapping functions referenced by their id *) type occurrence = { parent : Obj.t; field : int } let register_unwrapper' id f = if Js.Optdef.test (Js.array_get unwrap_table id) then failwith (Printf.sprintf ">> the unwrapper id %i is already registered" id); let f x = option_map Obj.repr (f (Obj.obj x)) in (* Store unwrapper *) Js.array_set unwrap_table id f let register_unwrapper id f = register_unwrapper' id (fun x -> Some (f x)) let apply_unwrapper unwrapper v = Js.Optdef.case (Js.array_get unwrap_table unwrapper.id) (fun () -> None) (* Use late unwrapping! *) (fun f -> f v) let late_unwrap_value old_value new_value = let old_value = Obj.repr old_value in List.iter (fun { parent; field } -> Js.Unsafe.set parent field new_value) (Obj.obj (Obj.field (Obj.field old_value (Obj.size old_value - 1)) 2)) let raw_unmarshal_and_unwrap : (unwrapper -> _ -> _ option) -> string -> int -> _ = Js.Unsafe.variable "caml_unwrap_value_from_string" let unwrap s i = (* if !Eliom_config.debug_timings then *) (* Firebug.console##time *) (* (Js.string "unwrap"); *) let res = raw_unmarshal_and_unwrap apply_unwrapper s i in (* if !Eliom_config.debug_timings then *) (* Firebug.console##timeEnd *) (* (Js.string "unwrap"); *) res let unwrap_js s = unwrap (Js.to_bytestring s) 0
null
https://raw.githubusercontent.com/ocsigen/eliomlang/42e55856574e058caca191e50edcb0023900b664/runtime/client/eliom_unwrap.ml
ocaml
let section = Lwt_log_js.Section.make "eliom.unwrap" let log_section = section XXX must be the same as in Ocsigen_wrap table containing all the unwrapping functions referenced by their id Store unwrapper Use late unwrapping! if !Eliom_config.debug_timings then Firebug.console##time (Js.string "unwrap"); if !Eliom_config.debug_timings then Firebug.console##timeEnd (Js.string "unwrap");
Ocsigen * * Copyright ( C ) 2011 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2011 Pierre Chambart * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) TODO : implement with WeakMap when standardised : class type [ ' a,'b ] weakMap = object method get : ' a - > ' b Js.optdef Js.meth method set : ' a - > ' b - > unit Js.meth method has : ' a - > bool Js.t Js.meth end let weakMap : ( ' a,'b ) weakMap = Js.Unsafe.global##_WeakMap let map : ( Obj.t , Obj.t ) weakMap weakMap ( ) let get_obj_copy map o = Js . Optdef.to_option ( ) ) let set_obj_copy map o c = map##set(o , c ) class type ['a,'b] weakMap = object method get : 'a -> 'b Js.optdef Js.meth method set : 'a -> 'b -> unit Js.meth method has : 'a -> bool Js.t Js.meth end let weakMap : ('a,'b) weakMap Js.t Js.constr = Js.Unsafe.global##_WeakMap let map : (Obj.t,Obj.t) weakMap Js.t = jsnew weakMap () let get_obj_copy map o = Js.Optdef.to_option ( map##get(o) ) let set_obj_copy map o c = map##set(o,c) *) let _ = Lwt_log_js . Section.set_level section Lwt_log_js . Info let option_map f = function | None -> None | Some x -> Some (f x) module Mark : sig type t end = struct type t = string end type unwrap_id = int let id_of_int x = x type unwrapper = { id : unwrap_id; mutable umark : Mark.t; } let unwrap_table : (Obj.t -> Obj.t option) Js.js_array Js.t = new%js Js.array_empty type occurrence = { parent : Obj.t; field : int } let register_unwrapper' id f = if Js.Optdef.test (Js.array_get unwrap_table id) then failwith (Printf.sprintf ">> the unwrapper id %i is already registered" id); let f x = option_map Obj.repr (f (Obj.obj x)) in Js.array_set unwrap_table id f let register_unwrapper id f = register_unwrapper' id (fun x -> Some (f x)) let apply_unwrapper unwrapper v = Js.Optdef.case (Js.array_get unwrap_table unwrapper.id) (fun f -> f v) let late_unwrap_value old_value new_value = let old_value = Obj.repr old_value in List.iter (fun { parent; field } -> Js.Unsafe.set parent field new_value) (Obj.obj (Obj.field (Obj.field old_value (Obj.size old_value - 1)) 2)) let raw_unmarshal_and_unwrap : (unwrapper -> _ -> _ option) -> string -> int -> _ = Js.Unsafe.variable "caml_unwrap_value_from_string" let unwrap s i = let res = raw_unmarshal_and_unwrap apply_unwrapper s i in res let unwrap_js s = unwrap (Js.to_bytestring s) 0
fa1a06041b8ea03aaa8817aec640cc63472ce9a3f8ce66a7a93438dc8af4f416
nasser/magic
novel.clj
;; a place for new ideas (ns magic.analyzer.novel (:require [magic.analyzer.analyze-host-forms :as host])) (def operators '{++ op_Increment -- op_Decrement ; - op_UnaryNegation ; + op_UnaryPlus ! op_LogicalNot |~| op_OnesComplement / op_Division % op_Modulus * op_Multiply + op_Addition - op_Subtraction << op_LeftShift >> op_RightShift > op_GreaterThan < op_LessThan >= op_GreaterThanOrEqual <= op_LessThanOrEqual == op_Equality != op_Inequality & op_BitwiseAnd |^| op_ExclusiveOr ; | op_BitwiseOr }) (defn csharp-operators "Analyze (Foo/+ bar) into (Foo/op_Addition bar)" {:pass-info {:walk :post :depends #{} :before #{#'host/analyze-byref #'host/analyze-type #'host/analyze-host-field #'host/analyze-constructor #'host/analyze-host-interop #'host/analyze-host-call}}} [{:keys [method target args op] :as ast}] (if (= :host-call op) (if-let [operator-method (operators method)] (assoc ast :method operator-method :novel true) ast) ast))
null
https://raw.githubusercontent.com/nasser/magic/7a46f773bc7785c82d9527d52c1a8c28ac16e195/src/magic/analyzer/novel.clj
clojure
a place for new ideas - op_UnaryNegation + op_UnaryPlus | op_BitwiseOr
(ns magic.analyzer.novel (:require [magic.analyzer.analyze-host-forms :as host])) (def operators '{++ op_Increment -- op_Decrement ! op_LogicalNot |~| op_OnesComplement / op_Division % op_Modulus * op_Multiply + op_Addition - op_Subtraction << op_LeftShift >> op_RightShift > op_GreaterThan < op_LessThan >= op_GreaterThanOrEqual <= op_LessThanOrEqual == op_Equality != op_Inequality & op_BitwiseAnd |^| op_ExclusiveOr }) (defn csharp-operators "Analyze (Foo/+ bar) into (Foo/op_Addition bar)" {:pass-info {:walk :post :depends #{} :before #{#'host/analyze-byref #'host/analyze-type #'host/analyze-host-field #'host/analyze-constructor #'host/analyze-host-interop #'host/analyze-host-call}}} [{:keys [method target args op] :as ast}] (if (= :host-call op) (if-let [operator-method (operators method)] (assoc ast :method operator-method :novel true) ast) ast))
c54cf95763886338929e5e822c03c7d3d776ed95e6ef0e935becb97c489bdc02
lojic/RacketChess
pgn.rkt
#lang racket (require "./board-slow.rkt" "./board.rkt" "./global.rkt" "./make-move.rkt" "./move.rkt" "./movement.rkt" "./piece.rkt") (provide make-pgn-move! pgn-load-file! pgn-move) Groups for pat - pawn : 2 - From file when capturing ( optional ) e.g. " cx " 3 - To file e.g. " e " 4 - To rank e.g. " 4 " ;; 5 - Promotion (optional) e.g. "=N" 6 - Check indication ( optional ) e.g. " + " or " # " (define pat-pawn #px"^([a-h]x)?([a-h])([1-8])(=[QBNR])?([+]|#)?$") Groups for pat - piece ;; 2 - Piece letter e.g. "Q" 3 - From file ( optional ) e.g. " c " 4 - From rank ( optional ) e.g. " 4 " ;; 5 - Capture e.g. "x" 6 - To file & rank e.g. " d5 " 7 - Check indication ( optional ) e.g. " + " or " # " (define pat-piece #px"^([KQBNR])([a-h])?([1-8])?(x)?([a-h][1-8])([+]|#)?$") Groups for pat - castle 2 - Castle move e.g. " O - O " or " O - O - O " 3 - Check indication (define pat-castle #px"^(O-O|O-O-O)([+]|#)?$") (define (pgn-load-file! b path) (printf "Loading file: ~a\n" path) (for ([ line (in-list (file->lines path)) ]) (printf "~a\n" line) (let* ([ groups (regexp-match #px"^([0-9]+)[.] ([-a-zQBNRO0-9]+) ([-a-zQBNRO0-9]+)$" line) ] [ n (second groups) ] [ wstr (third groups) ] [ bstr (fourth groups) ]) (let ([ m (pgn-move b wstr) ]) (printf "~a's move: " (if (is-whites-move? b) "White" "Black")) (print-move m) (make-move! b m)) (let ([ m (pgn-move b bstr) ]) (printf "~a's move: " (if (is-whites-move? b) "White" "Black")) (print-move m) (make-move! b m)) (printf "\n")))) (define (make-pgn-move! b str) (make-move! b (pgn-move b str)) (reset-depth! b)) (define (pgn-move b str) (define moves (generate-moves b)) (let loop ([ lst pat-func ]) (if (null? lst) (error "pgn-move: no pattern found for move") (match-let* ([ (list pat func) (car lst) ] [ groups (regexp-match pat str) ]) (if groups (let ([ m (func b (is-whites-move? b) (cdr groups)) ]) (if (member m moves) m (begin (println m) (for ([ mv (in-list moves) ]) (print-move mv)) (error "Move not in generated list")))) (loop (cdr lst))))))) (define (generate-moves b) (init-moves! b) (generate-moves! b) (let ([ result (append (get-moves b tactical-head tactical-moves) (get-moves b quiet-head quiet-moves)) ]) (init-moves! b) result)) (define (get-moves b head moves) (let loop ([ i 0 ][ result '() ]) (if (> i (head b)) result (loop (add1 i) (cons (vector-ref (moves b) i) result))))) ;; groups is of the form: ;; '(<from file> (optional) indication of source file when capturing e.g. "cx" ;; <to file> e.g. "d" < to rank > e.g. " 4 " ;; <promotion> (optional) e.g. "=N" ;; <check>) (optional) indication of check e.g. "+" or "#" for mate (define (pgn-pawn-move b white? groups) (define (get-promoted-piece letter) (if white? (match letter [ "Q" white-queen ] [ "B" white-bishop ] [ "N" white-knight ] [ "R" white-rook ]) (match letter [ "Q" black-queen ] [ "B" black-bishop ] [ "N" black-knight ] [ "R" black-rook ]))) (match-let* ([ (list from-file to-file to-rank promotion check) groups ] [ from-file (if (non-empty-string? from-file) (substring from-file 0 1) #f) ] [ to-rank (string->number to-rank) ] [ promoted (if (non-empty-string? promotion) (get-promoted-piece (substring promotion 1 2)) #f) ]) (if from-file (pgn-pawn-capture b white? from-file to-file to-rank promoted) (pgn-pawn-push b white? to-file to-rank promoted)))) (define (pgn-pawn-capture b white? from-file to-file to-rank promoted) (define squares (board-squares b)) (let* ([ dst-idx (pos->idx (format "~a~a" to-file to-rank)) ] [ dst (get-square squares dst-idx) ] [ src-rank (if white? (sub1 to-rank) (add1 to-rank)) ] [ src-idx (pos->idx (format "~a~a" from-file src-rank)) ] [ src (get-square squares src-idx) ]) (if (= dst empty-square) ;; En passant capture (let* ([ cap-idx (pos->idx (format "~a~a" to-file src-rank)) ] [ cap-piece (get-square squares cap-idx) ]) (create-move src src-idx dst-idx #:captured-piece cap-piece #:is-ep-capture? #t #:promoted-piece promoted)) ;; Regular capture (create-move src src-idx dst-idx #:captured-piece dst #:promoted-piece promoted)))) (define (pgn-pawn-push b white? to-file to-rank promoted) (define squares (board-squares b)) (let* ([ dst-idx (pos->idx (format "~a~a" to-file to-rank)) ] [ dst (get-square squares dst-idx) ] [ s1-idx (+ dst-idx (if white? south north)) ] [ s1 (get-square squares s1-idx) ] [ s1-ok (and (is-pawn? s1) (is-right-color-piece? s1 white?)) ] [ s2-idx (+ s1-idx (if white? south north)) ] [ s2 (get-square squares s2-idx) ] [ s2-ok (and (is-pawn? s2) (is-right-color-piece? s2 white?)) ]) (cond [ (and (not s1-ok) s2-ok) ;; Double push (create-move s2 s2-idx dst-idx) ] [ (and promoted s1-ok (= to-rank (if white? 8 1))) ;; Promotion push (create-move s1 s1-idx dst-idx #:promoted-piece promoted) ] [ s1-ok ;; Regular single push (create-move s1 s1-idx dst-idx) ] [ else (error "pgn-pawn-push: invalid move") ]))) (define (pgn-piece-move b white? groups) (match-let* ([ (list letter from-file from-rank capture to-file-rank check) groups ] [ (list src src-idx) (pgn-get-src-idx b letter white? from-file from-rank to-file-rank) ] [ dst-idx (pos->idx to-file-rank) ]) (if capture (let ([ piece (get-square (board-squares b) dst-idx) ]) (create-move src src-idx dst-idx #:captured-piece piece)) (create-move src src-idx dst-idx)))) ;; Return a list of the form: ;; (piece src-idx) (define (pgn-get-src-idx b letter white? from-file from-rank pos) (define (get-predicate) (let ([ color-pred? (if white? is-white? is-black?) ] [ piece-pred? (match letter [ "K" is-king? ] [ "Q" is-queen? ] [ "B" is-bishop? ] [ "N" is-knight? ] [ "R" is-rook? ]) ]) (λ (p) (and (color-pred? p) (piece-pred? p))))) (let* ([ lst (get-pieces-file-rank b (get-predicate)) ] [ len (length lst) ]) (cond [ (= len 1) (match-let ([ (list piece file rank) (car lst) ]) (list piece (pos->idx (format "~a~a" file rank)))) ] [ (> len 1) (disambiguate lst b from-file from-rank pos) ] [ else (error "pgn-get-src-idx: invalid move") ]))) (define (disambiguate lst b from-file from-rank pos) (define (file-ok? file) (if from-file (char=? file (string-ref from-file 0)) #t)) (define (rank-ok? rank) (if from-rank (char=? rank (string-ref from-rank 0)) #t)) (define (pred? tuple) (match-let ([ (list piece file rank) tuple ]) (and (file-ok? file) (rank-ok? rank) (member pos (targets b piece file rank))))) (let ([ lst (filter pred? lst) ]) (if (= 1 (length lst)) (match-let ([ (list piece file rank) (car lst) ]) (list piece (pos->idx (format "~a~a" file rank)))) (error "disambiguate: invalid move")))) ;; Not sure how I feel about this function. Due to the way ;; movement.rkt was coded for maximum efficiency, there isn't a "nice" ;; way to obtain the target squares for a particular piece. ;; The method employed here is to generate the moves into the two ;; vectors on the board, and then extract the information from them. (define (targets b piece file rank) (let ([ idx (pos->idx (format "~a~a" file rank)) ]) (init-moves! b) (cond [ (is-king? piece) (generate-king-moves! b idx piece) ] [ (is-queen? piece) (generate-queen-moves! b idx piece) ] [ (is-rook? piece) (generate-rook-moves! b idx piece) ] [ (is-bishop? piece) (generate-bishop-moves! b idx piece) ] [ (is-knight? piece) (generate-knight-moves! b idx piece) ] [ else (error "targets: invalid piece") ]) (let* ([ qhead (quiet-head b) ] [ qmoves (quiet-moves b) ] [ thead (tactical-head b) ] [ tmoves (tactical-moves b) ] [ targets (append (for/list ([ i (in-range (add1 qhead)) ]) (idx->pos (move-dst-idx (vector-ref qmoves i)))) (for/list ([ i (in-range (add1 thead)) ]) (idx->pos (move-dst-idx (vector-ref tmoves i))))) ]) (init-moves! b) targets))) Groups : 1 - Castle move e.g. " O - O " or " O - O - O " 2 - Check indication (define (pgn-castle-move b white? groups) (define squares (board-squares b)) (let* ([ castle (car groups) ] [ kingside? (cond [ (string=? castle "O-O") #t ] [ (string=? castle "O-O-O") #f ] [ else (error "pgn-castle-move: invalid castle spec") ]) ] [ king-idx (if white? (pos->idx "e1") (pos->idx "e8")) ] [ king (get-square squares king-idx) ] [ dst-pos (if white? (if kingside? "g1" "c1") (if kingside? "g8" "c8")) ] [ dst-idx (pos->idx dst-pos) ]) (create-move king king-idx dst-idx #:is-castle-queenside? (not kingside?) #:is-castle-kingside? kingside?))) (define pat-func (list (list pat-pawn pgn-pawn-move) (list pat-piece pgn-piece-move) (list pat-castle pgn-castle-move))) (define (pgn-castle-kingside b white?) (let-values ([ (src-idx dst-idx) (if white? (values (pos->idx "e1") (pos->idx "g1")) (values (pos->idx "e8") (pos->idx "g8"))) ]) (create-move (get-square (board-squares b) src-idx) src-idx dst-idx #:is-castle-kingside? #t))) (define (pgn-castle-queenside b white?) (let-values ([ (src-idx dst-idx) (if white? (values (pos->idx "e1") (pos->idx "c1")) (values (pos->idx "e8") (pos->idx "c8"))) ]) (create-move (get-square (board-squares b) src-idx) src-idx dst-idx #:is-castle-queenside? #t))) (module+ test (require rackunit) ;; ------------------------------------------------------------------------------------------ ;; regex patterns ;; ------------------------------------------------------------------------------------------ ;; pat-pawn --------------------------------------------------------------------------------- (for ([ pair (in-list '(("d4" (#f "d" "4" #f #f)) ("d4+" (#f "d" "4" #f "+")) ("d4#" (#f "d" "4" #f "#")) ("d8=N" (#f "d" "8" "=N" #f)) ("d8=Q+" (#f "d" "8" "=Q" "+")) ("d8=Q#" (#f "d" "8" "=Q" "#")) ("cxd4" ("cx" "d" "4" #f #f)) ("cxd4+" ("cx" "d" "4" #f "+")) ("cxd4#" ("cx" "d" "4" #f "#")) ("cxd8=B" ("cx" "d" "8" "=B" #f)) ("cxd8=R+" ("cx" "d" "8" "=R" "+")) ("cxd8=R#" ("cx" "d" "8" "=R" "#")))) ]) (match-let ([ (list str groups) pair ]) (check-equal? (regexp-match pat-pawn str) (cons str groups)))) ;; pat-piece -------------------------------------------------------------------------------- ;; pat-piece move (for ([ pair (in-list '(("Qd4" ("Q" #f #f #f "d4" #f)) ("Qd4+" ("Q" #f #f #f "d4" "+")) ("Qd4#" ("Q" #f #f #f "d4" "#")) ("Q3d4" ("Q" #f "3" #f "d4" #f)) ("Q3d4+" ("Q" #f "3" #f "d4" "+")) ("Q3d4#" ("Q" #f "3" #f "d4" "#")) ("Qcd4" ("Q" "c" #f #f "d4" #f)) ("Qcd4+" ("Q" "c" #f #f "d4" "+")) ("Qcd4#" ("Q" "c" #f #f "d4" "#")) ("Qc3d4" ("Q" "c" "3" #f "d4" #f)) ("Qc3d4+" ("Q" "c" "3" #f "d4" "+")) ("Qc3d4#" ("Q" "c" "3" #f "d4" "#")))) ]) (match-let ([ (list str groups) pair ]) (check-equal? (regexp-match pat-piece str) (cons str groups)))) ;; pat-piece capture (for ([ pair (in-list '(("Qxd4" ("Q" #f #f "x" "d4" #f)) ("Qxd4+" ("Q" #f #f "x" "d4" "+")) ("Qxd4#" ("Q" #f #f "x" "d4" "#")) ("Q3xd4" ("Q" #f "3" "x" "d4" #f)) ("Q3xd4+" ("Q" #f "3" "x" "d4" "+")) ("Q3xd4#" ("Q" #f "3" "x" "d4" "#")) ("Qcxd4" ("Q" "c" #f "x" "d4" #f)) ("Qcxd4+" ("Q" "c" #f "x" "d4" "+")) ("Qcxd4#" ("Q" "c" #f "x" "d4" "#")) ("Qc3xd4" ("Q" "c" "3" "x" "d4" #f)) ("Qc3xd4+" ("Q" "c" "3" "x" "d4" "+")) ("Qc3xd4#" ("Q" "c" "3" "x" "d4" "#")))) ]) (match-let ([ (list str groups) pair ]) (check-equal? (regexp-match pat-piece str) (cons str groups)))) ;; pat-castle ------------------------------------------------------------------------------- (for ([ pair (in-list '( ("O-O" ("O-O" #f)) ("O-O-O" ("O-O-O" #f)) ("O-O+" ("O-O" "+")) ("O-O-O+" ("O-O-O" "+")) ("O-O#" ("O-O" "#")) ("O-O-O#" ("O-O-O" "#")) )) ]) (match-let ([ (list str groups) pair ]) (check-equal? (regexp-match pat-castle str) (cons str groups)))) )
null
https://raw.githubusercontent.com/lojic/RacketChess/115ca7fecca9eaf31f9b2f4ef59935372c9920c8/src/pgn.rkt
racket
5 - Promotion (optional) e.g. "=N" 2 - Piece letter e.g. "Q" 5 - Capture e.g. "x" groups is of the form: '(<from file> (optional) indication of source file when capturing e.g. "cx" <to file> e.g. "d" <promotion> (optional) e.g. "=N" <check>) (optional) indication of check e.g. "+" or "#" for mate En passant capture Regular capture Double push Promotion push Regular single push Return a list of the form: (piece src-idx) Not sure how I feel about this function. Due to the way movement.rkt was coded for maximum efficiency, there isn't a "nice" way to obtain the target squares for a particular piece. vectors on the board, and then extract the information from them. ------------------------------------------------------------------------------------------ regex patterns ------------------------------------------------------------------------------------------ pat-pawn --------------------------------------------------------------------------------- pat-piece -------------------------------------------------------------------------------- pat-piece move pat-piece capture pat-castle -------------------------------------------------------------------------------
#lang racket (require "./board-slow.rkt" "./board.rkt" "./global.rkt" "./make-move.rkt" "./move.rkt" "./movement.rkt" "./piece.rkt") (provide make-pgn-move! pgn-load-file! pgn-move) Groups for pat - pawn : 2 - From file when capturing ( optional ) e.g. " cx " 3 - To file e.g. " e " 4 - To rank e.g. " 4 " 6 - Check indication ( optional ) e.g. " + " or " # " (define pat-pawn #px"^([a-h]x)?([a-h])([1-8])(=[QBNR])?([+]|#)?$") Groups for pat - piece 3 - From file ( optional ) e.g. " c " 4 - From rank ( optional ) e.g. " 4 " 6 - To file & rank e.g. " d5 " 7 - Check indication ( optional ) e.g. " + " or " # " (define pat-piece #px"^([KQBNR])([a-h])?([1-8])?(x)?([a-h][1-8])([+]|#)?$") Groups for pat - castle 2 - Castle move e.g. " O - O " or " O - O - O " 3 - Check indication (define pat-castle #px"^(O-O|O-O-O)([+]|#)?$") (define (pgn-load-file! b path) (printf "Loading file: ~a\n" path) (for ([ line (in-list (file->lines path)) ]) (printf "~a\n" line) (let* ([ groups (regexp-match #px"^([0-9]+)[.] ([-a-zQBNRO0-9]+) ([-a-zQBNRO0-9]+)$" line) ] [ n (second groups) ] [ wstr (third groups) ] [ bstr (fourth groups) ]) (let ([ m (pgn-move b wstr) ]) (printf "~a's move: " (if (is-whites-move? b) "White" "Black")) (print-move m) (make-move! b m)) (let ([ m (pgn-move b bstr) ]) (printf "~a's move: " (if (is-whites-move? b) "White" "Black")) (print-move m) (make-move! b m)) (printf "\n")))) (define (make-pgn-move! b str) (make-move! b (pgn-move b str)) (reset-depth! b)) (define (pgn-move b str) (define moves (generate-moves b)) (let loop ([ lst pat-func ]) (if (null? lst) (error "pgn-move: no pattern found for move") (match-let* ([ (list pat func) (car lst) ] [ groups (regexp-match pat str) ]) (if groups (let ([ m (func b (is-whites-move? b) (cdr groups)) ]) (if (member m moves) m (begin (println m) (for ([ mv (in-list moves) ]) (print-move mv)) (error "Move not in generated list")))) (loop (cdr lst))))))) (define (generate-moves b) (init-moves! b) (generate-moves! b) (let ([ result (append (get-moves b tactical-head tactical-moves) (get-moves b quiet-head quiet-moves)) ]) (init-moves! b) result)) (define (get-moves b head moves) (let loop ([ i 0 ][ result '() ]) (if (> i (head b)) result (loop (add1 i) (cons (vector-ref (moves b) i) result))))) < to rank > e.g. " 4 " (define (pgn-pawn-move b white? groups) (define (get-promoted-piece letter) (if white? (match letter [ "Q" white-queen ] [ "B" white-bishop ] [ "N" white-knight ] [ "R" white-rook ]) (match letter [ "Q" black-queen ] [ "B" black-bishop ] [ "N" black-knight ] [ "R" black-rook ]))) (match-let* ([ (list from-file to-file to-rank promotion check) groups ] [ from-file (if (non-empty-string? from-file) (substring from-file 0 1) #f) ] [ to-rank (string->number to-rank) ] [ promoted (if (non-empty-string? promotion) (get-promoted-piece (substring promotion 1 2)) #f) ]) (if from-file (pgn-pawn-capture b white? from-file to-file to-rank promoted) (pgn-pawn-push b white? to-file to-rank promoted)))) (define (pgn-pawn-capture b white? from-file to-file to-rank promoted) (define squares (board-squares b)) (let* ([ dst-idx (pos->idx (format "~a~a" to-file to-rank)) ] [ dst (get-square squares dst-idx) ] [ src-rank (if white? (sub1 to-rank) (add1 to-rank)) ] [ src-idx (pos->idx (format "~a~a" from-file src-rank)) ] [ src (get-square squares src-idx) ]) (if (= dst empty-square) (let* ([ cap-idx (pos->idx (format "~a~a" to-file src-rank)) ] [ cap-piece (get-square squares cap-idx) ]) (create-move src src-idx dst-idx #:captured-piece cap-piece #:is-ep-capture? #t #:promoted-piece promoted)) (create-move src src-idx dst-idx #:captured-piece dst #:promoted-piece promoted)))) (define (pgn-pawn-push b white? to-file to-rank promoted) (define squares (board-squares b)) (let* ([ dst-idx (pos->idx (format "~a~a" to-file to-rank)) ] [ dst (get-square squares dst-idx) ] [ s1-idx (+ dst-idx (if white? south north)) ] [ s1 (get-square squares s1-idx) ] [ s1-ok (and (is-pawn? s1) (is-right-color-piece? s1 white?)) ] [ s2-idx (+ s1-idx (if white? south north)) ] [ s2 (get-square squares s2-idx) ] [ s2-ok (and (is-pawn? s2) (is-right-color-piece? s2 white?)) ]) (cond [ (and (not s1-ok) s2-ok) (create-move s2 s2-idx dst-idx) ] [ (and promoted s1-ok (= to-rank (if white? 8 1))) (create-move s1 s1-idx dst-idx #:promoted-piece promoted) ] [ s1-ok (create-move s1 s1-idx dst-idx) ] [ else (error "pgn-pawn-push: invalid move") ]))) (define (pgn-piece-move b white? groups) (match-let* ([ (list letter from-file from-rank capture to-file-rank check) groups ] [ (list src src-idx) (pgn-get-src-idx b letter white? from-file from-rank to-file-rank) ] [ dst-idx (pos->idx to-file-rank) ]) (if capture (let ([ piece (get-square (board-squares b) dst-idx) ]) (create-move src src-idx dst-idx #:captured-piece piece)) (create-move src src-idx dst-idx)))) (define (pgn-get-src-idx b letter white? from-file from-rank pos) (define (get-predicate) (let ([ color-pred? (if white? is-white? is-black?) ] [ piece-pred? (match letter [ "K" is-king? ] [ "Q" is-queen? ] [ "B" is-bishop? ] [ "N" is-knight? ] [ "R" is-rook? ]) ]) (λ (p) (and (color-pred? p) (piece-pred? p))))) (let* ([ lst (get-pieces-file-rank b (get-predicate)) ] [ len (length lst) ]) (cond [ (= len 1) (match-let ([ (list piece file rank) (car lst) ]) (list piece (pos->idx (format "~a~a" file rank)))) ] [ (> len 1) (disambiguate lst b from-file from-rank pos) ] [ else (error "pgn-get-src-idx: invalid move") ]))) (define (disambiguate lst b from-file from-rank pos) (define (file-ok? file) (if from-file (char=? file (string-ref from-file 0)) #t)) (define (rank-ok? rank) (if from-rank (char=? rank (string-ref from-rank 0)) #t)) (define (pred? tuple) (match-let ([ (list piece file rank) tuple ]) (and (file-ok? file) (rank-ok? rank) (member pos (targets b piece file rank))))) (let ([ lst (filter pred? lst) ]) (if (= 1 (length lst)) (match-let ([ (list piece file rank) (car lst) ]) (list piece (pos->idx (format "~a~a" file rank)))) (error "disambiguate: invalid move")))) The method employed here is to generate the moves into the two (define (targets b piece file rank) (let ([ idx (pos->idx (format "~a~a" file rank)) ]) (init-moves! b) (cond [ (is-king? piece) (generate-king-moves! b idx piece) ] [ (is-queen? piece) (generate-queen-moves! b idx piece) ] [ (is-rook? piece) (generate-rook-moves! b idx piece) ] [ (is-bishop? piece) (generate-bishop-moves! b idx piece) ] [ (is-knight? piece) (generate-knight-moves! b idx piece) ] [ else (error "targets: invalid piece") ]) (let* ([ qhead (quiet-head b) ] [ qmoves (quiet-moves b) ] [ thead (tactical-head b) ] [ tmoves (tactical-moves b) ] [ targets (append (for/list ([ i (in-range (add1 qhead)) ]) (idx->pos (move-dst-idx (vector-ref qmoves i)))) (for/list ([ i (in-range (add1 thead)) ]) (idx->pos (move-dst-idx (vector-ref tmoves i))))) ]) (init-moves! b) targets))) Groups : 1 - Castle move e.g. " O - O " or " O - O - O " 2 - Check indication (define (pgn-castle-move b white? groups) (define squares (board-squares b)) (let* ([ castle (car groups) ] [ kingside? (cond [ (string=? castle "O-O") #t ] [ (string=? castle "O-O-O") #f ] [ else (error "pgn-castle-move: invalid castle spec") ]) ] [ king-idx (if white? (pos->idx "e1") (pos->idx "e8")) ] [ king (get-square squares king-idx) ] [ dst-pos (if white? (if kingside? "g1" "c1") (if kingside? "g8" "c8")) ] [ dst-idx (pos->idx dst-pos) ]) (create-move king king-idx dst-idx #:is-castle-queenside? (not kingside?) #:is-castle-kingside? kingside?))) (define pat-func (list (list pat-pawn pgn-pawn-move) (list pat-piece pgn-piece-move) (list pat-castle pgn-castle-move))) (define (pgn-castle-kingside b white?) (let-values ([ (src-idx dst-idx) (if white? (values (pos->idx "e1") (pos->idx "g1")) (values (pos->idx "e8") (pos->idx "g8"))) ]) (create-move (get-square (board-squares b) src-idx) src-idx dst-idx #:is-castle-kingside? #t))) (define (pgn-castle-queenside b white?) (let-values ([ (src-idx dst-idx) (if white? (values (pos->idx "e1") (pos->idx "c1")) (values (pos->idx "e8") (pos->idx "c8"))) ]) (create-move (get-square (board-squares b) src-idx) src-idx dst-idx #:is-castle-queenside? #t))) (module+ test (require rackunit) (for ([ pair (in-list '(("d4" (#f "d" "4" #f #f)) ("d4+" (#f "d" "4" #f "+")) ("d4#" (#f "d" "4" #f "#")) ("d8=N" (#f "d" "8" "=N" #f)) ("d8=Q+" (#f "d" "8" "=Q" "+")) ("d8=Q#" (#f "d" "8" "=Q" "#")) ("cxd4" ("cx" "d" "4" #f #f)) ("cxd4+" ("cx" "d" "4" #f "+")) ("cxd4#" ("cx" "d" "4" #f "#")) ("cxd8=B" ("cx" "d" "8" "=B" #f)) ("cxd8=R+" ("cx" "d" "8" "=R" "+")) ("cxd8=R#" ("cx" "d" "8" "=R" "#")))) ]) (match-let ([ (list str groups) pair ]) (check-equal? (regexp-match pat-pawn str) (cons str groups)))) (for ([ pair (in-list '(("Qd4" ("Q" #f #f #f "d4" #f)) ("Qd4+" ("Q" #f #f #f "d4" "+")) ("Qd4#" ("Q" #f #f #f "d4" "#")) ("Q3d4" ("Q" #f "3" #f "d4" #f)) ("Q3d4+" ("Q" #f "3" #f "d4" "+")) ("Q3d4#" ("Q" #f "3" #f "d4" "#")) ("Qcd4" ("Q" "c" #f #f "d4" #f)) ("Qcd4+" ("Q" "c" #f #f "d4" "+")) ("Qcd4#" ("Q" "c" #f #f "d4" "#")) ("Qc3d4" ("Q" "c" "3" #f "d4" #f)) ("Qc3d4+" ("Q" "c" "3" #f "d4" "+")) ("Qc3d4#" ("Q" "c" "3" #f "d4" "#")))) ]) (match-let ([ (list str groups) pair ]) (check-equal? (regexp-match pat-piece str) (cons str groups)))) (for ([ pair (in-list '(("Qxd4" ("Q" #f #f "x" "d4" #f)) ("Qxd4+" ("Q" #f #f "x" "d4" "+")) ("Qxd4#" ("Q" #f #f "x" "d4" "#")) ("Q3xd4" ("Q" #f "3" "x" "d4" #f)) ("Q3xd4+" ("Q" #f "3" "x" "d4" "+")) ("Q3xd4#" ("Q" #f "3" "x" "d4" "#")) ("Qcxd4" ("Q" "c" #f "x" "d4" #f)) ("Qcxd4+" ("Q" "c" #f "x" "d4" "+")) ("Qcxd4#" ("Q" "c" #f "x" "d4" "#")) ("Qc3xd4" ("Q" "c" "3" "x" "d4" #f)) ("Qc3xd4+" ("Q" "c" "3" "x" "d4" "+")) ("Qc3xd4#" ("Q" "c" "3" "x" "d4" "#")))) ]) (match-let ([ (list str groups) pair ]) (check-equal? (regexp-match pat-piece str) (cons str groups)))) (for ([ pair (in-list '( ("O-O" ("O-O" #f)) ("O-O-O" ("O-O-O" #f)) ("O-O+" ("O-O" "+")) ("O-O-O+" ("O-O-O" "+")) ("O-O#" ("O-O" "#")) ("O-O-O#" ("O-O-O" "#")) )) ]) (match-let ([ (list str groups) pair ]) (check-equal? (regexp-match pat-castle str) (cons str groups)))) )
d624d346af91c2535ddb14247c459381360566086c45f8f6ea157fd59896081c
unclebob/more-speech
relays.clj
(ns more-speech.nostr.relays (:require [clojure.spec.alpha :as s] [more-speech [config :as config] [relay :as relay] [websocket-relay :as ws-relay]] [more-speech.mem :refer [relays]])) (defn- connection? [c] (= (::relay/type c) ::ws-relay/websocket)) (s/def ::read #{:read-all :read-trusted :read-web-of-trust :read-none}) (s/def ::write boolean?) (s/def ::retries integer?) (s/def ::retrying boolean?) (s/def ::subscribed boolean?) (s/def ::connection (s/nilable connection?)) (s/def ::relay (s/keys :req-un [::read ::write ::subscribed ::connection] :req-opt [::retries ::retrying])) (s/def ::relays (s/map-of string? ::relay)) (defn set-relay-defaults [relays] (loop [urls (keys relays) relays relays] (if (empty? urls) relays (let [url (first urls) relay (get relays url) relay (assoc relay :connection nil :subscribed false)] (recur (rest urls) (assoc relays url relay)))))) (defn load-relays [relay-text] (let [loaded-relays (if (empty? relay-text) {} (read-string relay-text)) loaded-relays (set-relay-defaults loaded-relays)] (reset! relays loaded-relays))) (defn load-relays-from-file [file-name] (load-relays (slurp file-name))) (defn relays-for-writing [] (loop [urls (keys @relays) relays-to-write {}] (if (empty? urls) relays-to-write (let [url (first urls) relay (get @relays url) read (:read relay) write (:write relay)] (recur (rest urls) (assoc relays-to-write url {:read read :write write})))))) (defn validate-relay-url [url] (if (empty? url) nil (let [lurl (.trim (.toLowerCase url))] (if (and (re-matches config/relay-pattern lurl) (= -1 (.indexOf lurl "localhost"))) lurl nil))) ) (defn add-relay [url] (let [checked-url (validate-relay-url url)] (when (and (not (empty? url)) (empty? checked-url)) (prn 'invalid-relay url)) (when (and (not (empty? checked-url)) (not (contains? @relays checked-url))) (prn 'adding-relay checked-url) (swap! relays assoc checked-url {:read :read-none :write false})))) (defn add-recommended-relays-in-tags [event] (loop [tags (:tags event)] (if (empty? tags) nil (let [[tag-type _ url] (first tags)] (when (or (= tag-type :e) (= tag-type :p)) (add-relay url) (recur (rest tags)))))))
null
https://raw.githubusercontent.com/unclebob/more-speech/f453281e2e718bb2928e3e8436c556951edc64a2/src/more_speech/nostr/relays.clj
clojure
(ns more-speech.nostr.relays (:require [clojure.spec.alpha :as s] [more-speech [config :as config] [relay :as relay] [websocket-relay :as ws-relay]] [more-speech.mem :refer [relays]])) (defn- connection? [c] (= (::relay/type c) ::ws-relay/websocket)) (s/def ::read #{:read-all :read-trusted :read-web-of-trust :read-none}) (s/def ::write boolean?) (s/def ::retries integer?) (s/def ::retrying boolean?) (s/def ::subscribed boolean?) (s/def ::connection (s/nilable connection?)) (s/def ::relay (s/keys :req-un [::read ::write ::subscribed ::connection] :req-opt [::retries ::retrying])) (s/def ::relays (s/map-of string? ::relay)) (defn set-relay-defaults [relays] (loop [urls (keys relays) relays relays] (if (empty? urls) relays (let [url (first urls) relay (get relays url) relay (assoc relay :connection nil :subscribed false)] (recur (rest urls) (assoc relays url relay)))))) (defn load-relays [relay-text] (let [loaded-relays (if (empty? relay-text) {} (read-string relay-text)) loaded-relays (set-relay-defaults loaded-relays)] (reset! relays loaded-relays))) (defn load-relays-from-file [file-name] (load-relays (slurp file-name))) (defn relays-for-writing [] (loop [urls (keys @relays) relays-to-write {}] (if (empty? urls) relays-to-write (let [url (first urls) relay (get @relays url) read (:read relay) write (:write relay)] (recur (rest urls) (assoc relays-to-write url {:read read :write write})))))) (defn validate-relay-url [url] (if (empty? url) nil (let [lurl (.trim (.toLowerCase url))] (if (and (re-matches config/relay-pattern lurl) (= -1 (.indexOf lurl "localhost"))) lurl nil))) ) (defn add-relay [url] (let [checked-url (validate-relay-url url)] (when (and (not (empty? url)) (empty? checked-url)) (prn 'invalid-relay url)) (when (and (not (empty? checked-url)) (not (contains? @relays checked-url))) (prn 'adding-relay checked-url) (swap! relays assoc checked-url {:read :read-none :write false})))) (defn add-recommended-relays-in-tags [event] (loop [tags (:tags event)] (if (empty? tags) nil (let [[tag-type _ url] (first tags)] (when (or (= tag-type :e) (= tag-type :p)) (add-relay url) (recur (rest tags)))))))
294abab8d3ada35b1dd29472114158b25f3254444227952aa87cd6c21bd7e471
scrintal/heroicons-reagent
ellipsis_horizontal.cljs
(ns com.scrintal.heroicons.outline.ellipsis-horizontal) (defn render [] [:svg {:xmlns "" :fill "none" :viewBox "0 0 24 24" :strokeWidth "1.5" :stroke "currentColor" :aria-hidden "true"} [:path {:strokeLinecap "round" :strokeLinejoin "round" :d "M6.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM12.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM18.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0z"}]])
null
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/outline/ellipsis_horizontal.cljs
clojure
(ns com.scrintal.heroicons.outline.ellipsis-horizontal) (defn render [] [:svg {:xmlns "" :fill "none" :viewBox "0 0 24 24" :strokeWidth "1.5" :stroke "currentColor" :aria-hidden "true"} [:path {:strokeLinecap "round" :strokeLinejoin "round" :d "M6.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM12.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM18.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0z"}]])
e35f94312e22185c7187ef22e015c017a664bbb57d34e092ef48fce28550fbb1
liquidz/iced-nrepl
bar.clj
(ns icedtest.namespace.foo.bar)
null
https://raw.githubusercontent.com/liquidz/iced-nrepl/f63ae00385be912196fceb9d26e174cc5d68295a/test_files/icedtest/namespace/foo/bar.clj
clojure
(ns icedtest.namespace.foo.bar)
f4019e8289b6339739b8383dd1c7833d4ff367d8ef579048378378c598415e21
janestreet/base
invariant.mli
* @inline
null
https://raw.githubusercontent.com/janestreet/base/221b085f3fcd77597f8245b4d73de3970b238e71/src/invariant.mli
ocaml
* @inline
8bdb066a3f53a9c64d36c7059f2fc745d3586b7f41e6010828452a14a822e9ec
tetigi/unearthing-clojurescript
project.clj
(defproject unearthing-clojurescript "0.0.1" :description "A set of demos detailing how to make a basic reagent application" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.9.0"] [binaryage/devtools "0.9.4"] [org.clojure/clojurescript "1.10.238" :scope "provided"] [reagent "0.7.0"]] :source-paths ["src/cljs"] :plugins [[lein-figwheel "0.5.16"] [lein-cljsbuild "1.1.7" :exclusions [[org.clojure/clojure]]]] :cljsbuild {:builds [{:id "dev" :source-paths ["src/cljs"] :figwheel {:on-jsload "unearthing-clojurescript.core/on-js-reload" :open-urls [":3449/index.html"]} :compiler {:main unearthing-clojurescript.core :asset-path "js/compiled/out" :output-to "resources/public/js/compiled/unearthing-clojurescript.js" :output-dir "resources/public/js/compiled/out" :source-map-timestamp true}}]} :figwheel {:css-dirs ["resources/public/css"]} :profiles {:dev {:dependencies [[binaryage/devtools "0.9.9"] [figwheel-sidecar "0.5.16"] [cider/piggieback "0.3.1"]] :source-paths ["dev"] :clean-targets ^{:protect false} ["resources/public/js/compiled"]}})
null
https://raw.githubusercontent.com/tetigi/unearthing-clojurescript/fe698adb2690a5f4d19efa99be6c2d40d79e3b9a/project.clj
clojure
(defproject unearthing-clojurescript "0.0.1" :description "A set of demos detailing how to make a basic reagent application" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.9.0"] [binaryage/devtools "0.9.4"] [org.clojure/clojurescript "1.10.238" :scope "provided"] [reagent "0.7.0"]] :source-paths ["src/cljs"] :plugins [[lein-figwheel "0.5.16"] [lein-cljsbuild "1.1.7" :exclusions [[org.clojure/clojure]]]] :cljsbuild {:builds [{:id "dev" :source-paths ["src/cljs"] :figwheel {:on-jsload "unearthing-clojurescript.core/on-js-reload" :open-urls [":3449/index.html"]} :compiler {:main unearthing-clojurescript.core :asset-path "js/compiled/out" :output-to "resources/public/js/compiled/unearthing-clojurescript.js" :output-dir "resources/public/js/compiled/out" :source-map-timestamp true}}]} :figwheel {:css-dirs ["resources/public/css"]} :profiles {:dev {:dependencies [[binaryage/devtools "0.9.9"] [figwheel-sidecar "0.5.16"] [cider/piggieback "0.3.1"]] :source-paths ["dev"] :clean-targets ^{:protect false} ["resources/public/js/compiled"]}})
6a39c6f2d4759596aa9de79e35552204446079356953a10817ab7661e5e97c20
ocsigen/ocsimore
seminaire_sql.ml
(*-*-coding: utf-8;-*-*) open CalendarLib let (>>=) = Lwt.(>>=) module PGOCaml = Common_sql.PGOCaml open Event_sql.Event (***) (*XXX Quote the strings *) let cat_pattern category = if category = [""] then "%" else String.concat "/" category ^ "/%" let find_in_interval filter category start finish = let pat = cat_pattern category in Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "select event.id, minor_version, major_version, last_updated, category, status, start, finish, event.room, event.location, title, event.description from announcement.event, announcement.category where start < $finish :: timestamp and finish > $start :: timestamp and event.category = category.id and path like $pat order by start") >>= Event_sql.make_events filter let find_after filter category date = let pat = cat_pattern category in Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "select event.id, minor_version, major_version, last_updated, category, status, start, finish, event.room, event.location, title, event.description from announcement.event, announcement.category where start >= $date :: timestamp and event.category = category.id and path like $pat order by start") >>= Event_sql.make_events filter let find_before category date count show_all = let pat = cat_pattern category in let max_status = if show_all then Event_sql.max_status else Event_sql.visible_status in Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "select event.id, minor_version, major_version, last_updated, category, status, start, finish, event.room, event.location, title, event.description from announcement.event, announcement.category where finish <= $date :: timestamp and event.category = category.id and path like $pat and status <= $max_status order by start desc limit $count") >>= Event_sql.make_events (fun _ -> true) let find_category_defaults cat = Lwt_pool.use Common_sql.dbpool (fun dbh -> Common_sql.unique_row (PGSQL(dbh) "select time, duration, room, location from announcement.category where id = $cat")) let archive_start_date category = let pat = cat_pattern category in Lwt_pool.use Common_sql.dbpool (fun dbh -> Common_sql.unique_row (PGSQL(dbh) "select min(start :: timestamp) from announcement.event, announcement.category where event.category = category.id and path like $pat")) (****) let find_categories () = Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL (dbh) "select id, path, name from announcement.category order by path") let insert_talk category start finish room location speaker affiliation title abstract = Lwt_pool.use Common_sql.dbpool ( fun dbh - > PGSQL(dbh ) " insert into announcement.event ( start , finish , category , room , location , title , event.description ) values ( $ start,$finish,$category,$room,'',$title,$abstract ) " > > = fun ( ) - > PGOCaml.serial4 dbh " announcement.event_id_seq " > > = fun event - > PGSQL(dbh ) " insert into announcement.talk ( event , speaker , affiliation ) values ( $ event , $ speaker , $ affiliation ) " > > = fun ( ) - > Lwt.return event ) let update_talk i d start finish room location speaker affiliation title abstract = Lwt_pool.use Common_sql.dbpool ( fun dbh - > PGSQL(dbh ) " update announcement.event set start = $ start , finish = $ finish , room = $ room , location = $ location , title = $ title , event.description = $ abstract where i d = $ i d " > > = fun ( ) - > PGSQL(dbh ) " update announcement.talk set speaker = $ speaker , affiliation = $ affiliation where event = $ i d " ) let delete_talk i d = Lwt_pool.use Common_sql.dbpool ( fun dbh - > PGSQL(dbh ) " delete from announcement.talk where event = $ i d " > > = fun ( ) - > PGSQL(dbh ) " delete from announcement.event where i d = $ i d " ) let insert_talk category start finish room location speaker affiliation title abstract = Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "insert into announcement.event (start, finish, category, room, location, title, event.description) values ($start,$finish,$category,$room,'',$title,$abstract)" >>= fun () -> PGOCaml.serial4 dbh "announcement.event_id_seq" >>= fun event -> PGSQL(dbh) "insert into announcement.talk (event, speaker, affiliation) values ($event, $speaker, $affiliation)" >>= fun () -> Lwt.return event) let update_talk id start finish room location speaker affiliation title abstract = Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "update announcement.event set start = $start, finish = $finish, room = $room, location = $location, title = $title, event.description = $abstract where id = $id" >>= fun () -> PGSQL(dbh) "update announcement.talk set speaker = $speaker, affiliation = $affiliation where event = $id") let delete_talk id = Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "delete from announcement.talk where event = $id" >>= fun () -> PGSQL(dbh) "delete from announcement.event where id = $id") *)
null
https://raw.githubusercontent.com/ocsigen/ocsimore/8eeaf043ed6f1f167a96cbdc5f72a5225d9516d5/src/announce/seminaire_sql.ml
ocaml
-*-coding: utf-8;-*- * XXX Quote the strings **
open CalendarLib let (>>=) = Lwt.(>>=) module PGOCaml = Common_sql.PGOCaml open Event_sql.Event let cat_pattern category = if category = [""] then "%" else String.concat "/" category ^ "/%" let find_in_interval filter category start finish = let pat = cat_pattern category in Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "select event.id, minor_version, major_version, last_updated, category, status, start, finish, event.room, event.location, title, event.description from announcement.event, announcement.category where start < $finish :: timestamp and finish > $start :: timestamp and event.category = category.id and path like $pat order by start") >>= Event_sql.make_events filter let find_after filter category date = let pat = cat_pattern category in Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "select event.id, minor_version, major_version, last_updated, category, status, start, finish, event.room, event.location, title, event.description from announcement.event, announcement.category where start >= $date :: timestamp and event.category = category.id and path like $pat order by start") >>= Event_sql.make_events filter let find_before category date count show_all = let pat = cat_pattern category in let max_status = if show_all then Event_sql.max_status else Event_sql.visible_status in Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "select event.id, minor_version, major_version, last_updated, category, status, start, finish, event.room, event.location, title, event.description from announcement.event, announcement.category where finish <= $date :: timestamp and event.category = category.id and path like $pat and status <= $max_status order by start desc limit $count") >>= Event_sql.make_events (fun _ -> true) let find_category_defaults cat = Lwt_pool.use Common_sql.dbpool (fun dbh -> Common_sql.unique_row (PGSQL(dbh) "select time, duration, room, location from announcement.category where id = $cat")) let archive_start_date category = let pat = cat_pattern category in Lwt_pool.use Common_sql.dbpool (fun dbh -> Common_sql.unique_row (PGSQL(dbh) "select min(start :: timestamp) from announcement.event, announcement.category where event.category = category.id and path like $pat")) let find_categories () = Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL (dbh) "select id, path, name from announcement.category order by path") let insert_talk category start finish room location speaker affiliation title abstract = Lwt_pool.use Common_sql.dbpool ( fun dbh - > PGSQL(dbh ) " insert into announcement.event ( start , finish , category , room , location , title , event.description ) values ( $ start,$finish,$category,$room,'',$title,$abstract ) " > > = fun ( ) - > PGOCaml.serial4 dbh " announcement.event_id_seq " > > = fun event - > PGSQL(dbh ) " insert into announcement.talk ( event , speaker , affiliation ) values ( $ event , $ speaker , $ affiliation ) " > > = fun ( ) - > Lwt.return event ) let update_talk i d start finish room location speaker affiliation title abstract = Lwt_pool.use Common_sql.dbpool ( fun dbh - > PGSQL(dbh ) " update announcement.event set start = $ start , finish = $ finish , room = $ room , location = $ location , title = $ title , event.description = $ abstract where i d = $ i d " > > = fun ( ) - > PGSQL(dbh ) " update announcement.talk set speaker = $ speaker , affiliation = $ affiliation where event = $ i d " ) let delete_talk i d = Lwt_pool.use Common_sql.dbpool ( fun dbh - > PGSQL(dbh ) " delete from announcement.talk where event = $ i d " > > = fun ( ) - > PGSQL(dbh ) " delete from announcement.event where i d = $ i d " ) let insert_talk category start finish room location speaker affiliation title abstract = Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "insert into announcement.event (start, finish, category, room, location, title, event.description) values ($start,$finish,$category,$room,'',$title,$abstract)" >>= fun () -> PGOCaml.serial4 dbh "announcement.event_id_seq" >>= fun event -> PGSQL(dbh) "insert into announcement.talk (event, speaker, affiliation) values ($event, $speaker, $affiliation)" >>= fun () -> Lwt.return event) let update_talk id start finish room location speaker affiliation title abstract = Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "update announcement.event set start = $start, finish = $finish, room = $room, location = $location, title = $title, event.description = $abstract where id = $id" >>= fun () -> PGSQL(dbh) "update announcement.talk set speaker = $speaker, affiliation = $affiliation where event = $id") let delete_talk id = Lwt_pool.use Common_sql.dbpool (fun dbh -> PGSQL(dbh) "delete from announcement.talk where event = $id" >>= fun () -> PGSQL(dbh) "delete from announcement.event where id = $id") *)
5e937ae341bee6ae3a076ff0bf35720084daa3c3901c61be9b79b4c8c2a5144a
markhibberd/postmark
Response.hs
module Network.Api.Postmark.Response ( PostmarkResponse (..), PostmarkUnexpectedType (..), PostmarkResponse', syntaxErr, formatErr ) where import qualified Data.ByteString.Lazy as BL import Data.Text import Network.Api.Postmark.Data (toText) import Network.Api.Postmark.Error data PostmarkResponse e a = PostmarkSuccess a | PostmarkUnauthorized | PostmarkFailure e | PostmarkUnexpected PostmarkUnexpectedType Int (Maybe Text) (Maybe Text) deriving (Eq, Show) data PostmarkUnexpectedType = ServerError | UnexpectedResponseCode | JsonSyntaxError | JsonFormatError deriving (Eq, Show) type PostmarkResponse' a = PostmarkResponse PostmarkError a syntaxErr :: Int -> BL.ByteString -> Text -> PostmarkResponse e a syntaxErr code body msg = PostmarkUnexpected JsonSyntaxError code (Just . toText $ body) (Just msg) formatErr :: Int -> BL.ByteString -> Text -> PostmarkResponse e a formatErr code body msg = PostmarkUnexpected JsonFormatError code (Just . toText $ body) (Just msg)
null
https://raw.githubusercontent.com/markhibberd/postmark/2eb6087bbb19421f1dd765b973702f37c1d386e9/src/Network/Api/Postmark/Response.hs
haskell
module Network.Api.Postmark.Response ( PostmarkResponse (..), PostmarkUnexpectedType (..), PostmarkResponse', syntaxErr, formatErr ) where import qualified Data.ByteString.Lazy as BL import Data.Text import Network.Api.Postmark.Data (toText) import Network.Api.Postmark.Error data PostmarkResponse e a = PostmarkSuccess a | PostmarkUnauthorized | PostmarkFailure e | PostmarkUnexpected PostmarkUnexpectedType Int (Maybe Text) (Maybe Text) deriving (Eq, Show) data PostmarkUnexpectedType = ServerError | UnexpectedResponseCode | JsonSyntaxError | JsonFormatError deriving (Eq, Show) type PostmarkResponse' a = PostmarkResponse PostmarkError a syntaxErr :: Int -> BL.ByteString -> Text -> PostmarkResponse e a syntaxErr code body msg = PostmarkUnexpected JsonSyntaxError code (Just . toText $ body) (Just msg) formatErr :: Int -> BL.ByteString -> Text -> PostmarkResponse e a formatErr code body msg = PostmarkUnexpected JsonFormatError code (Just . toText $ body) (Just msg)
545143cf24846150cacf1b4ee96d157590c3306033478dbee0770f73947db7ec
haskell-repa/repa
Seq.hs
-- | Sequential flows provide an incremental version of array fusion that -- allows the computation to be suspended and resumed at a later time. -- -- The operators provided are guaranteed to use only a constant amount of space. -- For example, we provide a `dup_oo` operator but no `dup_ii` because if all -- input elements were pulled from one of the out-flows before the other, then -- we would need to buffer the entire input flow. Similarly, we don't provide a -- `zip_oo` operator for the dual reason. -- -- The parallel flow operators are defined in terms of these sequential -- ones. -- module Data.Array.Repa.Flow.Seq ( FD , FS , Size (..) -- * Sources , Source (..) , SourceState (..) , joinSourceStates , getSourceState , startSource , Step1 (..) , Step8 (..) -- * Sinks , Sink (..) , SinkState (..) , joinSinkStates , getSinkState , startSink , Snack1 (..) , Snack8 (..) -- * Conversion , flow , drain , slurp , unflowIO -- * Map , map_i , map_o -- * Dup , dup_oo , dup_io , dup_oi -- * Zip , zip_ii , zipWith_ii , zipLeft_i , zipLeftWith_i -- * Construction , generate_i , replicate_i , replicates_bi , enumFromN_i , appends_bb -- * Projection , gather_bi -- * Pack , packByTag_i , packByFlag_i , filter_i -- * Combine , combine2_iii , combines2_iii -- * Reduction , foldl_i , folds_ii , sums_ii) where import Data.Array.Repa.Flow.Seq.Base import Data.Array.Repa.Flow.Seq.Source import Data.Array.Repa.Flow.Seq.Sink import Data.Array.Repa.Flow.Seq.Operator.Slurp import Data.Array.Repa.Flow.Seq.Operator.Dup import Data.Array.Repa.Flow.Seq.Operator.Map import Data.Array.Repa.Flow.Seq.Operator.Zip import Data.Array.Repa.Flow.Seq.Operator.Generate import Data.Array.Repa.Flow.Seq.Operator.Append import Data.Array.Repa.Flow.Seq.Operator.Pack import Data.Array.Repa.Flow.Seq.Operator.Combine import Data.Array.Repa.Flow.Seq.Operator.Project import Data.Array.Repa.Flow.Seq.Operator.Fold import Prelude hiding (map, zip, zipWith, unzip, foldl, filter, replicate, take)
null
https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/icebox/abandoned/repa-flow/Data/Array/Repa/Flow/Seq.hs
haskell
| Sequential flows provide an incremental version of array fusion that allows the computation to be suspended and resumed at a later time. The operators provided are guaranteed to use only a constant amount of space. For example, we provide a `dup_oo` operator but no `dup_ii` because if all input elements were pulled from one of the out-flows before the other, then we would need to buffer the entire input flow. Similarly, we don't provide a `zip_oo` operator for the dual reason. The parallel flow operators are defined in terms of these sequential ones. * Sources * Sinks * Conversion * Map * Dup * Zip * Construction * Projection * Pack * Combine * Reduction
module Data.Array.Repa.Flow.Seq ( FD , FS , Size (..) , Source (..) , SourceState (..) , joinSourceStates , getSourceState , startSource , Step1 (..) , Step8 (..) , Sink (..) , SinkState (..) , joinSinkStates , getSinkState , startSink , Snack1 (..) , Snack8 (..) , flow , drain , slurp , unflowIO , map_i , map_o , dup_oo , dup_io , dup_oi , zip_ii , zipWith_ii , zipLeft_i , zipLeftWith_i , generate_i , replicate_i , replicates_bi , enumFromN_i , appends_bb , gather_bi , packByTag_i , packByFlag_i , filter_i , combine2_iii , combines2_iii , foldl_i , folds_ii , sums_ii) where import Data.Array.Repa.Flow.Seq.Base import Data.Array.Repa.Flow.Seq.Source import Data.Array.Repa.Flow.Seq.Sink import Data.Array.Repa.Flow.Seq.Operator.Slurp import Data.Array.Repa.Flow.Seq.Operator.Dup import Data.Array.Repa.Flow.Seq.Operator.Map import Data.Array.Repa.Flow.Seq.Operator.Zip import Data.Array.Repa.Flow.Seq.Operator.Generate import Data.Array.Repa.Flow.Seq.Operator.Append import Data.Array.Repa.Flow.Seq.Operator.Pack import Data.Array.Repa.Flow.Seq.Operator.Combine import Data.Array.Repa.Flow.Seq.Operator.Project import Data.Array.Repa.Flow.Seq.Operator.Fold import Prelude hiding (map, zip, zipWith, unzip, foldl, filter, replicate, take)
f0a3114e77e7495c048cb681fc0527ade8fab95e7f36cc92431e7357ed13b04c
kahua/Kahua
plugin.scm
plugin manager ;; Copyright ( c ) 2003 - 2007 Scheme Arts , L.L.C. , All rights reserved . Copyright ( c ) 2003 - 2007 Time Intermedia Corporation , All rights reserved . ;; See COPYING for terms and conditions of using this software ;; (define-module kahua.plugin (use srfi-1) (use srfi-13) (use file.util) (export define-export <kahua-plugin> lookup-exports expand-define %load-plugin use-plugin define-plugin allow-module register-plugin initialize-plugins refresh-plugin all-plugins) ) (select-module kahua.plugin) ;; plugin meta-information container (define-constant *plugins* (make-hash-table 'string=?)) ;; plugin's procedures are bound this module. (define-constant *sandbox-plugin* (make-hash-table 'eq?)) ;; make anonymous module for binding plugin procedures. (define (make-sandbox-module) (let ((m (make-module #f))) (eval '(import kahua.plugin) m) m)) (define (get-sandbox-module name) (if (hash-table-exists? *sandbox-plugin* name) (hash-table-get *sandbox-plugin* name) (let ((m (make-sandbox-module))) (hash-table-put! *sandbox-plugin* name m) m))) ;; plugin class. (define-class <kahua-plugin> () ( (name :init-keyword :name) (version :init-keyword :version) (export :init-keyword :export) (depend :init-keyword :depend) )) ;; explicitly. define a procedue globally in somewhere, ;; normally in *sandbox-plugin*. (define-macro (define-export def . body) (if (pair? def) `(define-export ,(car def) (lambda ,(cdr def) ,@body)) `(begin (define ,def ,@body) ))) ;; get symbols which exported from module, ;; this procedure treats the case of 'export-all'd module. (define (%get-export-symbols name) (let1 m (filter (lambda (m) (eq? (module-name m) name)) (all-modules)) (if (null? m) '() (hash-table-map (module-table (car m)) (lambda (k v) k))))) ;; find out which symbols a plugin defines. (define (lookup-exports name) (let ((symbols (ref (hash-table-get *plugins* (symbol->string name)) 'export)) (modules (cons (get-sandbox-module name) (append (filter (lambda (m) (eq? (module-name m) name)) (all-modules)) (hash-table-values *sandbox-plugin*) (all-modules))))) (map (lambda (s) (cons s (or (find (lambda (m) (hash-table-exists? (module-table m) s)) modules) (error "symbol not found." name s)))) (if (eq? symbols #t) (%get-export-symbols name) symbols)))) ;; find symbol then define in sandbox plugin module. (define-macro (expand-define name module) (let ((exports (lookup-exports name))) `(begin ,@(map (lambda (e) `(define-in-module ,module ,(car e) (eval ',(car e) ,(cdr e)))) exports) ))) ;; safe plugin loader for sandbox. (define-syntax use-plugin (syntax-rules () ((use-plugin name) (if (hash-table-exists? *plugins* (symbol->string 'name)) (%load-plugin 'name (current-module)) (error "cannot find plugin" 'name))))) (define (%load-plugin name target-module) (eval `(expand-define ,name ,target-module) (get-sandbox-module name))) (define (register-plugin name version export depend) (hash-table-put! *plugins* name (make <kahua-plugin> :name name :version version :export export :depend depend)) (hash-table-put! *sandbox-plugin* (string->symbol name) (get-sandbox-module (string->symbol (port-name (current-load-port)))))) ;; plugin registrar. (define-syntax define-plugin (syntax-rules (version export depend) ;; for backward compatibility ((_ name (version v) (export symbol1 symbol2 ...) (depend #f)) (define-plugin name (version v) (export symbol1 symbol2 ...))) ((_ name (version v) (export symbol1 symbol2 ...)) (register-plugin name v '(symbol1 symbol2 ...) '())) ((_ name (version v) (export symbol1 symbol2 ...) (depend module1 ...)) (register-plugin name v '(symbol1 symbol2 ...) '(module1 ...))) ((_ arg1 ...) (syntax-error "malformed syntax: " (define-plugin arg1 ...))) )) ;; plugin registrar for gauche module. (define-syntax allow-module (syntax-rules () ((allow-module module) (let ((m (get-sandbox-module 'module))) (eval '(use module) m) (eval '(register-plugin (symbol->string 'module) "1.0" (module-exports (find-module 'module)) ()) m) )))) ;; load all plugin file. (define (initialize-plugins plugin-dir) (let1 plugin-files (directory-list plugin-dir :filter (lambda (n) (string-suffix? ".scm" n))) (hash-table-clear! *plugins*) (hash-table-clear! *sandbox-plugin*) (for-each (cut refresh-plugin <> plugin-dir) plugin-files))) ;; refresh a target plugin. (define (refresh-plugin filename dir) (let1 plugin (sys-normalize-pathname (build-path dir filename) :absolute #t) (load plugin :environment (get-sandbox-module (string->symbol plugin))))) (define (all-plugins) (hash-table-map *plugins* (lambda (name p) (cons name (ref p 'version))))) (provide "kahua/plugin")
null
https://raw.githubusercontent.com/kahua/Kahua/c90fe590233e4540923e4e5cc9f61da32873692c/src/kahua/plugin.scm
scheme
See COPYING for terms and conditions of using this software plugin meta-information container plugin's procedures are bound this module. make anonymous module for binding plugin procedures. plugin class. explicitly. define a procedue globally in somewhere, normally in *sandbox-plugin*. get symbols which exported from module, this procedure treats the case of 'export-all'd module. find out which symbols a plugin defines. find symbol then define in sandbox plugin module. safe plugin loader for sandbox. plugin registrar. for backward compatibility plugin registrar for gauche module. load all plugin file. refresh a target plugin.
plugin manager Copyright ( c ) 2003 - 2007 Scheme Arts , L.L.C. , All rights reserved . Copyright ( c ) 2003 - 2007 Time Intermedia Corporation , All rights reserved . (define-module kahua.plugin (use srfi-1) (use srfi-13) (use file.util) (export define-export <kahua-plugin> lookup-exports expand-define %load-plugin use-plugin define-plugin allow-module register-plugin initialize-plugins refresh-plugin all-plugins) ) (select-module kahua.plugin) (define-constant *plugins* (make-hash-table 'string=?)) (define-constant *sandbox-plugin* (make-hash-table 'eq?)) (define (make-sandbox-module) (let ((m (make-module #f))) (eval '(import kahua.plugin) m) m)) (define (get-sandbox-module name) (if (hash-table-exists? *sandbox-plugin* name) (hash-table-get *sandbox-plugin* name) (let ((m (make-sandbox-module))) (hash-table-put! *sandbox-plugin* name m) m))) (define-class <kahua-plugin> () ( (name :init-keyword :name) (version :init-keyword :version) (export :init-keyword :export) (depend :init-keyword :depend) )) (define-macro (define-export def . body) (if (pair? def) `(define-export ,(car def) (lambda ,(cdr def) ,@body)) `(begin (define ,def ,@body) ))) (define (%get-export-symbols name) (let1 m (filter (lambda (m) (eq? (module-name m) name)) (all-modules)) (if (null? m) '() (hash-table-map (module-table (car m)) (lambda (k v) k))))) (define (lookup-exports name) (let ((symbols (ref (hash-table-get *plugins* (symbol->string name)) 'export)) (modules (cons (get-sandbox-module name) (append (filter (lambda (m) (eq? (module-name m) name)) (all-modules)) (hash-table-values *sandbox-plugin*) (all-modules))))) (map (lambda (s) (cons s (or (find (lambda (m) (hash-table-exists? (module-table m) s)) modules) (error "symbol not found." name s)))) (if (eq? symbols #t) (%get-export-symbols name) symbols)))) (define-macro (expand-define name module) (let ((exports (lookup-exports name))) `(begin ,@(map (lambda (e) `(define-in-module ,module ,(car e) (eval ',(car e) ,(cdr e)))) exports) ))) (define-syntax use-plugin (syntax-rules () ((use-plugin name) (if (hash-table-exists? *plugins* (symbol->string 'name)) (%load-plugin 'name (current-module)) (error "cannot find plugin" 'name))))) (define (%load-plugin name target-module) (eval `(expand-define ,name ,target-module) (get-sandbox-module name))) (define (register-plugin name version export depend) (hash-table-put! *plugins* name (make <kahua-plugin> :name name :version version :export export :depend depend)) (hash-table-put! *sandbox-plugin* (string->symbol name) (get-sandbox-module (string->symbol (port-name (current-load-port)))))) (define-syntax define-plugin (syntax-rules (version export depend) ((_ name (version v) (export symbol1 symbol2 ...) (depend #f)) (define-plugin name (version v) (export symbol1 symbol2 ...))) ((_ name (version v) (export symbol1 symbol2 ...)) (register-plugin name v '(symbol1 symbol2 ...) '())) ((_ name (version v) (export symbol1 symbol2 ...) (depend module1 ...)) (register-plugin name v '(symbol1 symbol2 ...) '(module1 ...))) ((_ arg1 ...) (syntax-error "malformed syntax: " (define-plugin arg1 ...))) )) (define-syntax allow-module (syntax-rules () ((allow-module module) (let ((m (get-sandbox-module 'module))) (eval '(use module) m) (eval '(register-plugin (symbol->string 'module) "1.0" (module-exports (find-module 'module)) ()) m) )))) (define (initialize-plugins plugin-dir) (let1 plugin-files (directory-list plugin-dir :filter (lambda (n) (string-suffix? ".scm" n))) (hash-table-clear! *plugins*) (hash-table-clear! *sandbox-plugin*) (for-each (cut refresh-plugin <> plugin-dir) plugin-files))) (define (refresh-plugin filename dir) (let1 plugin (sys-normalize-pathname (build-path dir filename) :absolute #t) (load plugin :environment (get-sandbox-module (string->symbol plugin))))) (define (all-plugins) (hash-table-map *plugins* (lambda (name p) (cons name (ref p 'version))))) (provide "kahua/plugin")
bce2cdd2dcf0b9900f7903b4978f857c655dae0a6f5cda9355f15f0c4b128de2
xvw/preface
join.mli
(** [Join] produces a [Functor] from a [Bifunctor] using both arguments of a Bifunctor. *) * { 2 Produces a Functor from a Bifunctor } module Functor (B : Preface_specs.Bifunctor.CORE) : Preface_specs.FUNCTOR with type 'a t = ('a, 'a) B.t
null
https://raw.githubusercontent.com/xvw/preface/8b0154ba20cf46fbd58eb7df707b874504070938/lib/preface_make/join.mli
ocaml
* [Join] produces a [Functor] from a [Bifunctor] using both arguments of a Bifunctor.
* { 2 Produces a Functor from a Bifunctor } module Functor (B : Preface_specs.Bifunctor.CORE) : Preface_specs.FUNCTOR with type 'a t = ('a, 'a) B.t
df301a1a6f69897e91bcb7fc4bca2cff7459b67cd41f000e9638a5b1ba60deb7
leksah/leksah-server
VersionUtils.hs
# LANGUAGE CPP , ScopedTypeVariables , BangPatterns , OverloadedStrings # ----------------------------------------------------------------------------- -- Module : IDE.Utils . VersionUtils Copyright : 2007 - 2011 , -- License : GPL Nothing -- -- Maintainer : -- Stability : provisional -- Portability : -- -- | -- ----------------------------------------------------------------------------- module IDE.Utils.VersionUtils ( getHaddockVersion , getDefaultGhcVersion , getGhcInfo , supportedGhcVersions , ghcExeName ) where import Prelude () import Prelude.Compat import IDE.Utils.Tool (ToolOutput(..), runTool') import Data.Char (ord) import Data.List (nub) import System.Log.Logger (debugM) import Control.Exception as E (SomeException, catch) import qualified Data.Text as T (unlines, unpack, init, last) import Data.Text (Text) import Control.DeepSeq (deepseq) import GHC.Stack (HasCallStack) supportedGhcVersions :: [FilePath] supportedGhcVersions = nub ["8.0.2", "8.2.2", VERSION_ghc] getDefaultGhcVersion :: HasCallStack => IO FilePath getDefaultGhcVersion = E.catch (do (!output,_) <- runTool' "ghc" ["--numeric-version"] Nothing Nothing let vers = head [l | ToolOutput l <- output] vers2 = if ord (T.last vers) == 13 then T.init vers else vers debugM "leksah-server" $ "Got GHC Version " ++ T.unpack vers2 output `deepseq` return $ T.unpack vers2 ) $ \ (e :: SomeException) -> do debugM "leksah-server" $ "No `ghc` in path defaulting to " ++ VERSION_ghc return VERSION_ghc ghcExeName :: Maybe FilePath -> FilePath #ifdef mingw32_HOST_OS ghcExeName Nothing = "ghc.exe" ghcExeName (Just ver) = "ghc-" <> ver <> ".exe" #else ghcExeName = maybe "ghc" ("ghc-" <>) #endif getGhcInfo :: Maybe FilePath -> IO Text getGhcInfo ver = E.catch (do (!output,_) <- runTool' (ghcExeName ver) ["--info"] Nothing Nothing output `deepseq` return $ T.unlines [l | ToolOutput l <- output] ) $ \ (e :: SomeException) -> error $ "FileUtils>>getGhcInfo failed with " ++ show e getHaddockVersion :: IO Text getHaddockVersion = E.catch (do (!output,_) <- runTool' "haddock" ["--version"] Nothing Nothing let vers = head [l | ToolOutput l <- output] vers2 = if ord (T.last vers) == 13 then T.init vers else vers output `deepseq` return vers2 ) $ \ (e :: SomeException) -> error $ "FileUtils>>getHaddockVersion failed with " ++ show e
null
https://raw.githubusercontent.com/leksah/leksah-server/a7840a2caad6d294fb8e6024addf8aa1077b578c/src/IDE/Utils/VersionUtils.hs
haskell
--------------------------------------------------------------------------- License : GPL Nothing Maintainer : Stability : provisional Portability : | ---------------------------------------------------------------------------
# LANGUAGE CPP , ScopedTypeVariables , BangPatterns , OverloadedStrings # Module : IDE.Utils . VersionUtils Copyright : 2007 - 2011 , module IDE.Utils.VersionUtils ( getHaddockVersion , getDefaultGhcVersion , getGhcInfo , supportedGhcVersions , ghcExeName ) where import Prelude () import Prelude.Compat import IDE.Utils.Tool (ToolOutput(..), runTool') import Data.Char (ord) import Data.List (nub) import System.Log.Logger (debugM) import Control.Exception as E (SomeException, catch) import qualified Data.Text as T (unlines, unpack, init, last) import Data.Text (Text) import Control.DeepSeq (deepseq) import GHC.Stack (HasCallStack) supportedGhcVersions :: [FilePath] supportedGhcVersions = nub ["8.0.2", "8.2.2", VERSION_ghc] getDefaultGhcVersion :: HasCallStack => IO FilePath getDefaultGhcVersion = E.catch (do (!output,_) <- runTool' "ghc" ["--numeric-version"] Nothing Nothing let vers = head [l | ToolOutput l <- output] vers2 = if ord (T.last vers) == 13 then T.init vers else vers debugM "leksah-server" $ "Got GHC Version " ++ T.unpack vers2 output `deepseq` return $ T.unpack vers2 ) $ \ (e :: SomeException) -> do debugM "leksah-server" $ "No `ghc` in path defaulting to " ++ VERSION_ghc return VERSION_ghc ghcExeName :: Maybe FilePath -> FilePath #ifdef mingw32_HOST_OS ghcExeName Nothing = "ghc.exe" ghcExeName (Just ver) = "ghc-" <> ver <> ".exe" #else ghcExeName = maybe "ghc" ("ghc-" <>) #endif getGhcInfo :: Maybe FilePath -> IO Text getGhcInfo ver = E.catch (do (!output,_) <- runTool' (ghcExeName ver) ["--info"] Nothing Nothing output `deepseq` return $ T.unlines [l | ToolOutput l <- output] ) $ \ (e :: SomeException) -> error $ "FileUtils>>getGhcInfo failed with " ++ show e getHaddockVersion :: IO Text getHaddockVersion = E.catch (do (!output,_) <- runTool' "haddock" ["--version"] Nothing Nothing let vers = head [l | ToolOutput l <- output] vers2 = if ord (T.last vers) == 13 then T.init vers else vers output `deepseq` return vers2 ) $ \ (e :: SomeException) -> error $ "FileUtils>>getHaddockVersion failed with " ++ show e
cbccd3ecfe50e24acc8bdcb6d0473edb448be892166704f52eca194ecc9e3540
keechma/keechma-next
core.cljs
(ns keechma.next.core (:require [keechma.next.controller :as ctrl] [keechma.next.graph :refer [subgraph-reachable-from-set]] [keechma.next.util :refer [get-dirty-deps get-lowest-common-ancestor-for-paths]] [keechma.next.protocols :as protocols :refer [IAppInstance IRootAppInstance]] [keechma.next.conformer :refer [conform conform-factory-produced]] [keechma.next.tracing :refer [trace! with-tracing]] [medley.core :refer [dissoc-in]] [weavejester.dependency :as dep] [clojure.set :as set])) (declare -dispatch) (declare reconcile-after-transaction!) (declare reconcile-initial!) (def ^:dynamic *transaction-depth* 0) (def ^:dynamic *app-id->transaction-depth* {}) (def ^:dynamic *stopping* false) (defn transacting? [] (pos? *transaction-depth*)) (defn factory-produced-deps-valid? [app-db factory-deps factory-produced-deps] (let [expanded-factory-deps (reduce (fn [acc d] (let [dep-produced-keys (get-in app-db [d :produced-keys])] (if (seq dep-produced-keys) (set/union acc #{d} dep-produced-keys) (conj acc d)))) #{} factory-deps)] (set/subset? factory-produced-deps expanded-factory-deps))) (defn keechma-ex-info ([message anomaly] (keechma-ex-info message anomaly {})) ([message anomaly props] (ex-info message (assoc props :keechma.anomalies/category anomaly :keechma.anomalies/message message)))) (defn default-batcher [batched-fn] (batched-fn)) (defn build-controllers-graph [controllers] (reduce (fn [acc [k c]] (reduce (fn [acc' d] (dep/depend acc' k d)) acc (:keechma.controller/deps c))) (dep/graph) controllers)) (defn determine-actions [old-params new-params old-type new-type] (cond ;; controller types are different (and (not= old-type new-type) old-params new-params) #{:stop :start} (and (not= old-type new-type) (not old-params) new-params) #{:start} (and (not= old-type new-type) old-params (not new-params)) #{:stop} ;; controller types are same (and (= old-type new-type) (not old-params) new-params) #{:start} (and (= old-type new-type) old-params (not new-params)) #{:stop} (and (= old-type new-type) old-params new-params (not= old-params new-params)) #{:stop :start} (and (= old-type new-type) old-params new-params (= new-params old-params)) #{:deps-change} :else nil)) (defn controller-state-relevant? [controller] (->> controller :phase (contains? #{:starting :running}))) (defn get-derived-deps-state ([app-state controllers deps] (get-derived-deps-state app-state controllers deps nil)) ([app-state controllers deps renamed-deps] (let [app-db (:app-db app-state)] (when (seq deps) (-> (reduce (fn [acc dep-controller-name] (if (= :factory (get-in controllers [dep-controller-name :keechma.controller/variant])) (let [renamed-dep (get renamed-deps dep-controller-name)] (reduce (fn [acc' dep-controller-name'] (if (controller-state-relevant? (get app-db dep-controller-name')) (let [dep-controller-name'' (if renamed-dep (vec (concat renamed-dep (rest dep-controller-name'))) dep-controller-name')] (assoc! acc' dep-controller-name'' (get-in app-db [dep-controller-name' :derived-state]))) acc')) acc (get-in app-db [dep-controller-name :produced-keys]))) (if (controller-state-relevant? (get app-db dep-controller-name)) (let [dep-controller-name' (or (get renamed-deps dep-controller-name) dep-controller-name)] (assoc! acc dep-controller-name' (get-in app-db [dep-controller-name :derived-state]))) acc))) (transient {}) deps) persistent!))))) (defn get-controller-derived-deps-state [app-state controller-name] (let [controllers (:controllers app-state) controller (get controllers controller-name) controller-name' (or (get controller :keechma.controller/factory) controller-name) deps (get-in controllers [controller-name' :keechma.controller/deps]) renamed-deps (get-in controllers [controller-name :keechma.controller.deps/renamed])] (get-derived-deps-state app-state controllers deps renamed-deps))) (defn get-controller-running-deps-map [app-state controller-name] (let [app-db (:app-db app-state) controllers (:controllers app-state) controller (get controllers controller-name) controller-name' (or (get controller :keechma.controller/factory) controller-name) deps (get-in controllers [controller-name' :keechma.controller/deps]) renamed-deps (get-in controllers [controller-name :keechma.controller.deps/renamed])] (-> (reduce (fn [acc dep-controller-name] (if (= :factory (get-in controllers [dep-controller-name :keechma.controller/variant])) (let [renamed-dep (get renamed-deps dep-controller-name)] (reduce (fn [acc' dep-controller-name'] (if (contains? #{:starting :running} (get-in app-db [dep-controller-name' :phase])) (let [dep-controller-name'' (if renamed-dep (vec (concat renamed-dep (rest dep-controller-name'))) dep-controller-name')] (assoc! acc' dep-controller-name' dep-controller-name'')) acc')) acc (get-in app-db [dep-controller-name :produced-keys]))) (if (contains? #{:starting :running} (get-in app-db [dep-controller-name :phase])) (let [dep-controller-name' (or (get renamed-deps dep-controller-name) dep-controller-name)] (assoc! acc dep-controller-name dep-controller-name')) acc))) (transient {}) deps) persistent!))) (defn get-params-and-type [app-state controller-name] (let [controller (get-in app-state [:controllers controller-name]) derived-deps-state (get-controller-derived-deps-state app-state controller-name) params (:keechma.controller/params controller) type (:keechma.controller/type controller)] {:params (if (= :static (:keechma.controller.params/variant controller)) params (params derived-deps-state)) :type (if (= :static (:keechma.controller.type/variant controller)) type (type derived-deps-state))})) (defn get-factory-produced [app-state controller-name] (let [controller (get-in app-state [:controllers controller-name]) produce (:keechma.controller.factory/produce controller)] (produce (get-controller-derived-deps-state app-state controller-name)))) (defn get-app-store-path [app-path] (->> app-path (concat [:apps]) (interpose :apps) vec)) (defn make-controller-sort-comparator [controllers] (fn [ctrl-1 ctrl-2] (let [ctrl-1-is-global (get-in controllers [ctrl-1 :keechma.controller/is-global]) ctrl-2-is-global (get-in controllers [ctrl-2 :keechma.controller/is-global])] (cond (= ctrl-1-is-global ctrl-2-is-global) 0 ctrl-1-is-global -1 :else 1)))) (defn get-sorted-controllers-for-app [app-state path] (let [{:keys [controllers controllers-graph]} (get-in app-state (get-app-store-path path)) controller-sort-comparator (make-controller-sort-comparator controllers) nodeset (dep/nodes controllers-graph) sorted-controllers (->> controllers-graph (dep/topo-sort controller-sort-comparator) (filterv #(contains? controllers %))) isolated-controllers (->> (keys controllers) (filter #(not (contains? nodeset %))) (sort controller-sort-comparator))] (concat isolated-controllers sorted-controllers))) (defn unsubscribe! [app-state* controller-name sub-id] (swap! app-state* dissoc-in [:subscriptions controller-name sub-id])) (defn unsubscribe-meta! [app-state* controller-name sub-id] (swap! app-state* dissoc-in [:subscriptions-meta controller-name sub-id])) (defn merge-is-global-proxied-controller-with-proxy-controller [controller context] (let [parent-app (:keechma.root/parent context) proxied-controller (:keechma.controller/proxy controller) is-proxied-controller-global (-> parent-app protocols/-get-app-state* deref (get-in [:controllers proxied-controller :keechma.controller/is-global]))] (merge {:keechma.controller/is-global is-proxied-controller-global} controller))) TODO : validate - controllers ca n't depend on non - existing controller (defn prepare-controllers [controllers context] (->> controllers (map (fn [[k v]] (let [v' (cond-> v (= :static (:keechma.controller.type/variant v)) ctrl/prep (:keechma.controller/proxy v) (merge-is-global-proxied-controller-with-proxy-controller context))] [k (merge context v')]))) (into {}))) (defn prepare-apps [apps] (->> apps (map (fn [[k v]] [k (update v :keechma.app/deps set)])) (into {}))) (defn register-controllers-app-index [app-state path controllers] (let [app-controllers (->> controllers (map (fn [[k _]] [k path])) (into {}))] (-> app-state (assoc-in [:app->controllers-index path] (set (keys controllers))) (update :controller->app-index #(merge % app-controllers))))) (defn deregister-controllers-app-index [app-state path controller-names] (-> app-state (dissoc-in [:app->controllers-index path]) (update :controller->app-index #(apply dissoc % controller-names)))) (defn controller-exists? [{:keys [controllers]} controller-name] If we have a controller with composite key ( e.g. ` [: controller - name 1 ] ` ) we need to ;; check if the factory controller with the name `[:controller-name]` exists. (if (vector? controller-name) (or (contains? controllers controller-name) (contains? controllers (subvec controller-name 0 1))) (contains? controllers controller-name))) (defn validate-controller-exists! [app-state controller-name] (when-not (controller-exists? app-state controller-name) (throw (keechma-ex-info "Attempted to subscribe to a non existing controller" :keechma.controller.errors/missing {:keechma/controller controller-name})))) (defn validate-controllers-deps! [app-controllers visible-controllers] (let [errors (reduce-kv (fn [acc k v] (let [deps (:keechma.controller/deps v) visible-controllers' (disj visible-controllers k) missing-deps (set/difference (set deps) visible-controllers')] (if (seq missing-deps) (update acc k conj {:keechma.anomalies/category :keechma.controller.errors/missing-deps :keechma.controller/missing-deps missing-deps}) acc))) {} app-controllers)] (when-not (empty? errors) (throw (keechma-ex-info "Invalid controllers" :keechma.controllers.errors/invalid {:keeechma.controllers/invalid errors}))))) (defn validate-controllers-on-app-register! [controllers existing-controllers path] (let [errors (reduce-kv (fn [acc k _] (if (contains? existing-controllers k) (update acc k conj {:keechma.anomalies/category :keechma.controller.errors/duplicate-name :keechma.app/path path}) acc)) {} controllers)] (when-not (empty? errors) (throw (keechma-ex-info "Invalid controllers" :keechma.controllers.errors/invalid {:keeechma.controllers/invalid errors}))))) (defn register-app [app-state {:keys [path controllers] :as app-ctx}] (validate-controllers-on-app-register! controllers (:controllers app-state) path) (-> app-state (assoc-in (get-app-store-path path) app-ctx) (update :controllers merge controllers) (register-controllers-app-index path controllers))) (defn deregister-app [app-state path] (let [app-store-path (get-app-store-path path) app-ctx (get-in app-state app-store-path) controller-names (-> app-ctx :controllers keys set) remove-controllers #(apply dissoc % controller-names)] (-> app-state (dissoc-in app-store-path) (update :controllers remove-controllers) (update :app-db remove-controllers) (deregister-controllers-app-index path controller-names) (update-in [:transaction :dirty] set/difference controller-names)))) (def keechma-keys-to-dissoc #{:keechma/apps :keechma/controllers :keechma.subscriptions/batcher :keechma/is-transacting :keechma.app/should-run? :keechma.app/deps :keechma.app/variant :keechma/trace}) (defn dissoc-keechma-keys [app] (apply dissoc app keechma-keys-to-dissoc)) (defn make-ctx [app {:keys [context] :as initial-ctx}] (let [context' (merge context (dissoc-keechma-keys app)) apps (prepare-apps (:keechma/apps app)) controllers (prepare-controllers (:keechma/controllers app) context') ancestor-controllers (:visible-controllers initial-ctx) visible-controllers (set/union ancestor-controllers (set (keys controllers))) controllers-graph (build-controllers-graph controllers)] (validate-controllers-deps! controllers visible-controllers) (merge initial-ctx {:keechma/apps apps :controllers controllers :context context' :visible-controllers visible-controllers :controllers-graph controllers-graph :apps nil}))) (defn assoc-empty-transaction [app-state] (assoc app-state :transaction {:dirty #{} :dirty-meta #{}})) (defn get-controller-instance [app-state controller-name] (get-in app-state [:app-db controller-name :instance])) (defn stopped? [app-state] (= ::stopped (:keechma.app/state app-state))) (defn -transact [app-state* transaction] (when-not (stopped? @app-state*) (let [res (binding [*transaction-depth* (inc *transaction-depth*)] (transaction))] (reconcile-after-transaction! app-state*) res))) (defn -call [app-state* controller-name api-fn & args] (let [app-state @app-state*] (when-not (stopped? app-state) (let [controller-instance (get-controller-instance app-state controller-name)] (if (:keechma.controller/proxy controller-instance) (let [app (:keechma.root/parent controller-instance) controller-name (:keechma.controller/proxy controller-instance) app-id (:keechma.app/id app-state)] (binding [*app-id->transaction-depth* (assoc *app-id->transaction-depth* app-id *transaction-depth*) *transaction-depth* 0] (protocols/-call app controller-name api-fn args))) (let [api (:keechma.controller/api controller-instance)] (apply api-fn api args))))))) (defn -get-api* [app-state* controller-name] (reify IDeref (-deref [_] (get-in @app-state* [:app-db controller-name :instance :keechma.controller/api])))) (defn -dispatch ([app-state* controller-name event] (-dispatch app-state* controller-name event)) ([app-state* controller-name event payload] (let [app-state @app-state*] (when-not (stopped? app-state) (let [controller (get-in app-state [:app-db controller-name]) controller-instance (:instance controller) controller-phase (:phase controller) app-id (:keechma.app/id app-state)] (cond (and (not= controller-phase :proxied-controller-stopped) (:keechma.controller/proxy controller-instance)) (let [app (:keechma.root/parent controller-instance) controller-name (:keechma.controller/proxy controller-instance)] (binding [*app-id->transaction-depth* (assoc *app-id->transaction-depth* app-id *transaction-depth*) *transaction-depth* 0] (protocols/-dispatch app controller-name event payload))) (= :initializing controller-phase) (swap! app-state* update-in [:app-db controller-name :events-buffer] conj [event payload]) controller-instance (-transact app-state* #(ctrl/handle (assoc controller-instance :keechma/is-transacting true) event payload)))))))) (defn get-derived-app-state [app-state] (->> app-state :app-db (map (fn [[k v]] (when (and (not (and (vector? k) (= 1 (count k)))) (controller-state-relevant? v)) [k (:derived-state v)]))) (filter identity) (into {}))) (defn get-app-meta-state [app-state] (->> app-state :app-db (map (fn [[k v]] (when (and (not (and (vector? k) (= 1 (count k)))) (controller-state-relevant? v)) [k (:meta-state v)]))) (filter identity) (into {}))) (defn app-broadcast [app-state* path event payload is-broadcasting-from-proxied-controller] (let [app-state @app-state* ordered-controller-names (get-sorted-controllers-for-app app-state path) app-ctx (get-in app-state (get-app-store-path path)) apps-definitions (:keechma/apps app-ctx)] (binding [*transaction-depth* (inc *transaction-depth*)] (doseq [controller-name ordered-controller-names] (let [is-proxy-controller (get-in app-state [:app-db controller-name :instance :keechma.controller/proxy])] (when (or (not is-broadcasting-from-proxied-controller) (and is-broadcasting-from-proxied-controller (not is-proxy-controller))) (-dispatch app-state* controller-name event payload)))) (doseq [[app-name _] apps-definitions] (let [path (conj path app-name) app-ctx (get-in @app-state* (get-app-store-path path))] (when (:is-running app-ctx) (app-broadcast app-state* path event payload is-broadcasting-from-proxied-controller))))))) (defn -broadcast ([app-state* event] (-broadcast app-state* event nil false)) ([app-state* event payload] (-broadcast app-state* event payload false)) ([app-state* event payload is-broadcasting-from-proxied-controller] (when-not (stopped? @app-state*) (app-broadcast app-state* [] event payload is-broadcasting-from-proxied-controller) (reconcile-after-transaction! app-state*)))) (defn prep [controller] ;; TODO: Should we cache this? (if (= :dynamic (:keechma.controller.type/variant controller)) (ctrl/prep controller) controller)) (defn notify-proxied-controllers-apps-on-dispatch [app-state* controller-name target-controller-name event payload] (let [subscriptions (-> app-state* deref (get-in [:subscriptions-on-controller-dispatch controller-name]) vals)] (doseq [app-subs subscriptions] (let [subscribed-controllers (-> app-subs keys set) sub-fn (-> app-subs vals first)] (sub-fn subscribed-controllers target-controller-name event payload))))) (defn notify-proxied-controllers-apps-on-broadcast [app-state* controller-name event payload] (let [subscriptions (-> app-state* deref (get-in [:subscriptions-on-controller-broadcast controller-name]) vals)] (doseq [app-subs subscriptions] (let [subscribed-controllers (-> app-subs keys set) sub-fn (-> app-subs vals first)] (sub-fn subscribed-controllers event payload))))) (defn make-controller-instance [app-state* controller-name controller-type params] (let [{:keys [batcher] :as app-state} @app-state* controller (-> app-state (get-in [:controllers controller-name]) (assoc :keechma.controller/type controller-type) prep) params' (ctrl/params (assoc controller :keechma.controller/name controller-name) params)] (when params' (let [state* (atom nil) meta-state* (atom nil) id (keyword (gensym 'controller-instance-))] (assoc controller :keechma.controller/name controller-name :keechma.controller/params params' :keechma.controller/id id :keechma/app (reify IAppInstance (-dispatch [_ target-controller-name event] (batcher (fn [] (with-tracing app-state* (trace! :keechma.controller/dispatch {:keechma/controller target-controller-name :keechma.controller/source controller-name :event event :payload nil}) (-dispatch app-state* target-controller-name event nil) (notify-proxied-controllers-apps-on-dispatch app-state* controller-name target-controller-name event nil))))) (-dispatch [_ target-controller-name event payload] (batcher (fn [] (with-tracing app-state* (trace! :keechma.controller/dispatch {:keechma/controller target-controller-name :keechma.controller/source controller-name :event event :payload payload}) (-dispatch app-state* target-controller-name event payload) (notify-proxied-controllers-apps-on-dispatch app-state* controller-name target-controller-name event payload))))) (-broadcast [_ event] (batcher (fn [] (with-tracing app-state* (trace! :keechma.controller/broadcast {:keechma.controller/source controller-name :event event :payload nil}) (-broadcast app-state* event nil) (notify-proxied-controllers-apps-on-broadcast app-state* controller-name event nil))))) (-broadcast [_ event payload] (batcher (fn [] (with-tracing app-state* (trace! :keechma.controller/broadcast {:keechma.controller/source controller-name :event event :payload payload}) (-broadcast app-state* event payload) (notify-proxied-controllers-apps-on-broadcast app-state* controller-name event payload))))) (-call [_ target-controller-name api-fn args] (let [controller-running-deps-map (get-controller-running-deps-map @app-state* controller-name) deps-name->renamed (set/map-invert controller-running-deps-map) real-target-controller-name (get deps-name->renamed target-controller-name)] (if (not real-target-controller-name) (let [controller (get-in @app-state* [:controllers target-controller-name])] (if (:keechma.controller/is-global controller) (with-tracing app-state* (trace! :keechma.controller/call {:keechma.controller/source controller-name :keechma/controller target-controller-name :fn api-fn :args args}) (apply -call app-state* target-controller-name api-fn args)) (throw (keechma-ex-info "Attempted to call an API function on non-existing dep" :keechma.controller.deps/missing {:keechma.controller.api/fn api-fn :keechma.controller.api/args args :keechma.controller/dep target-controller-name})))) (with-tracing app-state* (trace! :keechma.controller/call {:keechma.controller/source controller-name :keechma/controller real-target-controller-name :fn api-fn :args args}) (apply -call app-state* real-target-controller-name api-fn args))))) (-get-api* [_ controller-name] (-get-api* app-state* controller-name)) (-transact [_ transaction] (with-tracing app-state* (-transact app-state* transaction))) (-get-id [_] (:keechma.app/id @app-state*))) :meta-state* meta-state* :state* state* :deps-state* (reify IDeref (-deref [_] (get-controller-derived-deps-state @app-state* controller-name)))))))) (defn notify-subscriptions-meta ([app-state] (notify-subscriptions-meta app-state nil)) ([app-state dirty-meta] (let [app-db (:app-db app-state) subscriptions-meta (:subscriptions-meta app-state) selected-subscriptions-meta (if dirty-meta (select-keys subscriptions-meta dirty-meta) subscriptions-meta)] (doseq [[controller-key subs] selected-subscriptions-meta] (let [meta-state (get-in app-db [controller-key :meta-state])] (doseq [sub (vals subs)] (sub meta-state))))))) (defn notify-subscriptions [app-state] (let [app-db (:app-db app-state) subscriptions (:subscriptions app-state)] (doseq [[controller-key subs] subscriptions] (let [derived-state (get-in app-db [controller-key :derived-state])] (doseq [sub (vals subs)] (sub derived-state)))) (notify-subscriptions-meta app-state))) (defn notify-fences [app-state] (let [fences-sub-fns (-> app-state :fences vals)] (when (seq fences-sub-fns) (let [derived-app-state (get-derived-app-state app-state) app-meta-state (get-app-meta-state app-state)] (doseq [fence-sub-fn fences-sub-fns] (fence-sub-fn derived-app-state app-meta-state)))))) (defn batched-notify-subscriptions-meta ([{:keys [batcher] :as app-state}] (batcher #(notify-subscriptions-meta app-state))) ([{:keys [batcher] :as app-state} dirty-meta] (batcher #(notify-subscriptions-meta app-state dirty-meta)))) (defn batched-notify-subscriptions [{:keys [batcher] :as app-state}] (batcher #(notify-subscriptions app-state))) (defn sync-controller->app-db! [app-state* controller-name] (let [app-state @app-state* app-db (:app-db app-state) controller (get app-db controller-name) instance (:instance controller) state (deref (:state* instance)) deps-state (get-controller-derived-deps-state app-state controller-name) new-derived-state (ctrl/derive-state instance state deps-state) new-app-db (-> app-db (dissoc-in [controller-name :events-buffer]) (assoc-in [controller-name :state] state) (assoc-in [controller-name :derived-state] new-derived-state))] (trace! :keechma.controller/state* {:keechma/controller controller-name :state.derived/prev (get-in app-state [:app-db controller-name :state]) :state.derived/next new-derived-state :state/next state}) (swap! app-state* assoc :app-db new-app-db))) (defn sync-controller-meta->app-db! [app-state* controller-name] (let [app-state @app-state* meta-state* (get-in app-state [:app-db controller-name :instance :meta-state*])] (trace! :keechma.controller/meta-state* {:keechma/controller controller-name :meta-state/prev (get-in app-state [:app-db controller-name :meta-state]) :meta-state/next @meta-state*}) (swap! app-state* assoc-in [:app-db controller-name :meta-state] @meta-state*))) (defn transaction-mark-dirty! [app-state* controller-name] (swap! app-state* update-in [:transaction :dirty] conj controller-name)) (defn transaction-unmark-dirty! [app-state* controller-name] (swap! app-state* update-in [:transaction :dirty] disj controller-name)) (defn transaction-mark-dirty-meta! [app-state* controller-name] (swap! app-state* update-in [:transaction :dirty-meta] conj controller-name)) (defn on-controller-state-change! [app-state* controller-name] (with-tracing app-state* (when-not *stopping* (sync-controller->app-db! app-state* controller-name) (if (transacting?) (transaction-mark-dirty! app-state* controller-name) (do (when ^boolean goog.DEBUG (js/console.warn "Controller state updated outside transact block. Controller:" (str controller-name))) (transaction-mark-dirty! app-state* controller-name) (reconcile-after-transaction! app-state*)))))) (defn on-controller-meta-state-change! [app-state* controller-name] (with-tracing app-state* (when-not *stopping* (sync-controller-meta->app-db! app-state* controller-name) (if (transacting?) (transaction-mark-dirty-meta! app-state* controller-name) (do (notify-fences @app-state*) (batched-notify-subscriptions-meta @app-state* #{controller-name})))))) (defn get-proxied-controller [app-state controller-name] (let [controller-instance (get-in app-state [:app-db controller-name :instance]) parent-app (:keechma.root/parent controller-instance) proxied-controller-name (:keechma.controller/proxy controller-instance)] (-> parent-app protocols/-get-app-state* deref (get-in [:app-db proxied-controller-name])))) (defn on-proxied-controller-change! [app-state* controller-name] (when-not *stopping* (let [app-state @app-state* app-id (:keechma.app/id app-state) controller (get-in app-state [:app-db controller-name]) proxied-controller (get-proxied-controller app-state controller-name) {:keys [phase derived-state meta-state]} controller {proxied-phase :phase proxied-derived-state :derived-state proxied-meta-state :meta-state} proxied-controller is-derived-state-identical (identical? derived-state proxied-derived-state) is-meta-state-identical (identical? meta-state proxied-meta-state) is-phase-equal (= phase proxied-phase)] (binding [*transaction-depth* (get *app-id->transaction-depth* app-id 0)] (if proxied-controller (swap! app-state* update-in [:app-db controller-name] merge {:phase proxied-phase :derived-state proxied-derived-state :meta-state proxied-meta-state}) (swap! app-state* update-in [:app-db controller-name] merge {:phase :proxied-controller-stopped :derived-state nil :meta-state nil})) (when (or (not is-derived-state-identical) (not is-phase-equal)) (if (transacting?) (transaction-mark-dirty! app-state* controller-name) (do (transaction-mark-dirty! app-state* controller-name) (reconcile-after-transaction! app-state*)))) (when-not is-meta-state-identical (if (transacting?) (transaction-mark-dirty-meta! app-state* controller-name) (do (notify-fences @app-state*) (batched-notify-subscriptions-meta @app-state* #{controller-name})))))))) (defn on-proxied-controller-dispatch [app-state* subscribed-controllers target-controller-name event payload] (let [{:keys [batcher app-db]} @app-state* controller-name (->> subscribed-controllers (select-keys app-db) (filter (fn [[_ controller]] (= :running (:phase controller)))) ffirst)] (when controller-name (batcher (fn [] (-dispatch app-state* target-controller-name event payload) (notify-proxied-controllers-apps-on-dispatch app-state* controller-name target-controller-name event payload)))))) (defn on-proxied-controller-broadcast [app-state* subscribed-controllers event payload] (let [{:keys [batcher app-db]} @app-state* controller-name (->> subscribed-controllers (select-keys app-db) (filter (fn [[_ controller]] (= :running (:phase controller)))) ffirst)] (when controller-name (batcher (fn [] (-broadcast app-state* event payload true) (notify-proxied-controllers-apps-on-broadcast app-state* controller-name event payload)))))) (defn controller-start! [app-state* controller-name controller-type params] Based on params so far , we 're going to try to start the controller . There is one last chance to prevent it ;; and it will happen in the `make-controller-instance`. In that function, we'll assoc the real :keechma.controller/type for ;; the controllers with the dynamic type (fn based), and then the call `ctrl/params` function. If that function returns falsy value, we'll ;; abort the starting, and restore the app-state* to the previous state. (let [prev-controller-state (get-in @app-state* [:app-db controller-name]) prev-state (:state prev-controller-state)] (swap! app-state* assoc-in [:app-db controller-name] {:params params :type controller-type :phase :initializing :events-buffer []}) (let [controller-instance (make-controller-instance app-state* controller-name controller-type params)] (if-not controller-instance (swap! app-state* assoc-in [:app-db controller-name] prev-controller-state) (let [config (make-controller-instance app-state* controller-name controller-type params) inited (ctrl/init config) api (ctrl/api inited) instance (assoc inited :keechma.controller/api api)] (swap! app-state* assoc-in [:app-db controller-name :instance] instance) (let [state* (:state* instance) meta-state* (:meta-state* instance) deps-state (get-controller-derived-deps-state @app-state* controller-name) state (ctrl/start instance params deps-state prev-state)] (reset! state* state) (swap! app-state* update-in [:app-db controller-name] #(merge % {:state state :phase :starting :prev-deps-state deps-state})) (trace! :keechma.on/start {:keechma/controller controller-name :event :keechma.on/start :payload params}) (-dispatch app-state* controller-name :keechma.on/start params) (swap! app-state* assoc-in [:app-db controller-name :phase] :running) (doseq [[event payload] (get-in @app-state* [:app-db controller-name :events-buffer])] (-dispatch app-state* controller-name event payload)) (sync-controller->app-db! app-state* controller-name) (sync-controller-meta->app-db! app-state* controller-name) (add-watch meta-state* :keechma/app #(on-controller-meta-state-change! app-state* controller-name)) (add-watch state* :keechma/app #(on-controller-state-change! app-state* controller-name)))))))) (defn controller-stop! [app-state* controller-name] (let [instance (get-controller-instance @app-state* controller-name)] (if (:keechma.controller/proxy instance) (let [{:keys [unsubscribe unsubscribe-meta unsubscribe-on-controller-dispatch unsubscribe-on-controller-broadcast]} instance] (unsubscribe) (unsubscribe-meta) (unsubscribe-on-controller-dispatch) (unsubscribe-on-controller-broadcast) (swap! app-state* dissoc-in [:app-db controller-name])) (let [params (:keechma.controller/params instance) state* (:state* instance)] (swap! app-state* assoc-in [:app-db controller-name :phase] :stopping) (remove-watch state* :keechma/app) (remove-watch (:meta-state* instance) :keechma/app) (trace! :keechma.on/stop {:keechma/controller controller-name :event :keechma.on/stop :payload nil}) (-dispatch app-state* controller-name :keechma.on/stop nil) (let [deps-state (get-controller-derived-deps-state @app-state* controller-name) state (ctrl/stop instance params @state* deps-state)] (reset! state* state) (swap! app-state* assoc-in [:app-db controller-name] {:state state})) (ctrl/terminate instance))))) (defn controller-on-deps-change! [app-state* controller-name] (let [app-state @app-state* prev-deps-state (get-in app-state [:app-db controller-name :prev-deps-state]) deps-state (get-controller-derived-deps-state @app-state* controller-name) instance (get-in app-state [:app-db controller-name :instance]) dirty-deps (get-dirty-deps prev-deps-state deps-state)] (when dirty-deps (trace! :keechma.on/deps-change {:keechma/controller controller-name :event :keechma.on/deps-change :payload dirty-deps}) (swap! app-state* assoc-in [:app-db controller-name :prev-deps-state] deps-state) (-dispatch app-state* controller-name :keechma.on/deps-change dirty-deps) (let [state (-> instance :state* deref) derived-state (ctrl/derive-state instance state deps-state)] (swap! app-state* assoc-in [:app-db controller-name :derived-state] derived-state))))) (defn idempotently-proxy-controller-start! [app-state* controller-name] (let [app-state @app-state*] (when-not (get-in app-state [:app-db controller-name :instance]) (let [controller (get-in app-state [:controllers controller-name]) proxied-controller-name (:keechma.controller/proxy controller) parent-app (:keechma.root/parent controller)] (when-not parent-app (throw (keechma-ex-info "Attempted to proxy controller from a non-existing parent app" :keechma.root.parent/missing {:keechma/controller controller-name :keechma.controller/proxy proxied-controller-name}))) (let [derived-state (protocols/-get-derived-state parent-app proxied-controller-name) meta-state (protocols/-get-meta-state parent-app proxied-controller-name) handler (fn [_] (on-proxied-controller-change! app-state* controller-name)) unsubscribe (protocols/-subscribe parent-app proxied-controller-name handler) unsubscribe-meta (protocols/-subscribe-meta parent-app proxied-controller-name handler) app-id (:keechma.app/id app-state) unsubscribe-on-controller-dispatch (protocols/-subscribe-on-controller-dispatch parent-app app-id proxied-controller-name controller-name (fn [subscribed-controllers target-controller-name event payload] (on-proxied-controller-dispatch app-state* subscribed-controllers target-controller-name event payload))) unsubscribe-on-controller-broadcast (protocols/-subscribe-on-controller-broadcast parent-app app-id proxied-controller-name controller-name (fn [subscribed-controllers event payload] (on-proxied-controller-broadcast app-state* subscribed-controllers event payload))) controller' (assoc controller :unsubscribe unsubscribe :unsubscribe-meta unsubscribe-meta :unsubscribe-on-controller-dispatch unsubscribe-on-controller-dispatch :unsubscribe-on-controller-broadcast unsubscribe-on-controller-broadcast)] (swap! app-state* update-in [:app-db controller-name] merge {:derived-state derived-state :meta-state meta-state :instance controller' :phase :running})))))) (defn reconcile-controller-lifecycle-state! [app-state* controller-name] (if (get-in @app-state* [:controllers controller-name :keechma.controller/proxy]) (idempotently-proxy-controller-start! app-state* controller-name) ;; For each controller in the to-reconcile vector do what is needed based on the return value of ;; the params and the type function ;; ;; ;; +---------------------------+-------------+----------------+-------------------------------+---------------------------------------------------------------------------+ ;; | Prev Type == Current Type | Prev Params | Current Params | Prev Params == Current Params | Actions | ;; +---------------------------+-------------+----------------+-------------------------------+---------------------------------------------------------------------------+ | false | | | - | Do nothing | | false | | | - | Stop the current controller instance | | false | | truthy | - | Start a new controller instance | | false | | truthy | - | Stop the current controller instance and start a new one | | true | | | - | Do nothing | | true | | | - | Stop the current controller instance | | true | | truthy | - | Start a new controller instance | | true | | truthy | false | Stop the current controller instance and start a new one | | true | | truthy | true | Dispatch : keechma.on/deps-change event to the running controller instance | ;; +---------------------------+-------------+----------------+-------------------------------+---------------------------------------------------------------------------+ (let [app-state @app-state* {params :params controller-type :type} (get-params-and-type app-state controller-name)] (assert (isa? controller-type :keechma/controller) (str "Controller " controller-name " has type " controller-type " which is not derived from :keechma/controller")) (let [current-params (get-in app-state [:app-db controller-name :params]) current-controller-type (get-in app-state [:app-db controller-name :type]) actions (determine-actions current-params params current-controller-type controller-type)] (when (contains? actions :stop) (controller-stop! app-state* controller-name)) (when (contains? actions :start) (controller-start! app-state* controller-name controller-type params)) (when (contains? actions :deps-change) (controller-on-deps-change! app-state* controller-name)))))) (defn reconcile-controller-factory! [app-state* controller-name] (let [app-state @app-state* controllers (:controllers app-state) app-db (:app-db app-state) config (get controllers controller-name) prev-produced-keys (get-in app-db [controller-name :produced-keys]) factory-deps (:keechma.controller/deps config) produced (->> (get-factory-produced @app-state* controller-name) (reduce (fn [acc [k produced-config]] (let [produced-controller-name (conj controller-name k) conformed-produced-config (conform-factory-produced produced-config) factory-produced-deps (:keechma.controller/deps conformed-produced-config)] (assert (factory-produced-deps-valid? app-db factory-deps factory-produced-deps)) (assoc! acc (conj controller-name k) (-> (merge config conformed-produced-config) (assoc :keechma.controller/variant :identity :keechma.controller/name produced-controller-name :keechma.controller/factory controller-name))))) (transient {})) persistent!) produced-keys (set (keys produced)) running-keys (->> @app-state* :app-db (filter (fn [[k v]] (and (contains? prev-produced-keys k) (= :running (:phase v))))) (map first) set) to-remove (set/difference running-keys produced-keys)] (doseq [controller-name to-remove] (controller-stop! app-state* controller-name)) (swap! app-state* (fn [app-state] (let [{:keys [controllers app-db]} app-state app-db' (-> (apply dissoc app-db to-remove) (assoc-in [controller-name :produced-keys] produced-keys)) controllers' (-> (apply dissoc controllers to-remove) (merge produced))] (assoc app-state :app-db app-db' :controllers controllers')))) (loop [produced-keys' produced-keys] (when (seq produced-keys') (let [[controller-name & rest-produced-keys] produced-keys'] (reconcile-controller-lifecycle-state! app-state* controller-name) (recur rest-produced-keys)))))) (defn reconcile-controllers! [app-state* to-reconcile] (loop [to-reconcile' to-reconcile] (when (seq to-reconcile') (let [[current & rest-to-reconcile] to-reconcile' controller-variant (get-in @app-state* [:controllers current :keechma.controller/variant])] (if (= :factory controller-variant) (reconcile-controller-factory! app-state* current) (reconcile-controller-lifecycle-state! app-state* current)) (transaction-unmark-dirty! app-state* current) (recur rest-to-reconcile))))) (defn stop-app! [app-state* path] (let [app-state @app-state* app-ctx (get-in app-state (get-app-store-path path))] (when app-ctx (trace! :keechma.app/stop {:keechma/app path}) (let [apps (:apps app-ctx) to-reconcile (reverse (get-sorted-controllers-for-app app-state path))] (doseq [[app-name _] apps] (stop-app! app-state* (conj path app-name))) (doseq [controller-name to-reconcile] (when (get-controller-instance @app-state* controller-name) (controller-stop! app-state* controller-name))) (swap! app-state* deregister-app path))))) (defn reconcile-app! [app-state* path dirty] (let [app-state @app-state* {:keys [controllers-graph]} (get-in app-state (get-app-store-path path)) subgraph (subgraph-reachable-from-set controllers-graph dirty) to-reconcile (->> subgraph dep/topo-sort (filterv #(= path (get-in app-state [:controller->app-index %]))))] (reconcile-controllers! app-state* to-reconcile) (let [app-state @app-state* app-ctx (get-in app-state (get-app-store-path path)) apps-definitions (:keechma/apps app-ctx) apps-by-should-run (reduce-kv (fn [acc app-name app] (let [should-run? (:keechma.app/should-run? app) deps (get-derived-deps-state app-state (:controllers app-state) (:keechma.app/deps app))] (update acc (boolean (should-run? deps)) conj app-name))) {true #{} false #{}} apps-definitions)] (doseq [app-name (get apps-by-should-run false)] (stop-app! app-state* (conj path app-name))) (doseq [app-name (get apps-by-should-run true)] (let [app-state @app-state* path (conj path app-name) child-app-ctx (get-in app-state (get-app-store-path path))] (if (:is-running child-app-ctx) (reconcile-app! app-state* path (set/union dirty (get-in app-state [:transaction :dirty]) (set to-reconcile))) (do (trace! :keechma.app/start {:keechma/app path}) (swap! app-state* register-app (make-ctx (get apps-definitions app-name) (merge app-ctx {:path path :is-running true}))) (reconcile-initial! app-state* path)))))))) (defn reconcile-after-transaction! [app-state*] (when-not (transacting?) (let [app-state @app-state* transaction (:transaction app-state) dirty (:dirty transaction) dirty-meta (:dirty-meta transaction)] (cond (seq dirty) (let [controller-apps (->> dirty (map #(get-in app-state [:controller->app-index %])) set) lca-path (get-lowest-common-ancestor-for-paths controller-apps)] (swap! app-state* assoc-empty-transaction) (binding [*transaction-depth* (inc *transaction-depth*)] (reconcile-app! app-state* lca-path dirty)) (let [app-state @app-state* dirty (get-in app-state [:transaction :dirty])] (if (seq dirty) (recur app-state*) (do (notify-fences @app-state*) (batched-notify-subscriptions @app-state*))))) (seq dirty-meta) (do (swap! app-state* assoc-empty-transaction) (notify-fences @app-state*) (batched-notify-subscriptions-meta @app-state* dirty-meta)))))) (defn reconcile-initial! ([app-state* path] (reconcile-initial! app-state* path 0)) ([app-state* path depth] (let [app-state @app-state* to-reconcile (get-sorted-controllers-for-app app-state path) app-ctx (get-in app-state (get-app-store-path path)) apps-definitions (:keechma/apps app-ctx)] (binding [*transaction-depth* (inc *transaction-depth*)] (reconcile-controllers! app-state* to-reconcile) (doseq [[app-name app] apps-definitions] (let [app-state @app-state* should-run? (:keechma.app/should-run? app) deps (get-derived-deps-state app-state (:controllers app-state) (:keechma.app/deps app))] (when (should-run? deps) (let [path (conj path app-name) app-ctx (make-ctx app (merge app-ctx {:path path :is-running true}))] (swap! app-state* register-app app-ctx) (reconcile-initial! app-state* path (inc depth))))))) (when (zero? depth) (reconcile-after-transaction! app-state*))))) (defn start! ([app] (start! app nil)) ([app parent-app] (let [app' (cond-> app parent-app (assoc :keechma.root/parent parent-app) true conform) app-id (str (gensym 'app-id)) parent-app-state (when parent-app (-> parent-app protocols/-get-app-state* deref)) parent-app-batcher (:batcher parent-app-state) parent-app-trace (:keechma/trace parent-app) batcher (or (:keechma.subscriptions/batcher app') parent-app-batcher default-batcher) trace (or (:keechma/trace app') parent-app-trace) ctx (make-ctx app' {:path [] :is-running true}) app-state* (atom (-> {:batcher batcher :keechma.app/state ::running :keechma.app/id app-id :keechma/trace trace :keechma.app.reconciliation/generation 0} (assoc-empty-transaction) (register-app ctx)))] (with-tracing app-state* (trace! :keechma.app/start nil) (reconcile-initial! app-state* [])) (reify IAppInstance (-dispatch [_ controller-name event] (-dispatch app-state* controller-name event nil)) (-dispatch [_ controller-name event payload] (-dispatch app-state* controller-name event payload)) (-broadcast [_ event] (-broadcast app-state* event nil)) (-broadcast [app-state* event payload] (-broadcast app-state* event payload)) (-call [_ controller-name api-fn args] (apply -call app-state* controller-name api-fn args)) (-get-api* [_ controller-name] (-get-api* app-state* controller-name)) (-transact [_ transaction] (-transact app-state* transaction)) (-get-id [_] app-id) IRootAppInstance (-stop! [_] (binding [*stopping* true] (stop-app! app-state* [])) (swap! app-state* assoc :keechma.app/state ::stopped)) (-get-batcher [_] batcher) (-subscribe [_ controller-name sub-fn] (validate-controller-exists! @app-state* controller-name) (let [sub-id (-> 'sub-id gensym keyword)] (swap! app-state* assoc-in [:subscriptions controller-name sub-id] sub-fn) (partial unsubscribe! app-state* controller-name sub-id))) (-subscribe-meta [_ controller-name sub-fn] (validate-controller-exists! @app-state* controller-name) (let [sub-id (-> 'sub-meta-id gensym keyword)] (swap! app-state* assoc-in [:subscriptions-meta controller-name sub-id] sub-fn) (partial unsubscribe-meta! app-state* controller-name sub-id))) (-subscribe-fence [_ sub-fn] (let [fence-sub-id (-> 'fence-sub-id gensym keyword)] (swap! app-state* assoc-in [:fences fence-sub-id] sub-fn) #(swap! app-state* dissoc-in [:fences fence-sub-id]))) (-subscribe-on-controller-dispatch [_ app-id controller-name subscribing-controller-name sub-fn] (validate-controller-exists! @app-state* controller-name) (swap! app-state* assoc-in [:subscriptions-on-controller-dispatch controller-name app-id subscribing-controller-name] sub-fn) #(swap! app-state* dissoc-in [:subscriptions-on-controller-dispatch controller-name app-id subscribing-controller-name])) (-subscribe-on-controller-broadcast [_ app-id controller-name subscribing-controller-name sub-fn] (validate-controller-exists! @app-state* controller-name) (swap! app-state* assoc-in [:subscriptions-on-controller-broadcast controller-name app-id subscribing-controller-name] sub-fn) #(swap! app-state* dissoc-in [:subscriptions-on-controller-broadcast controller-name app-id subscribing-controller-name])) (-get-derived-state [_] (get-derived-app-state @app-state*)) (-get-derived-state [_ controller-name] (get-in @app-state* [:app-db controller-name :derived-state])) (-get-meta-state [_] (get-app-meta-state @app-state*)) (-get-meta-state [_ controller-name] (get-in @app-state* [:app-db controller-name :meta-state])) (-get-app-state* [_] app-state*))))) (defn make-app-proxy [proxied-fn] (fn [& args] (apply proxied-fn args))) (def stop! ^{:doc "Stops the running application instance. This will stop and terminate all running controllers." :arglists '([app-instance])} (make-app-proxy protocols/-stop!)) (defn dispatch "Dispatches an event to a controller." ([app-instance controller-name event] (dispatch app-instance controller-name event nil)) ([app-instance controller-name event payload] (with-tracing (protocols/-get-app-state* app-instance) (trace! :keechma/dispatch {:keechma/controller controller-name :event event :payload payload}) (protocols/-dispatch app-instance controller-name event payload)))) (defn broadcast "Broadcasts an event to all running-controllers" ([app-instance event] (broadcast app-instance event nil)) ([app-instance event payload] (with-tracing (protocols/-get-app-state* app-instance) (trace! :keechma/broadcast {:event event :payload payload}) (protocols/-broadcast app-instance event payload)))) (defn transact "Runs the transaction fn inside the transact block." [app-instance transaction] (with-tracing (protocols/-get-app-state* app-instance) (protocols/-transact app-instance transaction))) (def subscribe ^{:doc "Subscribes to the controller's state. Subscription fn will be called whenever the controller's state changes." :arglists '([app-instance controller-name sub-fn])} (make-app-proxy protocols/-subscribe)) (def subscribe-meta ^{:doc "Subscribes to the controller's meta state. Subscription fn will be called whenever the controller's state changes." :arglists '([app-instance controller-name sub-fn])} (make-app-proxy protocols/-subscribe-meta)) (def get-derived-state ^{:doc "Returns the current state of all running controllers, or of the controller whose name is passed as the argument." :arglists '([app-instance] [app-instance controller-name])} (make-app-proxy protocols/-get-derived-state)) (def get-meta-state ^{:doc "Returns the current meta state of the controller." :arglists '([app-instance controller-name])} (make-app-proxy protocols/-get-meta-state)) (def get-batcher ^{:doc "Returns the batcher fn. Subscription fns are called inside the batcher - this is useful for React integration, to ensure that there are no unnecessary re-renderings." :arglists '([app-instance])} (make-app-proxy protocols/-get-batcher)) (def get-id ^{:doc "Returns the app-instance's id." :arglists '([app-instance])} (make-app-proxy protocols/-get-id)) (def get-api* ^{:doc "Returns controller's exposed API object wrapped in a derefable object." :arglists '([app-instance controller-name])} (make-app-proxy protocols/-get-api*)) (def get-app-state* ^{:doc "Returns the atom holding the app-state" :arglists '([app-instance])} (make-app-proxy protocols/-get-app-state*)) (defn call "Calls an API fn on the controller's exposed API object." [app-instance controller-name api-fn & args] (with-tracing (protocols/-get-app-state* app-instance) (trace! :keechma/call {:keechma/controller controller-name :fn api-fn :args args}) (protocols/-call app-instance controller-name api-fn args))) (defn get-running-controllers "Returns a map of running controllers. Useful for debugging." [app-instance] (let [app-state* (get-app-state* app-instance) app-state @app-state*] (:app-db app-state)))
null
https://raw.githubusercontent.com/keechma/keechma-next/324ca9a5ccae56ae5cc5e592c9681e85a1be1f0a/src/keechma/next/core.cljs
clojure
controller types are different controller types are same check if the factory controller with the name `[:controller-name]` exists. TODO: Should we cache this? and it will happen in the `make-controller-instance`. In that function, we'll assoc the real :keechma.controller/type for the controllers with the dynamic type (fn based), and then the call `ctrl/params` function. If that function returns falsy value, we'll abort the starting, and restore the app-state* to the previous state. For each controller in the to-reconcile vector do what is needed based on the return value of the params and the type function +---------------------------+-------------+----------------+-------------------------------+---------------------------------------------------------------------------+ | Prev Type == Current Type | Prev Params | Current Params | Prev Params == Current Params | Actions | +---------------------------+-------------+----------------+-------------------------------+---------------------------------------------------------------------------+ +---------------------------+-------------+----------------+-------------------------------+---------------------------------------------------------------------------+
(ns keechma.next.core (:require [keechma.next.controller :as ctrl] [keechma.next.graph :refer [subgraph-reachable-from-set]] [keechma.next.util :refer [get-dirty-deps get-lowest-common-ancestor-for-paths]] [keechma.next.protocols :as protocols :refer [IAppInstance IRootAppInstance]] [keechma.next.conformer :refer [conform conform-factory-produced]] [keechma.next.tracing :refer [trace! with-tracing]] [medley.core :refer [dissoc-in]] [weavejester.dependency :as dep] [clojure.set :as set])) (declare -dispatch) (declare reconcile-after-transaction!) (declare reconcile-initial!) (def ^:dynamic *transaction-depth* 0) (def ^:dynamic *app-id->transaction-depth* {}) (def ^:dynamic *stopping* false) (defn transacting? [] (pos? *transaction-depth*)) (defn factory-produced-deps-valid? [app-db factory-deps factory-produced-deps] (let [expanded-factory-deps (reduce (fn [acc d] (let [dep-produced-keys (get-in app-db [d :produced-keys])] (if (seq dep-produced-keys) (set/union acc #{d} dep-produced-keys) (conj acc d)))) #{} factory-deps)] (set/subset? factory-produced-deps expanded-factory-deps))) (defn keechma-ex-info ([message anomaly] (keechma-ex-info message anomaly {})) ([message anomaly props] (ex-info message (assoc props :keechma.anomalies/category anomaly :keechma.anomalies/message message)))) (defn default-batcher [batched-fn] (batched-fn)) (defn build-controllers-graph [controllers] (reduce (fn [acc [k c]] (reduce (fn [acc' d] (dep/depend acc' k d)) acc (:keechma.controller/deps c))) (dep/graph) controllers)) (defn determine-actions [old-params new-params old-type new-type] (cond (and (not= old-type new-type) old-params new-params) #{:stop :start} (and (not= old-type new-type) (not old-params) new-params) #{:start} (and (not= old-type new-type) old-params (not new-params)) #{:stop} (and (= old-type new-type) (not old-params) new-params) #{:start} (and (= old-type new-type) old-params (not new-params)) #{:stop} (and (= old-type new-type) old-params new-params (not= old-params new-params)) #{:stop :start} (and (= old-type new-type) old-params new-params (= new-params old-params)) #{:deps-change} :else nil)) (defn controller-state-relevant? [controller] (->> controller :phase (contains? #{:starting :running}))) (defn get-derived-deps-state ([app-state controllers deps] (get-derived-deps-state app-state controllers deps nil)) ([app-state controllers deps renamed-deps] (let [app-db (:app-db app-state)] (when (seq deps) (-> (reduce (fn [acc dep-controller-name] (if (= :factory (get-in controllers [dep-controller-name :keechma.controller/variant])) (let [renamed-dep (get renamed-deps dep-controller-name)] (reduce (fn [acc' dep-controller-name'] (if (controller-state-relevant? (get app-db dep-controller-name')) (let [dep-controller-name'' (if renamed-dep (vec (concat renamed-dep (rest dep-controller-name'))) dep-controller-name')] (assoc! acc' dep-controller-name'' (get-in app-db [dep-controller-name' :derived-state]))) acc')) acc (get-in app-db [dep-controller-name :produced-keys]))) (if (controller-state-relevant? (get app-db dep-controller-name)) (let [dep-controller-name' (or (get renamed-deps dep-controller-name) dep-controller-name)] (assoc! acc dep-controller-name' (get-in app-db [dep-controller-name :derived-state]))) acc))) (transient {}) deps) persistent!))))) (defn get-controller-derived-deps-state [app-state controller-name] (let [controllers (:controllers app-state) controller (get controllers controller-name) controller-name' (or (get controller :keechma.controller/factory) controller-name) deps (get-in controllers [controller-name' :keechma.controller/deps]) renamed-deps (get-in controllers [controller-name :keechma.controller.deps/renamed])] (get-derived-deps-state app-state controllers deps renamed-deps))) (defn get-controller-running-deps-map [app-state controller-name] (let [app-db (:app-db app-state) controllers (:controllers app-state) controller (get controllers controller-name) controller-name' (or (get controller :keechma.controller/factory) controller-name) deps (get-in controllers [controller-name' :keechma.controller/deps]) renamed-deps (get-in controllers [controller-name :keechma.controller.deps/renamed])] (-> (reduce (fn [acc dep-controller-name] (if (= :factory (get-in controllers [dep-controller-name :keechma.controller/variant])) (let [renamed-dep (get renamed-deps dep-controller-name)] (reduce (fn [acc' dep-controller-name'] (if (contains? #{:starting :running} (get-in app-db [dep-controller-name' :phase])) (let [dep-controller-name'' (if renamed-dep (vec (concat renamed-dep (rest dep-controller-name'))) dep-controller-name')] (assoc! acc' dep-controller-name' dep-controller-name'')) acc')) acc (get-in app-db [dep-controller-name :produced-keys]))) (if (contains? #{:starting :running} (get-in app-db [dep-controller-name :phase])) (let [dep-controller-name' (or (get renamed-deps dep-controller-name) dep-controller-name)] (assoc! acc dep-controller-name dep-controller-name')) acc))) (transient {}) deps) persistent!))) (defn get-params-and-type [app-state controller-name] (let [controller (get-in app-state [:controllers controller-name]) derived-deps-state (get-controller-derived-deps-state app-state controller-name) params (:keechma.controller/params controller) type (:keechma.controller/type controller)] {:params (if (= :static (:keechma.controller.params/variant controller)) params (params derived-deps-state)) :type (if (= :static (:keechma.controller.type/variant controller)) type (type derived-deps-state))})) (defn get-factory-produced [app-state controller-name] (let [controller (get-in app-state [:controllers controller-name]) produce (:keechma.controller.factory/produce controller)] (produce (get-controller-derived-deps-state app-state controller-name)))) (defn get-app-store-path [app-path] (->> app-path (concat [:apps]) (interpose :apps) vec)) (defn make-controller-sort-comparator [controllers] (fn [ctrl-1 ctrl-2] (let [ctrl-1-is-global (get-in controllers [ctrl-1 :keechma.controller/is-global]) ctrl-2-is-global (get-in controllers [ctrl-2 :keechma.controller/is-global])] (cond (= ctrl-1-is-global ctrl-2-is-global) 0 ctrl-1-is-global -1 :else 1)))) (defn get-sorted-controllers-for-app [app-state path] (let [{:keys [controllers controllers-graph]} (get-in app-state (get-app-store-path path)) controller-sort-comparator (make-controller-sort-comparator controllers) nodeset (dep/nodes controllers-graph) sorted-controllers (->> controllers-graph (dep/topo-sort controller-sort-comparator) (filterv #(contains? controllers %))) isolated-controllers (->> (keys controllers) (filter #(not (contains? nodeset %))) (sort controller-sort-comparator))] (concat isolated-controllers sorted-controllers))) (defn unsubscribe! [app-state* controller-name sub-id] (swap! app-state* dissoc-in [:subscriptions controller-name sub-id])) (defn unsubscribe-meta! [app-state* controller-name sub-id] (swap! app-state* dissoc-in [:subscriptions-meta controller-name sub-id])) (defn merge-is-global-proxied-controller-with-proxy-controller [controller context] (let [parent-app (:keechma.root/parent context) proxied-controller (:keechma.controller/proxy controller) is-proxied-controller-global (-> parent-app protocols/-get-app-state* deref (get-in [:controllers proxied-controller :keechma.controller/is-global]))] (merge {:keechma.controller/is-global is-proxied-controller-global} controller))) TODO : validate - controllers ca n't depend on non - existing controller (defn prepare-controllers [controllers context] (->> controllers (map (fn [[k v]] (let [v' (cond-> v (= :static (:keechma.controller.type/variant v)) ctrl/prep (:keechma.controller/proxy v) (merge-is-global-proxied-controller-with-proxy-controller context))] [k (merge context v')]))) (into {}))) (defn prepare-apps [apps] (->> apps (map (fn [[k v]] [k (update v :keechma.app/deps set)])) (into {}))) (defn register-controllers-app-index [app-state path controllers] (let [app-controllers (->> controllers (map (fn [[k _]] [k path])) (into {}))] (-> app-state (assoc-in [:app->controllers-index path] (set (keys controllers))) (update :controller->app-index #(merge % app-controllers))))) (defn deregister-controllers-app-index [app-state path controller-names] (-> app-state (dissoc-in [:app->controllers-index path]) (update :controller->app-index #(apply dissoc % controller-names)))) (defn controller-exists? [{:keys [controllers]} controller-name] If we have a controller with composite key ( e.g. ` [: controller - name 1 ] ` ) we need to (if (vector? controller-name) (or (contains? controllers controller-name) (contains? controllers (subvec controller-name 0 1))) (contains? controllers controller-name))) (defn validate-controller-exists! [app-state controller-name] (when-not (controller-exists? app-state controller-name) (throw (keechma-ex-info "Attempted to subscribe to a non existing controller" :keechma.controller.errors/missing {:keechma/controller controller-name})))) (defn validate-controllers-deps! [app-controllers visible-controllers] (let [errors (reduce-kv (fn [acc k v] (let [deps (:keechma.controller/deps v) visible-controllers' (disj visible-controllers k) missing-deps (set/difference (set deps) visible-controllers')] (if (seq missing-deps) (update acc k conj {:keechma.anomalies/category :keechma.controller.errors/missing-deps :keechma.controller/missing-deps missing-deps}) acc))) {} app-controllers)] (when-not (empty? errors) (throw (keechma-ex-info "Invalid controllers" :keechma.controllers.errors/invalid {:keeechma.controllers/invalid errors}))))) (defn validate-controllers-on-app-register! [controllers existing-controllers path] (let [errors (reduce-kv (fn [acc k _] (if (contains? existing-controllers k) (update acc k conj {:keechma.anomalies/category :keechma.controller.errors/duplicate-name :keechma.app/path path}) acc)) {} controllers)] (when-not (empty? errors) (throw (keechma-ex-info "Invalid controllers" :keechma.controllers.errors/invalid {:keeechma.controllers/invalid errors}))))) (defn register-app [app-state {:keys [path controllers] :as app-ctx}] (validate-controllers-on-app-register! controllers (:controllers app-state) path) (-> app-state (assoc-in (get-app-store-path path) app-ctx) (update :controllers merge controllers) (register-controllers-app-index path controllers))) (defn deregister-app [app-state path] (let [app-store-path (get-app-store-path path) app-ctx (get-in app-state app-store-path) controller-names (-> app-ctx :controllers keys set) remove-controllers #(apply dissoc % controller-names)] (-> app-state (dissoc-in app-store-path) (update :controllers remove-controllers) (update :app-db remove-controllers) (deregister-controllers-app-index path controller-names) (update-in [:transaction :dirty] set/difference controller-names)))) (def keechma-keys-to-dissoc #{:keechma/apps :keechma/controllers :keechma.subscriptions/batcher :keechma/is-transacting :keechma.app/should-run? :keechma.app/deps :keechma.app/variant :keechma/trace}) (defn dissoc-keechma-keys [app] (apply dissoc app keechma-keys-to-dissoc)) (defn make-ctx [app {:keys [context] :as initial-ctx}] (let [context' (merge context (dissoc-keechma-keys app)) apps (prepare-apps (:keechma/apps app)) controllers (prepare-controllers (:keechma/controllers app) context') ancestor-controllers (:visible-controllers initial-ctx) visible-controllers (set/union ancestor-controllers (set (keys controllers))) controllers-graph (build-controllers-graph controllers)] (validate-controllers-deps! controllers visible-controllers) (merge initial-ctx {:keechma/apps apps :controllers controllers :context context' :visible-controllers visible-controllers :controllers-graph controllers-graph :apps nil}))) (defn assoc-empty-transaction [app-state] (assoc app-state :transaction {:dirty #{} :dirty-meta #{}})) (defn get-controller-instance [app-state controller-name] (get-in app-state [:app-db controller-name :instance])) (defn stopped? [app-state] (= ::stopped (:keechma.app/state app-state))) (defn -transact [app-state* transaction] (when-not (stopped? @app-state*) (let [res (binding [*transaction-depth* (inc *transaction-depth*)] (transaction))] (reconcile-after-transaction! app-state*) res))) (defn -call [app-state* controller-name api-fn & args] (let [app-state @app-state*] (when-not (stopped? app-state) (let [controller-instance (get-controller-instance app-state controller-name)] (if (:keechma.controller/proxy controller-instance) (let [app (:keechma.root/parent controller-instance) controller-name (:keechma.controller/proxy controller-instance) app-id (:keechma.app/id app-state)] (binding [*app-id->transaction-depth* (assoc *app-id->transaction-depth* app-id *transaction-depth*) *transaction-depth* 0] (protocols/-call app controller-name api-fn args))) (let [api (:keechma.controller/api controller-instance)] (apply api-fn api args))))))) (defn -get-api* [app-state* controller-name] (reify IDeref (-deref [_] (get-in @app-state* [:app-db controller-name :instance :keechma.controller/api])))) (defn -dispatch ([app-state* controller-name event] (-dispatch app-state* controller-name event)) ([app-state* controller-name event payload] (let [app-state @app-state*] (when-not (stopped? app-state) (let [controller (get-in app-state [:app-db controller-name]) controller-instance (:instance controller) controller-phase (:phase controller) app-id (:keechma.app/id app-state)] (cond (and (not= controller-phase :proxied-controller-stopped) (:keechma.controller/proxy controller-instance)) (let [app (:keechma.root/parent controller-instance) controller-name (:keechma.controller/proxy controller-instance)] (binding [*app-id->transaction-depth* (assoc *app-id->transaction-depth* app-id *transaction-depth*) *transaction-depth* 0] (protocols/-dispatch app controller-name event payload))) (= :initializing controller-phase) (swap! app-state* update-in [:app-db controller-name :events-buffer] conj [event payload]) controller-instance (-transact app-state* #(ctrl/handle (assoc controller-instance :keechma/is-transacting true) event payload)))))))) (defn get-derived-app-state [app-state] (->> app-state :app-db (map (fn [[k v]] (when (and (not (and (vector? k) (= 1 (count k)))) (controller-state-relevant? v)) [k (:derived-state v)]))) (filter identity) (into {}))) (defn get-app-meta-state [app-state] (->> app-state :app-db (map (fn [[k v]] (when (and (not (and (vector? k) (= 1 (count k)))) (controller-state-relevant? v)) [k (:meta-state v)]))) (filter identity) (into {}))) (defn app-broadcast [app-state* path event payload is-broadcasting-from-proxied-controller] (let [app-state @app-state* ordered-controller-names (get-sorted-controllers-for-app app-state path) app-ctx (get-in app-state (get-app-store-path path)) apps-definitions (:keechma/apps app-ctx)] (binding [*transaction-depth* (inc *transaction-depth*)] (doseq [controller-name ordered-controller-names] (let [is-proxy-controller (get-in app-state [:app-db controller-name :instance :keechma.controller/proxy])] (when (or (not is-broadcasting-from-proxied-controller) (and is-broadcasting-from-proxied-controller (not is-proxy-controller))) (-dispatch app-state* controller-name event payload)))) (doseq [[app-name _] apps-definitions] (let [path (conj path app-name) app-ctx (get-in @app-state* (get-app-store-path path))] (when (:is-running app-ctx) (app-broadcast app-state* path event payload is-broadcasting-from-proxied-controller))))))) (defn -broadcast ([app-state* event] (-broadcast app-state* event nil false)) ([app-state* event payload] (-broadcast app-state* event payload false)) ([app-state* event payload is-broadcasting-from-proxied-controller] (when-not (stopped? @app-state*) (app-broadcast app-state* [] event payload is-broadcasting-from-proxied-controller) (reconcile-after-transaction! app-state*)))) (defn prep [controller] (if (= :dynamic (:keechma.controller.type/variant controller)) (ctrl/prep controller) controller)) (defn notify-proxied-controllers-apps-on-dispatch [app-state* controller-name target-controller-name event payload] (let [subscriptions (-> app-state* deref (get-in [:subscriptions-on-controller-dispatch controller-name]) vals)] (doseq [app-subs subscriptions] (let [subscribed-controllers (-> app-subs keys set) sub-fn (-> app-subs vals first)] (sub-fn subscribed-controllers target-controller-name event payload))))) (defn notify-proxied-controllers-apps-on-broadcast [app-state* controller-name event payload] (let [subscriptions (-> app-state* deref (get-in [:subscriptions-on-controller-broadcast controller-name]) vals)] (doseq [app-subs subscriptions] (let [subscribed-controllers (-> app-subs keys set) sub-fn (-> app-subs vals first)] (sub-fn subscribed-controllers event payload))))) (defn make-controller-instance [app-state* controller-name controller-type params] (let [{:keys [batcher] :as app-state} @app-state* controller (-> app-state (get-in [:controllers controller-name]) (assoc :keechma.controller/type controller-type) prep) params' (ctrl/params (assoc controller :keechma.controller/name controller-name) params)] (when params' (let [state* (atom nil) meta-state* (atom nil) id (keyword (gensym 'controller-instance-))] (assoc controller :keechma.controller/name controller-name :keechma.controller/params params' :keechma.controller/id id :keechma/app (reify IAppInstance (-dispatch [_ target-controller-name event] (batcher (fn [] (with-tracing app-state* (trace! :keechma.controller/dispatch {:keechma/controller target-controller-name :keechma.controller/source controller-name :event event :payload nil}) (-dispatch app-state* target-controller-name event nil) (notify-proxied-controllers-apps-on-dispatch app-state* controller-name target-controller-name event nil))))) (-dispatch [_ target-controller-name event payload] (batcher (fn [] (with-tracing app-state* (trace! :keechma.controller/dispatch {:keechma/controller target-controller-name :keechma.controller/source controller-name :event event :payload payload}) (-dispatch app-state* target-controller-name event payload) (notify-proxied-controllers-apps-on-dispatch app-state* controller-name target-controller-name event payload))))) (-broadcast [_ event] (batcher (fn [] (with-tracing app-state* (trace! :keechma.controller/broadcast {:keechma.controller/source controller-name :event event :payload nil}) (-broadcast app-state* event nil) (notify-proxied-controllers-apps-on-broadcast app-state* controller-name event nil))))) (-broadcast [_ event payload] (batcher (fn [] (with-tracing app-state* (trace! :keechma.controller/broadcast {:keechma.controller/source controller-name :event event :payload payload}) (-broadcast app-state* event payload) (notify-proxied-controllers-apps-on-broadcast app-state* controller-name event payload))))) (-call [_ target-controller-name api-fn args] (let [controller-running-deps-map (get-controller-running-deps-map @app-state* controller-name) deps-name->renamed (set/map-invert controller-running-deps-map) real-target-controller-name (get deps-name->renamed target-controller-name)] (if (not real-target-controller-name) (let [controller (get-in @app-state* [:controllers target-controller-name])] (if (:keechma.controller/is-global controller) (with-tracing app-state* (trace! :keechma.controller/call {:keechma.controller/source controller-name :keechma/controller target-controller-name :fn api-fn :args args}) (apply -call app-state* target-controller-name api-fn args)) (throw (keechma-ex-info "Attempted to call an API function on non-existing dep" :keechma.controller.deps/missing {:keechma.controller.api/fn api-fn :keechma.controller.api/args args :keechma.controller/dep target-controller-name})))) (with-tracing app-state* (trace! :keechma.controller/call {:keechma.controller/source controller-name :keechma/controller real-target-controller-name :fn api-fn :args args}) (apply -call app-state* real-target-controller-name api-fn args))))) (-get-api* [_ controller-name] (-get-api* app-state* controller-name)) (-transact [_ transaction] (with-tracing app-state* (-transact app-state* transaction))) (-get-id [_] (:keechma.app/id @app-state*))) :meta-state* meta-state* :state* state* :deps-state* (reify IDeref (-deref [_] (get-controller-derived-deps-state @app-state* controller-name)))))))) (defn notify-subscriptions-meta ([app-state] (notify-subscriptions-meta app-state nil)) ([app-state dirty-meta] (let [app-db (:app-db app-state) subscriptions-meta (:subscriptions-meta app-state) selected-subscriptions-meta (if dirty-meta (select-keys subscriptions-meta dirty-meta) subscriptions-meta)] (doseq [[controller-key subs] selected-subscriptions-meta] (let [meta-state (get-in app-db [controller-key :meta-state])] (doseq [sub (vals subs)] (sub meta-state))))))) (defn notify-subscriptions [app-state] (let [app-db (:app-db app-state) subscriptions (:subscriptions app-state)] (doseq [[controller-key subs] subscriptions] (let [derived-state (get-in app-db [controller-key :derived-state])] (doseq [sub (vals subs)] (sub derived-state)))) (notify-subscriptions-meta app-state))) (defn notify-fences [app-state] (let [fences-sub-fns (-> app-state :fences vals)] (when (seq fences-sub-fns) (let [derived-app-state (get-derived-app-state app-state) app-meta-state (get-app-meta-state app-state)] (doseq [fence-sub-fn fences-sub-fns] (fence-sub-fn derived-app-state app-meta-state)))))) (defn batched-notify-subscriptions-meta ([{:keys [batcher] :as app-state}] (batcher #(notify-subscriptions-meta app-state))) ([{:keys [batcher] :as app-state} dirty-meta] (batcher #(notify-subscriptions-meta app-state dirty-meta)))) (defn batched-notify-subscriptions [{:keys [batcher] :as app-state}] (batcher #(notify-subscriptions app-state))) (defn sync-controller->app-db! [app-state* controller-name] (let [app-state @app-state* app-db (:app-db app-state) controller (get app-db controller-name) instance (:instance controller) state (deref (:state* instance)) deps-state (get-controller-derived-deps-state app-state controller-name) new-derived-state (ctrl/derive-state instance state deps-state) new-app-db (-> app-db (dissoc-in [controller-name :events-buffer]) (assoc-in [controller-name :state] state) (assoc-in [controller-name :derived-state] new-derived-state))] (trace! :keechma.controller/state* {:keechma/controller controller-name :state.derived/prev (get-in app-state [:app-db controller-name :state]) :state.derived/next new-derived-state :state/next state}) (swap! app-state* assoc :app-db new-app-db))) (defn sync-controller-meta->app-db! [app-state* controller-name] (let [app-state @app-state* meta-state* (get-in app-state [:app-db controller-name :instance :meta-state*])] (trace! :keechma.controller/meta-state* {:keechma/controller controller-name :meta-state/prev (get-in app-state [:app-db controller-name :meta-state]) :meta-state/next @meta-state*}) (swap! app-state* assoc-in [:app-db controller-name :meta-state] @meta-state*))) (defn transaction-mark-dirty! [app-state* controller-name] (swap! app-state* update-in [:transaction :dirty] conj controller-name)) (defn transaction-unmark-dirty! [app-state* controller-name] (swap! app-state* update-in [:transaction :dirty] disj controller-name)) (defn transaction-mark-dirty-meta! [app-state* controller-name] (swap! app-state* update-in [:transaction :dirty-meta] conj controller-name)) (defn on-controller-state-change! [app-state* controller-name] (with-tracing app-state* (when-not *stopping* (sync-controller->app-db! app-state* controller-name) (if (transacting?) (transaction-mark-dirty! app-state* controller-name) (do (when ^boolean goog.DEBUG (js/console.warn "Controller state updated outside transact block. Controller:" (str controller-name))) (transaction-mark-dirty! app-state* controller-name) (reconcile-after-transaction! app-state*)))))) (defn on-controller-meta-state-change! [app-state* controller-name] (with-tracing app-state* (when-not *stopping* (sync-controller-meta->app-db! app-state* controller-name) (if (transacting?) (transaction-mark-dirty-meta! app-state* controller-name) (do (notify-fences @app-state*) (batched-notify-subscriptions-meta @app-state* #{controller-name})))))) (defn get-proxied-controller [app-state controller-name] (let [controller-instance (get-in app-state [:app-db controller-name :instance]) parent-app (:keechma.root/parent controller-instance) proxied-controller-name (:keechma.controller/proxy controller-instance)] (-> parent-app protocols/-get-app-state* deref (get-in [:app-db proxied-controller-name])))) (defn on-proxied-controller-change! [app-state* controller-name] (when-not *stopping* (let [app-state @app-state* app-id (:keechma.app/id app-state) controller (get-in app-state [:app-db controller-name]) proxied-controller (get-proxied-controller app-state controller-name) {:keys [phase derived-state meta-state]} controller {proxied-phase :phase proxied-derived-state :derived-state proxied-meta-state :meta-state} proxied-controller is-derived-state-identical (identical? derived-state proxied-derived-state) is-meta-state-identical (identical? meta-state proxied-meta-state) is-phase-equal (= phase proxied-phase)] (binding [*transaction-depth* (get *app-id->transaction-depth* app-id 0)] (if proxied-controller (swap! app-state* update-in [:app-db controller-name] merge {:phase proxied-phase :derived-state proxied-derived-state :meta-state proxied-meta-state}) (swap! app-state* update-in [:app-db controller-name] merge {:phase :proxied-controller-stopped :derived-state nil :meta-state nil})) (when (or (not is-derived-state-identical) (not is-phase-equal)) (if (transacting?) (transaction-mark-dirty! app-state* controller-name) (do (transaction-mark-dirty! app-state* controller-name) (reconcile-after-transaction! app-state*)))) (when-not is-meta-state-identical (if (transacting?) (transaction-mark-dirty-meta! app-state* controller-name) (do (notify-fences @app-state*) (batched-notify-subscriptions-meta @app-state* #{controller-name})))))))) (defn on-proxied-controller-dispatch [app-state* subscribed-controllers target-controller-name event payload] (let [{:keys [batcher app-db]} @app-state* controller-name (->> subscribed-controllers (select-keys app-db) (filter (fn [[_ controller]] (= :running (:phase controller)))) ffirst)] (when controller-name (batcher (fn [] (-dispatch app-state* target-controller-name event payload) (notify-proxied-controllers-apps-on-dispatch app-state* controller-name target-controller-name event payload)))))) (defn on-proxied-controller-broadcast [app-state* subscribed-controllers event payload] (let [{:keys [batcher app-db]} @app-state* controller-name (->> subscribed-controllers (select-keys app-db) (filter (fn [[_ controller]] (= :running (:phase controller)))) ffirst)] (when controller-name (batcher (fn [] (-broadcast app-state* event payload true) (notify-proxied-controllers-apps-on-broadcast app-state* controller-name event payload)))))) (defn controller-start! [app-state* controller-name controller-type params] Based on params so far , we 're going to try to start the controller . There is one last chance to prevent it (let [prev-controller-state (get-in @app-state* [:app-db controller-name]) prev-state (:state prev-controller-state)] (swap! app-state* assoc-in [:app-db controller-name] {:params params :type controller-type :phase :initializing :events-buffer []}) (let [controller-instance (make-controller-instance app-state* controller-name controller-type params)] (if-not controller-instance (swap! app-state* assoc-in [:app-db controller-name] prev-controller-state) (let [config (make-controller-instance app-state* controller-name controller-type params) inited (ctrl/init config) api (ctrl/api inited) instance (assoc inited :keechma.controller/api api)] (swap! app-state* assoc-in [:app-db controller-name :instance] instance) (let [state* (:state* instance) meta-state* (:meta-state* instance) deps-state (get-controller-derived-deps-state @app-state* controller-name) state (ctrl/start instance params deps-state prev-state)] (reset! state* state) (swap! app-state* update-in [:app-db controller-name] #(merge % {:state state :phase :starting :prev-deps-state deps-state})) (trace! :keechma.on/start {:keechma/controller controller-name :event :keechma.on/start :payload params}) (-dispatch app-state* controller-name :keechma.on/start params) (swap! app-state* assoc-in [:app-db controller-name :phase] :running) (doseq [[event payload] (get-in @app-state* [:app-db controller-name :events-buffer])] (-dispatch app-state* controller-name event payload)) (sync-controller->app-db! app-state* controller-name) (sync-controller-meta->app-db! app-state* controller-name) (add-watch meta-state* :keechma/app #(on-controller-meta-state-change! app-state* controller-name)) (add-watch state* :keechma/app #(on-controller-state-change! app-state* controller-name)))))))) (defn controller-stop! [app-state* controller-name] (let [instance (get-controller-instance @app-state* controller-name)] (if (:keechma.controller/proxy instance) (let [{:keys [unsubscribe unsubscribe-meta unsubscribe-on-controller-dispatch unsubscribe-on-controller-broadcast]} instance] (unsubscribe) (unsubscribe-meta) (unsubscribe-on-controller-dispatch) (unsubscribe-on-controller-broadcast) (swap! app-state* dissoc-in [:app-db controller-name])) (let [params (:keechma.controller/params instance) state* (:state* instance)] (swap! app-state* assoc-in [:app-db controller-name :phase] :stopping) (remove-watch state* :keechma/app) (remove-watch (:meta-state* instance) :keechma/app) (trace! :keechma.on/stop {:keechma/controller controller-name :event :keechma.on/stop :payload nil}) (-dispatch app-state* controller-name :keechma.on/stop nil) (let [deps-state (get-controller-derived-deps-state @app-state* controller-name) state (ctrl/stop instance params @state* deps-state)] (reset! state* state) (swap! app-state* assoc-in [:app-db controller-name] {:state state})) (ctrl/terminate instance))))) (defn controller-on-deps-change! [app-state* controller-name] (let [app-state @app-state* prev-deps-state (get-in app-state [:app-db controller-name :prev-deps-state]) deps-state (get-controller-derived-deps-state @app-state* controller-name) instance (get-in app-state [:app-db controller-name :instance]) dirty-deps (get-dirty-deps prev-deps-state deps-state)] (when dirty-deps (trace! :keechma.on/deps-change {:keechma/controller controller-name :event :keechma.on/deps-change :payload dirty-deps}) (swap! app-state* assoc-in [:app-db controller-name :prev-deps-state] deps-state) (-dispatch app-state* controller-name :keechma.on/deps-change dirty-deps) (let [state (-> instance :state* deref) derived-state (ctrl/derive-state instance state deps-state)] (swap! app-state* assoc-in [:app-db controller-name :derived-state] derived-state))))) (defn idempotently-proxy-controller-start! [app-state* controller-name] (let [app-state @app-state*] (when-not (get-in app-state [:app-db controller-name :instance]) (let [controller (get-in app-state [:controllers controller-name]) proxied-controller-name (:keechma.controller/proxy controller) parent-app (:keechma.root/parent controller)] (when-not parent-app (throw (keechma-ex-info "Attempted to proxy controller from a non-existing parent app" :keechma.root.parent/missing {:keechma/controller controller-name :keechma.controller/proxy proxied-controller-name}))) (let [derived-state (protocols/-get-derived-state parent-app proxied-controller-name) meta-state (protocols/-get-meta-state parent-app proxied-controller-name) handler (fn [_] (on-proxied-controller-change! app-state* controller-name)) unsubscribe (protocols/-subscribe parent-app proxied-controller-name handler) unsubscribe-meta (protocols/-subscribe-meta parent-app proxied-controller-name handler) app-id (:keechma.app/id app-state) unsubscribe-on-controller-dispatch (protocols/-subscribe-on-controller-dispatch parent-app app-id proxied-controller-name controller-name (fn [subscribed-controllers target-controller-name event payload] (on-proxied-controller-dispatch app-state* subscribed-controllers target-controller-name event payload))) unsubscribe-on-controller-broadcast (protocols/-subscribe-on-controller-broadcast parent-app app-id proxied-controller-name controller-name (fn [subscribed-controllers event payload] (on-proxied-controller-broadcast app-state* subscribed-controllers event payload))) controller' (assoc controller :unsubscribe unsubscribe :unsubscribe-meta unsubscribe-meta :unsubscribe-on-controller-dispatch unsubscribe-on-controller-dispatch :unsubscribe-on-controller-broadcast unsubscribe-on-controller-broadcast)] (swap! app-state* update-in [:app-db controller-name] merge {:derived-state derived-state :meta-state meta-state :instance controller' :phase :running})))))) (defn reconcile-controller-lifecycle-state! [app-state* controller-name] (if (get-in @app-state* [:controllers controller-name :keechma.controller/proxy]) (idempotently-proxy-controller-start! app-state* controller-name) | false | | | - | Do nothing | | false | | | - | Stop the current controller instance | | false | | truthy | - | Start a new controller instance | | false | | truthy | - | Stop the current controller instance and start a new one | | true | | | - | Do nothing | | true | | | - | Stop the current controller instance | | true | | truthy | - | Start a new controller instance | | true | | truthy | false | Stop the current controller instance and start a new one | | true | | truthy | true | Dispatch : keechma.on/deps-change event to the running controller instance | (let [app-state @app-state* {params :params controller-type :type} (get-params-and-type app-state controller-name)] (assert (isa? controller-type :keechma/controller) (str "Controller " controller-name " has type " controller-type " which is not derived from :keechma/controller")) (let [current-params (get-in app-state [:app-db controller-name :params]) current-controller-type (get-in app-state [:app-db controller-name :type]) actions (determine-actions current-params params current-controller-type controller-type)] (when (contains? actions :stop) (controller-stop! app-state* controller-name)) (when (contains? actions :start) (controller-start! app-state* controller-name controller-type params)) (when (contains? actions :deps-change) (controller-on-deps-change! app-state* controller-name)))))) (defn reconcile-controller-factory! [app-state* controller-name] (let [app-state @app-state* controllers (:controllers app-state) app-db (:app-db app-state) config (get controllers controller-name) prev-produced-keys (get-in app-db [controller-name :produced-keys]) factory-deps (:keechma.controller/deps config) produced (->> (get-factory-produced @app-state* controller-name) (reduce (fn [acc [k produced-config]] (let [produced-controller-name (conj controller-name k) conformed-produced-config (conform-factory-produced produced-config) factory-produced-deps (:keechma.controller/deps conformed-produced-config)] (assert (factory-produced-deps-valid? app-db factory-deps factory-produced-deps)) (assoc! acc (conj controller-name k) (-> (merge config conformed-produced-config) (assoc :keechma.controller/variant :identity :keechma.controller/name produced-controller-name :keechma.controller/factory controller-name))))) (transient {})) persistent!) produced-keys (set (keys produced)) running-keys (->> @app-state* :app-db (filter (fn [[k v]] (and (contains? prev-produced-keys k) (= :running (:phase v))))) (map first) set) to-remove (set/difference running-keys produced-keys)] (doseq [controller-name to-remove] (controller-stop! app-state* controller-name)) (swap! app-state* (fn [app-state] (let [{:keys [controllers app-db]} app-state app-db' (-> (apply dissoc app-db to-remove) (assoc-in [controller-name :produced-keys] produced-keys)) controllers' (-> (apply dissoc controllers to-remove) (merge produced))] (assoc app-state :app-db app-db' :controllers controllers')))) (loop [produced-keys' produced-keys] (when (seq produced-keys') (let [[controller-name & rest-produced-keys] produced-keys'] (reconcile-controller-lifecycle-state! app-state* controller-name) (recur rest-produced-keys)))))) (defn reconcile-controllers! [app-state* to-reconcile] (loop [to-reconcile' to-reconcile] (when (seq to-reconcile') (let [[current & rest-to-reconcile] to-reconcile' controller-variant (get-in @app-state* [:controllers current :keechma.controller/variant])] (if (= :factory controller-variant) (reconcile-controller-factory! app-state* current) (reconcile-controller-lifecycle-state! app-state* current)) (transaction-unmark-dirty! app-state* current) (recur rest-to-reconcile))))) (defn stop-app! [app-state* path] (let [app-state @app-state* app-ctx (get-in app-state (get-app-store-path path))] (when app-ctx (trace! :keechma.app/stop {:keechma/app path}) (let [apps (:apps app-ctx) to-reconcile (reverse (get-sorted-controllers-for-app app-state path))] (doseq [[app-name _] apps] (stop-app! app-state* (conj path app-name))) (doseq [controller-name to-reconcile] (when (get-controller-instance @app-state* controller-name) (controller-stop! app-state* controller-name))) (swap! app-state* deregister-app path))))) (defn reconcile-app! [app-state* path dirty] (let [app-state @app-state* {:keys [controllers-graph]} (get-in app-state (get-app-store-path path)) subgraph (subgraph-reachable-from-set controllers-graph dirty) to-reconcile (->> subgraph dep/topo-sort (filterv #(= path (get-in app-state [:controller->app-index %]))))] (reconcile-controllers! app-state* to-reconcile) (let [app-state @app-state* app-ctx (get-in app-state (get-app-store-path path)) apps-definitions (:keechma/apps app-ctx) apps-by-should-run (reduce-kv (fn [acc app-name app] (let [should-run? (:keechma.app/should-run? app) deps (get-derived-deps-state app-state (:controllers app-state) (:keechma.app/deps app))] (update acc (boolean (should-run? deps)) conj app-name))) {true #{} false #{}} apps-definitions)] (doseq [app-name (get apps-by-should-run false)] (stop-app! app-state* (conj path app-name))) (doseq [app-name (get apps-by-should-run true)] (let [app-state @app-state* path (conj path app-name) child-app-ctx (get-in app-state (get-app-store-path path))] (if (:is-running child-app-ctx) (reconcile-app! app-state* path (set/union dirty (get-in app-state [:transaction :dirty]) (set to-reconcile))) (do (trace! :keechma.app/start {:keechma/app path}) (swap! app-state* register-app (make-ctx (get apps-definitions app-name) (merge app-ctx {:path path :is-running true}))) (reconcile-initial! app-state* path)))))))) (defn reconcile-after-transaction! [app-state*] (when-not (transacting?) (let [app-state @app-state* transaction (:transaction app-state) dirty (:dirty transaction) dirty-meta (:dirty-meta transaction)] (cond (seq dirty) (let [controller-apps (->> dirty (map #(get-in app-state [:controller->app-index %])) set) lca-path (get-lowest-common-ancestor-for-paths controller-apps)] (swap! app-state* assoc-empty-transaction) (binding [*transaction-depth* (inc *transaction-depth*)] (reconcile-app! app-state* lca-path dirty)) (let [app-state @app-state* dirty (get-in app-state [:transaction :dirty])] (if (seq dirty) (recur app-state*) (do (notify-fences @app-state*) (batched-notify-subscriptions @app-state*))))) (seq dirty-meta) (do (swap! app-state* assoc-empty-transaction) (notify-fences @app-state*) (batched-notify-subscriptions-meta @app-state* dirty-meta)))))) (defn reconcile-initial! ([app-state* path] (reconcile-initial! app-state* path 0)) ([app-state* path depth] (let [app-state @app-state* to-reconcile (get-sorted-controllers-for-app app-state path) app-ctx (get-in app-state (get-app-store-path path)) apps-definitions (:keechma/apps app-ctx)] (binding [*transaction-depth* (inc *transaction-depth*)] (reconcile-controllers! app-state* to-reconcile) (doseq [[app-name app] apps-definitions] (let [app-state @app-state* should-run? (:keechma.app/should-run? app) deps (get-derived-deps-state app-state (:controllers app-state) (:keechma.app/deps app))] (when (should-run? deps) (let [path (conj path app-name) app-ctx (make-ctx app (merge app-ctx {:path path :is-running true}))] (swap! app-state* register-app app-ctx) (reconcile-initial! app-state* path (inc depth))))))) (when (zero? depth) (reconcile-after-transaction! app-state*))))) (defn start! ([app] (start! app nil)) ([app parent-app] (let [app' (cond-> app parent-app (assoc :keechma.root/parent parent-app) true conform) app-id (str (gensym 'app-id)) parent-app-state (when parent-app (-> parent-app protocols/-get-app-state* deref)) parent-app-batcher (:batcher parent-app-state) parent-app-trace (:keechma/trace parent-app) batcher (or (:keechma.subscriptions/batcher app') parent-app-batcher default-batcher) trace (or (:keechma/trace app') parent-app-trace) ctx (make-ctx app' {:path [] :is-running true}) app-state* (atom (-> {:batcher batcher :keechma.app/state ::running :keechma.app/id app-id :keechma/trace trace :keechma.app.reconciliation/generation 0} (assoc-empty-transaction) (register-app ctx)))] (with-tracing app-state* (trace! :keechma.app/start nil) (reconcile-initial! app-state* [])) (reify IAppInstance (-dispatch [_ controller-name event] (-dispatch app-state* controller-name event nil)) (-dispatch [_ controller-name event payload] (-dispatch app-state* controller-name event payload)) (-broadcast [_ event] (-broadcast app-state* event nil)) (-broadcast [app-state* event payload] (-broadcast app-state* event payload)) (-call [_ controller-name api-fn args] (apply -call app-state* controller-name api-fn args)) (-get-api* [_ controller-name] (-get-api* app-state* controller-name)) (-transact [_ transaction] (-transact app-state* transaction)) (-get-id [_] app-id) IRootAppInstance (-stop! [_] (binding [*stopping* true] (stop-app! app-state* [])) (swap! app-state* assoc :keechma.app/state ::stopped)) (-get-batcher [_] batcher) (-subscribe [_ controller-name sub-fn] (validate-controller-exists! @app-state* controller-name) (let [sub-id (-> 'sub-id gensym keyword)] (swap! app-state* assoc-in [:subscriptions controller-name sub-id] sub-fn) (partial unsubscribe! app-state* controller-name sub-id))) (-subscribe-meta [_ controller-name sub-fn] (validate-controller-exists! @app-state* controller-name) (let [sub-id (-> 'sub-meta-id gensym keyword)] (swap! app-state* assoc-in [:subscriptions-meta controller-name sub-id] sub-fn) (partial unsubscribe-meta! app-state* controller-name sub-id))) (-subscribe-fence [_ sub-fn] (let [fence-sub-id (-> 'fence-sub-id gensym keyword)] (swap! app-state* assoc-in [:fences fence-sub-id] sub-fn) #(swap! app-state* dissoc-in [:fences fence-sub-id]))) (-subscribe-on-controller-dispatch [_ app-id controller-name subscribing-controller-name sub-fn] (validate-controller-exists! @app-state* controller-name) (swap! app-state* assoc-in [:subscriptions-on-controller-dispatch controller-name app-id subscribing-controller-name] sub-fn) #(swap! app-state* dissoc-in [:subscriptions-on-controller-dispatch controller-name app-id subscribing-controller-name])) (-subscribe-on-controller-broadcast [_ app-id controller-name subscribing-controller-name sub-fn] (validate-controller-exists! @app-state* controller-name) (swap! app-state* assoc-in [:subscriptions-on-controller-broadcast controller-name app-id subscribing-controller-name] sub-fn) #(swap! app-state* dissoc-in [:subscriptions-on-controller-broadcast controller-name app-id subscribing-controller-name])) (-get-derived-state [_] (get-derived-app-state @app-state*)) (-get-derived-state [_ controller-name] (get-in @app-state* [:app-db controller-name :derived-state])) (-get-meta-state [_] (get-app-meta-state @app-state*)) (-get-meta-state [_ controller-name] (get-in @app-state* [:app-db controller-name :meta-state])) (-get-app-state* [_] app-state*))))) (defn make-app-proxy [proxied-fn] (fn [& args] (apply proxied-fn args))) (def stop! ^{:doc "Stops the running application instance. This will stop and terminate all running controllers." :arglists '([app-instance])} (make-app-proxy protocols/-stop!)) (defn dispatch "Dispatches an event to a controller." ([app-instance controller-name event] (dispatch app-instance controller-name event nil)) ([app-instance controller-name event payload] (with-tracing (protocols/-get-app-state* app-instance) (trace! :keechma/dispatch {:keechma/controller controller-name :event event :payload payload}) (protocols/-dispatch app-instance controller-name event payload)))) (defn broadcast "Broadcasts an event to all running-controllers" ([app-instance event] (broadcast app-instance event nil)) ([app-instance event payload] (with-tracing (protocols/-get-app-state* app-instance) (trace! :keechma/broadcast {:event event :payload payload}) (protocols/-broadcast app-instance event payload)))) (defn transact "Runs the transaction fn inside the transact block." [app-instance transaction] (with-tracing (protocols/-get-app-state* app-instance) (protocols/-transact app-instance transaction))) (def subscribe ^{:doc "Subscribes to the controller's state. Subscription fn will be called whenever the controller's state changes." :arglists '([app-instance controller-name sub-fn])} (make-app-proxy protocols/-subscribe)) (def subscribe-meta ^{:doc "Subscribes to the controller's meta state. Subscription fn will be called whenever the controller's state changes." :arglists '([app-instance controller-name sub-fn])} (make-app-proxy protocols/-subscribe-meta)) (def get-derived-state ^{:doc "Returns the current state of all running controllers, or of the controller whose name is passed as the argument." :arglists '([app-instance] [app-instance controller-name])} (make-app-proxy protocols/-get-derived-state)) (def get-meta-state ^{:doc "Returns the current meta state of the controller." :arglists '([app-instance controller-name])} (make-app-proxy protocols/-get-meta-state)) (def get-batcher ^{:doc "Returns the batcher fn. Subscription fns are called inside the batcher - this is useful for React integration, to ensure that there are no unnecessary re-renderings." :arglists '([app-instance])} (make-app-proxy protocols/-get-batcher)) (def get-id ^{:doc "Returns the app-instance's id." :arglists '([app-instance])} (make-app-proxy protocols/-get-id)) (def get-api* ^{:doc "Returns controller's exposed API object wrapped in a derefable object." :arglists '([app-instance controller-name])} (make-app-proxy protocols/-get-api*)) (def get-app-state* ^{:doc "Returns the atom holding the app-state" :arglists '([app-instance])} (make-app-proxy protocols/-get-app-state*)) (defn call "Calls an API fn on the controller's exposed API object." [app-instance controller-name api-fn & args] (with-tracing (protocols/-get-app-state* app-instance) (trace! :keechma/call {:keechma/controller controller-name :fn api-fn :args args}) (protocols/-call app-instance controller-name api-fn args))) (defn get-running-controllers "Returns a map of running controllers. Useful for debugging." [app-instance] (let [app-state* (get-app-state* app-instance) app-state @app-state*] (:app-db app-state)))
c3c75cc3e86eba113d5aa5a785fc947721693016f98711a9b112e1e4b75b741c
i-am-tom/world-building-in-haskell
Extra.hs
# LANGUAGE DataKinds # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Data.Nat.Extra where import Data.Nat (Nat (..)) import GHC.TypeLits (type (-)) import qualified GHC.TypeLits as TypeLits | Turn a ' GHC.TypeLits . ' into a ' Data . . ' . Useful really only to -- provide a neat API to the users while working internally with a unary -- representation for convenience (e.g. pattern-matching). type family Unarise (n :: TypeLits.Nat) :: Nat where Unarise 0 = 'Z Unarise n = 'S (Unarise (n - 1)) | Double a ' ' at the type level . We ca n't call it ' Double ' , though , -- because... well, they're already important. type family Twice (n :: Nat) :: Nat where Twice 'Z = 'Z Twice ('S n) = 'S ('S (Twice n))
null
https://raw.githubusercontent.com/i-am-tom/world-building-in-haskell/fe7369b9069793ee6dd2a11e031a53b4af764d1a/src/Data/Nat/Extra.hs
haskell
provide a neat API to the users while working internally with a unary representation for convenience (e.g. pattern-matching). because... well, they're already important.
# LANGUAGE DataKinds # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Data.Nat.Extra where import Data.Nat (Nat (..)) import GHC.TypeLits (type (-)) import qualified GHC.TypeLits as TypeLits | Turn a ' GHC.TypeLits . ' into a ' Data . . ' . Useful really only to type family Unarise (n :: TypeLits.Nat) :: Nat where Unarise 0 = 'Z Unarise n = 'S (Unarise (n - 1)) | Double a ' ' at the type level . We ca n't call it ' Double ' , though , type family Twice (n :: Nat) :: Nat where Twice 'Z = 'Z Twice ('S n) = 'S ('S (Twice n))
0548ed4586c70b14af45db1d12b27c5037d87de63ebf65abb709a2beb76a2383
jarrodhroberson/inet_mdns
inet_mdns.erl
-module(inet_mdns). -include_lib("kernel/src/inet_dns.hrl"). -export([start/0]). -export([stop/1,receiver/1]). -export([subscribe/2,unsubscribe/2,getsubs/1]). -export([send/0]). -define(ADDR,{224,0,0,251}). -define(PORT,5353). send() -> H = #dns_header{qr=1,aa=1}, {ok,HN} = inet:gethostname(), D = "test@" ++ HN ++ "._test._tcp.local", R = #dns_rr{domain="_test._tcp.local",type=ptr,ttl=4500,data=D}, Rec = #dns_rec{header=H,anlist=[R]}, {ok,S}=gen_udp:open(?PORT,[{ip,{192,168,0,105}}]), inet:setopts(S, [{reuseaddr,true},{broadcast,true}]), gen_udp:send(S,?ADDR,?PORT,inet_dns:encode(Rec)). get_timestamp() -> gets a timestamp in ms from the epoch 1970 - 01 - 01 {Mega,Sec,Micro} = erlang:now(), (Mega*1000000+Sec)*1000000+Micro. start() -> %% start the process listening for mdns messages {ok,S} = gen_udp:open(?PORT,[{reuseaddr,true},{ip,{192,168,0,105}},binary]), inet:setopts(S,[{add_membership,{?ADDR,{0,0,0,0}}}]), Pid=spawn(?MODULE,receiver,[dict:new()]), gen_udp:controlling_process(S,Pid), {S,Pid}. stop({S,Pid}) -> gen_udp:close(S), Pid ! stop. subscribe(Domain,Pid) -> Pid ! {sub,Domain}. unsubscribe(Domain,Pid) -> Pid ! {unsub,Domain}. getsubs(Pid) -> Pid ! {getsubs,self()}, receive {ok,Sub} -> {ok,Sub} end. receiver(Sub) -> receive {udp, _Socket, _IP, _InPortNo, Packet} -> NewSub = process_dnsrec(Sub,inet_dns:decode(Packet)), receiver(NewSub); {sub,Domain} -> receiver(dict:store(Domain,dict:new(),Sub)); {unsub,Domain} -> receiver(dict:erase(Domain, Sub)); {getsubs,Pid} -> Pid ! {ok,Sub}, receiver(Sub); stop -> true; AnythingElse -> io:format("RECEIVED: ~p~n",[AnythingElse]), receiver(Sub) end. process_dnsrec(Sub,{error,E}) -> io:format("Error: ~p~n", [E]), % TODO: Improve error handling Sub; process_dnsrec(Sub,{ok,#dns_rec{qdlist=Queries,anlist=Responses}}) -> process_queries(Queries), dict:map(fun(S,V) -> process_responses(S,V,Responses) end, Sub). process_queries([]) -> ok; process_queries(Queries) -> io:format("Queries: ~p~n",[Queries]), Reg = ["_see._tcp.local"], lists:foreach(fun(Q) -> case lists:member(Q#dns_query.domain,Reg) of true -> io:format("HIT: ~p~n",[Q]); false -> io:format("MISS: ~p~n",[Q]) end end, Queries), lists:foreach(fun(Q) -> process_query(true,Q) end, Queries). %lists:foreach(fun(Q) -> process_query(lists:member(Q#dns_query.domain,Reg),Q) end, Queries). process_query(false,_) -> ok; process_query(true,Query) -> io:format("Registered Query: ~p~n",[Query]), H = #dns_header{qr=1,aa=1}, D = "test@Blackintosh._test._tcp.local", R = #dns_rr{domain="_test._tcp.local",type=ptr,ttl=4500,data=D}, Rec = #dns_rec{header=H,anlist=[R]}, {ok,S} = gen_udp:open(5353,[{reuseaddr,true},{ip,{224,0,0,251}},{multicast_ttl,4},{broadcast,true}, binary]), gen_udp:send(S, {224,0,0,251}, 5353, inet_dns:encode(Rec)), gen_udp:close(S). process_responses(S, Value, Responses) -> io:format("Responses ~p~n",[Responses]), lists:foldl(fun(#dns_rr{domain = Domain} = Response, Val) -> process_response(lists:suffix(S, Domain), Response, Val) end, Value, Responses). process_response(false, _Response, Val) -> Val; process_response(true, #dns_rr{ttl=TTL} = _Response, _Val) when TTL == 0 -> the server left and lets us know this because = = Zero dict:new(); process_response(true, #dns_rr{domain = Domain, type = Type, class = Class} = Response, Val) when Type == txt -> DTXT = lists:foldl(fun(T,D) -> {K,V} = normalize_kv(T),dict:store(K,V,D) end,dict:new(),Response#dns_rr.data), NewRR = Response#dns_rr{tm=get_timestamp(),data=DTXT}, dict:store({Domain,Type,Class},NewRR,Val); process_response(true, #dns_rr{domain = Domain, type = Type, class = Class} = Response, Val) -> NewRR = Response#dns_rr{tm=get_timestamp()}, dict:store({Domain,Type,Class},NewRR,Val). normalize_kv(T) -> %% normalize single boolean key value entries %% make "key" == "key=true" %% make "key=" == "key=[]" case re:split(T,"=",[{return,list}]) of [K] -> {K,true}; [K,V] -> {K,V} end.
null
https://raw.githubusercontent.com/jarrodhroberson/inet_mdns/c068b662aa69edf68fea5f33388ea128cccbdaf1/src/inet_mdns.erl
erlang
start the process listening for mdns messages TODO: Improve error handling lists:foreach(fun(Q) -> process_query(lists:member(Q#dns_query.domain,Reg),Q) end, Queries). normalize single boolean key value entries make "key" == "key=true" make "key=" == "key=[]"
-module(inet_mdns). -include_lib("kernel/src/inet_dns.hrl"). -export([start/0]). -export([stop/1,receiver/1]). -export([subscribe/2,unsubscribe/2,getsubs/1]). -export([send/0]). -define(ADDR,{224,0,0,251}). -define(PORT,5353). send() -> H = #dns_header{qr=1,aa=1}, {ok,HN} = inet:gethostname(), D = "test@" ++ HN ++ "._test._tcp.local", R = #dns_rr{domain="_test._tcp.local",type=ptr,ttl=4500,data=D}, Rec = #dns_rec{header=H,anlist=[R]}, {ok,S}=gen_udp:open(?PORT,[{ip,{192,168,0,105}}]), inet:setopts(S, [{reuseaddr,true},{broadcast,true}]), gen_udp:send(S,?ADDR,?PORT,inet_dns:encode(Rec)). get_timestamp() -> gets a timestamp in ms from the epoch 1970 - 01 - 01 {Mega,Sec,Micro} = erlang:now(), (Mega*1000000+Sec)*1000000+Micro. start() -> {ok,S} = gen_udp:open(?PORT,[{reuseaddr,true},{ip,{192,168,0,105}},binary]), inet:setopts(S,[{add_membership,{?ADDR,{0,0,0,0}}}]), Pid=spawn(?MODULE,receiver,[dict:new()]), gen_udp:controlling_process(S,Pid), {S,Pid}. stop({S,Pid}) -> gen_udp:close(S), Pid ! stop. subscribe(Domain,Pid) -> Pid ! {sub,Domain}. unsubscribe(Domain,Pid) -> Pid ! {unsub,Domain}. getsubs(Pid) -> Pid ! {getsubs,self()}, receive {ok,Sub} -> {ok,Sub} end. receiver(Sub) -> receive {udp, _Socket, _IP, _InPortNo, Packet} -> NewSub = process_dnsrec(Sub,inet_dns:decode(Packet)), receiver(NewSub); {sub,Domain} -> receiver(dict:store(Domain,dict:new(),Sub)); {unsub,Domain} -> receiver(dict:erase(Domain, Sub)); {getsubs,Pid} -> Pid ! {ok,Sub}, receiver(Sub); stop -> true; AnythingElse -> io:format("RECEIVED: ~p~n",[AnythingElse]), receiver(Sub) end. process_dnsrec(Sub,{error,E}) -> Sub; process_dnsrec(Sub,{ok,#dns_rec{qdlist=Queries,anlist=Responses}}) -> process_queries(Queries), dict:map(fun(S,V) -> process_responses(S,V,Responses) end, Sub). process_queries([]) -> ok; process_queries(Queries) -> io:format("Queries: ~p~n",[Queries]), Reg = ["_see._tcp.local"], lists:foreach(fun(Q) -> case lists:member(Q#dns_query.domain,Reg) of true -> io:format("HIT: ~p~n",[Q]); false -> io:format("MISS: ~p~n",[Q]) end end, Queries), lists:foreach(fun(Q) -> process_query(true,Q) end, Queries). process_query(false,_) -> ok; process_query(true,Query) -> io:format("Registered Query: ~p~n",[Query]), H = #dns_header{qr=1,aa=1}, D = "test@Blackintosh._test._tcp.local", R = #dns_rr{domain="_test._tcp.local",type=ptr,ttl=4500,data=D}, Rec = #dns_rec{header=H,anlist=[R]}, {ok,S} = gen_udp:open(5353,[{reuseaddr,true},{ip,{224,0,0,251}},{multicast_ttl,4},{broadcast,true}, binary]), gen_udp:send(S, {224,0,0,251}, 5353, inet_dns:encode(Rec)), gen_udp:close(S). process_responses(S, Value, Responses) -> io:format("Responses ~p~n",[Responses]), lists:foldl(fun(#dns_rr{domain = Domain} = Response, Val) -> process_response(lists:suffix(S, Domain), Response, Val) end, Value, Responses). process_response(false, _Response, Val) -> Val; process_response(true, #dns_rr{ttl=TTL} = _Response, _Val) when TTL == 0 -> the server left and lets us know this because = = Zero dict:new(); process_response(true, #dns_rr{domain = Domain, type = Type, class = Class} = Response, Val) when Type == txt -> DTXT = lists:foldl(fun(T,D) -> {K,V} = normalize_kv(T),dict:store(K,V,D) end,dict:new(),Response#dns_rr.data), NewRR = Response#dns_rr{tm=get_timestamp(),data=DTXT}, dict:store({Domain,Type,Class},NewRR,Val); process_response(true, #dns_rr{domain = Domain, type = Type, class = Class} = Response, Val) -> NewRR = Response#dns_rr{tm=get_timestamp()}, dict:store({Domain,Type,Class},NewRR,Val). normalize_kv(T) -> case re:split(T,"=",[{return,list}]) of [K] -> {K,true}; [K,V] -> {K,V} end.
ea44ec61408bbe4c6aed93c418282f4813b68b6906e5d8ca381a2bb214bdde3a
ghc/packages-Cabal
Workdir.hs
# LANGUAGE CPP # -- | Functions for interrogating the current working directory module Test.Cabal.Workdir where import Distribution.Simple.Setup import Distribution.Simple.Configure import System.Directory import System.FilePath #if MIN_VERSION_base(4,6,0) import System.Environment ( getExecutablePath ) #endif -- | Guess what the dist directory of a running executable is, -- by using the conventional layout of built executables -- in relation to the top of a dist directory. Will not work -- if the executable has been installed somewhere else. guessDistDir :: IO FilePath guessDistDir = do #if MIN_VERSION_base(4,6,0) exe_path <- canonicalizePath =<< getExecutablePath let dist0 = dropFileName exe_path </> ".." </> ".." b <- doesFileExist (dist0 </> "setup-config") #else let dist0 = error "no path" b = False #endif if b then canonicalizePath dist0 else findDistPrefOrDefault NoFlag >>= canonicalizePath
null
https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/src/Test/Cabal/Workdir.hs
haskell
| Functions for interrogating the current working directory | Guess what the dist directory of a running executable is, by using the conventional layout of built executables in relation to the top of a dist directory. Will not work if the executable has been installed somewhere else.
# LANGUAGE CPP # module Test.Cabal.Workdir where import Distribution.Simple.Setup import Distribution.Simple.Configure import System.Directory import System.FilePath #if MIN_VERSION_base(4,6,0) import System.Environment ( getExecutablePath ) #endif guessDistDir :: IO FilePath guessDistDir = do #if MIN_VERSION_base(4,6,0) exe_path <- canonicalizePath =<< getExecutablePath let dist0 = dropFileName exe_path </> ".." </> ".." b <- doesFileExist (dist0 </> "setup-config") #else let dist0 = error "no path" b = False #endif if b then canonicalizePath dist0 else findDistPrefOrDefault NoFlag >>= canonicalizePath
ee2b41d0ea0376727548a14702691380270ce76c5b9322a2303510e87c90f840
kmi/irs
swift-services-ontology.lisp
Mode : Lisp ; Package : File created in WebOnto (in-package "OCML") (in-ontology swift-services-ontology) (def-class citizen-address () ((has-address-key :type integer) (has-postcode :type post-code-string) (has-premise-number :type integer) ;;; type positive-integer ?? (has-premise-name :type string) (has-street :type string) (has-locality :type string) (has-town :type string))) (def-class citizen-data () ((has-CitizenKey :type integer) (has-GenderCode :type integer) (has-MaritalStatusCode :type integer) (has-TitleCode :type integer) (has-EthnicityCode :type integer) (has-FamilyName :type string) (has-SpeechImpairment :type string) (has-HearingImpairment :type string) (has-FirstNames :type string) (has-Initials :type string) (has-DateOfBirth :type date) (has-DateOfDeath :type date) (has-ApproxDateOfBirth :type date) (has-Age :type integer) (has-ExpectedDateOfBirth :type date)))
null
https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/domains/swift-services-ontology/swift-services-ontology.lisp
lisp
Package : type positive-integer ??
File created in WebOnto (in-package "OCML") (in-ontology swift-services-ontology) (def-class citizen-address () ((has-address-key :type integer) (has-postcode :type post-code-string) (has-premise-name :type string) (has-street :type string) (has-locality :type string) (has-town :type string))) (def-class citizen-data () ((has-CitizenKey :type integer) (has-GenderCode :type integer) (has-MaritalStatusCode :type integer) (has-TitleCode :type integer) (has-EthnicityCode :type integer) (has-FamilyName :type string) (has-SpeechImpairment :type string) (has-HearingImpairment :type string) (has-FirstNames :type string) (has-Initials :type string) (has-DateOfBirth :type date) (has-DateOfDeath :type date) (has-ApproxDateOfBirth :type date) (has-Age :type integer) (has-ExpectedDateOfBirth :type date)))
b4d2791805ff3a4bc9363b2fc0e0e5d3f8674f36dc0b833b1e7757a82b08a566
vaclavsvejcar/headroom
UpdateCopyright.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # {-# LANGUAGE StrictData #-} # LANGUAGE TypeApplications # # LANGUAGE NoImplicitPrelude # -- | Module : Headroom . PostProcess . UpdateCopyright -- Description : /Post-processor/ for updating years in copyrights Copyright : ( c ) 2019 - 2022 -- License : BSD-3-Clause -- Maintainer : -- Stability : experimental -- Portability : POSIX -- -- This module provides functionality for updating years in copyright statements -- in already rendered /license headers/. module Headroom.PostProcess.UpdateCopyright ( -- * Data Types SelectedAuthors (..) , UpdateCopyrightMode (..) -- * Header Functions , updateCopyright -- * Helper Functions , updateYears ) where import Data.String.Interpolate (i) import Headroom.Data.Has (Has (..)) import Headroom.Data.Regex ( re , replace ) import Headroom.Data.Text ( mapLines , read ) import Headroom.PostProcess.Types (PostProcess (..)) import Headroom.Types (CurrentYear (..)) import RIO import qualified RIO.NonEmpty as NE import qualified RIO.Text as T --------------------------------- DATA TYPES --------------------------------- | Non - empty list of authors for which to update years in their copyrights . newtype SelectedAuthors = SelectedAuthors (NonEmpty Text) deriving (Eq, Show) -- | Mode that changes behaviour of the 'updateCopyright' function. data UpdateCopyrightMode = -- | updates years in copyrights for all authors UpdateAllAuthors | -- | updates years in copyrights only for selected authors UpdateSelectedAuthors SelectedAuthors deriving (Eq, Show) ------------------------------ PUBLIC FUNCTIONS ------------------------------ | /Post - processor/ that updates years and year ranges in any -- present copyright statements. -- -- = Reader Environment Parameters [ ' CurrentYear ' ] value of the current year -- ['UpdateCopyrightMode'] mode specifying the behaviour of the updater updateCopyright :: (Has CurrentYear env, Has UpdateCopyrightMode env) => PostProcess env updateCopyright = PostProcess $ \input -> do currentYear <- viewL mode <- viewL pure $ mapLines (update mode currentYear) input where update mode year line | shouldUpdate mode line = updateYears year line | otherwise = line shouldUpdate UpdateAllAuthors _ = True shouldUpdate (UpdateSelectedAuthors (SelectedAuthors authors)) input = any (`T.isInfixOf` input) (NE.toList authors) -- | Updates years and years ranges in given text. -- > > > ( CurrentYear 2020 ) " Copyright ( c ) 2020 " " Copyright ( c ) 2020 " -- > > > ( CurrentYear 2020 ) " Copyright ( c ) 2019 " " Copyright ( c ) 2019 - 2020 " -- > > > ( CurrentYear 2020 ) " Copyright ( c ) 2018 - 2020 " " Copyright ( c ) 2018 - 2020 " -- > > > ( CurrentYear 2020 ) " Copyright ( c ) 2018 - 2019 " " Copyright ( c ) 2018 - 2020 " updateYears :: CurrentYear ^ current year -> Text -- ^ text to update -> Text -- ^ text with updated years updateYears cy = replace [re|(\d{4})(?:-)?(\d{4})?|] go where go _ [r1] | (Just y1) <- read r1 = bumpYear cy y1 go _ rs@[_, _] | [Just y1, Just y2] <- read <$> rs = bumpRange cy y1 y2 go other _ = other ------------------------------ PRIVATE FUNCTIONS ----------------------------- bumpYear :: CurrentYear -> Integer -> Text bumpYear (CurrentYear cy) y | y >= cy = tshow y | otherwise = [i|#{y}-#{cy}|] bumpRange :: CurrentYear -> Integer -> Integer -> Text bumpRange (CurrentYear cy) y1 y2 | y2 >= cy = [i|#{y1}-#{y2}|] | otherwise = [i|#{y1}-#{cy}|]
null
https://raw.githubusercontent.com/vaclavsvejcar/headroom/3b20a89568248259d59f83f274f60f6e13d16f93/src/Headroom/PostProcess/UpdateCopyright.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Description : /Post-processor/ for updating years in copyrights License : BSD-3-Clause Maintainer : Stability : experimental Portability : POSIX This module provides functionality for updating years in copyright statements in already rendered /license headers/. * Data Types * Header Functions * Helper Functions ------------------------------- DATA TYPES --------------------------------- | Mode that changes behaviour of the 'updateCopyright' function. | updates years in copyrights for all authors | updates years in copyrights only for selected authors ---------------------------- PUBLIC FUNCTIONS ------------------------------ present copyright statements. = Reader Environment Parameters ['UpdateCopyrightMode'] mode specifying the behaviour of the updater | Updates years and years ranges in given text. ^ text to update ^ text with updated years ---------------------------- PRIVATE FUNCTIONS -----------------------------
# LANGUAGE FlexibleContexts # # LANGUAGE QuasiQuotes # # LANGUAGE TypeApplications # # LANGUAGE NoImplicitPrelude # Module : Headroom . PostProcess . UpdateCopyright Copyright : ( c ) 2019 - 2022 module Headroom.PostProcess.UpdateCopyright SelectedAuthors (..) , UpdateCopyrightMode (..) , updateCopyright , updateYears ) where import Data.String.Interpolate (i) import Headroom.Data.Has (Has (..)) import Headroom.Data.Regex ( re , replace ) import Headroom.Data.Text ( mapLines , read ) import Headroom.PostProcess.Types (PostProcess (..)) import Headroom.Types (CurrentYear (..)) import RIO import qualified RIO.NonEmpty as NE import qualified RIO.Text as T | Non - empty list of authors for which to update years in their copyrights . newtype SelectedAuthors = SelectedAuthors (NonEmpty Text) deriving (Eq, Show) data UpdateCopyrightMode UpdateAllAuthors UpdateSelectedAuthors SelectedAuthors deriving (Eq, Show) | /Post - processor/ that updates years and year ranges in any [ ' CurrentYear ' ] value of the current year updateCopyright :: (Has CurrentYear env, Has UpdateCopyrightMode env) => PostProcess env updateCopyright = PostProcess $ \input -> do currentYear <- viewL mode <- viewL pure $ mapLines (update mode currentYear) input where update mode year line | shouldUpdate mode line = updateYears year line | otherwise = line shouldUpdate UpdateAllAuthors _ = True shouldUpdate (UpdateSelectedAuthors (SelectedAuthors authors)) input = any (`T.isInfixOf` input) (NE.toList authors) > > > ( CurrentYear 2020 ) " Copyright ( c ) 2020 " " Copyright ( c ) 2020 " > > > ( CurrentYear 2020 ) " Copyright ( c ) 2019 " " Copyright ( c ) 2019 - 2020 " > > > ( CurrentYear 2020 ) " Copyright ( c ) 2018 - 2020 " " Copyright ( c ) 2018 - 2020 " > > > ( CurrentYear 2020 ) " Copyright ( c ) 2018 - 2019 " " Copyright ( c ) 2018 - 2020 " updateYears :: CurrentYear ^ current year -> Text -> Text updateYears cy = replace [re|(\d{4})(?:-)?(\d{4})?|] go where go _ [r1] | (Just y1) <- read r1 = bumpYear cy y1 go _ rs@[_, _] | [Just y1, Just y2] <- read <$> rs = bumpRange cy y1 y2 go other _ = other bumpYear :: CurrentYear -> Integer -> Text bumpYear (CurrentYear cy) y | y >= cy = tshow y | otherwise = [i|#{y}-#{cy}|] bumpRange :: CurrentYear -> Integer -> Integer -> Text bumpRange (CurrentYear cy) y1 y2 | y2 >= cy = [i|#{y1}-#{y2}|] | otherwise = [i|#{y1}-#{cy}|]
f31bfe00bae9e0e86b8fd9778cca43f174373f6a4d8350fdb4f6b18990e70d53
autolwe/autolwe
GuardRules.mli
(* * Guard rules (Guess) *) open Syms open Tactic val t_guess_maybe : AdvSym.t option -> Game.vs list option -> tactic
null
https://raw.githubusercontent.com/autolwe/autolwe/3452c3dae06fc8e9815d94133fdeb8f3b8315f32/src/Derived/GuardRules.mli
ocaml
* Guard rules (Guess)
open Syms open Tactic val t_guess_maybe : AdvSym.t option -> Game.vs list option -> tactic
bb095bf2484ffa1b464ecf5e9b99c40d4c85622d5b4d6a829ca732ca3d100a7a
xapi-project/xenopsd
xenops_server_skeleton.ml
* Copyright ( C ) Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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. *) open Xenops_interface open Xenops_utils let unimplemented x = raise (Xenopsd_error (Unimplemented x)) let init () = () module HOST = struct let stat () = { Host.cpu_info= { Host.cpu_count= 0 ; socket_count= 0 ; vendor= "unknown" ; speed= "" ; modelname= "" ; family= "" ; model= "" ; stepping= "" ; flags= "" ; features= [||] ; features_pv= [||] ; features_hvm= [||] ; features_oldstyle= [||] ; features_pv_host= [||] ; features_hvm_host= [||] } ; hypervisor= {Host.version= ""; capabilities= ""} ; chipset_info= {iommu= false; hvm= false} } let get_console_data () = "" let get_total_memory_mib () = 0L let send_debug_keys _ = () let update_guest_agent_features _ = () let upgrade_cpu_features _ _ = [||] end module VM = struct let add _ = () let rename _ _ _ = () let remove _ = () let create _ _ _ _ = unimplemented "VM.create" let build ?restore_fd:_ _ _ _ _ _ = unimplemented "VM.build" let create_device_model _ _ _ _ _ = unimplemented "VM.create_device_model" let destroy_device_model _ _ = unimplemented "VM.destroy_device_model" let destroy _ _ = unimplemented "VM.destroy" let pause _ _ = unimplemented "VM.pause" let unpause _ _ = unimplemented "VM.unpause" let set_xsdata _ _ _ = unimplemented "VM.set_xsdata" let set_vcpus _ _ _ = unimplemented "VM.set_vcpus" let set_shadow_multiplier _ _ _ = unimplemented "VM.set_shadow_multipler" let set_memory_dynamic_range _ _ _ _ = unimplemented "VM.set_memory_dynamic_range" let request_shutdown _ _ _ _ = unimplemented "VM.request_shutdown" let wait_shutdown _ _ _ _ = unimplemented "VM.wait_shutdown" let assert_can_save _ = unimplemented "VM.assert_can_save" let save _ _ _ _ _ _ _ = unimplemented "VM.save" let restore _ _ _ _ _ _ _ = unimplemented "VM.restore" let s3suspend _ _ = unimplemented "VM.s3suspend" let s3resume _ _ = unimplemented "VM.s3resume" let soft_reset _ _ = unimplemented "VM.soft_reset" let get_state _ = Xenops_utils.halted_vm let request_rdp _ _ = unimplemented "VM.request_rdp" let run_script _ _ _ = unimplemented "VM.run_script" let set_domain_action_request _ _ = () let get_domain_action_request _ = None let get_hook_args _ = [] let generate_state_string _ = "" let get_internal_state _ _ _ = "" let set_internal_state _ _ = () let wait_ballooning _ _ = () let minimum_reboot_delay = 0. end module PCI = struct let get_state _ _ = unplugged_pci let dequarantine _ = () let plug _ _ _ = unimplemented "PCI.plug" let unplug _ _ _ = unimplemented "PCI.unplug" let get_device_action_request _ _ = None end module VBD = struct let set_active _ _ _ _ = () let epoch_begin _ _ _ _ = () let epoch_end _ _ _ = () let plug _ _ _ = unimplemented "VBD.plug" let unplug _ _ _ _ = unimplemented "VBD.unplug" let insert _ _ _ _ = unimplemented "VBD.insert" let eject _ _ _ = unimplemented "VBD.eject" let set_qos _ _ _ = () let get_state _ _ = unplugged_vbd let get_device_action_request _ _ = None end module VIF = struct let set_active _ _ _ _ = () let plug _ _ _ = unimplemented "VIF.plug" let unplug _ _ _ _ = unimplemented "VIF.unplug" let move _ _ _ _ = unimplemented "VIF.move" let set_carrier _ _ _ _ = unimplemented "VIF.set_carrier" let set_locking_mode _ _ _ _ = unimplemented "VIF.set_locking_mode" let set_ipv4_configuration _ _ _ _ = unimplemented "VIF.set_ipv4_configuration" let set_ipv6_configuration _ _ _ _ = unimplemented "VIF.set_ipv6_configuration" let set_pvs_proxy _ _ _ _ = unimplemented "VIF.set_pvs_proxy" let get_state _ _ = unplugged_vif let get_device_action_request _ _ = None end module VGPU = struct let start _ _ _ _ = unimplemented "VGPU.start" let set_active _ _ _ _ = () let get_state _ _ = unplugged_vgpu end module VUSB = struct let plug _ _ _ = unimplemented "VUSB.plug" let unplug _ _ _ = unimplemented "VUSB.unplug" let get_state _ _ = unplugged_vusb let get_device_action_request _ _ = None end module UPDATES = struct let get _ _ = while true do Thread.delay 5. done ; assert false end module DEBUG = struct let trigger _ _ = unimplemented "DEBUG.trigger" end
null
https://raw.githubusercontent.com/xapi-project/xenopsd/f4da21a4ead7c6a7082af5ec32f778faf368cf1c/lib/xenops_server_skeleton.ml
ocaml
* Copyright ( C ) Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * 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 . * Copyright (C) Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * 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. *) open Xenops_interface open Xenops_utils let unimplemented x = raise (Xenopsd_error (Unimplemented x)) let init () = () module HOST = struct let stat () = { Host.cpu_info= { Host.cpu_count= 0 ; socket_count= 0 ; vendor= "unknown" ; speed= "" ; modelname= "" ; family= "" ; model= "" ; stepping= "" ; flags= "" ; features= [||] ; features_pv= [||] ; features_hvm= [||] ; features_oldstyle= [||] ; features_pv_host= [||] ; features_hvm_host= [||] } ; hypervisor= {Host.version= ""; capabilities= ""} ; chipset_info= {iommu= false; hvm= false} } let get_console_data () = "" let get_total_memory_mib () = 0L let send_debug_keys _ = () let update_guest_agent_features _ = () let upgrade_cpu_features _ _ = [||] end module VM = struct let add _ = () let rename _ _ _ = () let remove _ = () let create _ _ _ _ = unimplemented "VM.create" let build ?restore_fd:_ _ _ _ _ _ = unimplemented "VM.build" let create_device_model _ _ _ _ _ = unimplemented "VM.create_device_model" let destroy_device_model _ _ = unimplemented "VM.destroy_device_model" let destroy _ _ = unimplemented "VM.destroy" let pause _ _ = unimplemented "VM.pause" let unpause _ _ = unimplemented "VM.unpause" let set_xsdata _ _ _ = unimplemented "VM.set_xsdata" let set_vcpus _ _ _ = unimplemented "VM.set_vcpus" let set_shadow_multiplier _ _ _ = unimplemented "VM.set_shadow_multipler" let set_memory_dynamic_range _ _ _ _ = unimplemented "VM.set_memory_dynamic_range" let request_shutdown _ _ _ _ = unimplemented "VM.request_shutdown" let wait_shutdown _ _ _ _ = unimplemented "VM.wait_shutdown" let assert_can_save _ = unimplemented "VM.assert_can_save" let save _ _ _ _ _ _ _ = unimplemented "VM.save" let restore _ _ _ _ _ _ _ = unimplemented "VM.restore" let s3suspend _ _ = unimplemented "VM.s3suspend" let s3resume _ _ = unimplemented "VM.s3resume" let soft_reset _ _ = unimplemented "VM.soft_reset" let get_state _ = Xenops_utils.halted_vm let request_rdp _ _ = unimplemented "VM.request_rdp" let run_script _ _ _ = unimplemented "VM.run_script" let set_domain_action_request _ _ = () let get_domain_action_request _ = None let get_hook_args _ = [] let generate_state_string _ = "" let get_internal_state _ _ _ = "" let set_internal_state _ _ = () let wait_ballooning _ _ = () let minimum_reboot_delay = 0. end module PCI = struct let get_state _ _ = unplugged_pci let dequarantine _ = () let plug _ _ _ = unimplemented "PCI.plug" let unplug _ _ _ = unimplemented "PCI.unplug" let get_device_action_request _ _ = None end module VBD = struct let set_active _ _ _ _ = () let epoch_begin _ _ _ _ = () let epoch_end _ _ _ = () let plug _ _ _ = unimplemented "VBD.plug" let unplug _ _ _ _ = unimplemented "VBD.unplug" let insert _ _ _ _ = unimplemented "VBD.insert" let eject _ _ _ = unimplemented "VBD.eject" let set_qos _ _ _ = () let get_state _ _ = unplugged_vbd let get_device_action_request _ _ = None end module VIF = struct let set_active _ _ _ _ = () let plug _ _ _ = unimplemented "VIF.plug" let unplug _ _ _ _ = unimplemented "VIF.unplug" let move _ _ _ _ = unimplemented "VIF.move" let set_carrier _ _ _ _ = unimplemented "VIF.set_carrier" let set_locking_mode _ _ _ _ = unimplemented "VIF.set_locking_mode" let set_ipv4_configuration _ _ _ _ = unimplemented "VIF.set_ipv4_configuration" let set_ipv6_configuration _ _ _ _ = unimplemented "VIF.set_ipv6_configuration" let set_pvs_proxy _ _ _ _ = unimplemented "VIF.set_pvs_proxy" let get_state _ _ = unplugged_vif let get_device_action_request _ _ = None end module VGPU = struct let start _ _ _ _ = unimplemented "VGPU.start" let set_active _ _ _ _ = () let get_state _ _ = unplugged_vgpu end module VUSB = struct let plug _ _ _ = unimplemented "VUSB.plug" let unplug _ _ _ = unimplemented "VUSB.unplug" let get_state _ _ = unplugged_vusb let get_device_action_request _ _ = None end module UPDATES = struct let get _ _ = while true do Thread.delay 5. done ; assert false end module DEBUG = struct let trigger _ _ = unimplemented "DEBUG.trigger" end
7e8428f3e673125ff79f003ca5ad0b404b3bd61b29c24347b5167659bef9fbd5
travelping/exometer_fetch
exometer_fetch_test.erl
-module(exometer_fetch_test). -include_lib("eunit/include/eunit.hrl"). subscribtions_module_test() -> Subscribers = [ {reporters, [{exometer_report_fetch, [{autosubscribe, true}, {subscriptions_module, exometer_fetch_subscribe_mod}, {key_prefix, <<"/metrics">>}]}]}], error_logger:tty(false), application:set_env(lager, handlers, [{lager_console_backend, none}]), application:set_env(exometer, report, Subscribers), {ok, Apps} = application:ensure_all_started(exometer_fetch), exometer:update_or_create([metric, test1], 1, histogram, []), exometer:update_or_create([metric, test2], 2, histogram, []), timer:sleep(100), ?assertEqual(3, length(exometer_report:list_subscriptions(exometer_report_fetch))), %% subscribed via callback {ok, _} = exometer_fetch:fetch(<<"/metrics/my_key1">>), {ok, _} = exometer_fetch:fetch(<<"/metrics/my_key1">>, min), {ok, _} = exometer_fetch:fetch(<<"/metrics/">>), %% there is no subscription to datapoint 'n' {error, _} = exometer_fetch:fetch(<<"/metrics/my_key1">>, n), [application:stop(App) || App <- Apps], ok.
null
https://raw.githubusercontent.com/travelping/exometer_fetch/07cd2fb2162b8b77cbe51246272122a9149fc4ff/test/exometer_fetch_test.erl
erlang
subscribed via callback there is no subscription to datapoint 'n'
-module(exometer_fetch_test). -include_lib("eunit/include/eunit.hrl"). subscribtions_module_test() -> Subscribers = [ {reporters, [{exometer_report_fetch, [{autosubscribe, true}, {subscriptions_module, exometer_fetch_subscribe_mod}, {key_prefix, <<"/metrics">>}]}]}], error_logger:tty(false), application:set_env(lager, handlers, [{lager_console_backend, none}]), application:set_env(exometer, report, Subscribers), {ok, Apps} = application:ensure_all_started(exometer_fetch), exometer:update_or_create([metric, test1], 1, histogram, []), exometer:update_or_create([metric, test2], 2, histogram, []), timer:sleep(100), ?assertEqual(3, length(exometer_report:list_subscriptions(exometer_report_fetch))), {ok, _} = exometer_fetch:fetch(<<"/metrics/my_key1">>), {ok, _} = exometer_fetch:fetch(<<"/metrics/my_key1">>, min), {ok, _} = exometer_fetch:fetch(<<"/metrics/">>), {error, _} = exometer_fetch:fetch(<<"/metrics/my_key1">>, n), [application:stop(App) || App <- Apps], ok.
9cabd71cdfa0cf3283676019e29c07a3c9617c020cc348fb1fde0927ec8e7a80
jaspervdj/advent-of-code
24.hs
import AdventOfCode.Dijkstra (Bfs (..), bfs) import qualified AdventOfCode.Grid.Bounded as G import AdventOfCode.Main (pureMain) import AdventOfCode.V2 (V2 (..), (.+.)) import Control.Monad (guard) import qualified Data.Set as Set import qualified Data.Vector as V data Tile = Wall | Floor | Blizzard G.Dir parseTile :: Char -> Either String Tile parseTile c = case c of '#' -> Right Wall '.' -> Right Floor '^' -> Right $ Blizzard G.U '>' -> Right $ Blizzard G.R 'v' -> Right $ Blizzard G.D '<' -> Right $ Blizzard G.L _ -> Left $ "Unknown tile: " ++ show c precomputeBlizzards :: G.Grid Tile -> V.Vector (G.Grid Bool) precomputeBlizzards grid0 = V.map toGrid $ V.iterateN period step blizzards0 where period = lcm (G.gridWidth grid0) (G.gridHeight grid0) blizzards0 = [(d, pos) | (pos, Blizzard d) <- G.toList grid0] step blizzards = [(b, wrap (G.move 1 b p)) | (b, p) <- blizzards] toGrid blizzards = let set = Set.fromList $ map snd blizzards in G.generate (G.gridWidth grid0) (G.gridHeight grid0) $ \pos -> Set.member pos set wrap (V2 x y) = V2 (x `mod` G.gridWidth grid0) (y `mod` G.gridHeight grid0) removeEdges :: G.Grid a -> G.Grid a removeEdges big = G.generate (G.gridWidth big - 2) (G.gridHeight big - 2) $ \pos -> G.index (pos .+. V2 1 1) big main :: IO () main = pureMain $ \str -> do grid <- G.fromString str >>= traverse parseTile >>= pure . removeEdges let blizzards = precomputeBlizzards grid period = V.length blizzards dest = V2 (G.gridWidth grid - 1) (G.gridHeight grid) start = V2 0 (-1) neighbourStates (time, pos) = do pos' <- pos : map (\d -> G.move 1 d pos) [G.U, G.R, G.D, G.L] let time' = (time + 1) `mod` period guard $ case G.lookup pos' $ blizzards V.! time' of Nothing -> pos' == start || pos' == dest Just blizzard -> not blizzard pure (time', pos') part1 = pred . length . maybe [] snd . bfsGoal $ bfs neighbourStates ((== dest) . snd) (0, start) part2a = pred . length . maybe [] snd . bfsGoal $ bfs neighbourStates ((== start) . snd) (part1, dest) part2b = pred . length . maybe [] snd . bfsGoal $ bfs neighbourStates ((== dest) . snd) (part1 + part2a, start) part2 = part1 + part2a + part2b pure (pure part1, pure part2)
null
https://raw.githubusercontent.com/jaspervdj/advent-of-code/b87c4b711858f9d7cf21746b6fb870084a5d9aab/2022/24.hs
haskell
import AdventOfCode.Dijkstra (Bfs (..), bfs) import qualified AdventOfCode.Grid.Bounded as G import AdventOfCode.Main (pureMain) import AdventOfCode.V2 (V2 (..), (.+.)) import Control.Monad (guard) import qualified Data.Set as Set import qualified Data.Vector as V data Tile = Wall | Floor | Blizzard G.Dir parseTile :: Char -> Either String Tile parseTile c = case c of '#' -> Right Wall '.' -> Right Floor '^' -> Right $ Blizzard G.U '>' -> Right $ Blizzard G.R 'v' -> Right $ Blizzard G.D '<' -> Right $ Blizzard G.L _ -> Left $ "Unknown tile: " ++ show c precomputeBlizzards :: G.Grid Tile -> V.Vector (G.Grid Bool) precomputeBlizzards grid0 = V.map toGrid $ V.iterateN period step blizzards0 where period = lcm (G.gridWidth grid0) (G.gridHeight grid0) blizzards0 = [(d, pos) | (pos, Blizzard d) <- G.toList grid0] step blizzards = [(b, wrap (G.move 1 b p)) | (b, p) <- blizzards] toGrid blizzards = let set = Set.fromList $ map snd blizzards in G.generate (G.gridWidth grid0) (G.gridHeight grid0) $ \pos -> Set.member pos set wrap (V2 x y) = V2 (x `mod` G.gridWidth grid0) (y `mod` G.gridHeight grid0) removeEdges :: G.Grid a -> G.Grid a removeEdges big = G.generate (G.gridWidth big - 2) (G.gridHeight big - 2) $ \pos -> G.index (pos .+. V2 1 1) big main :: IO () main = pureMain $ \str -> do grid <- G.fromString str >>= traverse parseTile >>= pure . removeEdges let blizzards = precomputeBlizzards grid period = V.length blizzards dest = V2 (G.gridWidth grid - 1) (G.gridHeight grid) start = V2 0 (-1) neighbourStates (time, pos) = do pos' <- pos : map (\d -> G.move 1 d pos) [G.U, G.R, G.D, G.L] let time' = (time + 1) `mod` period guard $ case G.lookup pos' $ blizzards V.! time' of Nothing -> pos' == start || pos' == dest Just blizzard -> not blizzard pure (time', pos') part1 = pred . length . maybe [] snd . bfsGoal $ bfs neighbourStates ((== dest) . snd) (0, start) part2a = pred . length . maybe [] snd . bfsGoal $ bfs neighbourStates ((== start) . snd) (part1, dest) part2b = pred . length . maybe [] snd . bfsGoal $ bfs neighbourStates ((== dest) . snd) (part1 + part2a, start) part2 = part1 + part2a + part2b pure (pure part1, pure part2)
2563524916b17fb184140bee6f26f63776c889fd9bd1b65604c07046c50c2934
gebi/jungerl
base64.erl
Copyright ( C ) 1999 , Bluetail AB %% File : base64.erl Authors : < > , < > %% Purpose : Base64 encoding and decoding Created : 21 August 1999 This code was origonally written by and I ( ) removed some bugs ... And I ( ) rewrote the conversion functions %% to be reentrant so they could be used for LARGE input strings. -module(base64). -vsn("$Revision$ "). -export([to_string/1,from_string/1,from_string/2,from_end/1]). -export([base64_2_str/1, str_2_base64/1]). -export([str_2_b64/1]). -import(lists, [reverse/1,reverse/2]). to_string(B64) -> base64_2_str(B64). base64_2_str(Str) -> b642str(Str, 0, 0, []). b642str([$=|_], Acc, N, Out) -> case N of 2 -> If I have seen two characters before the = Them I 'm encoding one byte reverse([(Acc bsr 4)|Out]); 3 -> If I have seen three characters before the = Them I 'm encoding two bytes B1 = Acc bsr 10, B2 = (Acc bsr 2) band 16#ff, reverse([B2,B1|Out]); _ -> exit({bad,b64,N}) end; b642str([H|T], Acc, N, Out) -> case d(H) of no -> b642str(T, Acc, N, Out); I -> Acc1 = (Acc bsl 6) bor I, case N of 3 -> B1 = Acc1 bsr 16, B2 = (Acc1 band 16#ffff) bsr 8, B3 = (Acc1 band 16#ff), b642str(T, 0, 0, [B3,B2,B1|Out]); _ -> b642str(T, Acc1, N+1, Out) end end; b642str([], 0, 0, Out) -> reverse(Out). %%---------------------------------------------------------------------- %% from_string(String) -> Base64Str. %% Base64 convert a (multiline) string into a multiple line string with each line terminated by " " . from_string(String) -> case from_string(String, []) of {ok,Line,Rest} -> Line ++ "\n" ++ from_string(Rest); {more,Cont} -> from_end(Cont) end. str_2_b64(String) -> {more, Cont} = from_string_nonl(String, []), from_end(Cont). str_2_base64(Str) -> from_string(Str). %% from_string(String, Continuation) -> {more,Cont} | {ok,Line,Rest}. Return one 72 char line of base64 converted characters . If there %% are not enough input characters then {more,Cont} is returned %% signaling more characters are needed for this line. from_string(S, []) -> from_string(S, [], 0); from_string(S, {Rest,Acc,N}) -> from_string(Rest ++ S, Acc, N). from_string(S, Out, 72) -> {ok,reverse(Out),S}; from_string([C1,C2,C3|S], Out, N) -> O1 = e(C1 bsr 2), O2 = e(((C1 band 16#03) bsl 4) bor (C2 bsr 4)), O3 = e(((C2 band 16#0f) bsl 2) bor (C3 bsr 6)), O4 = e(C3 band 16#3f), from_string(S, [O4,O3,O2,O1|Out], N+4); from_string(S, Out, N) -> {more,{S,Out,N}}. from_string_nonl([C1,C2,C3|S], Out) -> O1 = e(C1 bsr 2), O2 = e(((C1 band 16#03) bsl 4) bor (C2 bsr 4)), O3 = e(((C2 band 16#0f) bsl 2) bor (C3 bsr 6)), O4 = e(C3 band 16#3f), from_string_nonl(S, [O4,O3,O2,O1|Out]); from_string_nonl(S, Out) -> {more,{S,Out,1}}. %% from_end(Continuation) -> Line. %% End a base64 conversion. Assume we have run from_string %% until end. from_end({[C1,C2],Out,_N}) -> O1 = e(C1 bsr 2), O2 = e(((C1 band 16#03) bsl 4) bor (C2 bsr 4)), O3 = e((C2 band 16#0f) bsl 2), reverse(Out, [O1,O2,O3,$=]); from_end({[C1],Out,_N}) -> O1 = e(C1 bsr 2), O2 = e((C1 band 16#03) bsl 4), reverse(Out, [O1,O2,$=,$=]); from_end({[],Out,_N}) -> reverse(Out); from_end([]) -> []. Table 1 : The Base64 Alphabet %% %% Value Encoding Value Encoding Value Encoding Value Encoding %% 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 %% 10 K 27 b 44 s 61 9 %% 11 L 28 c 45 t 62 + %% 12 M 29 d 46 u 63 / %% 13 N 30 e 47 v %% 14 O 31 f 48 w (pad) = %% 15 P 32 g 49 x %% 16 Q 33 h 50 y d(X) when X >= $A, X =<$Z -> X - $A; d(X) when X >= $a, X =<$z -> X - $a + 26; d(X) when X >= $0, X =<$9 -> X - $0 + 52; d($+) -> 62; d($/) -> 63; d(_) -> no. e(X) when X >= 0, X < 26 -> X + $A; e(X) when X >= 26, X < 52 -> X + $a - 26; e(X) when X >= 52, X < 62 -> X + $0 - 52; e(62) -> $+; e(63) -> $/; e(X) -> erlang:fault({badchar,X}).
null
https://raw.githubusercontent.com/gebi/jungerl/8f5c102295dbe903f47d79fd64714b7de17026ec/lib/msc/src/base64.erl
erlang
File : base64.erl Purpose : Base64 encoding and decoding to be reentrant so they could be used for LARGE input strings. ---------------------------------------------------------------------- from_string(String) -> Base64Str. Base64 convert a (multiline) string into a multiple line string from_string(String, Continuation) -> {more,Cont} | {ok,Line,Rest}. are not enough input characters then {more,Cont} is returned signaling more characters are needed for this line. from_end(Continuation) -> Line. End a base64 conversion. Assume we have run from_string until end. Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y
Copyright ( C ) 1999 , Bluetail AB Authors : < > , < > Created : 21 August 1999 This code was origonally written by and I ( ) removed some bugs ... And I ( ) rewrote the conversion functions -module(base64). -vsn("$Revision$ "). -export([to_string/1,from_string/1,from_string/2,from_end/1]). -export([base64_2_str/1, str_2_base64/1]). -export([str_2_b64/1]). -import(lists, [reverse/1,reverse/2]). to_string(B64) -> base64_2_str(B64). base64_2_str(Str) -> b642str(Str, 0, 0, []). b642str([$=|_], Acc, N, Out) -> case N of 2 -> If I have seen two characters before the = Them I 'm encoding one byte reverse([(Acc bsr 4)|Out]); 3 -> If I have seen three characters before the = Them I 'm encoding two bytes B1 = Acc bsr 10, B2 = (Acc bsr 2) band 16#ff, reverse([B2,B1|Out]); _ -> exit({bad,b64,N}) end; b642str([H|T], Acc, N, Out) -> case d(H) of no -> b642str(T, Acc, N, Out); I -> Acc1 = (Acc bsl 6) bor I, case N of 3 -> B1 = Acc1 bsr 16, B2 = (Acc1 band 16#ffff) bsr 8, B3 = (Acc1 band 16#ff), b642str(T, 0, 0, [B3,B2,B1|Out]); _ -> b642str(T, Acc1, N+1, Out) end end; b642str([], 0, 0, Out) -> reverse(Out). with each line terminated by " " . from_string(String) -> case from_string(String, []) of {ok,Line,Rest} -> Line ++ "\n" ++ from_string(Rest); {more,Cont} -> from_end(Cont) end. str_2_b64(String) -> {more, Cont} = from_string_nonl(String, []), from_end(Cont). str_2_base64(Str) -> from_string(Str). Return one 72 char line of base64 converted characters . If there from_string(S, []) -> from_string(S, [], 0); from_string(S, {Rest,Acc,N}) -> from_string(Rest ++ S, Acc, N). from_string(S, Out, 72) -> {ok,reverse(Out),S}; from_string([C1,C2,C3|S], Out, N) -> O1 = e(C1 bsr 2), O2 = e(((C1 band 16#03) bsl 4) bor (C2 bsr 4)), O3 = e(((C2 band 16#0f) bsl 2) bor (C3 bsr 6)), O4 = e(C3 band 16#3f), from_string(S, [O4,O3,O2,O1|Out], N+4); from_string(S, Out, N) -> {more,{S,Out,N}}. from_string_nonl([C1,C2,C3|S], Out) -> O1 = e(C1 bsr 2), O2 = e(((C1 band 16#03) bsl 4) bor (C2 bsr 4)), O3 = e(((C2 band 16#0f) bsl 2) bor (C3 bsr 6)), O4 = e(C3 band 16#3f), from_string_nonl(S, [O4,O3,O2,O1|Out]); from_string_nonl(S, Out) -> {more,{S,Out,1}}. from_end({[C1,C2],Out,_N}) -> O1 = e(C1 bsr 2), O2 = e(((C1 band 16#03) bsl 4) bor (C2 bsr 4)), O3 = e((C2 band 16#0f) bsl 2), reverse(Out, [O1,O2,O3,$=]); from_end({[C1],Out,_N}) -> O1 = e(C1 bsr 2), O2 = e((C1 band 16#03) bsl 4), reverse(Out, [O1,O2,$=,$=]); from_end({[],Out,_N}) -> reverse(Out); from_end([]) -> []. Table 1 : The Base64 Alphabet 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 d(X) when X >= $A, X =<$Z -> X - $A; d(X) when X >= $a, X =<$z -> X - $a + 26; d(X) when X >= $0, X =<$9 -> X - $0 + 52; d($+) -> 62; d($/) -> 63; d(_) -> no. e(X) when X >= 0, X < 26 -> X + $A; e(X) when X >= 26, X < 52 -> X + $a - 26; e(X) when X >= 52, X < 62 -> X + $0 - 52; e(62) -> $+; e(63) -> $/; e(X) -> erlang:fault({badchar,X}).
18ccb153aca745b7aa0b23e86e869f56447ba1335c0b930b59694e80eb684cb0
lpw25/ocaml-typed-effects
typecore.mli
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) (* Type inference for the core language *) open Asttypes open Types open Format val is_nonexpansive: Typedtree.expression -> bool val type_binding: Env.t -> Location.t -> Ctype.effect_expectation -> rec_flag -> Parsetree.value_binding list -> Annot.ident option -> Typedtree.value_binding list * Env.t val type_let: Env.t -> Location.t -> Ctype.effect_expectation -> rec_flag -> Parsetree.value_binding list -> Annot.ident option -> Typedtree.value_binding list * Env.t val type_expression: Env.t -> Ctype.effect_expectation -> Parsetree.expression -> Typedtree.expression val type_class_arg_pattern: string -> Env.t -> Env.t -> type_expr -> label -> Parsetree.pattern -> Typedtree.pattern * (Ident.t * string loc * Ident.t * type_expr) list * Env.t * Env.t val type_self_pattern: string -> type_expr -> Env.t -> Env.t -> Env.t -> type_expr -> Parsetree.pattern -> Typedtree.pattern * (Ident.t * type_expr) Meths.t ref * (Ident.t * Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr) Vars.t ref * Env.t * Env.t * Env.t val check_partial: ?lev:int -> env:Env.t -> outer_eff:type_expr -> inner_eff:type_expr -> cont_ty:type_expr -> type_expr -> Location.t -> Typedtree.case list -> Typedtree.partial * (label * int * bool * bool) list val type_expect: ?in_function:(Location.t * type_expr) -> Env.t -> type_expr -> Parsetree.expression -> type_expr -> Typedtree.expression val type_exp: Env.t -> type_expr -> Parsetree.expression -> Typedtree.expression val type_approx: Env.t -> Parsetree.expression -> type_expr * type_expr list val type_argument: Env.t -> type_expr -> Parsetree.expression -> type_expr -> type_expr -> Typedtree.expression val option_some: Typedtree.expression -> Typedtree.expression val option_none: type_expr -> Location.t -> Typedtree.expression val extract_option_type: Env.t -> type_expr -> type_expr val iter_pattern: (Typedtree.pattern -> unit) -> Typedtree.pattern -> unit val generalizable: int -> type_expr -> bool val reset_delayed_checks: unit -> unit val force_delayed_checks: unit -> unit val self_coercion : (Path.t * Location.t list ref) list ref val check_expectation: Ctype.effect_expectation -> unit type error = Polymorphic_label of Longident.t | Constructor_arity_mismatch of Longident.t * int * int | Label_mismatch of Longident.t * (type_expr * type_expr) list | Pattern_type_clash of (type_expr * type_expr) list | Pattern_inner_effect_clash of (type_expr * type_expr) list | Pattern_outer_effect_clash of (type_expr * type_expr) list | Or_pattern_type_clash of Ident.t * (type_expr * type_expr) list | Multiply_bound_variable of string | Orpat_vars of Ident.t | Expr_type_clash of (type_expr * type_expr) list | Expr_effect_clash of (type_expr * type_expr) list | Apply_non_function of type_expr | Apply_wrong_label of label * type_expr | Label_multiply_defined of string | Label_missing of Ident.t list | Label_not_mutable of Longident.t | Label_effect_clash of (type_expr * type_expr) list | Wrong_name of string * type_expr * string * Path.t * Longident.t | Name_type_mismatch of string * Longident.t * (Path.t * Path.t) * (Path.t * Path.t) list | Invalid_format of string | Undefined_method of type_expr * string | Undefined_inherited_method of string | Virtual_class of Longident.t | Private_type of type_expr | Private_label of Longident.t * type_expr | Unbound_instance_variable of string | Instance_variable_not_mutable of bool * string | Not_subtype of (type_expr * type_expr) list * (type_expr * type_expr) list | Outside_class | Value_multiply_overridden of string | Coercion_failure of type_expr * type_expr * (type_expr * type_expr) list * bool | Too_many_arguments of bool * type_expr | Abstract_wrong_label of label * type_expr | Scoping_let_module of string * type_expr | Masked_instance_variable of Longident.t | Not_a_variant_type of Longident.t | Incoherent_label_order | Less_general of string * (type_expr * type_expr) list | Modules_not_allowed | Cannot_infer_signature | Not_a_packed_module of type_expr | Recursive_local_constraint of (type_expr * type_expr) list | Unexpected_existential | Unqualified_gadt_pattern of Path.t * string | Invalid_interval | Invalid_for_loop_index | No_value_clauses | Exception_pattern_below_toplevel | Effect_pattern_below_toplevel | Invalid_continuation_pattern | Unexpected_continuation_pattern of Longident.t | Missing_continuation_pattern of Longident.t | Toplevel_no_default_handler of string * string | Toplevel_unknown_effects of type_expr * string exception Error of Location.t * Env.t * error exception Error_forward of Location.error val report_error: Env.t -> formatter -> error -> unit (* Deprecated. Use Location.{error_of_exn, report_error}. *) Forward declaration , to be filled in by val type_module: (Env.t -> Ctype.effect_expectation -> Parsetree.module_expr -> Typedtree.module_expr) ref (* Forward declaration, to be filled in by Typemod.type_open *) val type_open: (override_flag -> Env.t -> Location.t -> Longident.t loc -> Path.t * Env.t) ref Forward declaration , to be filled in by Typeclass.class_structure val type_object: (Env.t -> Location.t -> Parsetree.class_structure -> Typedtree.class_structure * Types.class_signature * string list) ref val type_package: (Env.t -> Ctype.effect_expectation -> Parsetree.module_expr -> Path.t -> Longident.t list -> type_expr list -> Typedtree.module_expr * type_expr list) ref val create_package_type : Location.t -> Env.t -> Longident.t * (Longident.t * Parsetree.core_type) list -> Path.t * (Longident.t * Typedtree.core_type) list * Types.type_expr
null
https://raw.githubusercontent.com/lpw25/ocaml-typed-effects/79ea08b285c1fd9caf3f5a4d2aa112877f882bea/typing/typecore.mli
ocaml
********************************************************************* OCaml ********************************************************************* Type inference for the core language Deprecated. Use Location.{error_of_exn, report_error}. Forward declaration, to be filled in by Typemod.type_open
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . open Asttypes open Types open Format val is_nonexpansive: Typedtree.expression -> bool val type_binding: Env.t -> Location.t -> Ctype.effect_expectation -> rec_flag -> Parsetree.value_binding list -> Annot.ident option -> Typedtree.value_binding list * Env.t val type_let: Env.t -> Location.t -> Ctype.effect_expectation -> rec_flag -> Parsetree.value_binding list -> Annot.ident option -> Typedtree.value_binding list * Env.t val type_expression: Env.t -> Ctype.effect_expectation -> Parsetree.expression -> Typedtree.expression val type_class_arg_pattern: string -> Env.t -> Env.t -> type_expr -> label -> Parsetree.pattern -> Typedtree.pattern * (Ident.t * string loc * Ident.t * type_expr) list * Env.t * Env.t val type_self_pattern: string -> type_expr -> Env.t -> Env.t -> Env.t -> type_expr -> Parsetree.pattern -> Typedtree.pattern * (Ident.t * type_expr) Meths.t ref * (Ident.t * Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr) Vars.t ref * Env.t * Env.t * Env.t val check_partial: ?lev:int -> env:Env.t -> outer_eff:type_expr -> inner_eff:type_expr -> cont_ty:type_expr -> type_expr -> Location.t -> Typedtree.case list -> Typedtree.partial * (label * int * bool * bool) list val type_expect: ?in_function:(Location.t * type_expr) -> Env.t -> type_expr -> Parsetree.expression -> type_expr -> Typedtree.expression val type_exp: Env.t -> type_expr -> Parsetree.expression -> Typedtree.expression val type_approx: Env.t -> Parsetree.expression -> type_expr * type_expr list val type_argument: Env.t -> type_expr -> Parsetree.expression -> type_expr -> type_expr -> Typedtree.expression val option_some: Typedtree.expression -> Typedtree.expression val option_none: type_expr -> Location.t -> Typedtree.expression val extract_option_type: Env.t -> type_expr -> type_expr val iter_pattern: (Typedtree.pattern -> unit) -> Typedtree.pattern -> unit val generalizable: int -> type_expr -> bool val reset_delayed_checks: unit -> unit val force_delayed_checks: unit -> unit val self_coercion : (Path.t * Location.t list ref) list ref val check_expectation: Ctype.effect_expectation -> unit type error = Polymorphic_label of Longident.t | Constructor_arity_mismatch of Longident.t * int * int | Label_mismatch of Longident.t * (type_expr * type_expr) list | Pattern_type_clash of (type_expr * type_expr) list | Pattern_inner_effect_clash of (type_expr * type_expr) list | Pattern_outer_effect_clash of (type_expr * type_expr) list | Or_pattern_type_clash of Ident.t * (type_expr * type_expr) list | Multiply_bound_variable of string | Orpat_vars of Ident.t | Expr_type_clash of (type_expr * type_expr) list | Expr_effect_clash of (type_expr * type_expr) list | Apply_non_function of type_expr | Apply_wrong_label of label * type_expr | Label_multiply_defined of string | Label_missing of Ident.t list | Label_not_mutable of Longident.t | Label_effect_clash of (type_expr * type_expr) list | Wrong_name of string * type_expr * string * Path.t * Longident.t | Name_type_mismatch of string * Longident.t * (Path.t * Path.t) * (Path.t * Path.t) list | Invalid_format of string | Undefined_method of type_expr * string | Undefined_inherited_method of string | Virtual_class of Longident.t | Private_type of type_expr | Private_label of Longident.t * type_expr | Unbound_instance_variable of string | Instance_variable_not_mutable of bool * string | Not_subtype of (type_expr * type_expr) list * (type_expr * type_expr) list | Outside_class | Value_multiply_overridden of string | Coercion_failure of type_expr * type_expr * (type_expr * type_expr) list * bool | Too_many_arguments of bool * type_expr | Abstract_wrong_label of label * type_expr | Scoping_let_module of string * type_expr | Masked_instance_variable of Longident.t | Not_a_variant_type of Longident.t | Incoherent_label_order | Less_general of string * (type_expr * type_expr) list | Modules_not_allowed | Cannot_infer_signature | Not_a_packed_module of type_expr | Recursive_local_constraint of (type_expr * type_expr) list | Unexpected_existential | Unqualified_gadt_pattern of Path.t * string | Invalid_interval | Invalid_for_loop_index | No_value_clauses | Exception_pattern_below_toplevel | Effect_pattern_below_toplevel | Invalid_continuation_pattern | Unexpected_continuation_pattern of Longident.t | Missing_continuation_pattern of Longident.t | Toplevel_no_default_handler of string * string | Toplevel_unknown_effects of type_expr * string exception Error of Location.t * Env.t * error exception Error_forward of Location.error val report_error: Env.t -> formatter -> error -> unit Forward declaration , to be filled in by val type_module: (Env.t -> Ctype.effect_expectation -> Parsetree.module_expr -> Typedtree.module_expr) ref val type_open: (override_flag -> Env.t -> Location.t -> Longident.t loc -> Path.t * Env.t) ref Forward declaration , to be filled in by Typeclass.class_structure val type_object: (Env.t -> Location.t -> Parsetree.class_structure -> Typedtree.class_structure * Types.class_signature * string list) ref val type_package: (Env.t -> Ctype.effect_expectation -> Parsetree.module_expr -> Path.t -> Longident.t list -> type_expr list -> Typedtree.module_expr * type_expr list) ref val create_package_type : Location.t -> Env.t -> Longident.t * (Longident.t * Parsetree.core_type) list -> Path.t * (Longident.t * Typedtree.core_type) list * Types.type_expr
efeac860a94e8fef6cb61d6a45d96f640eb204b69e733f5b53ff807e55bb8c3e
mikebroberts/clojurenote
use.clj
(ns clojurenote-demo.use (:require [clojurenote.notes :as notes] )) (defn list-notebooks [token notestore-url] (let [notebooks (notes/list-notebooks {:access-token token :notestore-url notestore-url})] (str "<html><body> <p>Notebooks for token: " token ", notestore: " notestore-url "</p>" "<ul>" (apply str (map (comp #(str "<li>" % "</li>") bean) notebooks)) "</ul>" "</body></html>")))
null
https://raw.githubusercontent.com/mikebroberts/clojurenote/db1f183fcb3766b9fb219484f3d9a17bd1fa4563/clojurenote-demo/src/clojurenote_demo/use.clj
clojure
(ns clojurenote-demo.use (:require [clojurenote.notes :as notes] )) (defn list-notebooks [token notestore-url] (let [notebooks (notes/list-notebooks {:access-token token :notestore-url notestore-url})] (str "<html><body> <p>Notebooks for token: " token ", notestore: " notestore-url "</p>" "<ul>" (apply str (map (comp #(str "<li>" % "</li>") bean) notebooks)) "</ul>" "</body></html>")))
532bd39f50b09f60f78e985d0ec0f8816ab4ea1208d878c984bf42d225186169
ocsigen/eliom
eliom_react.server.ml
Ocsigen * * Copyright ( C ) 2010 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2010 * Raphaël Proust * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) (* Module for event wrapping and related functions *) open Lwt_react module Down = struct type 'a stateful = { throttling : float option ; scope : Eliom_common.client_process_scope option ; react : 'a E.t ; name : string option ; size : int option } type 'a stateless = 'a Eliom_comet.Channel.t type 'a t' = Stateful of 'a stateful | Stateless of 'a stateless type 'a t = {t : 'a t'; react_down_mark : 'a t Eliom_common.wrapper} let wrap_stateful {throttling = t; scope; react = e; name; size} = let ee = Lwt.with_value Eliom_common.sp_key None @@ fun () -> match t with | None -> e | Some t -> E.limit (fun () -> Lwt_unix.sleep t) e in let channel = Eliom_comet.Channel.create_from_events ?scope ?name ?size ee in channel, Eliom_common.make_unwrapper Eliom_common.react_down_unwrap_id let wrap_stateless channel = channel, Eliom_common.make_unwrapper Eliom_common.react_down_unwrap_id let internal_wrap = function | {t = Stateful v} -> wrap_stateful v | {t = Stateless v} -> wrap_stateless v let react_down_mark () = Eliom_common.make_wrapper internal_wrap let stateful ?scope ?throttling ?name ?size (e : 'a E.t) = Stateful {throttling; scope; react = e; name; size} let stateless ?throttling ?name ?size (e : 'a E.t) = let ee = match throttling with | None -> e | Some t -> E.limit (fun () -> Lwt_unix.sleep t) e in Stateless (Eliom_comet.Channel.create_from_events ~scope:`Site ?name ?size ee) let of_react ?scope ?throttling ?name ?size (e : 'a E.t) = let t = match scope with | Some `Site -> stateless ?throttling ?name ?size e | None -> stateful ?throttling ?name ?size e | Some (`Client_process _ as scope) -> stateful ~scope ?throttling ?name ?size e in {t; react_down_mark = react_down_mark ()} end module Up = struct type 'a t = { event : 'a E.t ; service : ( unit , 'a , Eliom_service.post , Eliom_service.non_att , Eliom_service.co , Eliom_service.non_ext , Eliom_service.reg , [`WithoutSuffix] , unit , [`One of 'a Eliom_parameter.ocaml] Eliom_parameter.param_name , Eliom_registration.Action.return ) Eliom_service.t ; wrapper : 'a t Eliom_common.wrapper } let to_react t = t.event let internal_wrap t = t.service, Eliom_common.make_unwrapper Eliom_common.react_up_unwrap_id let up_event_wrapper () = Eliom_common.make_wrapper internal_wrap (* An event is created along with a service responsible for it's occurrences. * function takes a param_type *) let create ?scope ?name post_params = let e, push = E.create () in let sp = Eliom_common.get_sp_option () in let scope = match sp, scope with | _, Some l -> l | None, _ -> `Site | _ -> (Eliom_common.comet_client_process_scope :> Eliom_common.scope) in let e_writer = Eliom_service.create ?name ~meth:(Eliom_service.Post (Eliom_parameter.unit, post_params)) ~path:Eliom_service.No_path () in Eliom_registration.Action.register ~scope ~options:`NoReload ~service:e_writer (fun () value -> push value; Lwt.return_unit); {event = e; service = e_writer; wrapper = up_event_wrapper ()} end module S = struct module Down = struct type 'a stateful = { throttling : float option ; scope : Eliom_common.client_process_scope option ; signal : 'a S.t ; name : string option } type 'a stateless = { channel : 'a Eliom_comet.Channel.t ; stream : 'a Lwt_stream.t ; (* avoid garbage collection *) sl_signal : 'a S.t } type 'a t' = Stateful of 'a stateful | Stateless of 'a stateless type 'a t = {t : 'a t'; signal_down_mark : 'a t Eliom_common.wrapper} type 'a store = { s : unit S.t Lazy.t to avoid signal GC mutable value : 'a ; mutable read : bool ; condition : unit Lwt_condition.t } let make_store signal = let rec store = { s = s' ; value = S.value signal ; read = false ; condition = Lwt_condition.create () } and s' = lazy (S.map (fun v -> store.read <- false; store.value <- v; Lwt_condition.broadcast store.condition (); ()) signal) in ignore (Lazy.force store.s); store let read_store store = let rec aux () = if store.read then let%lwt () = Lwt_condition.wait store.condition in aux () else ( store.read <- true; Lwt.return_some store.value) in fun () -> Lwt.with_value Eliom_common.sp_key None @@ aux let wrap_stateful {throttling = t; signal = s; name} = let s : 'a S.t = match t with | None -> s | Some t -> S.limit (fun () -> Lwt_unix.sleep t) s in let store = make_store s in let stream = Lwt_stream.from (read_store store) in let channel = Eliom_comet.Channel.create_unlimited ?name stream in let value : 'a = S.value s in ( channel , value , Eliom_common.make_unwrapper Eliom_common.signal_down_unwrap_id ) let wrap_stateless {sl_signal = s; channel} = let value : 'a = S.value s in ( channel , value , Eliom_common.make_unwrapper Eliom_common.signal_down_unwrap_id ) let internal_wrap = function | {t = Stateful v} -> wrap_stateful v | {t = Stateless v} -> wrap_stateless v let signal_down_mark () = Eliom_common.make_wrapper internal_wrap let stateful ?scope ?throttling ?name (s : 'a S.t) = Stateful {throttling; scope; signal = s; name} let stateless ?throttling ?name (s : 'a S.t) = let s = match throttling with | None -> s | Some t -> S.limit (fun () -> Lwt_unix.sleep t) s in let e = S.changes s in let stream = E.to_stream e in Stateless { channel = Eliom_comet.Channel.create_newest ?name stream ; stream ; sl_signal = s } let of_react ?scope ?throttling ?name (s : 'a S.t) = let t = match scope with | Some `Site -> stateless ?throttling ?name s | None -> stateful ?throttling ?name s | Some (`Client_process _ as scope) -> stateful ~scope ?throttling ?name s in {t; signal_down_mark = signal_down_mark ()} end end
null
https://raw.githubusercontent.com/ocsigen/eliom/c3e0eea5bef02e0af3942b6d27585add95d01d6c/src/lib/eliom_react.server.ml
ocaml
Module for event wrapping and related functions An event is created along with a service responsible for it's occurrences. * function takes a param_type avoid garbage collection
Ocsigen * * Copyright ( C ) 2010 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2010 * Raphaël Proust * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) open Lwt_react module Down = struct type 'a stateful = { throttling : float option ; scope : Eliom_common.client_process_scope option ; react : 'a E.t ; name : string option ; size : int option } type 'a stateless = 'a Eliom_comet.Channel.t type 'a t' = Stateful of 'a stateful | Stateless of 'a stateless type 'a t = {t : 'a t'; react_down_mark : 'a t Eliom_common.wrapper} let wrap_stateful {throttling = t; scope; react = e; name; size} = let ee = Lwt.with_value Eliom_common.sp_key None @@ fun () -> match t with | None -> e | Some t -> E.limit (fun () -> Lwt_unix.sleep t) e in let channel = Eliom_comet.Channel.create_from_events ?scope ?name ?size ee in channel, Eliom_common.make_unwrapper Eliom_common.react_down_unwrap_id let wrap_stateless channel = channel, Eliom_common.make_unwrapper Eliom_common.react_down_unwrap_id let internal_wrap = function | {t = Stateful v} -> wrap_stateful v | {t = Stateless v} -> wrap_stateless v let react_down_mark () = Eliom_common.make_wrapper internal_wrap let stateful ?scope ?throttling ?name ?size (e : 'a E.t) = Stateful {throttling; scope; react = e; name; size} let stateless ?throttling ?name ?size (e : 'a E.t) = let ee = match throttling with | None -> e | Some t -> E.limit (fun () -> Lwt_unix.sleep t) e in Stateless (Eliom_comet.Channel.create_from_events ~scope:`Site ?name ?size ee) let of_react ?scope ?throttling ?name ?size (e : 'a E.t) = let t = match scope with | Some `Site -> stateless ?throttling ?name ?size e | None -> stateful ?throttling ?name ?size e | Some (`Client_process _ as scope) -> stateful ~scope ?throttling ?name ?size e in {t; react_down_mark = react_down_mark ()} end module Up = struct type 'a t = { event : 'a E.t ; service : ( unit , 'a , Eliom_service.post , Eliom_service.non_att , Eliom_service.co , Eliom_service.non_ext , Eliom_service.reg , [`WithoutSuffix] , unit , [`One of 'a Eliom_parameter.ocaml] Eliom_parameter.param_name , Eliom_registration.Action.return ) Eliom_service.t ; wrapper : 'a t Eliom_common.wrapper } let to_react t = t.event let internal_wrap t = t.service, Eliom_common.make_unwrapper Eliom_common.react_up_unwrap_id let up_event_wrapper () = Eliom_common.make_wrapper internal_wrap let create ?scope ?name post_params = let e, push = E.create () in let sp = Eliom_common.get_sp_option () in let scope = match sp, scope with | _, Some l -> l | None, _ -> `Site | _ -> (Eliom_common.comet_client_process_scope :> Eliom_common.scope) in let e_writer = Eliom_service.create ?name ~meth:(Eliom_service.Post (Eliom_parameter.unit, post_params)) ~path:Eliom_service.No_path () in Eliom_registration.Action.register ~scope ~options:`NoReload ~service:e_writer (fun () value -> push value; Lwt.return_unit); {event = e; service = e_writer; wrapper = up_event_wrapper ()} end module S = struct module Down = struct type 'a stateful = { throttling : float option ; scope : Eliom_common.client_process_scope option ; signal : 'a S.t ; name : string option } type 'a stateless = { channel : 'a Eliom_comet.Channel.t ; stream : 'a Lwt_stream.t sl_signal : 'a S.t } type 'a t' = Stateful of 'a stateful | Stateless of 'a stateless type 'a t = {t : 'a t'; signal_down_mark : 'a t Eliom_common.wrapper} type 'a store = { s : unit S.t Lazy.t to avoid signal GC mutable value : 'a ; mutable read : bool ; condition : unit Lwt_condition.t } let make_store signal = let rec store = { s = s' ; value = S.value signal ; read = false ; condition = Lwt_condition.create () } and s' = lazy (S.map (fun v -> store.read <- false; store.value <- v; Lwt_condition.broadcast store.condition (); ()) signal) in ignore (Lazy.force store.s); store let read_store store = let rec aux () = if store.read then let%lwt () = Lwt_condition.wait store.condition in aux () else ( store.read <- true; Lwt.return_some store.value) in fun () -> Lwt.with_value Eliom_common.sp_key None @@ aux let wrap_stateful {throttling = t; signal = s; name} = let s : 'a S.t = match t with | None -> s | Some t -> S.limit (fun () -> Lwt_unix.sleep t) s in let store = make_store s in let stream = Lwt_stream.from (read_store store) in let channel = Eliom_comet.Channel.create_unlimited ?name stream in let value : 'a = S.value s in ( channel , value , Eliom_common.make_unwrapper Eliom_common.signal_down_unwrap_id ) let wrap_stateless {sl_signal = s; channel} = let value : 'a = S.value s in ( channel , value , Eliom_common.make_unwrapper Eliom_common.signal_down_unwrap_id ) let internal_wrap = function | {t = Stateful v} -> wrap_stateful v | {t = Stateless v} -> wrap_stateless v let signal_down_mark () = Eliom_common.make_wrapper internal_wrap let stateful ?scope ?throttling ?name (s : 'a S.t) = Stateful {throttling; scope; signal = s; name} let stateless ?throttling ?name (s : 'a S.t) = let s = match throttling with | None -> s | Some t -> S.limit (fun () -> Lwt_unix.sleep t) s in let e = S.changes s in let stream = E.to_stream e in Stateless { channel = Eliom_comet.Channel.create_newest ?name stream ; stream ; sl_signal = s } let of_react ?scope ?throttling ?name (s : 'a S.t) = let t = match scope with | Some `Site -> stateless ?throttling ?name s | None -> stateful ?throttling ?name s | Some (`Client_process _ as scope) -> stateful ~scope ?throttling ?name s in {t; signal_down_mark = signal_down_mark ()} end end
1e490582445baa89372bc7a56f4105508275816a0ed77610e9647074e74f6239
input-output-hk/cardano-sl
Limits.hs
{-# LANGUAGE RankNTypes #-} -- | This module provides helpers to construct values that have -- serialization size under the certain limit. Used in block creation and stripping . module Pos.Core.Limits ( spanHashMap , stripHashMap ) where import Universum import qualified Data.HashMap.Strict as HM import Serokell.Data.Memory.Units (Byte) import Pos.Binary.Class (Bi, biSize) | Spans hash map into two ( almost same ) parts . spanHashMap :: (Hashable k, Eq k) => HashMap k v -> (HashMap k v, HashMap k v) spanHashMap m | HM.null m = (HM.empty, HM.empty) spanHashMap m = (HM.fromList esl, HM.fromList esr) where es = HM.toList m (esl, esr) = splitAt (length es `div` 2) es | Throws away map elements until map size is leq than limit . Will fail if limit is less than size of empty hashmap ( 1 byte ) . stripHashMap :: forall k v. (Hashable k, Ord k, Bi k, Bi v) => Byte -> HashMap k v -> Maybe (HashMap k v) stripHashMap lim m' | lim < biSize (HM.empty :: HashMap k v) = Nothing | otherwise = Just $ takeFromMapDo m' HM.empty where given two maps m and n where size of m is less than -- limit it tries to add as much as possible to it from n populate m _ | biSize m > lim = error "getLocalPayload@takeFromMap@populate" populate m n | HM.null n = m populate m n | HM.size n == 1 = let merged = m <> n in bool m merged (biSize merged <= lim) populate m n = let (n1,n2) = spanHashMap n mn1 = m `HM.union` n1 in bool (populate m n1) (populate mn1 n2) (biSize mn1 <= lim) takeFromMapDo l r = if biSize l > lim then uncurry takeFromMapDo $ spanHashMap l else populate l r
null
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/core/src/Pos/Core/Limits.hs
haskell
# LANGUAGE RankNTypes # | This module provides helpers to construct values that have serialization size under the certain limit. Used in block creation limit it tries to add as much as possible to it from n
and stripping . module Pos.Core.Limits ( spanHashMap , stripHashMap ) where import Universum import qualified Data.HashMap.Strict as HM import Serokell.Data.Memory.Units (Byte) import Pos.Binary.Class (Bi, biSize) | Spans hash map into two ( almost same ) parts . spanHashMap :: (Hashable k, Eq k) => HashMap k v -> (HashMap k v, HashMap k v) spanHashMap m | HM.null m = (HM.empty, HM.empty) spanHashMap m = (HM.fromList esl, HM.fromList esr) where es = HM.toList m (esl, esr) = splitAt (length es `div` 2) es | Throws away map elements until map size is leq than limit . Will fail if limit is less than size of empty hashmap ( 1 byte ) . stripHashMap :: forall k v. (Hashable k, Ord k, Bi k, Bi v) => Byte -> HashMap k v -> Maybe (HashMap k v) stripHashMap lim m' | lim < biSize (HM.empty :: HashMap k v) = Nothing | otherwise = Just $ takeFromMapDo m' HM.empty where given two maps m and n where size of m is less than populate m _ | biSize m > lim = error "getLocalPayload@takeFromMap@populate" populate m n | HM.null n = m populate m n | HM.size n == 1 = let merged = m <> n in bool m merged (biSize merged <= lim) populate m n = let (n1,n2) = spanHashMap n mn1 = m `HM.union` n1 in bool (populate m n1) (populate mn1 n2) (biSize mn1 <= lim) takeFromMapDo l r = if biSize l > lim then uncurry takeFromMapDo $ spanHashMap l else populate l r
0e8acb1aeb76e26de743d76b9c6dc3b3104706e3b2ec9dfbb28c152a4527598b
shayan-najd/QFeldspar
TemplateHaskell.hs
module Tests.TemplateHaskell where import QFeldspar.MyPrelude import Language.Haskell.TH.Syntax add :: Word32 -> Word32 -> Word32 add = (+) dbl :: Q (TExp (Word32 -> Word32)) dbl = [||\ x -> add x x ||] compose :: Q (TExp ((tb -> tc) -> (ta -> tb) -> ta -> tc)) compose = [|| \ x2 -> \ x1 -> \ x0 -> x2 (x1 x0) ||] four :: Q (TExp Word32) four = [|| ($$compose $$dbl $$dbl) 1 ||]
null
https://raw.githubusercontent.com/shayan-najd/QFeldspar/ed60ce02794a548833317388f6e82e2ab1eabc1c/Tests/TemplateHaskell.hs
haskell
module Tests.TemplateHaskell where import QFeldspar.MyPrelude import Language.Haskell.TH.Syntax add :: Word32 -> Word32 -> Word32 add = (+) dbl :: Q (TExp (Word32 -> Word32)) dbl = [||\ x -> add x x ||] compose :: Q (TExp ((tb -> tc) -> (ta -> tb) -> ta -> tc)) compose = [|| \ x2 -> \ x1 -> \ x0 -> x2 (x1 x0) ||] four :: Q (TExp Word32) four = [|| ($$compose $$dbl $$dbl) 1 ||]
a88629d34e6b809d187a21ac2924836670bf2a9296ef3c8f7b0df3f6a030ad9a
coq/coq
libnames.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) *) (************************************************************************) open Util open Names (**********************************************) (*s Operations on dirpaths *) let split_dirpath d = match DirPath.repr d with | id :: l -> DirPath.make l, id | _ -> failwith "split_dirpath" let pop_dirpath p = match DirPath.repr p with | _::l -> DirPath.make l | [] -> failwith "pop_dirpath" (* Pop the last n module idents *) let pop_dirpath_n n dir = DirPath.make (List.skipn n (DirPath.repr dir)) let is_dirpath_prefix_of d1 d2 = List.prefix_of Id.equal (List.rev (DirPath.repr d1)) (List.rev (DirPath.repr d2)) let is_dirpath_suffix_of dir1 dir2 = let dir1 = DirPath.repr dir1 in let dir2 = DirPath.repr dir2 in List.prefix_of Id.equal dir1 dir2 let chop_dirpath n d = let d1,d2 = List.chop n (List.rev (DirPath.repr d)) in DirPath.make (List.rev d1), DirPath.make (List.rev d2) let drop_dirpath_prefix d1 d2 = let d = List.drop_prefix Id.equal (List.rev (DirPath.repr d1)) (List.rev (DirPath.repr d2)) in DirPath.make (List.rev d) let append_dirpath d1 d2 = DirPath.make (DirPath.repr d2 @ DirPath.repr d1) let add_dirpath_prefix id d = DirPath.make (DirPath.repr d @ [id]) let add_dirpath_suffix p id = DirPath.make (id :: DirPath.repr p) (* parsing *) let parse_dir s = let len = String.length s in let rec decoupe_dirs dirs n = if Int.equal n len && n > 0 then CErrors.user_err Pp.(str @@ s ^ " is an invalid path."); if n >= len then dirs else let pos = try String.index_from s n '.' with Not_found -> len in if Int.equal pos n then CErrors.user_err Pp.(str @@ s ^ " is an invalid path."); let dir = String.sub s n (pos-n) in decoupe_dirs ((Id.of_string dir)::dirs) (pos+1) in decoupe_dirs [] 0 let dirpath_of_string s = let path = match s with | "" -> [] | _ -> parse_dir s in DirPath.make path (*s Section paths are absolute names *) type full_path = { dirpath : DirPath.t ; basename : Id.t } let dirpath sp = sp.dirpath let basename sp = sp.basename let make_path pa id = { dirpath = pa; basename = id } let repr_path { dirpath = pa; basename = id } = (pa,id) let eq_full_path p1 p2 = Id.equal p1.basename p2.basename && DirPath.equal p1.dirpath p2.dirpath (* parsing and printing of section paths *) let string_of_path sp = let (sl,id) = repr_path sp in match DirPath.repr sl with | [] -> Id.to_string id | _ -> (DirPath.to_string sl) ^ "." ^ (Id.to_string id) let sp_ord sp1 sp2 = let (p1,id1) = repr_path sp1 and (p2,id2) = repr_path sp2 in let p_bit = DirPath.compare p1 p2 in if Int.equal p_bit 0 then Id.compare id1 id2 else p_bit module SpOrdered = struct type t = full_path let compare = sp_ord end module Spmap = Map.Make(SpOrdered) let path_of_string s = try let dir, id = split_dirpath (dirpath_of_string s) in make_path dir id with | Invalid_argument _ -> invalid_arg "path_of_string" let pr_path sp = Pp.str (string_of_path sp) (*s qualified names *) type qualid_r = full_path type qualid = qualid_r CAst.t let make_qualid ?loc pa id = CAst.make ?loc (make_path pa id) let repr_qualid {CAst.v=qid} = repr_path qid let qualid_eq qid1 qid2 = eq_full_path qid1.CAst.v qid2.CAst.v let is_qualid_suffix_of_full_path CAst.{v={dirpath=dirpath1;basename=basename1}} {dirpath=dirpath2;basename=basename2} = let dir1 = DirPath.repr dirpath1 in let dir2 = DirPath.repr dirpath2 in Id.equal basename1 basename2 && List.prefix_of Id.equal dir1 dir2 let string_of_qualid qid = string_of_path qid.CAst.v let pr_qualid qid = pr_path qid.CAst.v let qualid_of_string ?loc s = CAst.make ?loc @@ path_of_string s let qualid_of_path ?loc sp = CAst.make ?loc sp let qualid_of_ident ?loc id = make_qualid ?loc DirPath.empty id let qualid_of_dirpath ?loc dir = let (l,a) = split_dirpath dir in make_qualid ?loc l a let qualid_of_lident lid = qualid_of_ident ?loc:lid.CAst.loc lid.CAst.v let qualid_is_ident qid = DirPath.is_empty qid.CAst.v.dirpath let qualid_basename qid = qid.CAst.v.basename let qualid_path qid = qid.CAst.v.dirpath let idset_mem_qualid qid s = qualid_is_ident qid && Id.Set.mem (qualid_basename qid) s (* Default paths *) (*s Roots of the space of absolute names *) let coq_string = "Coq" let coq_root = Id.of_string coq_string let default_root_prefix = DirPath.empty
null
https://raw.githubusercontent.com/coq/coq/f227d8ed33a5ba2343de962f404b0b094dcc86a3/library/libnames.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) ********************************************************************** ******************************************** s Operations on dirpaths Pop the last n module idents parsing s Section paths are absolute names parsing and printing of section paths s qualified names Default paths s Roots of the space of absolute names
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 open Util open Names let split_dirpath d = match DirPath.repr d with | id :: l -> DirPath.make l, id | _ -> failwith "split_dirpath" let pop_dirpath p = match DirPath.repr p with | _::l -> DirPath.make l | [] -> failwith "pop_dirpath" let pop_dirpath_n n dir = DirPath.make (List.skipn n (DirPath.repr dir)) let is_dirpath_prefix_of d1 d2 = List.prefix_of Id.equal (List.rev (DirPath.repr d1)) (List.rev (DirPath.repr d2)) let is_dirpath_suffix_of dir1 dir2 = let dir1 = DirPath.repr dir1 in let dir2 = DirPath.repr dir2 in List.prefix_of Id.equal dir1 dir2 let chop_dirpath n d = let d1,d2 = List.chop n (List.rev (DirPath.repr d)) in DirPath.make (List.rev d1), DirPath.make (List.rev d2) let drop_dirpath_prefix d1 d2 = let d = List.drop_prefix Id.equal (List.rev (DirPath.repr d1)) (List.rev (DirPath.repr d2)) in DirPath.make (List.rev d) let append_dirpath d1 d2 = DirPath.make (DirPath.repr d2 @ DirPath.repr d1) let add_dirpath_prefix id d = DirPath.make (DirPath.repr d @ [id]) let add_dirpath_suffix p id = DirPath.make (id :: DirPath.repr p) let parse_dir s = let len = String.length s in let rec decoupe_dirs dirs n = if Int.equal n len && n > 0 then CErrors.user_err Pp.(str @@ s ^ " is an invalid path."); if n >= len then dirs else let pos = try String.index_from s n '.' with Not_found -> len in if Int.equal pos n then CErrors.user_err Pp.(str @@ s ^ " is an invalid path."); let dir = String.sub s n (pos-n) in decoupe_dirs ((Id.of_string dir)::dirs) (pos+1) in decoupe_dirs [] 0 let dirpath_of_string s = let path = match s with | "" -> [] | _ -> parse_dir s in DirPath.make path type full_path = { dirpath : DirPath.t ; basename : Id.t } let dirpath sp = sp.dirpath let basename sp = sp.basename let make_path pa id = { dirpath = pa; basename = id } let repr_path { dirpath = pa; basename = id } = (pa,id) let eq_full_path p1 p2 = Id.equal p1.basename p2.basename && DirPath.equal p1.dirpath p2.dirpath let string_of_path sp = let (sl,id) = repr_path sp in match DirPath.repr sl with | [] -> Id.to_string id | _ -> (DirPath.to_string sl) ^ "." ^ (Id.to_string id) let sp_ord sp1 sp2 = let (p1,id1) = repr_path sp1 and (p2,id2) = repr_path sp2 in let p_bit = DirPath.compare p1 p2 in if Int.equal p_bit 0 then Id.compare id1 id2 else p_bit module SpOrdered = struct type t = full_path let compare = sp_ord end module Spmap = Map.Make(SpOrdered) let path_of_string s = try let dir, id = split_dirpath (dirpath_of_string s) in make_path dir id with | Invalid_argument _ -> invalid_arg "path_of_string" let pr_path sp = Pp.str (string_of_path sp) type qualid_r = full_path type qualid = qualid_r CAst.t let make_qualid ?loc pa id = CAst.make ?loc (make_path pa id) let repr_qualid {CAst.v=qid} = repr_path qid let qualid_eq qid1 qid2 = eq_full_path qid1.CAst.v qid2.CAst.v let is_qualid_suffix_of_full_path CAst.{v={dirpath=dirpath1;basename=basename1}} {dirpath=dirpath2;basename=basename2} = let dir1 = DirPath.repr dirpath1 in let dir2 = DirPath.repr dirpath2 in Id.equal basename1 basename2 && List.prefix_of Id.equal dir1 dir2 let string_of_qualid qid = string_of_path qid.CAst.v let pr_qualid qid = pr_path qid.CAst.v let qualid_of_string ?loc s = CAst.make ?loc @@ path_of_string s let qualid_of_path ?loc sp = CAst.make ?loc sp let qualid_of_ident ?loc id = make_qualid ?loc DirPath.empty id let qualid_of_dirpath ?loc dir = let (l,a) = split_dirpath dir in make_qualid ?loc l a let qualid_of_lident lid = qualid_of_ident ?loc:lid.CAst.loc lid.CAst.v let qualid_is_ident qid = DirPath.is_empty qid.CAst.v.dirpath let qualid_basename qid = qid.CAst.v.basename let qualid_path qid = qid.CAst.v.dirpath let idset_mem_qualid qid s = qualid_is_ident qid && Id.Set.mem (qualid_basename qid) s let coq_string = "Coq" let coq_root = Id.of_string coq_string let default_root_prefix = DirPath.empty
278a39c97b2f627e4b6b88a1c7b8d3b6959bc4887ad156124e748c44b52dfd99
input-output-hk/plutus
ParamName.hs
# LANGUAGE DerivingVia # module PlutusLedgerApi.V1.ParamName ( ParamName (..) , tagWithParamNames ) where import Data.Ix import GHC.Generics import PlutusLedgerApi.Common.ParamName {-| The enumeration of all possible cost model parameter names for this language version. IMPORTANT: The order of appearance of the data constructors here matters. DO NOT REORDER. See Note [Quotation marks in cost model parameter constructors] See Note [Cost model parameters from the ledger's point of view] -} data ParamName = AddInteger'cpu'arguments'intercept | AddInteger'cpu'arguments'slope | AddInteger'memory'arguments'intercept | AddInteger'memory'arguments'slope | AppendByteString'cpu'arguments'intercept | AppendByteString'cpu'arguments'slope | AppendByteString'memory'arguments'intercept | AppendByteString'memory'arguments'slope | AppendString'cpu'arguments'intercept | AppendString'cpu'arguments'slope | AppendString'memory'arguments'intercept | AppendString'memory'arguments'slope | BData'cpu'arguments | BData'memory'arguments | Blake2b_256'cpu'arguments'intercept | Blake2b_256'cpu'arguments'slope | Blake2b_256'memory'arguments | CekApplyCost'exBudgetCPU | CekApplyCost'exBudgetMemory | CekBuiltinCost'exBudgetCPU | CekBuiltinCost'exBudgetMemory | CekConstCost'exBudgetCPU | CekConstCost'exBudgetMemory | CekDelayCost'exBudgetCPU | CekDelayCost'exBudgetMemory | CekForceCost'exBudgetCPU | CekForceCost'exBudgetMemory | CekLamCost'exBudgetCPU | CekLamCost'exBudgetMemory | CekStartupCost'exBudgetCPU | CekStartupCost'exBudgetMemory | CekVarCost'exBudgetCPU | CekVarCost'exBudgetMemory | ChooseData'cpu'arguments | ChooseData'memory'arguments | ChooseList'cpu'arguments | ChooseList'memory'arguments | ChooseUnit'cpu'arguments | ChooseUnit'memory'arguments | ConsByteString'cpu'arguments'intercept | ConsByteString'cpu'arguments'slope | ConsByteString'memory'arguments'intercept | ConsByteString'memory'arguments'slope | ConstrData'cpu'arguments | ConstrData'memory'arguments | DecodeUtf8'cpu'arguments'intercept | DecodeUtf8'cpu'arguments'slope | DecodeUtf8'memory'arguments'intercept | DecodeUtf8'memory'arguments'slope | DivideInteger'cpu'arguments'constant | DivideInteger'cpu'arguments'model'arguments'intercept | DivideInteger'cpu'arguments'model'arguments'slope | DivideInteger'memory'arguments'intercept | DivideInteger'memory'arguments'minimum | DivideInteger'memory'arguments'slope | EncodeUtf8'cpu'arguments'intercept | EncodeUtf8'cpu'arguments'slope | EncodeUtf8'memory'arguments'intercept | EncodeUtf8'memory'arguments'slope | EqualsByteString'cpu'arguments'constant | EqualsByteString'cpu'arguments'intercept | EqualsByteString'cpu'arguments'slope | EqualsByteString'memory'arguments | EqualsData'cpu'arguments'intercept | EqualsData'cpu'arguments'slope | EqualsData'memory'arguments | EqualsInteger'cpu'arguments'intercept | EqualsInteger'cpu'arguments'slope | EqualsInteger'memory'arguments | EqualsString'cpu'arguments'constant | EqualsString'cpu'arguments'intercept | EqualsString'cpu'arguments'slope | EqualsString'memory'arguments | FstPair'cpu'arguments | FstPair'memory'arguments | HeadList'cpu'arguments | HeadList'memory'arguments | IData'cpu'arguments | IData'memory'arguments | IfThenElse'cpu'arguments | IfThenElse'memory'arguments | IndexByteString'cpu'arguments | IndexByteString'memory'arguments | LengthOfByteString'cpu'arguments | LengthOfByteString'memory'arguments | LessThanByteString'cpu'arguments'intercept | LessThanByteString'cpu'arguments'slope | LessThanByteString'memory'arguments | LessThanEqualsByteString'cpu'arguments'intercept | LessThanEqualsByteString'cpu'arguments'slope | LessThanEqualsByteString'memory'arguments | LessThanEqualsInteger'cpu'arguments'intercept | LessThanEqualsInteger'cpu'arguments'slope | LessThanEqualsInteger'memory'arguments | LessThanInteger'cpu'arguments'intercept | LessThanInteger'cpu'arguments'slope | LessThanInteger'memory'arguments | ListData'cpu'arguments | ListData'memory'arguments | MapData'cpu'arguments | MapData'memory'arguments | MkCons'cpu'arguments | MkCons'memory'arguments | MkNilData'cpu'arguments | MkNilData'memory'arguments | MkNilPairData'cpu'arguments | MkNilPairData'memory'arguments | MkPairData'cpu'arguments | MkPairData'memory'arguments | ModInteger'cpu'arguments'constant | ModInteger'cpu'arguments'model'arguments'intercept | ModInteger'cpu'arguments'model'arguments'slope | ModInteger'memory'arguments'intercept | ModInteger'memory'arguments'minimum | ModInteger'memory'arguments'slope | MultiplyInteger'cpu'arguments'intercept | MultiplyInteger'cpu'arguments'slope | MultiplyInteger'memory'arguments'intercept | MultiplyInteger'memory'arguments'slope | NullList'cpu'arguments | NullList'memory'arguments | QuotientInteger'cpu'arguments'constant | QuotientInteger'cpu'arguments'model'arguments'intercept | QuotientInteger'cpu'arguments'model'arguments'slope | QuotientInteger'memory'arguments'intercept | QuotientInteger'memory'arguments'minimum | QuotientInteger'memory'arguments'slope | RemainderInteger'cpu'arguments'constant | RemainderInteger'cpu'arguments'model'arguments'intercept | RemainderInteger'cpu'arguments'model'arguments'slope | RemainderInteger'memory'arguments'intercept | RemainderInteger'memory'arguments'minimum | RemainderInteger'memory'arguments'slope | Sha2_256'cpu'arguments'intercept | Sha2_256'cpu'arguments'slope | Sha2_256'memory'arguments | Sha3_256'cpu'arguments'intercept | Sha3_256'cpu'arguments'slope | Sha3_256'memory'arguments | SliceByteString'cpu'arguments'intercept | SliceByteString'cpu'arguments'slope | SliceByteString'memory'arguments'intercept | SliceByteString'memory'arguments'slope | SndPair'cpu'arguments | SndPair'memory'arguments | SubtractInteger'cpu'arguments'intercept | SubtractInteger'cpu'arguments'slope | SubtractInteger'memory'arguments'intercept | SubtractInteger'memory'arguments'slope | TailList'cpu'arguments | TailList'memory'arguments | Trace'cpu'arguments | Trace'memory'arguments | UnBData'cpu'arguments | UnBData'memory'arguments | UnConstrData'cpu'arguments | UnConstrData'memory'arguments | UnIData'cpu'arguments | UnIData'memory'arguments | UnListData'cpu'arguments | UnListData'memory'arguments | UnMapData'cpu'arguments | UnMapData'memory'arguments | VerifyEd25519Signature'cpu'arguments'intercept | VerifyEd25519Signature'cpu'arguments'slope | VerifyEd25519Signature'memory'arguments deriving stock (Eq, Ord, Enum, Ix, Bounded, Generic) deriving IsParamName via (GenericParamName ParamName)
null
https://raw.githubusercontent.com/input-output-hk/plutus/c3918d6027a9a34b6f72a6e4c7bf2e5350e6467e/plutus-ledger-api/src/PlutusLedgerApi/V1/ParamName.hs
haskell
| The enumeration of all possible cost model parameter names for this language version. IMPORTANT: The order of appearance of the data constructors here matters. DO NOT REORDER. See Note [Quotation marks in cost model parameter constructors] See Note [Cost model parameters from the ledger's point of view]
# LANGUAGE DerivingVia # module PlutusLedgerApi.V1.ParamName ( ParamName (..) , tagWithParamNames ) where import Data.Ix import GHC.Generics import PlutusLedgerApi.Common.ParamName data ParamName = AddInteger'cpu'arguments'intercept | AddInteger'cpu'arguments'slope | AddInteger'memory'arguments'intercept | AddInteger'memory'arguments'slope | AppendByteString'cpu'arguments'intercept | AppendByteString'cpu'arguments'slope | AppendByteString'memory'arguments'intercept | AppendByteString'memory'arguments'slope | AppendString'cpu'arguments'intercept | AppendString'cpu'arguments'slope | AppendString'memory'arguments'intercept | AppendString'memory'arguments'slope | BData'cpu'arguments | BData'memory'arguments | Blake2b_256'cpu'arguments'intercept | Blake2b_256'cpu'arguments'slope | Blake2b_256'memory'arguments | CekApplyCost'exBudgetCPU | CekApplyCost'exBudgetMemory | CekBuiltinCost'exBudgetCPU | CekBuiltinCost'exBudgetMemory | CekConstCost'exBudgetCPU | CekConstCost'exBudgetMemory | CekDelayCost'exBudgetCPU | CekDelayCost'exBudgetMemory | CekForceCost'exBudgetCPU | CekForceCost'exBudgetMemory | CekLamCost'exBudgetCPU | CekLamCost'exBudgetMemory | CekStartupCost'exBudgetCPU | CekStartupCost'exBudgetMemory | CekVarCost'exBudgetCPU | CekVarCost'exBudgetMemory | ChooseData'cpu'arguments | ChooseData'memory'arguments | ChooseList'cpu'arguments | ChooseList'memory'arguments | ChooseUnit'cpu'arguments | ChooseUnit'memory'arguments | ConsByteString'cpu'arguments'intercept | ConsByteString'cpu'arguments'slope | ConsByteString'memory'arguments'intercept | ConsByteString'memory'arguments'slope | ConstrData'cpu'arguments | ConstrData'memory'arguments | DecodeUtf8'cpu'arguments'intercept | DecodeUtf8'cpu'arguments'slope | DecodeUtf8'memory'arguments'intercept | DecodeUtf8'memory'arguments'slope | DivideInteger'cpu'arguments'constant | DivideInteger'cpu'arguments'model'arguments'intercept | DivideInteger'cpu'arguments'model'arguments'slope | DivideInteger'memory'arguments'intercept | DivideInteger'memory'arguments'minimum | DivideInteger'memory'arguments'slope | EncodeUtf8'cpu'arguments'intercept | EncodeUtf8'cpu'arguments'slope | EncodeUtf8'memory'arguments'intercept | EncodeUtf8'memory'arguments'slope | EqualsByteString'cpu'arguments'constant | EqualsByteString'cpu'arguments'intercept | EqualsByteString'cpu'arguments'slope | EqualsByteString'memory'arguments | EqualsData'cpu'arguments'intercept | EqualsData'cpu'arguments'slope | EqualsData'memory'arguments | EqualsInteger'cpu'arguments'intercept | EqualsInteger'cpu'arguments'slope | EqualsInteger'memory'arguments | EqualsString'cpu'arguments'constant | EqualsString'cpu'arguments'intercept | EqualsString'cpu'arguments'slope | EqualsString'memory'arguments | FstPair'cpu'arguments | FstPair'memory'arguments | HeadList'cpu'arguments | HeadList'memory'arguments | IData'cpu'arguments | IData'memory'arguments | IfThenElse'cpu'arguments | IfThenElse'memory'arguments | IndexByteString'cpu'arguments | IndexByteString'memory'arguments | LengthOfByteString'cpu'arguments | LengthOfByteString'memory'arguments | LessThanByteString'cpu'arguments'intercept | LessThanByteString'cpu'arguments'slope | LessThanByteString'memory'arguments | LessThanEqualsByteString'cpu'arguments'intercept | LessThanEqualsByteString'cpu'arguments'slope | LessThanEqualsByteString'memory'arguments | LessThanEqualsInteger'cpu'arguments'intercept | LessThanEqualsInteger'cpu'arguments'slope | LessThanEqualsInteger'memory'arguments | LessThanInteger'cpu'arguments'intercept | LessThanInteger'cpu'arguments'slope | LessThanInteger'memory'arguments | ListData'cpu'arguments | ListData'memory'arguments | MapData'cpu'arguments | MapData'memory'arguments | MkCons'cpu'arguments | MkCons'memory'arguments | MkNilData'cpu'arguments | MkNilData'memory'arguments | MkNilPairData'cpu'arguments | MkNilPairData'memory'arguments | MkPairData'cpu'arguments | MkPairData'memory'arguments | ModInteger'cpu'arguments'constant | ModInteger'cpu'arguments'model'arguments'intercept | ModInteger'cpu'arguments'model'arguments'slope | ModInteger'memory'arguments'intercept | ModInteger'memory'arguments'minimum | ModInteger'memory'arguments'slope | MultiplyInteger'cpu'arguments'intercept | MultiplyInteger'cpu'arguments'slope | MultiplyInteger'memory'arguments'intercept | MultiplyInteger'memory'arguments'slope | NullList'cpu'arguments | NullList'memory'arguments | QuotientInteger'cpu'arguments'constant | QuotientInteger'cpu'arguments'model'arguments'intercept | QuotientInteger'cpu'arguments'model'arguments'slope | QuotientInteger'memory'arguments'intercept | QuotientInteger'memory'arguments'minimum | QuotientInteger'memory'arguments'slope | RemainderInteger'cpu'arguments'constant | RemainderInteger'cpu'arguments'model'arguments'intercept | RemainderInteger'cpu'arguments'model'arguments'slope | RemainderInteger'memory'arguments'intercept | RemainderInteger'memory'arguments'minimum | RemainderInteger'memory'arguments'slope | Sha2_256'cpu'arguments'intercept | Sha2_256'cpu'arguments'slope | Sha2_256'memory'arguments | Sha3_256'cpu'arguments'intercept | Sha3_256'cpu'arguments'slope | Sha3_256'memory'arguments | SliceByteString'cpu'arguments'intercept | SliceByteString'cpu'arguments'slope | SliceByteString'memory'arguments'intercept | SliceByteString'memory'arguments'slope | SndPair'cpu'arguments | SndPair'memory'arguments | SubtractInteger'cpu'arguments'intercept | SubtractInteger'cpu'arguments'slope | SubtractInteger'memory'arguments'intercept | SubtractInteger'memory'arguments'slope | TailList'cpu'arguments | TailList'memory'arguments | Trace'cpu'arguments | Trace'memory'arguments | UnBData'cpu'arguments | UnBData'memory'arguments | UnConstrData'cpu'arguments | UnConstrData'memory'arguments | UnIData'cpu'arguments | UnIData'memory'arguments | UnListData'cpu'arguments | UnListData'memory'arguments | UnMapData'cpu'arguments | UnMapData'memory'arguments | VerifyEd25519Signature'cpu'arguments'intercept | VerifyEd25519Signature'cpu'arguments'slope | VerifyEd25519Signature'memory'arguments deriving stock (Eq, Ord, Enum, Ix, Bounded, Generic) deriving IsParamName via (GenericParamName ParamName)
5e36abe4a1564bcd0ed3ef89ee714a1a8ca07457278a702a04ec9fcfdde4c0f8
abdulapopoola/SICPBook
4.43.scm
#lang racket (define (father) (let ((Mary (amb 'Downing 'Hall 'Hood 'Parker 'Moore)) (Gabrielle (amb 'Downing 'Hall 'Hood 'Parker 'Moore)) (Lorna (amb 'Downing 'Hall 'Hood 'Parker 'Moore)) (Rosalind (amb 'Downing 'Hall 'Hood 'Parker 'Moore)) (Melissa (amb 'Downing 'Hall 'Hood 'Parker 'Moore))) (require (= Mary 'Moore)) (require (and (not (= Gabrielle 'Moore)) (not (= Gabrielle 'Hood))) (require (not (= Lorna 'Moore))) (require (not (= Rosalind 'Hall))) (require (= Melissa 'Hood)) (list (list 'Mary Mary) (list 'Gabrielle Gabrielle) (list 'Lorna Lorna) (list 'Rosalind Rosalind) (list 'Melissa Melissa)))) ;
null
https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%204/4.3/4.43.scm
scheme
#lang racket (define (father) (let ((Mary (amb 'Downing 'Hall 'Hood 'Parker 'Moore)) (Gabrielle (amb 'Downing 'Hall 'Hood 'Parker 'Moore)) (Lorna (amb 'Downing 'Hall 'Hood 'Parker 'Moore)) (Rosalind (amb 'Downing 'Hall 'Hood 'Parker 'Moore)) (Melissa (amb 'Downing 'Hall 'Hood 'Parker 'Moore))) (require (= Mary 'Moore)) (require (and (not (= Gabrielle 'Moore)) (not (= Gabrielle 'Hood))) (require (not (= Lorna 'Moore))) (require (not (= Rosalind 'Hall))) (require (= Melissa 'Hood)) (list (list 'Mary Mary) (list 'Gabrielle Gabrielle) (list 'Lorna Lorna) (list 'Rosalind Rosalind) (list 'Melissa Melissa))))
1097631c686f469f249c96772d9c19e20178a20d6efd2dd7292334378bf63b11
informatica-unica/lip
ast.ml
type boolExpr = True | False | Not of boolExpr | And of boolExpr * boolExpr | Or of boolExpr * boolExpr | If of boolExpr * boolExpr * boolExpr | Var of string type boolDecl = (string * boolExpr) list type boolProg = boolDecl * boolExpr
null
https://raw.githubusercontent.com/informatica-unica/lip/f3f0ab2297943957c7dd0534895f2367097043dc/expr/varboolexpr/src/ast.ml
ocaml
type boolExpr = True | False | Not of boolExpr | And of boolExpr * boolExpr | Or of boolExpr * boolExpr | If of boolExpr * boolExpr * boolExpr | Var of string type boolDecl = (string * boolExpr) list type boolProg = boolDecl * boolExpr
53130fcd8b9d050298da998bf477e3f002c13950b40168d1b30d6b9e9d07cba6
solita/mnt-teet
features.clj
(ns teet.gis.features "Utilities to fetch from PostgREST datasource/feature tables." (:require [org.httpkit.client :as http] [cheshire.core :as cheshire] [teet.auth.jwt-token :as jwt-token])) (defn- check-error [resp] (if-let [err (:error resp)] (throw (ex-info "PostGIS API error" {:error err})) resp)) (defn geojson-features-by-id [{:keys [api-url api-secret]} ids] (-> (str api-url "/rpc/geojson_features_by_id") (http/post {:body (cheshire/encode {"ids" (vec ids)}) :headers {"Accept" "text/plain" "Authorization" (str "Bearer " (jwt-token/create-backend-token api-secret))}}) deref check-error :body (cheshire/decode keyword)))
null
https://raw.githubusercontent.com/solita/mnt-teet/4a80d7d9e0d0a3c2d967bc371688d79f027d1d09/app/backend/src/clj/teet/gis/features.clj
clojure
(ns teet.gis.features "Utilities to fetch from PostgREST datasource/feature tables." (:require [org.httpkit.client :as http] [cheshire.core :as cheshire] [teet.auth.jwt-token :as jwt-token])) (defn- check-error [resp] (if-let [err (:error resp)] (throw (ex-info "PostGIS API error" {:error err})) resp)) (defn geojson-features-by-id [{:keys [api-url api-secret]} ids] (-> (str api-url "/rpc/geojson_features_by_id") (http/post {:body (cheshire/encode {"ids" (vec ids)}) :headers {"Accept" "text/plain" "Authorization" (str "Bearer " (jwt-token/create-backend-token api-secret))}}) deref check-error :body (cheshire/decode keyword)))
2c65cbba5d20a8648f9613b2bbe2c999876c72bf77f847ae6280bbaedc83278d
BinaryAnalysisPlatform/bap
arm_helpers.mli
open Core_kernel[@@warning "-D"] val sexpable_of_string : (Sexp.t -> 'a) -> string -> 'a option
null
https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/253afc171bbfd0fe1b34f6442795dbf4b1798348/lib/arm/arm_helpers.mli
ocaml
open Core_kernel[@@warning "-D"] val sexpable_of_string : (Sexp.t -> 'a) -> string -> 'a option
adb15578145cee7776d644ade63c1255cc6b0cfde2fd3bd03c6674c662cc99b7
johnwhitington/haskell-from-the-very-beginning-exercises
Exercises.hs
between :: (Fractional a, Fractional b) => (a, b) -> (a, b) -> (a, b) between (x, y) (x', y') = ((x + x') / 2, (y + y') / 2) roundNum :: (Integral b, RealFrac a) => a -> b roundNum x = if fromIntegral c - x <= x - fromIntegral f then c else f where c = ceiling x f = floor x parts :: RealFrac a => a -> (Integer, a) parts x = if x < 0 then let (a, b) = parts (- x) in (- a, b) else (floor x, x - fromIntegral (floor x)) replicate' :: (Eq a, Num a) => a -> b -> [b] replicate' 0 _ = [] replicate' n x = x : replicate' (n - 1) x makeLine :: (Num a, Eq a) => a -> String makeLine x = replicate' x ' ' ++ ['*', '\n'] star :: RealFrac a => a -> String star x = let i = floor (x * 50) in let i' = if i == 50 then 49 else i in makeLine (if i' == 0 then 0 else i' - 1) plot :: (Ord a, Num a, RealFrac b) => (a -> b) -> a -> a -> a -> String plot f a b dy = if a > b then [] else star (f a) ++ plot f (a + dy) b dy -- example: putStr (plot sin 0 pi (pi / 20))
null
https://raw.githubusercontent.com/johnwhitington/haskell-from-the-very-beginning-exercises/18bda69bf8a0233feb6f023c6a2219b7c20e9fa1/exercises/Chapter12/Exercises.hs
haskell
example: putStr (plot sin 0 pi (pi / 20))
between :: (Fractional a, Fractional b) => (a, b) -> (a, b) -> (a, b) between (x, y) (x', y') = ((x + x') / 2, (y + y') / 2) roundNum :: (Integral b, RealFrac a) => a -> b roundNum x = if fromIntegral c - x <= x - fromIntegral f then c else f where c = ceiling x f = floor x parts :: RealFrac a => a -> (Integer, a) parts x = if x < 0 then let (a, b) = parts (- x) in (- a, b) else (floor x, x - fromIntegral (floor x)) replicate' :: (Eq a, Num a) => a -> b -> [b] replicate' 0 _ = [] replicate' n x = x : replicate' (n - 1) x makeLine :: (Num a, Eq a) => a -> String makeLine x = replicate' x ' ' ++ ['*', '\n'] star :: RealFrac a => a -> String star x = let i = floor (x * 50) in let i' = if i == 50 then 49 else i in makeLine (if i' == 0 then 0 else i' - 1) plot :: (Ord a, Num a, RealFrac b) => (a -> b) -> a -> a -> a -> String plot f a b dy = if a > b then [] else star (f a) ++ plot f (a + dy) b dy