_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
|
---|---|---|---|---|---|---|---|---|
67a0b1651e356f8a56256ae9c0a14789214118a99fc921a7da137155eeacd11a | tsloughter/elna | elna_sup.erl | -module(elna_sup).
-export([start_link/5]).
-export([init/1]).
-include_lib("chatterbox/include/http2.hrl").
-spec start_link(elna:id(), elna:elli_opts(), elna:chatterbox_opts(), elna:listen_opts(), elna:acceptor_opts())
-> {ok, pid()}.
start_link(Id, ElliOpts, ChatterboxOpts, ListenOpts, AcceptorOpts) ->
ElliOpts1 = [{accept_timeout, maps:get(accept_timeout, ElliOpts, 10000)},
{request_timeout, maps:get(request_timeout, ElliOpts, 60000)},
{header_timeout, maps:get(header_timeout, ElliOpts, 10000)},
{body_timeout, maps:get(body_timeout, ElliOpts, 30000)},
{max_body_size, maps:get(max_body_size, ElliOpts, 1024000)}],
ChatterboxOpts1 = #settings{header_table_size=maps:get(header_table_size, ChatterboxOpts, 4096),
enable_push=maps:get(enable_push, ChatterboxOpts, 1),
max_concurrent_streams=maps:get(max_concurrent_streams, ChatterboxOpts, unlimited),
initial_window_size=maps:get(initial_window_size, ChatterboxOpts, 65535),
max_frame_size=maps:get(max_frame_size, ChatterboxOpts, 16384),
max_header_list_size=maps:get(max_header_list_size, ChatterboxOpts, unlimited)},
supervisor:start_link(?MODULE, [Id, ElliOpts1, ChatterboxOpts1, ListenOpts, AcceptorOpts]).
init([Id, ElliOpts, ChatterboxOpts, ListenOpts, AcceptorOpts]) ->
RestartStrategy = #{strategy => rest_for_one},
Pool = #{id => {elna_pool, Id},
start => {elna_pool, start_link, [Id, ElliOpts, ChatterboxOpts, ListenOpts]}},
Socket = #{id => {elna_socket, Id},
start => {elna_socket, start_link, [Id, ListenOpts, AcceptorOpts]}},
{ok, {RestartStrategy, [Pool, Socket]}}.
| null | https://raw.githubusercontent.com/tsloughter/elna/a444fdbd6d44c82eb61473e0d95c122b89a4e057/src/elna_sup.erl | erlang | -module(elna_sup).
-export([start_link/5]).
-export([init/1]).
-include_lib("chatterbox/include/http2.hrl").
-spec start_link(elna:id(), elna:elli_opts(), elna:chatterbox_opts(), elna:listen_opts(), elna:acceptor_opts())
-> {ok, pid()}.
start_link(Id, ElliOpts, ChatterboxOpts, ListenOpts, AcceptorOpts) ->
ElliOpts1 = [{accept_timeout, maps:get(accept_timeout, ElliOpts, 10000)},
{request_timeout, maps:get(request_timeout, ElliOpts, 60000)},
{header_timeout, maps:get(header_timeout, ElliOpts, 10000)},
{body_timeout, maps:get(body_timeout, ElliOpts, 30000)},
{max_body_size, maps:get(max_body_size, ElliOpts, 1024000)}],
ChatterboxOpts1 = #settings{header_table_size=maps:get(header_table_size, ChatterboxOpts, 4096),
enable_push=maps:get(enable_push, ChatterboxOpts, 1),
max_concurrent_streams=maps:get(max_concurrent_streams, ChatterboxOpts, unlimited),
initial_window_size=maps:get(initial_window_size, ChatterboxOpts, 65535),
max_frame_size=maps:get(max_frame_size, ChatterboxOpts, 16384),
max_header_list_size=maps:get(max_header_list_size, ChatterboxOpts, unlimited)},
supervisor:start_link(?MODULE, [Id, ElliOpts1, ChatterboxOpts1, ListenOpts, AcceptorOpts]).
init([Id, ElliOpts, ChatterboxOpts, ListenOpts, AcceptorOpts]) ->
RestartStrategy = #{strategy => rest_for_one},
Pool = #{id => {elna_pool, Id},
start => {elna_pool, start_link, [Id, ElliOpts, ChatterboxOpts, ListenOpts]}},
Socket = #{id => {elna_socket, Id},
start => {elna_socket, start_link, [Id, ListenOpts, AcceptorOpts]}},
{ok, {RestartStrategy, [Pool, Socket]}}.
|
|
5d9bf3b23187eb400dddf650494f9b7e9096a7c741e76cb9ab28c718d5fe58b4 | bobzhang/ocaml-book | priv.ml |
module Int = struct
type t = int
let of_int x = x
let to_int x = x
end
module Priv : sig
type t = private int
val of_int : int -> t
val to_int : t -> int
end = Int
module Abstr : sig
type t
val of_int : int -> t
val to_int : t -> int
end = Int
let _ =
print_int (Priv.of_int 3 :> int)
let _ =
List.iter (print_int)
([Priv.of_int 1; Priv.of_int 3] :> int list)
(** non-container type *)
type 'a f =
|A of (int -> 'a)
|B
(** this is is hard to do when abstract types *)
let a =
((A (fun x -> Priv.of_int x )) :> int f)
| null | https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/code/types/priv.ml | ocaml | * non-container type
* this is is hard to do when abstract types |
module Int = struct
type t = int
let of_int x = x
let to_int x = x
end
module Priv : sig
type t = private int
val of_int : int -> t
val to_int : t -> int
end = Int
module Abstr : sig
type t
val of_int : int -> t
val to_int : t -> int
end = Int
let _ =
print_int (Priv.of_int 3 :> int)
let _ =
List.iter (print_int)
([Priv.of_int 1; Priv.of_int 3] :> int list)
type 'a f =
|A of (int -> 'a)
|B
let a =
((A (fun x -> Priv.of_int x )) :> int f)
|
b2364ad807364cb26a90c208773af5b4e751982f92425351db5eab194346393f | OCamlPro/ez_pgocaml | ezPG_lwt.ml | module PGOCaml = PGOCaml_generic.Make(Thread)
module Pool = struct
let pool = ref (None : PGOCaml.pa_pg_data PGOCaml.t Lwt_pool.t option)
let init ?(n=20) ?host ?port ?user ?password ?database ?unix_domain_socket_dir () =
pool := Some (
Lwt_pool.create n
~check:(fun _conn ok -> ok false)
~validate:PGOCaml.alive
~dispose:PGOCaml.close @@
PGOCaml.connect ?host ?port ?user ?password ?database ?unix_domain_socket_dir)
let use f = match !pool with
| None -> failwith "database pool not initialised"
| Some pool -> Lwt_pool.use pool f
end
| null | https://raw.githubusercontent.com/OCamlPro/ez_pgocaml/e84e6835e6048a27fcdfdc58403ca3a8ce16d744/src/impl/lwt/ezPG_lwt.ml | ocaml | module PGOCaml = PGOCaml_generic.Make(Thread)
module Pool = struct
let pool = ref (None : PGOCaml.pa_pg_data PGOCaml.t Lwt_pool.t option)
let init ?(n=20) ?host ?port ?user ?password ?database ?unix_domain_socket_dir () =
pool := Some (
Lwt_pool.create n
~check:(fun _conn ok -> ok false)
~validate:PGOCaml.alive
~dispose:PGOCaml.close @@
PGOCaml.connect ?host ?port ?user ?password ?database ?unix_domain_socket_dir)
let use f = match !pool with
| None -> failwith "database pool not initialised"
| Some pool -> Lwt_pool.use pool f
end
|
|
ca8d2753b7fbab9ced86abf0289b0db74201db3dd97cc9d762cc7f2a97222659 | NetComposer/nksip | auth_test_client3.erl | %% -------------------------------------------------------------------
%%
%% auth_test: Authentication Tests
%%
Copyright ( c ) 2013 . All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(auth_test_client3).
-include_lib("eunit/include/eunit.hrl").
-include_lib("nksip/include/nksip.hrl").
-include_lib("nkserver/include/nkserver_module.hrl").
-export([sip_get_user_pass/4, sip_authorize/3]).
-export([sip_invite/2, sip_ack/2, sip_bye/2]).
sip_get_user_pass(User, Realm, _Req, _Call) ->
case Realm of
<<"auth_test_client1">> ->
% A hash can be used instead of the plain password
nksip_auth:make_ha1(User, "4321", "auth_test_client1");
<<"auth_test_client2">> ->
"1234";
<<"auth_test_client3">> ->
"abcd";
_ ->
false
end.
% Authorization is only used for "auth" suite
sip_authorize(Auth, _Req, _Call) ->
BinId = nklib_util:to_binary(?MODULE),
case nklib_util:get_value({digest, BinId}, Auth) of
At least one user is authenticated
false -> forbidden; % Failed authentication
undefined -> {authenticate, BinId} % No auth header
end.
sip_invite(Req, _Call) ->
tests_util:save_ref(Req),
{reply, ok}.
sip_ack(Req, _Call) ->
tests_util:send_ref(ack, Req),
ok.
sip_bye(Req, _Call) ->
tests_util:send_ref(bye, Req),
{reply, ok}.
| null | https://raw.githubusercontent.com/NetComposer/nksip/7fbcc66806635dc8ecc5d11c30322e4d1df36f0a/test/callbacks/auth_test_client3.erl | erlang | -------------------------------------------------------------------
auth_test: Authentication Tests
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
A hash can be used instead of the plain password
Authorization is only used for "auth" suite
Failed authentication
No auth header | Copyright ( c ) 2013 . All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(auth_test_client3).
-include_lib("eunit/include/eunit.hrl").
-include_lib("nksip/include/nksip.hrl").
-include_lib("nkserver/include/nkserver_module.hrl").
-export([sip_get_user_pass/4, sip_authorize/3]).
-export([sip_invite/2, sip_ack/2, sip_bye/2]).
sip_get_user_pass(User, Realm, _Req, _Call) ->
case Realm of
<<"auth_test_client1">> ->
nksip_auth:make_ha1(User, "4321", "auth_test_client1");
<<"auth_test_client2">> ->
"1234";
<<"auth_test_client3">> ->
"abcd";
_ ->
false
end.
sip_authorize(Auth, _Req, _Call) ->
BinId = nklib_util:to_binary(?MODULE),
case nklib_util:get_value({digest, BinId}, Auth) of
At least one user is authenticated
end.
sip_invite(Req, _Call) ->
tests_util:save_ref(Req),
{reply, ok}.
sip_ack(Req, _Call) ->
tests_util:send_ref(ack, Req),
ok.
sip_bye(Req, _Call) ->
tests_util:send_ref(bye, Req),
{reply, ok}.
|
f3caae17126aa67410771fcf16494d0ded5cd74418b81b403c2ec6b8c7776013 | potatosalad/erlang-jose | jose_jws_alg.erl | -*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*-
%% vim: ts=4 sw=4 ft=erlang noet
%%%-------------------------------------------------------------------
@author < >
2014 - 2022 ,
%%% @doc
%%%
%%% @end
Created : 29 Jul 2015 by < >
%%%-------------------------------------------------------------------
-module(jose_jws_alg).
-callback generate_key(ALG, Fields) -> JWK
when
ALG :: any(),
Fields :: map(),
JWK :: jose_jwk:key().
-callback sign(Key, Message, ALG) -> Signature
when
Key :: any(),
Message :: iodata(),
ALG :: any(),
Signature :: iodata().
-callback verify(Key, Message, Signature, ALG) -> boolean()
when
Key :: any(),
Message :: iodata(),
Signature :: iodata(),
ALG :: any().
-callback presign(Key, ALG) -> NewALG
when
Key :: any(),
ALG :: any(),
NewALG :: any().
-optional_callbacks([presign/2]).
%% API
-export([generate_key/2]).
%%====================================================================
%% API functions
%%====================================================================
generate_key(Parameters, Algorithm) ->
jose_jwk:merge(jose_jwk:generate_key(Parameters), #{
<<"alg">> => Algorithm,
<<"use">> => <<"sig">>
}).
| null | https://raw.githubusercontent.com/potatosalad/erlang-jose/dbc4074066080692246afe613345ef6becc2a3fe/src/jws/jose_jws_alg.erl | erlang | vim: ts=4 sw=4 ft=erlang noet
-------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
====================================================================
API functions
==================================================================== | -*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*-
@author < >
2014 - 2022 ,
Created : 29 Jul 2015 by < >
-module(jose_jws_alg).
-callback generate_key(ALG, Fields) -> JWK
when
ALG :: any(),
Fields :: map(),
JWK :: jose_jwk:key().
-callback sign(Key, Message, ALG) -> Signature
when
Key :: any(),
Message :: iodata(),
ALG :: any(),
Signature :: iodata().
-callback verify(Key, Message, Signature, ALG) -> boolean()
when
Key :: any(),
Message :: iodata(),
Signature :: iodata(),
ALG :: any().
-callback presign(Key, ALG) -> NewALG
when
Key :: any(),
ALG :: any(),
NewALG :: any().
-optional_callbacks([presign/2]).
-export([generate_key/2]).
generate_key(Parameters, Algorithm) ->
jose_jwk:merge(jose_jwk:generate_key(Parameters), #{
<<"alg">> => Algorithm,
<<"use">> => <<"sig">>
}).
|
db7b79e53abd39b37ae8c5be5736104bf96a28cb4454d0711b29a7d7c5e6bdbb | janestreet/ecaml | buffer_helper.mli | open! Core
open! Import
(** [with_buffer_and_point contents { col; row } ~f] runs [f] in a temp buffer with
[contents] and point at [row] and [col]. *)
val with_buffer_and_point
: (_, 'a) Sync_or_async.t
-> string
-> Line_and_column.t
-> f:(unit -> 'a)
-> 'a
val show_buffer : block_out:Position.t list -> unit
(** Print buffer contents with the point shown as a solid block. *)
val show_point : unit -> unit
module Region : sig
type t =
{ start : Line_and_column.t
; end_ : Line_and_column.t
}
[@@deriving sexp_of]
end
(** [with_buffer_and_active_region contents region ~f] runs [f] in a temp buffer with
[contents], mark at [region.start], and point at [region.end_]. *)
val with_buffer_and_active_region
: (_, 'a) Sync_or_async.t
-> string
-> Region.t
-> f:(unit -> 'a)
-> 'a
(** Print buffer contents with the start and the end of the active region replaced by
solid blocks. *)
val show_active_region : unit -> unit
(** Print buffer contents with the [before-string] and [after-string] properties from any
overlays rendered as though they were present in the buffer. Also, mark any text
specified as [invisible] through overlays (but not through text properties). This
does not reflect the actual contents of the buffer, but rather how the contents would
appear to the user. *)
val show_with_overlay_text : unit -> unit
module Sample_input : sig
(** Both have "next step" columns, but with different bounds. *)
val table1 : string
val table2 : string
end
| null | https://raw.githubusercontent.com/janestreet/ecaml/25a5a2972b3a94f5529a46363b37670a6c1de195/ecaml_test_helpers/src/buffer_helper.mli | ocaml | * [with_buffer_and_point contents { col; row } ~f] runs [f] in a temp buffer with
[contents] and point at [row] and [col].
* Print buffer contents with the point shown as a solid block.
* [with_buffer_and_active_region contents region ~f] runs [f] in a temp buffer with
[contents], mark at [region.start], and point at [region.end_].
* Print buffer contents with the start and the end of the active region replaced by
solid blocks.
* Print buffer contents with the [before-string] and [after-string] properties from any
overlays rendered as though they were present in the buffer. Also, mark any text
specified as [invisible] through overlays (but not through text properties). This
does not reflect the actual contents of the buffer, but rather how the contents would
appear to the user.
* Both have "next step" columns, but with different bounds. | open! Core
open! Import
val with_buffer_and_point
: (_, 'a) Sync_or_async.t
-> string
-> Line_and_column.t
-> f:(unit -> 'a)
-> 'a
val show_buffer : block_out:Position.t list -> unit
val show_point : unit -> unit
module Region : sig
type t =
{ start : Line_and_column.t
; end_ : Line_and_column.t
}
[@@deriving sexp_of]
end
val with_buffer_and_active_region
: (_, 'a) Sync_or_async.t
-> string
-> Region.t
-> f:(unit -> 'a)
-> 'a
val show_active_region : unit -> unit
val show_with_overlay_text : unit -> unit
module Sample_input : sig
val table1 : string
val table2 : string
end
|
3a09e2118ea97d767ffedb9dc34e928891cce07654981210474f7df02a2a379b | rickardlindberg/brainfuck | Brainfuck.hs | module Brainfuck where
import Data.Char (chr, ord)
import Prelude hiding (Left, Right)
import qualified Data.Map as M
class Data d where
emptyData :: d
dataGet :: d -> Int
dataModifyValue :: d -> (Int -> Int) -> d
dataModifyPos :: (Int -> Int) -> d -> d
dataMoveRight :: Data d => d -> d
dataMoveRight = dataModifyPos (+1)
dataMoveLeft :: Data d => d -> d
dataMoveLeft = dataModifyPos (\x -> x - 1)
data DataMap = DataMap
{ currentPos :: Int
, values :: M.Map Int Int
}
emptyDataMap :: DataMap
emptyDataMap = DataMap 0 M.empty
instance Data DataMap where
emptyData = emptyDataMap
dataGet dat = M.findWithDefault 0 (currentPos dat) (values dat)
dataModifyValue dat fn = dat { values = newValues }
where
value = M.findWithDefault 0 (currentPos dat) (values dat)
newValues = M.insert (currentPos dat) (fn value) (values dat)
dataModifyPos fn dat = dat { currentPos = fn (currentPos dat) }
data CachingData = CachingData
{ currentValue :: Maybe Int
, dataMap :: DataMap
}
emptyCachingDataMap :: CachingData
emptyCachingDataMap = CachingData (Just 0) emptyDataMap
instance Data CachingData where
emptyData = emptyCachingDataMap
dataGet (CachingData Nothing dataMap) = dataGet dataMap
dataGet (CachingData (Just x) _) = x
dataModifyValue (CachingData Nothing dataMap) fn = CachingData (Just $ fn $ dataGet dataMap) dataMap
dataModifyValue (CachingData (Just x) dataMap) fn = CachingData (Just $ fn x) dataMap
dataModifyPos fn (CachingData Nothing dataMap) = CachingData Nothing $ dataModifyPos fn dataMap
dataModifyPos fn (CachingData (Just x) dataMap) = CachingData Nothing $ dataModifyPos fn $ dataModifyValue dataMap $ const x
data Instruction
= Inc
| Dec
| Left
| Right
| Print
| Read
| Loop [Instruction]
deriving (Show, Eq)
parse :: String -> [Instruction]
parse input = let ("", instructios) = parseBlock input [] in instructios
parseBlock :: String -> [Instruction] -> (String, [Instruction])
parseBlock [] opTail = ([], opTail)
parseBlock ('[':charsAfterOpening) opTail = (charTail, knot)
where
(charsAfterClosing, loopBody) = parseBlock charsAfterOpening knot
(charTail, restOps) = parseBlock charsAfterClosing opTail
knot = (Loop loopBody):restOps
parseBlock (']':charsAfterClosing) opTail = (charsAfterClosing, opTail)
parseBlock (x:xs) opTail
| x `elem` "+-<>.," = let (a, b) = parseBlock xs opTail in (a, parseSingle x:b)
| otherwise = parseBlock xs opTail
parseSingle :: Char -> Instruction
parseSingle '+' = Inc
parseSingle '-' = Dec
parseSingle '<' = Left
parseSingle '>' = Right
parseSingle '.' = Print
parseSingle ',' = Read
run :: Data d => [Instruction] -> String -> d -> String
run [] input dat = "done!\n"
run (Inc:next) input dat = run next input (dataModifyValue dat (+1))
run (Dec:next) input dat = run next input (dataModifyValue dat (\x -> x - 1))
run (Left:next) input dat = run next input (dataMoveLeft dat)
run (Right:next) input dat = run next input (dataMoveRight dat)
run (Print:next) input dat = chr (dataGet dat) : run next input dat
run (Read:next) [] dat = error "no input"
run (Read:next) (i:is) dat = run next is (dataModifyValue dat (const (ord i)))
run ((Loop xs):next) input dat = if dataGet dat == 0
then run next input dat
else run xs input dat
execute :: String -> IO ()
execute program = interact (\input -> run (parse program) input emptyCachingDataMap)
| null | https://raw.githubusercontent.com/rickardlindberg/brainfuck/fa4940f131adb3682b892f05bb5debef9576b27d/versions/bitetail/Brainfuck.hs | haskell | module Brainfuck where
import Data.Char (chr, ord)
import Prelude hiding (Left, Right)
import qualified Data.Map as M
class Data d where
emptyData :: d
dataGet :: d -> Int
dataModifyValue :: d -> (Int -> Int) -> d
dataModifyPos :: (Int -> Int) -> d -> d
dataMoveRight :: Data d => d -> d
dataMoveRight = dataModifyPos (+1)
dataMoveLeft :: Data d => d -> d
dataMoveLeft = dataModifyPos (\x -> x - 1)
data DataMap = DataMap
{ currentPos :: Int
, values :: M.Map Int Int
}
emptyDataMap :: DataMap
emptyDataMap = DataMap 0 M.empty
instance Data DataMap where
emptyData = emptyDataMap
dataGet dat = M.findWithDefault 0 (currentPos dat) (values dat)
dataModifyValue dat fn = dat { values = newValues }
where
value = M.findWithDefault 0 (currentPos dat) (values dat)
newValues = M.insert (currentPos dat) (fn value) (values dat)
dataModifyPos fn dat = dat { currentPos = fn (currentPos dat) }
data CachingData = CachingData
{ currentValue :: Maybe Int
, dataMap :: DataMap
}
emptyCachingDataMap :: CachingData
emptyCachingDataMap = CachingData (Just 0) emptyDataMap
instance Data CachingData where
emptyData = emptyCachingDataMap
dataGet (CachingData Nothing dataMap) = dataGet dataMap
dataGet (CachingData (Just x) _) = x
dataModifyValue (CachingData Nothing dataMap) fn = CachingData (Just $ fn $ dataGet dataMap) dataMap
dataModifyValue (CachingData (Just x) dataMap) fn = CachingData (Just $ fn x) dataMap
dataModifyPos fn (CachingData Nothing dataMap) = CachingData Nothing $ dataModifyPos fn dataMap
dataModifyPos fn (CachingData (Just x) dataMap) = CachingData Nothing $ dataModifyPos fn $ dataModifyValue dataMap $ const x
data Instruction
= Inc
| Dec
| Left
| Right
| Print
| Read
| Loop [Instruction]
deriving (Show, Eq)
parse :: String -> [Instruction]
parse input = let ("", instructios) = parseBlock input [] in instructios
parseBlock :: String -> [Instruction] -> (String, [Instruction])
parseBlock [] opTail = ([], opTail)
parseBlock ('[':charsAfterOpening) opTail = (charTail, knot)
where
(charsAfterClosing, loopBody) = parseBlock charsAfterOpening knot
(charTail, restOps) = parseBlock charsAfterClosing opTail
knot = (Loop loopBody):restOps
parseBlock (']':charsAfterClosing) opTail = (charsAfterClosing, opTail)
parseBlock (x:xs) opTail
| x `elem` "+-<>.," = let (a, b) = parseBlock xs opTail in (a, parseSingle x:b)
| otherwise = parseBlock xs opTail
parseSingle :: Char -> Instruction
parseSingle '+' = Inc
parseSingle '-' = Dec
parseSingle '<' = Left
parseSingle '>' = Right
parseSingle '.' = Print
parseSingle ',' = Read
run :: Data d => [Instruction] -> String -> d -> String
run [] input dat = "done!\n"
run (Inc:next) input dat = run next input (dataModifyValue dat (+1))
run (Dec:next) input dat = run next input (dataModifyValue dat (\x -> x - 1))
run (Left:next) input dat = run next input (dataMoveLeft dat)
run (Right:next) input dat = run next input (dataMoveRight dat)
run (Print:next) input dat = chr (dataGet dat) : run next input dat
run (Read:next) [] dat = error "no input"
run (Read:next) (i:is) dat = run next is (dataModifyValue dat (const (ord i)))
run ((Loop xs):next) input dat = if dataGet dat == 0
then run next input dat
else run xs input dat
execute :: String -> IO ()
execute program = interact (\input -> run (parse program) input emptyCachingDataMap)
|
|
d7aa81d7f2b61c3f117474e4d6644fdbb916bbcf6fd80450a83309576134a89a | michaelochurch/summer-2015-haskell-class | Builtins.hs | module Lisp.Builtins where
import Control.Lens
import Control.Monad.Trans (liftIO)
import qualified Data.Map as M
import qualified Data.Set as S
import Lisp.Evaluator
import Lisp.Parser
import Lisp.Printer
import Lisp.Reader
import Lisp.Types
dSum :: [Double] -> Double
dSum = sum
plus :: LispFunction
plus = liftFunction dSum Nothing "+"
dMinus :: [Double] -> Double
dMinus [] = 0
dMinus [d1] = -d1
dMinus (d1:ds) = d1 - (sum ds)
minus :: LispFunction
minus = liftFunction dMinus Nothing "-"
dProd :: [Double] -> Double
dProd = product
times :: LispFunction
times = liftFunction dProd Nothing "*"
dDiv :: [Double] -> Double
dDiv [] = 1
dDiv [d1] = 1 / d1
dDiv (d1:ds) = d1 / (product ds)
divide :: LispFunction
divide = liftFunction dDiv Nothing "/"
dCmp :: (Double -> Double -> Bool) -> [Double] -> Bool
dCmp f [d1, d2] = d1 `f` d2
dCmp _ _ = error "arity error in dCmp"
numCmp :: (Double -> Double -> Bool) -> String -> LispValue
numCmp f str = LVFunction $ liftFunction (dCmp f) (Just 2) str
lispNot :: LispFunction
lispNot = LFPrimitive "not" $ \vs ->
case vs of
[(LVBool False)] -> Right $ LVBool True
[_] -> Right $ LVBool False
_ -> Left $ LispError $ LVString "not requires one argument"
eq :: LispValue -> LispValue -> Bool
eq (LVString v1) (LVString v2) = v1 == v2
eq (LVSymbol v1) (LVSymbol v2) = v1 == v2
eq (LVNumber v1) (LVNumber v2) = v1 == v2
eq (LVBool v1) (LVBool v2) = v1 == v2
eq (LVList l1) (LVList l2) =
(length l1 == length l2) && (and $ zipWith eq l1 l2)
eq _ _ = False
lispEq :: LispFunction
lispEq = LFPrimitive "eq" $ \vs ->
case vs of
[v1, v2] -> Right (LVBool $ eq v1 v2)
_ -> Left (LispError $ LVString "eq: requires two arguments")
atom :: LispValue -> Bool
atom (LVSymbol _) = True
atom (LVString _) = True
atom (LVNumber _) = True
atom (LVBool _) = True
atom (LVFunction _) = True
atom (LVList []) = True
atom _ = False
lispAtom :: LispFunction
lispAtom = LFPrimitive "atom" $ \vs ->
case vs of
[v] -> Right $ LVBool $ atom v
_ -> Left $ LispError $ LVString "atom: requires one argument"
lispCar :: LispFunction
lispCar = LFPrimitive "car" $ \vs ->
case vs of
[(LVList (x:_))] -> Right x
_ -> Left $ LispError $ LVString "car: requires a non-empty list"
lispCdr :: LispFunction
lispCdr = LFPrimitive "cdr" $ \vs ->
case vs of
[(LVList (_:xs))] -> Right $ LVList xs
_ -> Left $ LispError $ LVString "cdr: requires a non-empty list"
lispCons :: LispFunction
lispCons = LFPrimitive "cons" $ \vs ->
case vs of
[x, LVList xs] -> Right $ LVList (x:xs)
_ -> Left $ LispError $ LVString "cons: requires 2 args, 2nd must be list"
quit :: LispFunction
quit = LFAction "quit" $ \_ -> error "user quit"
gensym :: LispFunction
gensym = LFAction "gensym" $ \_ -> fmap LVSymbol genStr
setMacroAction :: [LispValue] -> Lisp LispValue
setMacroAction vals =
case vals of
[(LVSymbol name)] -> do
macros . at name .= Just ()
return $ LVBool True
_ -> failWithString "set-macro! requires one symbol"
setMacro :: LispFunction
setMacro = LFAction "set-macro!" $ setMacroAction
macroexpand1Action :: LispFunction
macroexpand1Action = LFAction "macroexpand-1" $ \vs ->
case vs of
[v] -> macroexpand1 v
_ -> failWithString "macroexpand-1 requires 1 value"
macroexpandAction :: LispFunction
macroexpandAction = LFAction "macroexpand" $ \vs ->
case vs of
[v] -> macroexpand v
_ -> failWithString "macroexpand requires 1 value"
macroexpandAllAction :: LispFunction
macroexpandAllAction = LFAction "macroexpand-all" $ \vs ->
case vs of
[v] -> macroexpandAll v
_ -> failWithString "macroexpand-all requires 1 value"
evalAction :: LispFunction
evalAction = LFAction "eval" $ \vs ->
case vs of
[v] -> eval v
_ -> failWithString "eval requires 1 value"
printActionCore :: [LispValue] -> Lisp LispValue
printActionCore vs = do
mapM_ (liftIO . lispPrint) vs
case vs of
[v] -> return v
_ -> return $ LVList vs
printAction :: LispFunction
printAction = LFAction "print" printActionCore
execFile :: String -> Lisp LispValue
execFile filename = do
parsedSExps <- liftIO $ loadSExps filename
case parsedSExps of
Left anError -> failWithString anError
Right sexps -> do
mapM_ (eval . readSExp) sexps
return $ LVBool True
loadFileAction :: LispFunction
loadFileAction = LFAction "load-file" $ \vs ->
case vs of
[(LVString filename)] -> execFile filename
_ -> failWithString "load-file: requires 1 string"
throwLispError :: LispFunction
throwLispError = LFAction "error" $ \vs ->
case vs of
[v] -> lispFail $ LispError v
_ -> lispFail $ LispError $ LVList vs
globalBuiltins :: M.Map String LispValue
globalBuiltins = M.fromList [("+", LVFunction plus),
("-", LVFunction minus),
("*", LVFunction times),
("/", LVFunction divide),
("==", numCmp (==) "=="),
("<=", numCmp (<=) "<="),
(">=", numCmp (>=) ">="),
("/=", numCmp (/=) "/="),
("<" , numCmp (<) "<"),
(">" , numCmp (>) ">"),
("atom", LVFunction lispAtom),
("car", LVFunction lispCar),
("cdr", LVFunction lispCdr),
("cons", LVFunction lispCons),
("eq", LVFunction lispEq),
("error", LVFunction throwLispError),
("eval", LVFunction evalAction),
("gensym", LVFunction gensym),
("load-file", LVFunction loadFileAction),
("macroexpand", LVFunction macroexpandAction),
("macroexpand-1", LVFunction macroexpand1Action),
("macroexpand-all", LVFunction macroexpandAllAction),
("not", LVFunction lispNot),
("pi", LVNumber pi),
("print", LVFunction printAction),
("quit", LVFunction quit),
("set-macro!", LVFunction setMacro)]
initEnv :: LispEnv
initEnv = LispEnv [] globalBuiltins 1 S.empty
withPreludeEnv :: IO LispEnv
withPreludeEnv = fmap snd $ execFile "prelude.lisp" `runLisp` initEnv
| null | https://raw.githubusercontent.com/michaelochurch/summer-2015-haskell-class/2513dc5951604766850255484da37fe480048e0d/Lisp/Builtins.hs | haskell | module Lisp.Builtins where
import Control.Lens
import Control.Monad.Trans (liftIO)
import qualified Data.Map as M
import qualified Data.Set as S
import Lisp.Evaluator
import Lisp.Parser
import Lisp.Printer
import Lisp.Reader
import Lisp.Types
dSum :: [Double] -> Double
dSum = sum
plus :: LispFunction
plus = liftFunction dSum Nothing "+"
dMinus :: [Double] -> Double
dMinus [] = 0
dMinus [d1] = -d1
dMinus (d1:ds) = d1 - (sum ds)
minus :: LispFunction
minus = liftFunction dMinus Nothing "-"
dProd :: [Double] -> Double
dProd = product
times :: LispFunction
times = liftFunction dProd Nothing "*"
dDiv :: [Double] -> Double
dDiv [] = 1
dDiv [d1] = 1 / d1
dDiv (d1:ds) = d1 / (product ds)
divide :: LispFunction
divide = liftFunction dDiv Nothing "/"
dCmp :: (Double -> Double -> Bool) -> [Double] -> Bool
dCmp f [d1, d2] = d1 `f` d2
dCmp _ _ = error "arity error in dCmp"
numCmp :: (Double -> Double -> Bool) -> String -> LispValue
numCmp f str = LVFunction $ liftFunction (dCmp f) (Just 2) str
lispNot :: LispFunction
lispNot = LFPrimitive "not" $ \vs ->
case vs of
[(LVBool False)] -> Right $ LVBool True
[_] -> Right $ LVBool False
_ -> Left $ LispError $ LVString "not requires one argument"
eq :: LispValue -> LispValue -> Bool
eq (LVString v1) (LVString v2) = v1 == v2
eq (LVSymbol v1) (LVSymbol v2) = v1 == v2
eq (LVNumber v1) (LVNumber v2) = v1 == v2
eq (LVBool v1) (LVBool v2) = v1 == v2
eq (LVList l1) (LVList l2) =
(length l1 == length l2) && (and $ zipWith eq l1 l2)
eq _ _ = False
lispEq :: LispFunction
lispEq = LFPrimitive "eq" $ \vs ->
case vs of
[v1, v2] -> Right (LVBool $ eq v1 v2)
_ -> Left (LispError $ LVString "eq: requires two arguments")
atom :: LispValue -> Bool
atom (LVSymbol _) = True
atom (LVString _) = True
atom (LVNumber _) = True
atom (LVBool _) = True
atom (LVFunction _) = True
atom (LVList []) = True
atom _ = False
lispAtom :: LispFunction
lispAtom = LFPrimitive "atom" $ \vs ->
case vs of
[v] -> Right $ LVBool $ atom v
_ -> Left $ LispError $ LVString "atom: requires one argument"
lispCar :: LispFunction
lispCar = LFPrimitive "car" $ \vs ->
case vs of
[(LVList (x:_))] -> Right x
_ -> Left $ LispError $ LVString "car: requires a non-empty list"
lispCdr :: LispFunction
lispCdr = LFPrimitive "cdr" $ \vs ->
case vs of
[(LVList (_:xs))] -> Right $ LVList xs
_ -> Left $ LispError $ LVString "cdr: requires a non-empty list"
lispCons :: LispFunction
lispCons = LFPrimitive "cons" $ \vs ->
case vs of
[x, LVList xs] -> Right $ LVList (x:xs)
_ -> Left $ LispError $ LVString "cons: requires 2 args, 2nd must be list"
quit :: LispFunction
quit = LFAction "quit" $ \_ -> error "user quit"
gensym :: LispFunction
gensym = LFAction "gensym" $ \_ -> fmap LVSymbol genStr
setMacroAction :: [LispValue] -> Lisp LispValue
setMacroAction vals =
case vals of
[(LVSymbol name)] -> do
macros . at name .= Just ()
return $ LVBool True
_ -> failWithString "set-macro! requires one symbol"
setMacro :: LispFunction
setMacro = LFAction "set-macro!" $ setMacroAction
macroexpand1Action :: LispFunction
macroexpand1Action = LFAction "macroexpand-1" $ \vs ->
case vs of
[v] -> macroexpand1 v
_ -> failWithString "macroexpand-1 requires 1 value"
macroexpandAction :: LispFunction
macroexpandAction = LFAction "macroexpand" $ \vs ->
case vs of
[v] -> macroexpand v
_ -> failWithString "macroexpand requires 1 value"
macroexpandAllAction :: LispFunction
macroexpandAllAction = LFAction "macroexpand-all" $ \vs ->
case vs of
[v] -> macroexpandAll v
_ -> failWithString "macroexpand-all requires 1 value"
evalAction :: LispFunction
evalAction = LFAction "eval" $ \vs ->
case vs of
[v] -> eval v
_ -> failWithString "eval requires 1 value"
printActionCore :: [LispValue] -> Lisp LispValue
printActionCore vs = do
mapM_ (liftIO . lispPrint) vs
case vs of
[v] -> return v
_ -> return $ LVList vs
printAction :: LispFunction
printAction = LFAction "print" printActionCore
execFile :: String -> Lisp LispValue
execFile filename = do
parsedSExps <- liftIO $ loadSExps filename
case parsedSExps of
Left anError -> failWithString anError
Right sexps -> do
mapM_ (eval . readSExp) sexps
return $ LVBool True
loadFileAction :: LispFunction
loadFileAction = LFAction "load-file" $ \vs ->
case vs of
[(LVString filename)] -> execFile filename
_ -> failWithString "load-file: requires 1 string"
throwLispError :: LispFunction
throwLispError = LFAction "error" $ \vs ->
case vs of
[v] -> lispFail $ LispError v
_ -> lispFail $ LispError $ LVList vs
globalBuiltins :: M.Map String LispValue
globalBuiltins = M.fromList [("+", LVFunction plus),
("-", LVFunction minus),
("*", LVFunction times),
("/", LVFunction divide),
("==", numCmp (==) "=="),
("<=", numCmp (<=) "<="),
(">=", numCmp (>=) ">="),
("/=", numCmp (/=) "/="),
("<" , numCmp (<) "<"),
(">" , numCmp (>) ">"),
("atom", LVFunction lispAtom),
("car", LVFunction lispCar),
("cdr", LVFunction lispCdr),
("cons", LVFunction lispCons),
("eq", LVFunction lispEq),
("error", LVFunction throwLispError),
("eval", LVFunction evalAction),
("gensym", LVFunction gensym),
("load-file", LVFunction loadFileAction),
("macroexpand", LVFunction macroexpandAction),
("macroexpand-1", LVFunction macroexpand1Action),
("macroexpand-all", LVFunction macroexpandAllAction),
("not", LVFunction lispNot),
("pi", LVNumber pi),
("print", LVFunction printAction),
("quit", LVFunction quit),
("set-macro!", LVFunction setMacro)]
initEnv :: LispEnv
initEnv = LispEnv [] globalBuiltins 1 S.empty
withPreludeEnv :: IO LispEnv
withPreludeEnv = fmap snd $ execFile "prelude.lisp" `runLisp` initEnv
|
|
f1e83887a14f66c0519d200699b374782ac8a53d47f0131577e73e61ea997b52 | input-output-hk/plutus-apps | V1.hs | # LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE NamedFieldPuns #-}
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
# OPTIONS_GHC -Wno - simplifiable - class - constraints #
# OPTIONS_GHC -fno - specialise #
# OPTIONS_GHC -fno - omit - interface - pragmas #
module Ledger.Tx.Constraints.OnChain.V1
( checkScriptContext
, checkOwnInputConstraint
, checkOwnOutputConstraint
) where
import PlutusTx (ToData (toBuiltinData))
import PlutusTx.Prelude (Bool (False, True), Eq ((==)), Functor (fmap), Maybe (Just), all, any, elem, isJust, isNothing,
maybe, snd, traceIfFalse, ($), (&&), (.))
import Ledger qualified
import Ledger.Address (PaymentPubKeyHash (unPaymentPubKeyHash))
import Ledger.Credential (Credential (ScriptCredential))
import Ledger.Tx.Constraints.TxConstraints (ScriptInputConstraint (ScriptInputConstraint, icRedeemer, icReferenceTxOutRef, icTxOutRef),
ScriptOutputConstraint (ScriptOutputConstraint, ocDatum, ocReferenceScriptHash, ocValue),
TxConstraint (MustBeSignedBy, MustIncludeDatumInTx, MustIncludeDatumInTxWithHash, MustMintValue, MustPayToAddress, MustProduceAtLeast, MustReferenceOutput, MustSatisfyAnyOf, MustSpendAtLeast, MustSpendPubKeyOutput, MustSpendScriptOutput, MustUseOutputAsCollateral, MustValidateInTimeRange),
TxConstraintFun (MustSpendScriptOutputWithMatchingDatumAndValue),
TxConstraintFuns (TxConstraintFuns),
TxConstraints (TxConstraints, txConstraintFuns, txConstraints, txOwnInputs, txOwnOutputs),
TxOutDatum (TxOutDatumHash, TxOutDatumInTx))
import Ledger.Tx.Constraints.ValidityInterval (toPlutusInterval)
import Plutus.Script.Utils.V1.Contexts (ScriptContext (ScriptContext, scriptContextTxInfo),
TxInInfo (TxInInfo, txInInfoResolved),
TxInfo (txInfoData, txInfoInputs, txInfoMint, txInfoValidRange),
TxOut (TxOut, txOutAddress, txOutDatumHash))
import Plutus.Script.Utils.V1.Contexts qualified as V
import Plutus.Script.Utils.Value (leq)
import Plutus.Script.Utils.Value qualified as Value
import Plutus.V1.Ledger.Interval (contains)
# INLINABLE checkScriptContext #
-- | Does the 'ScriptContext' satisfy the constraints?
checkScriptContext :: forall i o. (ToData i, ToData o) => TxConstraints i o -> ScriptContext -> Bool
checkScriptContext TxConstraints{txConstraints, txConstraintFuns = TxConstraintFuns txCnsFuns, txOwnInputs, txOwnOutputs} ptx =
" checkScriptContext failed "
$ all (checkTxConstraint ptx) txConstraints
&& all (checkTxConstraintFun ptx) txCnsFuns
&& all (checkOwnInputConstraint ptx) txOwnInputs
&& all (checkOwnOutputConstraint ptx) txOwnOutputs
# INLINABLE checkOwnInputConstraint #
checkOwnInputConstraint
:: ToData i
=> ScriptContext
-> ScriptInputConstraint i
-> Bool
checkOwnInputConstraint ctx ScriptInputConstraint{icTxOutRef, icRedeemer, icReferenceTxOutRef} =
traceIfFalse "L0" -- "Input constraint"
$ checkTxConstraint ctx (MustSpendScriptOutput icTxOutRef (Ledger.Redeemer $ toBuiltinData icRedeemer) icReferenceTxOutRef)
# INLINABLE checkOwnOutputConstraint #
checkOwnOutputConstraint
:: ToData o
=> ScriptContext
-> ScriptOutputConstraint o
-> Bool
checkOwnOutputConstraint ctx ScriptOutputConstraint{ocDatum, ocValue, ocReferenceScriptHash} =
let d = fmap (Ledger.Datum . toBuiltinData) ocDatum
in traceIfFalse "L1" -- "Output constraint"
$ maybe False (\TxInInfo{txInInfoResolved=TxOut{txOutAddress}} ->
checkTxConstraint ctx (MustPayToAddress txOutAddress (Just d) ocReferenceScriptHash ocValue))
(V.findOwnInput ctx)
# INLINABLE checkTxConstraint #
checkTxConstraint :: ScriptContext -> TxConstraint -> Bool
checkTxConstraint ctx@ScriptContext{scriptContextTxInfo} = \case
MustIncludeDatumInTx dv ->
traceIfFalse "L2" -- "Missing datum"
$ dv `elem` fmap snd (txInfoData scriptContextTxInfo)
MustValidateInTimeRange interval ->
traceIfFalse "L3" -- "Wrong validation interval"
$ toPlutusInterval interval `contains` txInfoValidRange scriptContextTxInfo
MustBeSignedBy pkh ->
traceIfFalse "L4" -- "Missing signature"
$ scriptContextTxInfo `V.txSignedBy` unPaymentPubKeyHash pkh
MustSpendAtLeast vl ->
traceIfFalse "L5" -- "Spent value not OK"
$ vl `leq` V.valueSpent scriptContextTxInfo
MustProduceAtLeast vl ->
traceIfFalse "L6" -- "Produced value not OK"
$ vl `leq` V.valueProduced scriptContextTxInfo
MustSpendPubKeyOutput txOutRef ->
traceIfFalse "L7" -- "Public key output not spent"
$ maybe False (isNothing . txOutDatumHash . txInInfoResolved) (V.findTxInByTxOutRef txOutRef scriptContextTxInfo)
MustSpendScriptOutput txOutRef _ _ ->
traceIfFalse "L8" -- "Script output not spent"
Unfortunately we ca n't check the redeemer , because TxInfo only
gives us the redeemer 's hash , but ' MustSpendScriptOutput ' gives
us the full redeemer
$ isJust (V.findTxInByTxOutRef txOutRef scriptContextTxInfo)
MustMintValue mps _ tn v _ ->
traceIfFalse "L9" -- "Value minted not OK"
$ Value.valueOf (txInfoMint scriptContextTxInfo) (Value.mpsSymbol mps) tn == v
MustPayToAddress addr mdv refScript vl ->
let outs = V.txInfoOutputs scriptContextTxInfo
hsh dv = V.findDatumHash dv scriptContextTxInfo
checkOutput (TxOutDatumHash _) TxOut{txOutDatumHash=Just _} =
The datum is not added in the tx body with so we ca n't verify
that the tx output 's datum hash is the correct one w.r.t the
-- provide datum.
True
checkOutput (TxOutDatumInTx dv) TxOut{txOutDatumHash=Just svh} =
hsh dv == Just svh
checkOutput _ _ = False
in
" "
$ vl `leq` V.valuePaidTo scriptContextTxInfo addr
&& maybe True (\dv -> any (checkOutput dv) outs) mdv
&& isNothing refScript
MustIncludeDatumInTxWithHash dvh dv ->
traceIfFalse "Lc" -- "missing datum"
$ V.findDatum dvh scriptContextTxInfo == Just dv
MustSatisfyAnyOf xs ->
traceIfFalse "Ld" -- "MustSatisfyAnyOf"
$ any (all (checkTxConstraint ctx)) xs
MustUseOutputAsCollateral _ ->
TxInfo does not have the collateral inputs
MustReferenceOutput _ ->
" Can not use reference inputs in PlutusV1.ScriptContext "
False
{-# INLINABLE checkTxConstraintFun #-}
checkTxConstraintFun :: ScriptContext -> TxConstraintFun -> Bool
checkTxConstraintFun ScriptContext{scriptContextTxInfo} = \case
MustSpendScriptOutputWithMatchingDatumAndValue vh datumPred valuePred _ ->
let findDatum mdh = do
dh <- mdh
V.findDatum dh scriptContextTxInfo
isMatch (TxOut (Ledger.Address (ScriptCredential vh') _) val (findDatum -> Just d)) =
vh == vh' && valuePred val && datumPred d
isMatch _ = False
in
traceIfFalse "Le" -- "MustSpendScriptOutputWithMatchingDatumAndValue"
$ any (isMatch . txInInfoResolved) (txInfoInputs scriptContextTxInfo)
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/006f4ae4461094d3e9405a445b0c9cf48727fa81/plutus-tx-constraints/src/Ledger/Tx/Constraints/OnChain/V1.hs | haskell | # LANGUAGE MonoLocalBinds #
# LANGUAGE NamedFieldPuns #
# LANGUAGE OverloadedStrings #
# LANGUAGE ViewPatterns #
| Does the 'ScriptContext' satisfy the constraints?
"Input constraint"
"Output constraint"
"Missing datum"
"Wrong validation interval"
"Missing signature"
"Spent value not OK"
"Produced value not OK"
"Public key output not spent"
"Script output not spent"
"Value minted not OK"
provide datum.
"missing datum"
"MustSatisfyAnyOf"
# INLINABLE checkTxConstraintFun #
"MustSpendScriptOutputWithMatchingDatumAndValue" | # LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -Wno - simplifiable - class - constraints #
# OPTIONS_GHC -fno - specialise #
# OPTIONS_GHC -fno - omit - interface - pragmas #
module Ledger.Tx.Constraints.OnChain.V1
( checkScriptContext
, checkOwnInputConstraint
, checkOwnOutputConstraint
) where
import PlutusTx (ToData (toBuiltinData))
import PlutusTx.Prelude (Bool (False, True), Eq ((==)), Functor (fmap), Maybe (Just), all, any, elem, isJust, isNothing,
maybe, snd, traceIfFalse, ($), (&&), (.))
import Ledger qualified
import Ledger.Address (PaymentPubKeyHash (unPaymentPubKeyHash))
import Ledger.Credential (Credential (ScriptCredential))
import Ledger.Tx.Constraints.TxConstraints (ScriptInputConstraint (ScriptInputConstraint, icRedeemer, icReferenceTxOutRef, icTxOutRef),
ScriptOutputConstraint (ScriptOutputConstraint, ocDatum, ocReferenceScriptHash, ocValue),
TxConstraint (MustBeSignedBy, MustIncludeDatumInTx, MustIncludeDatumInTxWithHash, MustMintValue, MustPayToAddress, MustProduceAtLeast, MustReferenceOutput, MustSatisfyAnyOf, MustSpendAtLeast, MustSpendPubKeyOutput, MustSpendScriptOutput, MustUseOutputAsCollateral, MustValidateInTimeRange),
TxConstraintFun (MustSpendScriptOutputWithMatchingDatumAndValue),
TxConstraintFuns (TxConstraintFuns),
TxConstraints (TxConstraints, txConstraintFuns, txConstraints, txOwnInputs, txOwnOutputs),
TxOutDatum (TxOutDatumHash, TxOutDatumInTx))
import Ledger.Tx.Constraints.ValidityInterval (toPlutusInterval)
import Plutus.Script.Utils.V1.Contexts (ScriptContext (ScriptContext, scriptContextTxInfo),
TxInInfo (TxInInfo, txInInfoResolved),
TxInfo (txInfoData, txInfoInputs, txInfoMint, txInfoValidRange),
TxOut (TxOut, txOutAddress, txOutDatumHash))
import Plutus.Script.Utils.V1.Contexts qualified as V
import Plutus.Script.Utils.Value (leq)
import Plutus.Script.Utils.Value qualified as Value
import Plutus.V1.Ledger.Interval (contains)
# INLINABLE checkScriptContext #
checkScriptContext :: forall i o. (ToData i, ToData o) => TxConstraints i o -> ScriptContext -> Bool
checkScriptContext TxConstraints{txConstraints, txConstraintFuns = TxConstraintFuns txCnsFuns, txOwnInputs, txOwnOutputs} ptx =
" checkScriptContext failed "
$ all (checkTxConstraint ptx) txConstraints
&& all (checkTxConstraintFun ptx) txCnsFuns
&& all (checkOwnInputConstraint ptx) txOwnInputs
&& all (checkOwnOutputConstraint ptx) txOwnOutputs
# INLINABLE checkOwnInputConstraint #
checkOwnInputConstraint
:: ToData i
=> ScriptContext
-> ScriptInputConstraint i
-> Bool
checkOwnInputConstraint ctx ScriptInputConstraint{icTxOutRef, icRedeemer, icReferenceTxOutRef} =
$ checkTxConstraint ctx (MustSpendScriptOutput icTxOutRef (Ledger.Redeemer $ toBuiltinData icRedeemer) icReferenceTxOutRef)
# INLINABLE checkOwnOutputConstraint #
checkOwnOutputConstraint
:: ToData o
=> ScriptContext
-> ScriptOutputConstraint o
-> Bool
checkOwnOutputConstraint ctx ScriptOutputConstraint{ocDatum, ocValue, ocReferenceScriptHash} =
let d = fmap (Ledger.Datum . toBuiltinData) ocDatum
$ maybe False (\TxInInfo{txInInfoResolved=TxOut{txOutAddress}} ->
checkTxConstraint ctx (MustPayToAddress txOutAddress (Just d) ocReferenceScriptHash ocValue))
(V.findOwnInput ctx)
# INLINABLE checkTxConstraint #
checkTxConstraint :: ScriptContext -> TxConstraint -> Bool
checkTxConstraint ctx@ScriptContext{scriptContextTxInfo} = \case
MustIncludeDatumInTx dv ->
$ dv `elem` fmap snd (txInfoData scriptContextTxInfo)
MustValidateInTimeRange interval ->
$ toPlutusInterval interval `contains` txInfoValidRange scriptContextTxInfo
MustBeSignedBy pkh ->
$ scriptContextTxInfo `V.txSignedBy` unPaymentPubKeyHash pkh
MustSpendAtLeast vl ->
$ vl `leq` V.valueSpent scriptContextTxInfo
MustProduceAtLeast vl ->
$ vl `leq` V.valueProduced scriptContextTxInfo
MustSpendPubKeyOutput txOutRef ->
$ maybe False (isNothing . txOutDatumHash . txInInfoResolved) (V.findTxInByTxOutRef txOutRef scriptContextTxInfo)
MustSpendScriptOutput txOutRef _ _ ->
Unfortunately we ca n't check the redeemer , because TxInfo only
gives us the redeemer 's hash , but ' MustSpendScriptOutput ' gives
us the full redeemer
$ isJust (V.findTxInByTxOutRef txOutRef scriptContextTxInfo)
MustMintValue mps _ tn v _ ->
$ Value.valueOf (txInfoMint scriptContextTxInfo) (Value.mpsSymbol mps) tn == v
MustPayToAddress addr mdv refScript vl ->
let outs = V.txInfoOutputs scriptContextTxInfo
hsh dv = V.findDatumHash dv scriptContextTxInfo
checkOutput (TxOutDatumHash _) TxOut{txOutDatumHash=Just _} =
The datum is not added in the tx body with so we ca n't verify
that the tx output 's datum hash is the correct one w.r.t the
True
checkOutput (TxOutDatumInTx dv) TxOut{txOutDatumHash=Just svh} =
hsh dv == Just svh
checkOutput _ _ = False
in
" "
$ vl `leq` V.valuePaidTo scriptContextTxInfo addr
&& maybe True (\dv -> any (checkOutput dv) outs) mdv
&& isNothing refScript
MustIncludeDatumInTxWithHash dvh dv ->
$ V.findDatum dvh scriptContextTxInfo == Just dv
MustSatisfyAnyOf xs ->
$ any (all (checkTxConstraint ctx)) xs
MustUseOutputAsCollateral _ ->
TxInfo does not have the collateral inputs
MustReferenceOutput _ ->
" Can not use reference inputs in PlutusV1.ScriptContext "
False
checkTxConstraintFun :: ScriptContext -> TxConstraintFun -> Bool
checkTxConstraintFun ScriptContext{scriptContextTxInfo} = \case
MustSpendScriptOutputWithMatchingDatumAndValue vh datumPred valuePred _ ->
let findDatum mdh = do
dh <- mdh
V.findDatum dh scriptContextTxInfo
isMatch (TxOut (Ledger.Address (ScriptCredential vh') _) val (findDatum -> Just d)) =
vh == vh' && valuePred val && datumPred d
isMatch _ = False
in
$ any (isMatch . txInInfoResolved) (txInfoInputs scriptContextTxInfo)
|
2421b6a5da6deed82f9e1bc98fe4e223ae9638480265152a0ef629f2168ad0b6 | tekul/jose-jwt | JweSpec.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -fno - warn - missing - signatures -fno - warn - orphans #
module Tests.JweSpec where
import Data.Aeson (decodeStrict')
import Data.Bits (xor)
import Data.Word (Word8, Word64)
import qualified Data.ByteArray as BA
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import Test.Hspec
import Test.HUnit hiding (Test)
import Test.QuickCheck
import qualified Crypto.PubKey.RSA as RSA
import Crypto.Hash (SHA1(..), hashDigestSize)
import Crypto.PubKey.RSA.Prim (dp)
import Crypto.PubKey.MaskGenFunction
import Crypto.Cipher.Types (AuthTag(..))
import Crypto.Random (DRG(..), withDRG, drgNewTest)
import Jose.Jwt
import qualified Jose.Jwe as Jwe
import Jose.Jwa
import qualified Jose.Jwk as Jwk
import Jose.Internal.Crypto
import Jose.Internal.Parser(Tag(..), IV(..))
import qualified Jose.Internal.Base64 as B64
--------------------------------------------------------------------------------
Appendix Data Tests ( plus quickcheck )
--------------------------------------------------------------------------------
spec :: Spec
spec =
describe "JWE encoding and decoding" $ do
context "when using JWE Appendix 1 data" $ do
let a1Header = defJweHdr {jweAlg = RSA_OAEP, jweEnc = A256GCM}
it "generates the expected IV and CMK from the RNG" $
withDRG (RNG . BA.convert $ BA.append a1cek a1iv)
(generateCmkAndIV A256GCM) @?= ((a1cek, a1iv), RNG "")
it "generates the expected RSA-encrypted content key" $
withDRG (RNG a1oaepSeed)
(rsaEncrypt a1PubKey RSA_OAEP a1cek) @?= (Right a1jweKey, RNG "")
it "encrypts the payload to the expected ciphertext and authentication tag" $ do
let aad = B64.encode ("{\"alg\":\"RSA-OAEP\",\"enc\":\"A256GCM\"}" :: B.ByteString)
encryptPayload A256GCM a1cek a1iv aad a1Payload @?= Just (AuthTag a1Tag, a1Ciphertext)
it "encodes the payload to the expected JWT, leaving the RNG empty" $
withDRG (RNG $ BA.concat [a1cek, a1iv, BA.convert a1oaepSeed])
(Jwe.rsaEncode RSA_OAEP A256GCM a1PubKey a1Payload) @?= (Right (Jwt a1), RNG "")
it "decodes the JWT to the expected header and payload" $
withBlinder (Jwe.rsaDecode a1PrivKey a1) @?= Right (a1Header, a1Payload)
it "decodes the JWK to the correct RSA key values" $ do
let Just (Jwk.RsaPrivateJwk (RSA.PrivateKey pubKey d 0 0 0 0 0) _ _ _) = decodeStrict' a1jwk
RSA.public_n pubKey @?= a1RsaModulus
RSA.public_e pubKey @?= rsaExponent
d @?= a1RsaPrivateExponent
it "decodes the JWT using the JWK" $ do
let Just k1 = decodeStrict' a1jwk
Just k2 = decodeStrict' a2jwk
withBlinder (decode [k2, k1] (Just $ JweEncoding RSA_OAEP A256GCM) a1) @?= Right (Jwe (a1Header, a1Payload))
it "a truncated CEK returns BadCrypto" $ do
let [hdr, _, iv, payload, tag] = BC.split '.' a1
newEk = encryptCek a1PubKey RSA_OAEP (BA.drop 1 a1cek)
withBlinder (Jwe.rsaDecode a1PrivKey (B.intercalate "." [hdr, B64.encode newEk, iv, payload, tag])) @?= Left BadCrypto
it "a truncated payload returns BadCrypto" $ do
let [hdr, ek, iv, payload, tag] = BC.split '.' a1
Right ct = B64.decode payload
withBlinder (Jwe.rsaDecode a1PrivKey (B.intercalate "." [hdr, ek, iv, B64.encode (B.tail ct), tag])) @?= Left BadCrypto
it "a truncated auth tag returns BadCrypto" $ do
let [hdr, ek, iv, payload, tag] = BC.split '.' a1
Right tagBytes = B64.decode tag
badTag = B64.encode $ BC.take 2 tagBytes
withBlinder (Jwe.rsaDecode a1PrivKey (B.intercalate "." [hdr, ek, iv, payload, badTag])) @?= Left BadCrypto
it "a truncated IV returns BadCrypto" $ do
let (fore, aft) = BC.breakSubstring (B64.encode a1iv) a1
newIv = B64.encode (BA.drop 1 a1iv)
withBlinder (Jwe.rsaDecode a1PrivKey (B.concat [fore, newIv, aft])) @?= Left BadCrypto
context "when using JWE Appendix 2 data" $ do
let a2Header = defJweHdr {jweAlg = RSA1_5, jweEnc = A128CBC_HS256}
let aad = B64.encode ("{\"alg\":\"RSA1_5\",\"enc\":\"A128CBC-HS256\"}" :: B.ByteString)
it "generates the expected RSA-encrypted content key" $
withDRG (RNG a2seed) (rsaEncrypt a2PubKey RSA1_5 a2cek) @?= (Right a2jweKey, RNG "")
it "encrypts the payload to the expected ciphertext and authentication tag" $
encryptPayload A128CBC_HS256 a2cek a2iv aad a2Payload @?= Just (AuthTag (BA.convert a2Tag), a2Ciphertext)
it "encodes the payload to the expected JWT" $
withDRG (RNG $ BA.concat [BA.convert a2cek, a2iv, a2seed])
(Jwe.rsaEncode RSA1_5 A128CBC_HS256 a2PubKey a2Payload) @?= (Right (Jwt a2), RNG "")
it "decrypts the ciphertext to the correct payload" $
decryptPayload A128CBC_HS256 a2cek (IV16 a2iv) aad (Tag16 a2Tag) a2Ciphertext @?= Just a2Payload
it "decodes the JWT to the expected header and payload" $
withBlinder (Jwe.rsaDecode a2PrivKey a2) @?= Right (a2Header, a2Payload)
it "a truncated CEK returns BadCrypto" $ do
let [hdr, _, iv, payload, tag] = BC.split '.' a2
newEk = encryptCek a2PubKey RSA1_5 (BA.drop 1 a2cek)
withBlinder (Jwe.rsaDecode a2PrivKey (B.intercalate "." [hdr, B64.encode newEk, iv, payload, tag])) @?= Left BadCrypto
it "a truncated payload returns BadCrypto" $ do
let [hdr, ek, iv, payload, tag] = BC.split '.' a2
Right ct = B64.decode payload
withBlinder (Jwe.rsaDecode a2PrivKey (B.intercalate "." [hdr, ek, iv, B64.encode (B.tail ct), tag])) @?= Left BadCrypto
it "a truncated IV returns BadCrypto" $ do
let (fore, aft) = BC.breakSubstring (B64.encode a2iv) a2
newIv = B64.encode (B.tail a2iv)
withBlinder (Jwe.rsaDecode a2PrivKey (B.concat [fore, newIv, aft])) @?= Left BadCrypto
context "when using JWE Appendix 3 data" $ do
let Just jwk = decodeStrict' a3jwk
a3Header = defJweHdr {jweAlg = A128KW, jweEnc = A128CBC_HS256}
it "encodes the payload to the expected JWT" $
withDRG (RNG $ B.concat [a3cek, a3iv])
(Jwe.jwkEncode A128KW A128CBC_HS256 jwk (Claims a3Payload)) @?= (Right (Jwt a3), RNG "")
it "decodes the JWT using the JWK" $
withBlinder (decode [jwk] Nothing a3) @?= Right (Jwe (a3Header, a3Payload))
context "when used with quickcheck" $ do
it "padded msg is always a multiple of 16" $ property $
\s -> B.length (pad (B.pack s)) `mod` 16 == 0
it "unpad is the inverse of pad" $ property $
\s -> let msg = B.pack s in (unpad . pad) msg == Just msg
it "jwe decode/decode returns the original payload" $ property jweRoundTrip
context "miscellaneous tests" $ do
it "Padding byte larger than 16 is rejected" $
up "111a" @?= Nothing
it "Padding byte which doesn't match padding length is rejected" $
up "111\t\t\t\t\t\t\t" @?= Nothing
it "Padding byte which matches padding length is OK" $
up "1111111\t\t\t\t\t\t\t\t\t" @?= Just "1111111"
it "Rejects invalid Base64 JWT" $
withBlinder (Jwe.rsaDecode a2PrivKey "=.") @?= Left BadCrypto
up :: BC.ByteString -> Maybe BC.ByteString
up = unpad
verboseQuickCheckWith quickCheckWith stdArgs { maxSuccess=10000 } jweRoundTrip
jweRoundTrip :: RNG -> JWEAlgs -> [Word8] -> Bool
jweRoundTrip g (JWEAlgs a e) msg = encodeDecode == Right (Jwe (defJweHdr {jweAlg = a, jweEnc = e }, bs))
where
jwks = [a1jwk, a2jwk, a3jwk, aes192jwk, aes256jwk] >>= \j -> let Just jwk = decodeStrict' j in [jwk]
bs = B.pack msg
encodeDecode = fst (withDRG blinderRNG (decode jwks Nothing encoded))
Right encoded = unJwt <$> fst (withDRG g (encode jwks (JweEncoding a e) (Claims bs)))
encryptCek kpub a cek =
let
(Right newEk, _) = withDRG blinderRNG $ rsaEncrypt kpub a (BA.drop 1 cek)
in
newEk :: BC.ByteString
withBlinder = fst . withDRG blinderRNG
-- A decidedly non-random, random number generator which allows specific
sequences of bytes to be supplied which match the JWE test data .
newtype RNG = RNG B.ByteString deriving (Eq, Show)
genBytes :: BA.ByteArray ba => Int -> RNG -> (ba, RNG)
genBytes 0 g = (BA.empty, g)
genBytes n (RNG bs) = (BA.convert bytes, RNG next)
where
(bytes, next) = if BA.null bs
then error "RNG is empty"
else BA.splitAt n bs
instance DRG RNG where
randomBytesGenerate = genBytes
blinderRNG = drgNewTest (w, w, w, w, w) where w = 1 :: Word64
--------------------------------------------------------------------------------
JWE Appendix 1 Test Data
--------------------------------------------------------------------------------
a1 :: B.ByteString
a1 = "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ.OKOawDo13gRp2ojaHV7LFpZcgV7T6DVZKTyKOMTYUmKoTCVJRgckCL9kiMT03JGeipsEdY3mx_etLbbWSrFr05kLzcSr4qKAq7YN7e9jwQRb23nfa6c9d-StnImGyFDbSv04uVuxIp5Zms1gNxKKK2Da14B8S4rzVRltdYwam_lDp5XnZAYpQdb76FdIKLaVmqgfwX7XWRxv2322i-vDxRfqNzo_tETKzpVLzfiwQyeyPGLBIO56YJ7eObdv0je81860ppamavo35UgoRdbYaBcoh9QcfylQr66oc6vFWXRcZ_ZT2LawVCWTIy3brGPi6UklfCpIMfIjf7iGdXKHzg.48V1_ALb6US04U3b.5eym8TW_c8SuK0ltJ3rpYIzOeDQz7TALvtu6UG9oMo4vpzs9tX_EFShS8iB7j6jiSdiwkIr3ajwQzaBtQD_A.XFBoMYUZodetZdvTiFvSkQ"
a1Payload = "The true sign of intelligence is not knowledge but imagination."
a1cek :: BA.ScrubbedBytes
a1cek = BA.pack [177, 161, 244, 128, 84, 143, 225, 115, 63, 180, 3, 255, 107, 154, 212, 246, 138, 7, 110, 91, 112, 46, 34, 105, 47, 130, 203, 46, 122, 234, 64, 252]
a1iv :: BA.ScrubbedBytes
a1iv = BA.pack [227, 197, 117, 252, 2, 219, 233, 68, 180, 225, 77, 219]
a1aad = B.pack [101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 48, 69, 116, 84, 48, 70, 70, 85, 67, 73, 115, 73, 109, 86, 117, 89, 121, 73, 54, 73, 107, 69, 121, 78, 84, 90, 72, 81, 48, 48, 105, 102, 81]
a1Ciphertext = B.pack [229, 236, 166, 241, 53, 191, 115, 196, 174, 43, 73, 109, 39, 122, 233, 96, 140, 206, 120, 52, 51, 237, 48, 11, 190, 219, 186, 80, 111, 104, 50, 142, 47, 167, 59, 61, 181, 127, 196, 21, 40, 82, 242, 32, 123, 143, 168, 226, 73, 216, 176, 144, 138, 247, 106, 60, 16, 205, 160, 109, 64, 63, 192]
a1Tag = BA.pack [92, 80, 104, 49, 133, 25, 161, 215, 173, 101, 219, 211, 136, 91, 210, 145]
Right a1jweKey = B64.decode $ BC.pack "OKOawDo13gRp2ojaHV7LFpZcgV7T6DVZKTyKOMTYUmKoTCVJRgckCL9kiMT03JGeipsEdY3mx_etLbbWSrFr05kLzcSr4qKAq7YN7e9jwQRb23nfa6c9d-StnImGyFDbSv04uVuxIp5Zms1gNxKKK2Da14B8S4rzVRltdYwam_lDp5XnZAYpQdb76FdIKLaVmqgfwX7XWRxv2322i-vDxRfqNzo_tETKzpVLzfiwQyeyPGLBIO56YJ7eObdv0je81860ppamavo35UgoRdbYaBcoh9QcfylQr66oc6vFWXRcZ_ZT2LawVCWTIy3brGPi6UklfCpIMfIjf7iGdXKHzg"
a1jwk = "{\"kty\":\"RSA\", \"n\":\"oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUWcJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3Spsk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2asbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMStPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2djYgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw\", \"e\":\"AQAB\", \"d\":\"kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5NWV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD93Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghkqDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vlt3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSndVTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ\" }"
a1RsaModulus = 20407373051396142380600281265251892119308905183562582378265551916401741797298132714477564366125574073854325621181754666299468042787718090965019045494120492365709229334674806858420600185271825023335981142192553851711447185679749878133484409202142610505370119489349112667599681596271324052456163162582257897587607185901342235063647947816589525124013368466111231306949063172170503467209564034546753006291531308789606255762727496010190006847721118463557533668762287451483156476421856126198680670740028037673487624895510756370816101325723975021588898704953504010419555312457504338174094966173304768490140232017447246019099
rsaExponent = 65537 :: Integer
a1RsaPrivateExponent = 18268766796654718362565236454995853620820821188251417451980738596264305499270399136757621249007756005599271096771478165267306874014871487538744562309757162619646837295513011635819128008143685281506609665247035139326775637222412463191989209202137797209813686014322033219332678022668756745556718137625135245640638710814390273901357613670762406363679831247433360271391936119294533419667412739496199381069233394069901435128732415071218792819358792459421008659625326677236263304891550388749907992141902573512326268421915766834378108391128385175130554819679860804655689526143903449732010240859012168194104458903308465660105
a1oaepSeed = extractOaepSeed a1PrivKey a1jweKey
(a1PubKey, a1PrivKey) = createKeyPair a1RsaModulus a1RsaPrivateExponent
--------------------------------------------------------------------------------
JWE Appendix 2 Test Data
--------------------------------------------------------------------------------
a2Payload = "Live long and prosper."
a2cek :: BA.ScrubbedBytes
a2cek = BA.pack [4, 211, 31, 197, 84, 157, 252, 254, 11, 100, 157, 250, 63, 170, 106, 206, 107, 124, 212, 45, 111, 107, 9, 219, 200, 177, 0, 240, 143, 156, 44, 207]
a2cek = B.pack [ 203 , 165 , 180 , 113 , 62 , 195 , 22 , 98 , 91 , 153 , 210 , 38 , 112 , 35 , 230 , 236 ]
a2cik = B.pack [ 218 , 24 , 160 , 17 , 160 , 50 , 235 , 35 , 216 , 209 , 100 , 174 , 155 , 163 , 10 , 117 , 180 , 111 , 172 , 200 , 127 , 201 , 206 , 173 , 40 , 45 , 58 , 170 , 35 , 93 , 9 , 60 ]
a2iv = B.pack [3, 22, 60, 12, 43, 67, 104, 105, 108, 108, 105, 99, 111, 116, 104, 101]
a2Ciphertext = B.pack [40, 57, 83, 181, 119, 33, 133, 148, 198, 185, 243, 24, 152, 230, 6, 75, 129, 223, 127, 19, 210, 82, 183, 230, 168, 33, 215, 104, 143, 112, 56, 102]
a2Tag = B.pack [246, 17, 244, 190, 4, 95, 98, 3, 231, 0, 115, 157, 242, 203, 100, 191]
Right a2jweKey = B64.decode $ BC.pack "UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-kFm1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKxGHZ7PcHALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3YvkkysZIFNPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPhcCdZ6XDP0_F8rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv-B3oWh2TbqmScqXMR4gp_A"
a2jwk = "{\"kty\":\"RSA\", \"n\":\"sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw\", \"e\":\"AQAB\", \"d\":\"VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-rynq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-QgajZGPbE_0ZaVDJHfyd7UUBUKunFMScbflYAAOYJqVIVwaYR5zWEEceUjNnTNo_CVSj-VvXLO5VZfCUAVLgW4dpf1SrtZjSt34YLsRarSb127reG_DUwg9Ch-KyvjT1SkHgUWRVGcyly7uvVGRSDwsXypdrNinPA4jlhoNdizK2zF2CWQ\" }"
a2RsaModulus = 22402924734748322419583087865046136971812964522608965289668050862528140628890468829261358173206844190609885548664216273129288787509446229835492005268681636400878070687042995563617837593077316848511917526886594334868053765054121327206058496913599608196082088434862911200952954663261204130886151917541465131565772711448256433529200865576041706962504490609565420543616528240562874975930318078653328569211055310553145904641192292907110395318778917935975962359665382660933281263049927785938817901532807037136641587608303638483543899849101763615990006657357057710971983052920787558713523025279998057051825799400286243909447
a2RsaPrivateExponent = 10643756465292254988457796463889735064030094089452909840615134957452106668931481879498770304395097541282329162591478128330968231330113176654221501869950411410564116254672288216799191435916328405513154035654178369543717138143188973636496077305930253145572851787483810154020967535132278148578697716656066036003388130625459567907864689911133288140117207430454310073863484450086676106606775792171446149215594844607410066899028283290532626577379520547350399030663657813726123700613989625283009134539244470878688076926304079342487789922656366430636978871435674556143884272163840709196449089335092169596187792960067104244313
a2 :: B.ByteString
a2 = "eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-kFm1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKxGHZ7PcHALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3YvkkysZIFNPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPhcCdZ6XDP0_F8rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv-B3oWh2TbqmScqXMR4gp_A.AxY8DCtDaGlsbGljb3RoZQ.KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.9hH0vgRfYgPnAHOd8stkvw"
(a2PubKey, a2PrivKey) = createKeyPair a2RsaModulus a2RsaPrivateExponent
a2seed = extractPKCS15Seed a2PrivKey a2jweKey
a3Payload = a2Payload
a3jwk = "{\"kty\":\"oct\", \"k\":\"GawgguFyGrWKav7AX4VKUg\"}"
-- We need keys that are valid for AES192 and AES256 for quickcheck tests
aes192jwk = "{\"kty\":\"oct\", \"k\":\"FatNm7ez26tyPGsXdaqhYHtvThX0jSAA\"}"
aes256jwk = "{\"kty\":\"oct\", \"k\":\"1MeiHdxK8CQBsmjgOM8SCxg06MTjFzG7sFa7EnDCJzo\"}"
a3cek = B.pack [4, 211, 31, 197, 84, 157, 252, 254, 11, 100, 157, 250, 63, 170, 106, 206, 107, 124, 212, 45, 111, 107, 9, 219, 200, 177, 0, 240, 143, 156, 44, 207]
a3iv = B.pack [3, 22, 60, 12, 43, 67, 104, 105, 108, 108, 105, 99, 111, 116, 104, 101]
a3 :: B.ByteString
a3 = "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ.AxY8DCtDaGlsbGljb3RoZQ.KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.U0m_YmjN04DJvceFICbCVQ"
--------------------------------------------------------------------------------
-- Quickcheck Stuff
--------------------------------------------------------------------------------
-- Valid JWE Alg/Enc combinations
data JWEAlgs = JWEAlgs JweAlg Enc deriving Show
instance Arbitrary Enc where
arbitrary = elements [A128CBC_HS256, A192CBC_HS384, A256CBC_HS512, A128GCM, A192GCM, A256GCM]
instance Arbitrary JWEAlgs where
arbitrary = do
a <- elements [RSA1_5, RSA_OAEP, RSA_OAEP_256, A128KW, A192KW, A256KW]
e <- arbitrary
return $ JWEAlgs a e
instance Arbitrary RNG where
arbitrary = RNG . B.pack <$> vector 600
--------------------------------------------------------------------------------
-- Utility Functions
--------------------------------------------------------------------------------
createKeyPair n d = (pubKey, privKey)
where
privKey = RSA.PrivateKey
{ RSA.private_pub = pubKey
, RSA.private_d = d
, RSA.private_q = 0
, RSA.private_p = 0
, RSA.private_dP = 0
, RSA.private_dQ = 0
, RSA.private_qinv = 0
}
pubKey = RSA.PublicKey
{ RSA.public_size = 256
, RSA.public_n = n
, RSA.public_e = rsaExponent
}
-- Extracts the random padding bytes from the decrypted content key
-- allowing them to be used in the test RNG
extractOaepSeed :: RSA.PrivateKey -> B.ByteString -> B.ByteString
extractOaepSeed key ct = B.pack $ B.zipWith xor maskedSeed seedMask
where
em = dp Nothing key ct
hashLen = hashDigestSize SHA1
em0 = B.tail em
(maskedSeed, maskedDB) = B.splitAt hashLen em0
seedMask = mgf1 SHA1 maskedDB hashLen
-- Decrypt, drop the 02 at the start and take the bytes up to the next 0
extractPKCS15Seed :: RSA.PrivateKey -> B.ByteString -> B.ByteString
extractPKCS15Seed key ct = B.takeWhile (/= 0) . B.drop 2 $ dp Nothing key ct
| null | https://raw.githubusercontent.com/tekul/jose-jwt/1ac2335d4feda47da21075f39b8c8805a51583f0/tests/Tests/JweSpec.hs | haskell | # LANGUAGE OverloadedStrings #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
A decidedly non-random, random number generator which allows specific
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
We need keys that are valid for AES192 and AES256 for quickcheck tests
------------------------------------------------------------------------------
Quickcheck Stuff
------------------------------------------------------------------------------
Valid JWE Alg/Enc combinations
------------------------------------------------------------------------------
Utility Functions
------------------------------------------------------------------------------
Extracts the random padding bytes from the decrypted content key
allowing them to be used in the test RNG
Decrypt, drop the 02 at the start and take the bytes up to the next 0 | # LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -fno - warn - missing - signatures -fno - warn - orphans #
module Tests.JweSpec where
import Data.Aeson (decodeStrict')
import Data.Bits (xor)
import Data.Word (Word8, Word64)
import qualified Data.ByteArray as BA
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import Test.Hspec
import Test.HUnit hiding (Test)
import Test.QuickCheck
import qualified Crypto.PubKey.RSA as RSA
import Crypto.Hash (SHA1(..), hashDigestSize)
import Crypto.PubKey.RSA.Prim (dp)
import Crypto.PubKey.MaskGenFunction
import Crypto.Cipher.Types (AuthTag(..))
import Crypto.Random (DRG(..), withDRG, drgNewTest)
import Jose.Jwt
import qualified Jose.Jwe as Jwe
import Jose.Jwa
import qualified Jose.Jwk as Jwk
import Jose.Internal.Crypto
import Jose.Internal.Parser(Tag(..), IV(..))
import qualified Jose.Internal.Base64 as B64
Appendix Data Tests ( plus quickcheck )
spec :: Spec
spec =
describe "JWE encoding and decoding" $ do
context "when using JWE Appendix 1 data" $ do
let a1Header = defJweHdr {jweAlg = RSA_OAEP, jweEnc = A256GCM}
it "generates the expected IV and CMK from the RNG" $
withDRG (RNG . BA.convert $ BA.append a1cek a1iv)
(generateCmkAndIV A256GCM) @?= ((a1cek, a1iv), RNG "")
it "generates the expected RSA-encrypted content key" $
withDRG (RNG a1oaepSeed)
(rsaEncrypt a1PubKey RSA_OAEP a1cek) @?= (Right a1jweKey, RNG "")
it "encrypts the payload to the expected ciphertext and authentication tag" $ do
let aad = B64.encode ("{\"alg\":\"RSA-OAEP\",\"enc\":\"A256GCM\"}" :: B.ByteString)
encryptPayload A256GCM a1cek a1iv aad a1Payload @?= Just (AuthTag a1Tag, a1Ciphertext)
it "encodes the payload to the expected JWT, leaving the RNG empty" $
withDRG (RNG $ BA.concat [a1cek, a1iv, BA.convert a1oaepSeed])
(Jwe.rsaEncode RSA_OAEP A256GCM a1PubKey a1Payload) @?= (Right (Jwt a1), RNG "")
it "decodes the JWT to the expected header and payload" $
withBlinder (Jwe.rsaDecode a1PrivKey a1) @?= Right (a1Header, a1Payload)
it "decodes the JWK to the correct RSA key values" $ do
let Just (Jwk.RsaPrivateJwk (RSA.PrivateKey pubKey d 0 0 0 0 0) _ _ _) = decodeStrict' a1jwk
RSA.public_n pubKey @?= a1RsaModulus
RSA.public_e pubKey @?= rsaExponent
d @?= a1RsaPrivateExponent
it "decodes the JWT using the JWK" $ do
let Just k1 = decodeStrict' a1jwk
Just k2 = decodeStrict' a2jwk
withBlinder (decode [k2, k1] (Just $ JweEncoding RSA_OAEP A256GCM) a1) @?= Right (Jwe (a1Header, a1Payload))
it "a truncated CEK returns BadCrypto" $ do
let [hdr, _, iv, payload, tag] = BC.split '.' a1
newEk = encryptCek a1PubKey RSA_OAEP (BA.drop 1 a1cek)
withBlinder (Jwe.rsaDecode a1PrivKey (B.intercalate "." [hdr, B64.encode newEk, iv, payload, tag])) @?= Left BadCrypto
it "a truncated payload returns BadCrypto" $ do
let [hdr, ek, iv, payload, tag] = BC.split '.' a1
Right ct = B64.decode payload
withBlinder (Jwe.rsaDecode a1PrivKey (B.intercalate "." [hdr, ek, iv, B64.encode (B.tail ct), tag])) @?= Left BadCrypto
it "a truncated auth tag returns BadCrypto" $ do
let [hdr, ek, iv, payload, tag] = BC.split '.' a1
Right tagBytes = B64.decode tag
badTag = B64.encode $ BC.take 2 tagBytes
withBlinder (Jwe.rsaDecode a1PrivKey (B.intercalate "." [hdr, ek, iv, payload, badTag])) @?= Left BadCrypto
it "a truncated IV returns BadCrypto" $ do
let (fore, aft) = BC.breakSubstring (B64.encode a1iv) a1
newIv = B64.encode (BA.drop 1 a1iv)
withBlinder (Jwe.rsaDecode a1PrivKey (B.concat [fore, newIv, aft])) @?= Left BadCrypto
context "when using JWE Appendix 2 data" $ do
let a2Header = defJweHdr {jweAlg = RSA1_5, jweEnc = A128CBC_HS256}
let aad = B64.encode ("{\"alg\":\"RSA1_5\",\"enc\":\"A128CBC-HS256\"}" :: B.ByteString)
it "generates the expected RSA-encrypted content key" $
withDRG (RNG a2seed) (rsaEncrypt a2PubKey RSA1_5 a2cek) @?= (Right a2jweKey, RNG "")
it "encrypts the payload to the expected ciphertext and authentication tag" $
encryptPayload A128CBC_HS256 a2cek a2iv aad a2Payload @?= Just (AuthTag (BA.convert a2Tag), a2Ciphertext)
it "encodes the payload to the expected JWT" $
withDRG (RNG $ BA.concat [BA.convert a2cek, a2iv, a2seed])
(Jwe.rsaEncode RSA1_5 A128CBC_HS256 a2PubKey a2Payload) @?= (Right (Jwt a2), RNG "")
it "decrypts the ciphertext to the correct payload" $
decryptPayload A128CBC_HS256 a2cek (IV16 a2iv) aad (Tag16 a2Tag) a2Ciphertext @?= Just a2Payload
it "decodes the JWT to the expected header and payload" $
withBlinder (Jwe.rsaDecode a2PrivKey a2) @?= Right (a2Header, a2Payload)
it "a truncated CEK returns BadCrypto" $ do
let [hdr, _, iv, payload, tag] = BC.split '.' a2
newEk = encryptCek a2PubKey RSA1_5 (BA.drop 1 a2cek)
withBlinder (Jwe.rsaDecode a2PrivKey (B.intercalate "." [hdr, B64.encode newEk, iv, payload, tag])) @?= Left BadCrypto
it "a truncated payload returns BadCrypto" $ do
let [hdr, ek, iv, payload, tag] = BC.split '.' a2
Right ct = B64.decode payload
withBlinder (Jwe.rsaDecode a2PrivKey (B.intercalate "." [hdr, ek, iv, B64.encode (B.tail ct), tag])) @?= Left BadCrypto
it "a truncated IV returns BadCrypto" $ do
let (fore, aft) = BC.breakSubstring (B64.encode a2iv) a2
newIv = B64.encode (B.tail a2iv)
withBlinder (Jwe.rsaDecode a2PrivKey (B.concat [fore, newIv, aft])) @?= Left BadCrypto
context "when using JWE Appendix 3 data" $ do
let Just jwk = decodeStrict' a3jwk
a3Header = defJweHdr {jweAlg = A128KW, jweEnc = A128CBC_HS256}
it "encodes the payload to the expected JWT" $
withDRG (RNG $ B.concat [a3cek, a3iv])
(Jwe.jwkEncode A128KW A128CBC_HS256 jwk (Claims a3Payload)) @?= (Right (Jwt a3), RNG "")
it "decodes the JWT using the JWK" $
withBlinder (decode [jwk] Nothing a3) @?= Right (Jwe (a3Header, a3Payload))
context "when used with quickcheck" $ do
it "padded msg is always a multiple of 16" $ property $
\s -> B.length (pad (B.pack s)) `mod` 16 == 0
it "unpad is the inverse of pad" $ property $
\s -> let msg = B.pack s in (unpad . pad) msg == Just msg
it "jwe decode/decode returns the original payload" $ property jweRoundTrip
context "miscellaneous tests" $ do
it "Padding byte larger than 16 is rejected" $
up "111a" @?= Nothing
it "Padding byte which doesn't match padding length is rejected" $
up "111\t\t\t\t\t\t\t" @?= Nothing
it "Padding byte which matches padding length is OK" $
up "1111111\t\t\t\t\t\t\t\t\t" @?= Just "1111111"
it "Rejects invalid Base64 JWT" $
withBlinder (Jwe.rsaDecode a2PrivKey "=.") @?= Left BadCrypto
up :: BC.ByteString -> Maybe BC.ByteString
up = unpad
verboseQuickCheckWith quickCheckWith stdArgs { maxSuccess=10000 } jweRoundTrip
jweRoundTrip :: RNG -> JWEAlgs -> [Word8] -> Bool
jweRoundTrip g (JWEAlgs a e) msg = encodeDecode == Right (Jwe (defJweHdr {jweAlg = a, jweEnc = e }, bs))
where
jwks = [a1jwk, a2jwk, a3jwk, aes192jwk, aes256jwk] >>= \j -> let Just jwk = decodeStrict' j in [jwk]
bs = B.pack msg
encodeDecode = fst (withDRG blinderRNG (decode jwks Nothing encoded))
Right encoded = unJwt <$> fst (withDRG g (encode jwks (JweEncoding a e) (Claims bs)))
encryptCek kpub a cek =
let
(Right newEk, _) = withDRG blinderRNG $ rsaEncrypt kpub a (BA.drop 1 cek)
in
newEk :: BC.ByteString
withBlinder = fst . withDRG blinderRNG
sequences of bytes to be supplied which match the JWE test data .
newtype RNG = RNG B.ByteString deriving (Eq, Show)
genBytes :: BA.ByteArray ba => Int -> RNG -> (ba, RNG)
genBytes 0 g = (BA.empty, g)
genBytes n (RNG bs) = (BA.convert bytes, RNG next)
where
(bytes, next) = if BA.null bs
then error "RNG is empty"
else BA.splitAt n bs
instance DRG RNG where
randomBytesGenerate = genBytes
blinderRNG = drgNewTest (w, w, w, w, w) where w = 1 :: Word64
JWE Appendix 1 Test Data
a1 :: B.ByteString
a1 = "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ.OKOawDo13gRp2ojaHV7LFpZcgV7T6DVZKTyKOMTYUmKoTCVJRgckCL9kiMT03JGeipsEdY3mx_etLbbWSrFr05kLzcSr4qKAq7YN7e9jwQRb23nfa6c9d-StnImGyFDbSv04uVuxIp5Zms1gNxKKK2Da14B8S4rzVRltdYwam_lDp5XnZAYpQdb76FdIKLaVmqgfwX7XWRxv2322i-vDxRfqNzo_tETKzpVLzfiwQyeyPGLBIO56YJ7eObdv0je81860ppamavo35UgoRdbYaBcoh9QcfylQr66oc6vFWXRcZ_ZT2LawVCWTIy3brGPi6UklfCpIMfIjf7iGdXKHzg.48V1_ALb6US04U3b.5eym8TW_c8SuK0ltJ3rpYIzOeDQz7TALvtu6UG9oMo4vpzs9tX_EFShS8iB7j6jiSdiwkIr3ajwQzaBtQD_A.XFBoMYUZodetZdvTiFvSkQ"
a1Payload = "The true sign of intelligence is not knowledge but imagination."
a1cek :: BA.ScrubbedBytes
a1cek = BA.pack [177, 161, 244, 128, 84, 143, 225, 115, 63, 180, 3, 255, 107, 154, 212, 246, 138, 7, 110, 91, 112, 46, 34, 105, 47, 130, 203, 46, 122, 234, 64, 252]
a1iv :: BA.ScrubbedBytes
a1iv = BA.pack [227, 197, 117, 252, 2, 219, 233, 68, 180, 225, 77, 219]
a1aad = B.pack [101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 48, 69, 116, 84, 48, 70, 70, 85, 67, 73, 115, 73, 109, 86, 117, 89, 121, 73, 54, 73, 107, 69, 121, 78, 84, 90, 72, 81, 48, 48, 105, 102, 81]
a1Ciphertext = B.pack [229, 236, 166, 241, 53, 191, 115, 196, 174, 43, 73, 109, 39, 122, 233, 96, 140, 206, 120, 52, 51, 237, 48, 11, 190, 219, 186, 80, 111, 104, 50, 142, 47, 167, 59, 61, 181, 127, 196, 21, 40, 82, 242, 32, 123, 143, 168, 226, 73, 216, 176, 144, 138, 247, 106, 60, 16, 205, 160, 109, 64, 63, 192]
a1Tag = BA.pack [92, 80, 104, 49, 133, 25, 161, 215, 173, 101, 219, 211, 136, 91, 210, 145]
Right a1jweKey = B64.decode $ BC.pack "OKOawDo13gRp2ojaHV7LFpZcgV7T6DVZKTyKOMTYUmKoTCVJRgckCL9kiMT03JGeipsEdY3mx_etLbbWSrFr05kLzcSr4qKAq7YN7e9jwQRb23nfa6c9d-StnImGyFDbSv04uVuxIp5Zms1gNxKKK2Da14B8S4rzVRltdYwam_lDp5XnZAYpQdb76FdIKLaVmqgfwX7XWRxv2322i-vDxRfqNzo_tETKzpVLzfiwQyeyPGLBIO56YJ7eObdv0je81860ppamavo35UgoRdbYaBcoh9QcfylQr66oc6vFWXRcZ_ZT2LawVCWTIy3brGPi6UklfCpIMfIjf7iGdXKHzg"
a1jwk = "{\"kty\":\"RSA\", \"n\":\"oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUWcJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3Spsk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2asbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMStPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2djYgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw\", \"e\":\"AQAB\", \"d\":\"kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5NWV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD93Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghkqDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vlt3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSndVTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ\" }"
a1RsaModulus = 20407373051396142380600281265251892119308905183562582378265551916401741797298132714477564366125574073854325621181754666299468042787718090965019045494120492365709229334674806858420600185271825023335981142192553851711447185679749878133484409202142610505370119489349112667599681596271324052456163162582257897587607185901342235063647947816589525124013368466111231306949063172170503467209564034546753006291531308789606255762727496010190006847721118463557533668762287451483156476421856126198680670740028037673487624895510756370816101325723975021588898704953504010419555312457504338174094966173304768490140232017447246019099
rsaExponent = 65537 :: Integer
a1RsaPrivateExponent = 18268766796654718362565236454995853620820821188251417451980738596264305499270399136757621249007756005599271096771478165267306874014871487538744562309757162619646837295513011635819128008143685281506609665247035139326775637222412463191989209202137797209813686014322033219332678022668756745556718137625135245640638710814390273901357613670762406363679831247433360271391936119294533419667412739496199381069233394069901435128732415071218792819358792459421008659625326677236263304891550388749907992141902573512326268421915766834378108391128385175130554819679860804655689526143903449732010240859012168194104458903308465660105
a1oaepSeed = extractOaepSeed a1PrivKey a1jweKey
(a1PubKey, a1PrivKey) = createKeyPair a1RsaModulus a1RsaPrivateExponent
JWE Appendix 2 Test Data
a2Payload = "Live long and prosper."
a2cek :: BA.ScrubbedBytes
a2cek = BA.pack [4, 211, 31, 197, 84, 157, 252, 254, 11, 100, 157, 250, 63, 170, 106, 206, 107, 124, 212, 45, 111, 107, 9, 219, 200, 177, 0, 240, 143, 156, 44, 207]
a2cek = B.pack [ 203 , 165 , 180 , 113 , 62 , 195 , 22 , 98 , 91 , 153 , 210 , 38 , 112 , 35 , 230 , 236 ]
a2cik = B.pack [ 218 , 24 , 160 , 17 , 160 , 50 , 235 , 35 , 216 , 209 , 100 , 174 , 155 , 163 , 10 , 117 , 180 , 111 , 172 , 200 , 127 , 201 , 206 , 173 , 40 , 45 , 58 , 170 , 35 , 93 , 9 , 60 ]
a2iv = B.pack [3, 22, 60, 12, 43, 67, 104, 105, 108, 108, 105, 99, 111, 116, 104, 101]
a2Ciphertext = B.pack [40, 57, 83, 181, 119, 33, 133, 148, 198, 185, 243, 24, 152, 230, 6, 75, 129, 223, 127, 19, 210, 82, 183, 230, 168, 33, 215, 104, 143, 112, 56, 102]
a2Tag = B.pack [246, 17, 244, 190, 4, 95, 98, 3, 231, 0, 115, 157, 242, 203, 100, 191]
Right a2jweKey = B64.decode $ BC.pack "UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-kFm1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKxGHZ7PcHALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3YvkkysZIFNPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPhcCdZ6XDP0_F8rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv-B3oWh2TbqmScqXMR4gp_A"
a2jwk = "{\"kty\":\"RSA\", \"n\":\"sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw\", \"e\":\"AQAB\", \"d\":\"VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-rynq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-QgajZGPbE_0ZaVDJHfyd7UUBUKunFMScbflYAAOYJqVIVwaYR5zWEEceUjNnTNo_CVSj-VvXLO5VZfCUAVLgW4dpf1SrtZjSt34YLsRarSb127reG_DUwg9Ch-KyvjT1SkHgUWRVGcyly7uvVGRSDwsXypdrNinPA4jlhoNdizK2zF2CWQ\" }"
a2RsaModulus = 22402924734748322419583087865046136971812964522608965289668050862528140628890468829261358173206844190609885548664216273129288787509446229835492005268681636400878070687042995563617837593077316848511917526886594334868053765054121327206058496913599608196082088434862911200952954663261204130886151917541465131565772711448256433529200865576041706962504490609565420543616528240562874975930318078653328569211055310553145904641192292907110395318778917935975962359665382660933281263049927785938817901532807037136641587608303638483543899849101763615990006657357057710971983052920787558713523025279998057051825799400286243909447
a2RsaPrivateExponent = 10643756465292254988457796463889735064030094089452909840615134957452106668931481879498770304395097541282329162591478128330968231330113176654221501869950411410564116254672288216799191435916328405513154035654178369543717138143188973636496077305930253145572851787483810154020967535132278148578697716656066036003388130625459567907864689911133288140117207430454310073863484450086676106606775792171446149215594844607410066899028283290532626577379520547350399030663657813726123700613989625283009134539244470878688076926304079342487789922656366430636978871435674556143884272163840709196449089335092169596187792960067104244313
a2 :: B.ByteString
a2 = "eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-kFm1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKxGHZ7PcHALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3YvkkysZIFNPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPhcCdZ6XDP0_F8rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv-B3oWh2TbqmScqXMR4gp_A.AxY8DCtDaGlsbGljb3RoZQ.KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.9hH0vgRfYgPnAHOd8stkvw"
(a2PubKey, a2PrivKey) = createKeyPair a2RsaModulus a2RsaPrivateExponent
a2seed = extractPKCS15Seed a2PrivKey a2jweKey
a3Payload = a2Payload
a3jwk = "{\"kty\":\"oct\", \"k\":\"GawgguFyGrWKav7AX4VKUg\"}"
aes192jwk = "{\"kty\":\"oct\", \"k\":\"FatNm7ez26tyPGsXdaqhYHtvThX0jSAA\"}"
aes256jwk = "{\"kty\":\"oct\", \"k\":\"1MeiHdxK8CQBsmjgOM8SCxg06MTjFzG7sFa7EnDCJzo\"}"
a3cek = B.pack [4, 211, 31, 197, 84, 157, 252, 254, 11, 100, 157, 250, 63, 170, 106, 206, 107, 124, 212, 45, 111, 107, 9, 219, 200, 177, 0, 240, 143, 156, 44, 207]
a3iv = B.pack [3, 22, 60, 12, 43, 67, 104, 105, 108, 108, 105, 99, 111, 116, 104, 101]
a3 :: B.ByteString
a3 = "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ.AxY8DCtDaGlsbGljb3RoZQ.KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.U0m_YmjN04DJvceFICbCVQ"
data JWEAlgs = JWEAlgs JweAlg Enc deriving Show
instance Arbitrary Enc where
arbitrary = elements [A128CBC_HS256, A192CBC_HS384, A256CBC_HS512, A128GCM, A192GCM, A256GCM]
instance Arbitrary JWEAlgs where
arbitrary = do
a <- elements [RSA1_5, RSA_OAEP, RSA_OAEP_256, A128KW, A192KW, A256KW]
e <- arbitrary
return $ JWEAlgs a e
instance Arbitrary RNG where
arbitrary = RNG . B.pack <$> vector 600
createKeyPair n d = (pubKey, privKey)
where
privKey = RSA.PrivateKey
{ RSA.private_pub = pubKey
, RSA.private_d = d
, RSA.private_q = 0
, RSA.private_p = 0
, RSA.private_dP = 0
, RSA.private_dQ = 0
, RSA.private_qinv = 0
}
pubKey = RSA.PublicKey
{ RSA.public_size = 256
, RSA.public_n = n
, RSA.public_e = rsaExponent
}
extractOaepSeed :: RSA.PrivateKey -> B.ByteString -> B.ByteString
extractOaepSeed key ct = B.pack $ B.zipWith xor maskedSeed seedMask
where
em = dp Nothing key ct
hashLen = hashDigestSize SHA1
em0 = B.tail em
(maskedSeed, maskedDB) = B.splitAt hashLen em0
seedMask = mgf1 SHA1 maskedDB hashLen
extractPKCS15Seed :: RSA.PrivateKey -> B.ByteString -> B.ByteString
extractPKCS15Seed key ct = B.takeWhile (/= 0) . B.drop 2 $ dp Nothing key ct
|
b8e2eae29054f1c3bcf050d9030bcf78bb4e7c9df044caa460aef0d2a277fff0 | threatgrid/ctia | update_index_state_test.clj | (ns ctia.task.update-index-state-test
(:require [clojure.test :refer [deftest is use-fixtures]]
[ctia.task.update-index-state :as sut]
[ductile.index :as es-index]
[ctia.test-helpers.core :as h]
[ctia.test-helpers.es :as es-helpers]))
(use-fixtures :once
es-helpers/fixture-properties:es-store)
(deftest update-index-state-test
(es-helpers/for-each-es-version
"update-index-state task"
[5 7]
#(ductile.index/delete! % "ctia_*")
(es-helpers/fixture-properties:es-store
(fn []
(is (= 0 (sut/do-task (h/build-transformed-init-config))))
(is (= 1 (sut/do-task {})))))))
| null | https://raw.githubusercontent.com/threatgrid/ctia/9b9f333aeb91dd9faf2541f9d736b8539162d6e9/test/ctia/task/update_index_state_test.clj | clojure | (ns ctia.task.update-index-state-test
(:require [clojure.test :refer [deftest is use-fixtures]]
[ctia.task.update-index-state :as sut]
[ductile.index :as es-index]
[ctia.test-helpers.core :as h]
[ctia.test-helpers.es :as es-helpers]))
(use-fixtures :once
es-helpers/fixture-properties:es-store)
(deftest update-index-state-test
(es-helpers/for-each-es-version
"update-index-state task"
[5 7]
#(ductile.index/delete! % "ctia_*")
(es-helpers/fixture-properties:es-store
(fn []
(is (= 0 (sut/do-task (h/build-transformed-init-config))))
(is (= 1 (sut/do-task {})))))))
|
|
10cdc841cb4ccceaa098d939ec8b13b3a4b9bf9e28a22dd064ef20a6eca5fea2 | synsem/texhs | Walk.hs | # LANGUAGE GeneralizedNewtypeDeriving #
----------------------------------------------------------------------
-- |
Module : Text . TeX.Context . Walk
Copyright : 2015 - 2017 ,
2015 - 2016 Language Science Press .
-- License : GPL-3
--
-- Maintainer :
-- Stability : experimental
Portability : GHC
--
Parser type for walking contexts
----------------------------------------------------------------------
module Text.TeX.Context.Walk
( -- * Types
Parser
, ParserS
, runParser
, runParserWithState
* Parser State
, getMeta
, putMeta
, modifyMeta
-- * Basic combinators
, choice
, count
, sepBy
, sepBy1
, sepEndBy
, sepEndBy1
, list
-- * Command parsers
-- ** Specific command
, cmd
, inCmd
, inCmd2
, inCmd3
, inCmdOpt2
, inCmdCheckStar
, inCmdWithOpts
, cmdDown
-- * Group parsers
-- ** Specific group
, grp
, inGrp
, inGrpChoice
, inMathGrp
, inSubScript
, inSupScript
, grpDown
, grpUnwrap
-- ** Any group
, optNested
, goDown
, goUp
, safeUp
-- * Lift TeX Context traversals
, step
, stepRes
-- * Low-level parsers
, satisfy
, peek
, item
, eof
, eog
, dropParents
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans.Class (lift)
import qualified Control.Monad.Trans.Except as E
import qualified Control.Monad.Trans.State as S
import Text.TeX.Parser.Types
import Text.TeX.Context.Types
import Text.Doc.Types (Meta(..), defaultMeta)
---------- Types
-- Note: All of the functions defined below could be generalized from
-- @Parser@ to @ParserS s@. However, since we currently only use the
-- @Parser@ type directly, we keep the simpler type declarations.
| A parser for walking ,
-- parameterized by user state.
newtype ParserS s a = Parser
{ parser :: S.StateT TeXContext (S.StateT s (E.Except [TeXDocError])) a }
deriving (Functor, Applicative, Monad, Alternative, MonadPlus)
| A parser for walking ,
with a ' Meta ' user state .
type Parser = ParserS Meta
| Run a parser on a TeX AST .
--
Include final ' Meta ' state in the result .
runParserWithState :: Parser a -> TeX -> ThrowsError (a, Meta)
runParserWithState p xs =
E.runExcept (S.runStateT (S.evalStateT
(parser p) (pureTeXContext xs)) defaultMeta)
| Run a parser on a TeX AST .
runParser :: Parser a -> TeX -> ThrowsError a
runParser p xs = fst <$> runParserWithState p xs
state :: (TeXContext -> (a, TeXContext)) -> Parser a
state = Parser . S.state
put :: TeXContext -> Parser ()
put = Parser . S.put
get :: Parser TeXContext
get = Parser S.get
| Set the value of the ' Meta ' state .
putMeta :: Meta -> Parser ()
putMeta = Parser . lift . S.put
| Fetch the current value of the ' Meta ' state .
getMeta :: Parser Meta
getMeta = Parser (lift S.get)
| Modify the value of the ' Meta ' state .
modifyMeta :: (Meta -> Meta) -> Parser ()
modifyMeta = Parser . lift . S.modify
throwE :: TeXDocError -> Parser a
throwE e = Parser (lift (lift (E.throwE [e])))
---------- Low-level parsers
-- | Return the next 'TeXAtom' if it satisfies the provided predicate.
satisfy :: (TeXAtom -> Bool) -> Parser TeXAtom
satisfy p = peek p *> item
-- | Peek at head of focus.
--
-- Like 'satisfy' but does not consume the matched 'TeXAtom'.
peek :: (TeXAtom -> Bool) -> Parser ()
peek = step . testHeadErr
-- | Return the next 'TeXAtom'.
item :: Parser TeXAtom
item = stepRes unconsFocus
-- | Succeed if context is empty.
eof :: Parser ()
eof = step testEof
-- | Succeed if focus is empty (i.e. if we hit an end of group).
eog :: Parser ()
eog = step testEog
-- | Restrict context to focus.
dropParents :: Parser ()
dropParents = step resetParents
---------- Basic combinators
| Try parsers from a list until one succeeds .
choice :: [Parser a] -> Parser a
choice = msum
| Run parser @n@ times .
count :: Int -> Parser a -> Parser [a]
count n p
| n <= 0 = return []
| otherwise = (:) <$> p <*> count (n-1) p
| @sepBy p sep@ parses zero or more occurrences of @p@ ,
separated by @sep@. Returns a list of values returned by @p@.
sepBy :: Parser a -> Parser b -> Parser [a]
sepBy p sep = sepBy1 p sep <|> pure []
| @sepBy p sep@ parses one or more occurrences of @p@ ,
separated by @sep@. Returns a list of values returned by @p@.
sepBy1 :: Parser a -> Parser b -> Parser [a]
sepBy1 p sep = (:) <$> p <*> list sep p
| @sepEndBy p sep@ parses zero or more occurrences of @p@ ,
separated and optionally ended by @sep@.
Returns a list of values returned by @p@.
sepEndBy :: Parser a -> Parser b -> Parser [a]
sepEndBy p sep = sepEndBy1 p sep <|> pure []
| @sepEndBy1 p sep@ parses one or more occurrences of @p@ ,
separated and optionally ended by @sep@.
Returns a list of values returned by @p@.
sepEndBy1 :: Parser a -> Parser b -> Parser [a]
sepEndBy1 p sep = (:) <$> p <*> ((sep *> sepEndBy p sep) <|> pure [])
| @list bullet p@ parses zero or more occurrences of @p@ , each prefixed by
Returns a list of values returned by @p@.
--
Note : @p@ must not overlap with
list :: Parser a -> Parser b -> Parser [b]
list bullet p = many (bullet *> p)
---------- Command parsers
-- | Parse a specific command.
cmd :: String -> Parser TeXAtom
cmd = satisfy . isCmd
| Apply parser to the first mandatory argument of a specific command
-- (all other arguments are dropped).
inCmd :: String -> Parser a -> Parser a
inCmd n p = cmdDown n *> p <* safeUp
| Apply parser to the first mandatory argument of a specific command
-- (all other arguments are dropped). Return a boolean flag that indicates
whether the command had a ' StarArg ' , i.e. whether it was starred .
inCmdCheckStar :: String -> Parser a -> Parser (Bool, a)
inCmdCheckStar n p =
(,) True <$> (cmdDownWithStar n *> p <* safeUp) <|>
(,) False <$> (cmdDown n *> p <* safeUp)
| Descend into the first mandatory argument of a specific command
-- (all other arguments are dropped).
cmdDown :: String -> Parser ()
cmdDown n = peek (isCmd n) *> step intoCmdArg
| Descend into the first mandatory argument of a specific command
-- (all other arguments are dropped), but only if it is starred.
cmdDownWithStar :: String -> Parser ()
cmdDownWithStar n = peek (isCmdWithStar n) *> step intoCmdArg
-- Note: We are not creating an isolated context for the argument.
Parsers are expected to operate on the focus value only ( no ' up ' ) .
--
-- | Apply parser to the n-th mandatory argument of a command,
-- without consuming the command.
cmdPeekOblArg :: Int -> Parser a -> Parser a
cmdPeekOblArg n p = step (peekOblArg n) *> p <* safeUp
-- Note: We are not creating an isolated context for the argument.
Parsers are expected to operate on the focus value only ( no ' up ' ) .
--
-- | Apply parser to the n-th optional argument of a command,
-- without consuming the command.
cmdPeekOptArg :: Int -> Parser a -> Parser a
cmdPeekOptArg n p = step (peekOptArg n) *> p <* safeUp
| Parse a specific command and apply two parsers
to its first two mandatory arguments .
inCmd2 :: String -> Parser a -> Parser b -> Parser (a,b)
inCmd2 n p0 p1 = (,) <$> (peek (isCmd n) *>
cmdPeekOblArg 0 p0) <*>
cmdPeekOblArg 1 p1 <* cmd n
| Parse a specific command and apply three parsers
to its first three mandatory arguments .
inCmd3 :: String -> Parser a -> Parser b -> Parser c -> Parser (a,b,c)
inCmd3 n p0 p1 p2 = (,,) <$> (peek (isCmd n) *>
cmdPeekOblArg 0 p0) <*>
cmdPeekOblArg 1 p1 <*>
cmdPeekOblArg 2 p2 <* cmd n
| @inCmdOpt2 name opt0 opt1 p@ parses the command @name@ and
applies the parsers @opt0@ and @opt1@ to its first two optional
-- arguments, respectively, and applies the parser @p@ to its
first mandatory argument .
inCmdOpt2 :: String -> Parser oa -> Parser ob -> Parser a -> Parser (oa,ob,a)
inCmdOpt2 n opt0 opt1 obl = (,,) <$> (peek (isCmd n) *>
cmdPeekOptArg 0 opt0) <*>
cmdPeekOptArg 1 opt1 <*>
inCmd n obl
| @inCmdWithOpts name opts p@ parses the command @name@ and
-- applies the parsers @opts@ to its optional arguments and
the parser @p@ to its first mandatory argument .
inCmdWithOpts :: String -> [Parser a] -> Parser b -> Parser ([a],b)
inCmdWithOpts n opts obl = (,) <$> (peek (isCmd n) *>
zipWithM cmdPeekOptArg [0..] opts) <*>
inCmd n obl
---------- Group parsers
-- | Parse a specific group.
grp :: String -> Parser TeXAtom
grp = satisfy . isGrp
-- | Apply parser to specific group body.
inGrp :: String -> Parser a -> Parser a
inGrp n p = grpDown n *> p <* safeUp
| Apply parser to the body of one of the specified groups .
inGrpChoice :: [String] -> Parser a -> Parser a
inGrpChoice ns p = choice (map grpDown ns) *> p <* safeUp
-- | Descend into a specific group (ignoring all group arguments).
grpDown :: String -> Parser ()
grpDown n = peek (isGrp n) *> goDown
-- | Unwrap the content of a specific group.
--
-- Warning: This may extend the scope of contained commands.
grpUnwrap :: String -> Parser ()
grpUnwrap n = peek (isGrp n) *> step unwrap
-- | Apply parser inside a math group,
and also return its ' MathType ' .
inMathGrp :: Parser a -> Parser (MathType, a)
inMathGrp p = (,) <$> stepRes downMath <*> p <* safeUp
-- | Apply parser to a subscript group.
inSubScript :: Parser a -> Parser a
inSubScript p = peek isSubScript *> inAnyGroup p
-- | Apply parser to a superscript group.
inSupScript :: Parser a -> Parser a
inSupScript p = peek isSupScript *> inAnyGroup p
-- Apply parser inside a group (any group).
-- The parser must exhaust the group content.
inAnyGroup :: Parser a -> Parser a
inAnyGroup p = goDown *> p <* safeUp
-- | Allow parser to walk into groups (if it fails at the top level).
-- If the parser opens a group, it must exhaust its content.
optNested :: Parser a -> Parser a
optNested p = p <|> inAnyGroup (optNested p)
-- | Descend into a group. See 'down'.
goDown :: Parser ()
goDown = step down
| Drop focus and climb up one level . See ' up ' .
goUp :: Parser ()
goUp = step up
| If focus is empty , climb up one level .
safeUp :: Parser ()
safeUp = eog *> goUp
---------- Lift TeX Context traversals
-- | Execute a 'TeXStep' (no result).
step :: TeXStep -> Parser ()
step dir = get >>= either throwE put . dir
-- | Execute a 'TeXStepRes' (with result).
stepRes :: TeXStepRes a -> Parser a
stepRes dir = get >>= either throwE (state . const) . dir
| null | https://raw.githubusercontent.com/synsem/texhs/9e2dce4ec8ae0b2c024e1883d9a93bab15f9a86f/src/Text/TeX/Context/Walk.hs | haskell | --------------------------------------------------------------------
|
License : GPL-3
Maintainer :
Stability : experimental
--------------------------------------------------------------------
* Types
* Basic combinators
* Command parsers
** Specific command
* Group parsers
** Specific group
** Any group
* Lift TeX Context traversals
* Low-level parsers
-------- Types
Note: All of the functions defined below could be generalized from
@Parser@ to @ParserS s@. However, since we currently only use the
@Parser@ type directly, we keep the simpler type declarations.
parameterized by user state.
-------- Low-level parsers
| Return the next 'TeXAtom' if it satisfies the provided predicate.
| Peek at head of focus.
Like 'satisfy' but does not consume the matched 'TeXAtom'.
| Return the next 'TeXAtom'.
| Succeed if context is empty.
| Succeed if focus is empty (i.e. if we hit an end of group).
| Restrict context to focus.
-------- Basic combinators
-------- Command parsers
| Parse a specific command.
(all other arguments are dropped).
(all other arguments are dropped). Return a boolean flag that indicates
(all other arguments are dropped).
(all other arguments are dropped), but only if it is starred.
Note: We are not creating an isolated context for the argument.
| Apply parser to the n-th mandatory argument of a command,
without consuming the command.
Note: We are not creating an isolated context for the argument.
| Apply parser to the n-th optional argument of a command,
without consuming the command.
arguments, respectively, and applies the parser @p@ to its
applies the parsers @opts@ to its optional arguments and
-------- Group parsers
| Parse a specific group.
| Apply parser to specific group body.
| Descend into a specific group (ignoring all group arguments).
| Unwrap the content of a specific group.
Warning: This may extend the scope of contained commands.
| Apply parser inside a math group,
| Apply parser to a subscript group.
| Apply parser to a superscript group.
Apply parser inside a group (any group).
The parser must exhaust the group content.
| Allow parser to walk into groups (if it fails at the top level).
If the parser opens a group, it must exhaust its content.
| Descend into a group. See 'down'.
-------- Lift TeX Context traversals
| Execute a 'TeXStep' (no result).
| Execute a 'TeXStepRes' (with result). | # LANGUAGE GeneralizedNewtypeDeriving #
Module : Text . TeX.Context . Walk
Copyright : 2015 - 2017 ,
2015 - 2016 Language Science Press .
Portability : GHC
Parser type for walking contexts
module Text.TeX.Context.Walk
Parser
, ParserS
, runParser
, runParserWithState
* Parser State
, getMeta
, putMeta
, modifyMeta
, choice
, count
, sepBy
, sepBy1
, sepEndBy
, sepEndBy1
, list
, cmd
, inCmd
, inCmd2
, inCmd3
, inCmdOpt2
, inCmdCheckStar
, inCmdWithOpts
, cmdDown
, grp
, inGrp
, inGrpChoice
, inMathGrp
, inSubScript
, inSupScript
, grpDown
, grpUnwrap
, optNested
, goDown
, goUp
, safeUp
, step
, stepRes
, satisfy
, peek
, item
, eof
, eog
, dropParents
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Trans.Class (lift)
import qualified Control.Monad.Trans.Except as E
import qualified Control.Monad.Trans.State as S
import Text.TeX.Parser.Types
import Text.TeX.Context.Types
import Text.Doc.Types (Meta(..), defaultMeta)
| A parser for walking ,
newtype ParserS s a = Parser
{ parser :: S.StateT TeXContext (S.StateT s (E.Except [TeXDocError])) a }
deriving (Functor, Applicative, Monad, Alternative, MonadPlus)
| A parser for walking ,
with a ' Meta ' user state .
type Parser = ParserS Meta
| Run a parser on a TeX AST .
Include final ' Meta ' state in the result .
runParserWithState :: Parser a -> TeX -> ThrowsError (a, Meta)
runParserWithState p xs =
E.runExcept (S.runStateT (S.evalStateT
(parser p) (pureTeXContext xs)) defaultMeta)
| Run a parser on a TeX AST .
runParser :: Parser a -> TeX -> ThrowsError a
runParser p xs = fst <$> runParserWithState p xs
state :: (TeXContext -> (a, TeXContext)) -> Parser a
state = Parser . S.state
put :: TeXContext -> Parser ()
put = Parser . S.put
get :: Parser TeXContext
get = Parser S.get
| Set the value of the ' Meta ' state .
putMeta :: Meta -> Parser ()
putMeta = Parser . lift . S.put
| Fetch the current value of the ' Meta ' state .
getMeta :: Parser Meta
getMeta = Parser (lift S.get)
| Modify the value of the ' Meta ' state .
modifyMeta :: (Meta -> Meta) -> Parser ()
modifyMeta = Parser . lift . S.modify
throwE :: TeXDocError -> Parser a
throwE e = Parser (lift (lift (E.throwE [e])))
satisfy :: (TeXAtom -> Bool) -> Parser TeXAtom
satisfy p = peek p *> item
peek :: (TeXAtom -> Bool) -> Parser ()
peek = step . testHeadErr
item :: Parser TeXAtom
item = stepRes unconsFocus
eof :: Parser ()
eof = step testEof
eog :: Parser ()
eog = step testEog
dropParents :: Parser ()
dropParents = step resetParents
| Try parsers from a list until one succeeds .
choice :: [Parser a] -> Parser a
choice = msum
| Run parser @n@ times .
count :: Int -> Parser a -> Parser [a]
count n p
| n <= 0 = return []
| otherwise = (:) <$> p <*> count (n-1) p
| @sepBy p sep@ parses zero or more occurrences of @p@ ,
separated by @sep@. Returns a list of values returned by @p@.
sepBy :: Parser a -> Parser b -> Parser [a]
sepBy p sep = sepBy1 p sep <|> pure []
| @sepBy p sep@ parses one or more occurrences of @p@ ,
separated by @sep@. Returns a list of values returned by @p@.
sepBy1 :: Parser a -> Parser b -> Parser [a]
sepBy1 p sep = (:) <$> p <*> list sep p
| @sepEndBy p sep@ parses zero or more occurrences of @p@ ,
separated and optionally ended by @sep@.
Returns a list of values returned by @p@.
sepEndBy :: Parser a -> Parser b -> Parser [a]
sepEndBy p sep = sepEndBy1 p sep <|> pure []
| @sepEndBy1 p sep@ parses one or more occurrences of @p@ ,
separated and optionally ended by @sep@.
Returns a list of values returned by @p@.
sepEndBy1 :: Parser a -> Parser b -> Parser [a]
sepEndBy1 p sep = (:) <$> p <*> ((sep *> sepEndBy p sep) <|> pure [])
| @list bullet p@ parses zero or more occurrences of @p@ , each prefixed by
Returns a list of values returned by @p@.
Note : @p@ must not overlap with
list :: Parser a -> Parser b -> Parser [b]
list bullet p = many (bullet *> p)
cmd :: String -> Parser TeXAtom
cmd = satisfy . isCmd
| Apply parser to the first mandatory argument of a specific command
inCmd :: String -> Parser a -> Parser a
inCmd n p = cmdDown n *> p <* safeUp
| Apply parser to the first mandatory argument of a specific command
whether the command had a ' StarArg ' , i.e. whether it was starred .
inCmdCheckStar :: String -> Parser a -> Parser (Bool, a)
inCmdCheckStar n p =
(,) True <$> (cmdDownWithStar n *> p <* safeUp) <|>
(,) False <$> (cmdDown n *> p <* safeUp)
| Descend into the first mandatory argument of a specific command
cmdDown :: String -> Parser ()
cmdDown n = peek (isCmd n) *> step intoCmdArg
| Descend into the first mandatory argument of a specific command
cmdDownWithStar :: String -> Parser ()
cmdDownWithStar n = peek (isCmdWithStar n) *> step intoCmdArg
Parsers are expected to operate on the focus value only ( no ' up ' ) .
cmdPeekOblArg :: Int -> Parser a -> Parser a
cmdPeekOblArg n p = step (peekOblArg n) *> p <* safeUp
Parsers are expected to operate on the focus value only ( no ' up ' ) .
cmdPeekOptArg :: Int -> Parser a -> Parser a
cmdPeekOptArg n p = step (peekOptArg n) *> p <* safeUp
| Parse a specific command and apply two parsers
to its first two mandatory arguments .
inCmd2 :: String -> Parser a -> Parser b -> Parser (a,b)
inCmd2 n p0 p1 = (,) <$> (peek (isCmd n) *>
cmdPeekOblArg 0 p0) <*>
cmdPeekOblArg 1 p1 <* cmd n
| Parse a specific command and apply three parsers
to its first three mandatory arguments .
inCmd3 :: String -> Parser a -> Parser b -> Parser c -> Parser (a,b,c)
inCmd3 n p0 p1 p2 = (,,) <$> (peek (isCmd n) *>
cmdPeekOblArg 0 p0) <*>
cmdPeekOblArg 1 p1 <*>
cmdPeekOblArg 2 p2 <* cmd n
| @inCmdOpt2 name opt0 opt1 p@ parses the command @name@ and
applies the parsers @opt0@ and @opt1@ to its first two optional
first mandatory argument .
inCmdOpt2 :: String -> Parser oa -> Parser ob -> Parser a -> Parser (oa,ob,a)
inCmdOpt2 n opt0 opt1 obl = (,,) <$> (peek (isCmd n) *>
cmdPeekOptArg 0 opt0) <*>
cmdPeekOptArg 1 opt1 <*>
inCmd n obl
| @inCmdWithOpts name opts p@ parses the command @name@ and
the parser @p@ to its first mandatory argument .
inCmdWithOpts :: String -> [Parser a] -> Parser b -> Parser ([a],b)
inCmdWithOpts n opts obl = (,) <$> (peek (isCmd n) *>
zipWithM cmdPeekOptArg [0..] opts) <*>
inCmd n obl
grp :: String -> Parser TeXAtom
grp = satisfy . isGrp
inGrp :: String -> Parser a -> Parser a
inGrp n p = grpDown n *> p <* safeUp
| Apply parser to the body of one of the specified groups .
inGrpChoice :: [String] -> Parser a -> Parser a
inGrpChoice ns p = choice (map grpDown ns) *> p <* safeUp
grpDown :: String -> Parser ()
grpDown n = peek (isGrp n) *> goDown
grpUnwrap :: String -> Parser ()
grpUnwrap n = peek (isGrp n) *> step unwrap
and also return its ' MathType ' .
inMathGrp :: Parser a -> Parser (MathType, a)
inMathGrp p = (,) <$> stepRes downMath <*> p <* safeUp
inSubScript :: Parser a -> Parser a
inSubScript p = peek isSubScript *> inAnyGroup p
inSupScript :: Parser a -> Parser a
inSupScript p = peek isSupScript *> inAnyGroup p
inAnyGroup :: Parser a -> Parser a
inAnyGroup p = goDown *> p <* safeUp
optNested :: Parser a -> Parser a
optNested p = p <|> inAnyGroup (optNested p)
goDown :: Parser ()
goDown = step down
| Drop focus and climb up one level . See ' up ' .
goUp :: Parser ()
goUp = step up
| If focus is empty , climb up one level .
safeUp :: Parser ()
safeUp = eog *> goUp
step :: TeXStep -> Parser ()
step dir = get >>= either throwE put . dir
stepRes :: TeXStepRes a -> Parser a
stepRes dir = get >>= either throwE (state . const) . dir
|
f8e893ba88852888c940b7bf57dc855b3ead2f7d6f6638d644bf282058fa80cb | nasa/Common-Metadata-Repository | search_service.clj | (ns cmr.metadata-db.services.search-service
"Contains functions for retrieving concepts using parameter search"
(:require
[clojure.set :as set]
[cmr.common.concepts :as cc]
[cmr.common.log :refer (debug info warn error)]
[cmr.common.util :as util]
[cmr.metadata-db.data.concepts :as c]
[cmr.metadata-db.services.messages :as msg]
[cmr.metadata-db.services.provider-service :as provider-service]
[cmr.metadata-db.services.util :as db-util]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Validations for find concepts
(def default-supported-find-parameters
"The set of find parameters supported by most concepts."
#{:concept-id :provider-id :native-id})
(def supported-find-parameters
"Map of concept-types to sets of parameters supported by find for each type."
(merge
{:collection #{:concept-id :provider-id :entry-title :entry-id :short-name :version-id :native-id}
:tag #{:concept-id :native-id}
:tag-association #{:concept-id :native-id :associated-concept-id :associated-revision-id :tag-key}
:service #{:provider-id :concept-id :native-id}
:tool #{:provider-id :concept-id :native-id}
:access-group default-supported-find-parameters
:acl default-supported-find-parameters
:humanizer #{:concept-id :native-id}
:subscription #{:provider-id :concept-id :native-id :collection-concept-id :subscriber-id :normalized-query
:subscription-type}
:variable #{:provider-id :concept-id :native-id}
:variable-association #{:concept-id :native-id :associated-concept-id :associated-revision-id
:variable-concept-id}
:service-association #{:concept-id :native-id :associated-concept-id :associated-revision-id
:service-concept-id}
:tool-association #{:concept-id :native-id :associated-concept-id :associated-revision-id
:tool-concept-id}
:generic-association #{:concept-id :native-id :associated-concept-id :associated-revision-id
:source-concept-identifier :source-revision-id :association-type}}
(zipmap (cc/get-generic-concept-types-array)
(repeat #{:concept-id :provider-id :native-id}))))
(def granule-supported-parameter-combinations
"Supported search parameter combination sets for granule find. This does not include flags
like 'exclude-metadata' or 'latest'."
#{#{:provider-id :granule-ur}
#{:provider-id :native-id}})
(def find-concepts-flags
"Flags that affect find concepts but aren't part of the actual search parameters."
#{:exclude-metadata :latest})
(defmulti supported-parameter-combinations-validation
"Validates the find parameters for a concept type."
(fn [params]
(keyword (:concept-type params))))
;; For performance reasons we only support finding granules using combinations of indexed fields,
;; so we validate the parameters for granules separately from other concept types that allow
;; finds using single fields.
(defmethod supported-parameter-combinations-validation :granule
[{:keys [concept-type] :as params}]
(let [params (dissoc params :concept-type)
search-params (set (keys (apply dissoc params find-concepts-flags)))]
(when-not (contains? granule-supported-parameter-combinations search-params)
[(msg/find-not-supported-combination concept-type (keys params))])))
(defmethod supported-parameter-combinations-validation :default
[params]
(let [concept-type (:concept-type params)
params (dissoc params :concept-type)
supported-params (set/union (get supported-find-parameters concept-type)
find-concepts-flags)]
(when-let [unsupported-params (seq (set/difference (set (keys params))
supported-params))]
[(msg/find-not-supported concept-type unsupported-params)])))
(def find-params-validation
"Validates parameters for finding a concept."
(util/compose-validations [supported-parameter-combinations-validation]))
(def validate-find-params
"Validates find parameters. Throws an error if invalid."
(util/build-validator :bad-request find-params-validation))
(defn- find-providers-for-params
"Find providers that match the given parameters. If no providers are specified we return all
providers as possible providers that could match the parameters."
[context params]
(if-let [provider-id (:provider-id params)]
(when-let [provider (provider-service/get-provider-by-id context provider-id)]
[provider])
(let [providers (provider-service/get-providers context)]
(if (= :subscription (:concept-type params))
(concat [{:provider-id "CMR"}] providers)
providers))))
(defn- find-cmr-concepts
"Find tags or tag associations with specific parameters"
[context params]
(when (or (nil? (:provider-id params))
(= "CMR" (:provider-id params)))
(let [db (db-util/context->db context)
latest-only? (or (true? (:latest params))
(= "true" (:latest params)))
params (dissoc params :latest)]
(if latest-only?
(c/find-latest-concepts db {:provider-id "CMR"} params)
(c/find-concepts db [{:provider-id "CMR"}] params)))))
(defn- find-provider-concepts
"Find concepts with specific parameters"
[context params]
(let [db (db-util/context->db context)
latest-only? (or (true? (:latest params))
(= "true" (:latest params)))
params (dissoc params :latest)
providers (find-providers-for-params context params)]
(when (seq providers)
(if latest-only?
(mapcat #(c/find-latest-concepts db % params) providers)
(c/find-concepts db providers params)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Service methods for finding concepts
(defn find-concepts
"Find concepts with specific parameters"
[context params]
(validate-find-params params)
(cond
(contains? #{:tag
:tag-association
:acl
:humanizer
:variable-association
:service-association
:tool-association
:generic-association}
(:concept-type params))
(find-cmr-concepts context params)
(= :access-group (:concept-type params))
(concat
(find-cmr-concepts context params)
(find-provider-concepts context params))
:else
(find-provider-concepts context params)))
(defn find-associations
"Find associations with specific parameters."
[context params]
(let [db (db-util/context->db context)
latest-only? (or (true? (:latest params))
(= "true" (:latest params)))
params (dissoc params :latest)]
(if latest-only?
(c/find-latest-associations db params)
(c/find-associations db params))))
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/98b8c05fa0e0dbba5cec095aa4cc7fd7ebf1f912/metadata-db-app/src/cmr/metadata_db/services/search_service.clj | clojure |
For performance reasons we only support finding granules using combinations of indexed fields,
so we validate the parameters for granules separately from other concept types that allow
finds using single fields.
Service methods for finding concepts | (ns cmr.metadata-db.services.search-service
"Contains functions for retrieving concepts using parameter search"
(:require
[clojure.set :as set]
[cmr.common.concepts :as cc]
[cmr.common.log :refer (debug info warn error)]
[cmr.common.util :as util]
[cmr.metadata-db.data.concepts :as c]
[cmr.metadata-db.services.messages :as msg]
[cmr.metadata-db.services.provider-service :as provider-service]
[cmr.metadata-db.services.util :as db-util]))
Validations for find concepts
(def default-supported-find-parameters
"The set of find parameters supported by most concepts."
#{:concept-id :provider-id :native-id})
(def supported-find-parameters
"Map of concept-types to sets of parameters supported by find for each type."
(merge
{:collection #{:concept-id :provider-id :entry-title :entry-id :short-name :version-id :native-id}
:tag #{:concept-id :native-id}
:tag-association #{:concept-id :native-id :associated-concept-id :associated-revision-id :tag-key}
:service #{:provider-id :concept-id :native-id}
:tool #{:provider-id :concept-id :native-id}
:access-group default-supported-find-parameters
:acl default-supported-find-parameters
:humanizer #{:concept-id :native-id}
:subscription #{:provider-id :concept-id :native-id :collection-concept-id :subscriber-id :normalized-query
:subscription-type}
:variable #{:provider-id :concept-id :native-id}
:variable-association #{:concept-id :native-id :associated-concept-id :associated-revision-id
:variable-concept-id}
:service-association #{:concept-id :native-id :associated-concept-id :associated-revision-id
:service-concept-id}
:tool-association #{:concept-id :native-id :associated-concept-id :associated-revision-id
:tool-concept-id}
:generic-association #{:concept-id :native-id :associated-concept-id :associated-revision-id
:source-concept-identifier :source-revision-id :association-type}}
(zipmap (cc/get-generic-concept-types-array)
(repeat #{:concept-id :provider-id :native-id}))))
(def granule-supported-parameter-combinations
"Supported search parameter combination sets for granule find. This does not include flags
like 'exclude-metadata' or 'latest'."
#{#{:provider-id :granule-ur}
#{:provider-id :native-id}})
(def find-concepts-flags
"Flags that affect find concepts but aren't part of the actual search parameters."
#{:exclude-metadata :latest})
(defmulti supported-parameter-combinations-validation
"Validates the find parameters for a concept type."
(fn [params]
(keyword (:concept-type params))))
(defmethod supported-parameter-combinations-validation :granule
[{:keys [concept-type] :as params}]
(let [params (dissoc params :concept-type)
search-params (set (keys (apply dissoc params find-concepts-flags)))]
(when-not (contains? granule-supported-parameter-combinations search-params)
[(msg/find-not-supported-combination concept-type (keys params))])))
(defmethod supported-parameter-combinations-validation :default
[params]
(let [concept-type (:concept-type params)
params (dissoc params :concept-type)
supported-params (set/union (get supported-find-parameters concept-type)
find-concepts-flags)]
(when-let [unsupported-params (seq (set/difference (set (keys params))
supported-params))]
[(msg/find-not-supported concept-type unsupported-params)])))
(def find-params-validation
"Validates parameters for finding a concept."
(util/compose-validations [supported-parameter-combinations-validation]))
(def validate-find-params
"Validates find parameters. Throws an error if invalid."
(util/build-validator :bad-request find-params-validation))
(defn- find-providers-for-params
"Find providers that match the given parameters. If no providers are specified we return all
providers as possible providers that could match the parameters."
[context params]
(if-let [provider-id (:provider-id params)]
(when-let [provider (provider-service/get-provider-by-id context provider-id)]
[provider])
(let [providers (provider-service/get-providers context)]
(if (= :subscription (:concept-type params))
(concat [{:provider-id "CMR"}] providers)
providers))))
(defn- find-cmr-concepts
"Find tags or tag associations with specific parameters"
[context params]
(when (or (nil? (:provider-id params))
(= "CMR" (:provider-id params)))
(let [db (db-util/context->db context)
latest-only? (or (true? (:latest params))
(= "true" (:latest params)))
params (dissoc params :latest)]
(if latest-only?
(c/find-latest-concepts db {:provider-id "CMR"} params)
(c/find-concepts db [{:provider-id "CMR"}] params)))))
(defn- find-provider-concepts
"Find concepts with specific parameters"
[context params]
(let [db (db-util/context->db context)
latest-only? (or (true? (:latest params))
(= "true" (:latest params)))
params (dissoc params :latest)
providers (find-providers-for-params context params)]
(when (seq providers)
(if latest-only?
(mapcat #(c/find-latest-concepts db % params) providers)
(c/find-concepts db providers params)))))
(defn find-concepts
"Find concepts with specific parameters"
[context params]
(validate-find-params params)
(cond
(contains? #{:tag
:tag-association
:acl
:humanizer
:variable-association
:service-association
:tool-association
:generic-association}
(:concept-type params))
(find-cmr-concepts context params)
(= :access-group (:concept-type params))
(concat
(find-cmr-concepts context params)
(find-provider-concepts context params))
:else
(find-provider-concepts context params)))
(defn find-associations
"Find associations with specific parameters."
[context params]
(let [db (db-util/context->db context)
latest-only? (or (true? (:latest params))
(= "true" (:latest params)))
params (dissoc params :latest)]
(if latest-only?
(c/find-latest-associations db params)
(c/find-associations db params))))
|
a042c7f66bfb2658600401714220b9865bcbf85e15226a5086b26ce19ff4b535 | lesguillemets/sicp-haskell | 2.28.hs | module TwoTwentyeight where
import TList
fringe :: TList a -> [a]
fringe Nil = []
fringe (V a) = [a]
fringe (Cons p q) = fringe p ++ fringe q
-- |
> > > let x = list [ fromList [ 1,2 ] , fromList [ 3,4 ] ]
-- >>> fringe x
-- [1,2,3,4]
--
-- >>> fringe $ list [x,x]
[ 1,2,3,4,1,2,3,4 ]
| null | https://raw.githubusercontent.com/lesguillemets/sicp-haskell/df524a1e28c45fb16a56f539cad8babc881d0431/exercise/chap02/sect2/2.28.hs | haskell | |
>>> fringe x
[1,2,3,4]
>>> fringe $ list [x,x] | module TwoTwentyeight where
import TList
fringe :: TList a -> [a]
fringe Nil = []
fringe (V a) = [a]
fringe (Cons p q) = fringe p ++ fringe q
> > > let x = list [ fromList [ 1,2 ] , fromList [ 3,4 ] ]
[ 1,2,3,4,1,2,3,4 ]
|
2ea81cdc463a464a671ed014b4c4c8d658e98c819863d3ccca7c10735b8a4591 | tolysz/prepare-ghcjs | Traversable.hs | {-# LANGUAGE DeriveTraversable #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE StandaloneDeriving #
# LANGUAGE Trustworthy #
# LANGUAGE TypeOperators #
-----------------------------------------------------------------------------
-- |
Module : Data .
Copyright : and 2005
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
-- Class of data structures that can be traversed from left to right,
-- performing an action on each element.
--
-- See also
--
-- * \"Applicative Programming with Effects\",
by and ,
/Journal of Functional Programming/ 18:1 ( 2008 ) 1 - 13 , online at
-- </~ross/papers/Applicative.html>.
--
-- * \"The Essence of the Iterator Pattern\",
by and ,
in /Mathematically - Structured Functional Programming/ , 2006 , online at
-- </#iterator>.
--
-- * \"An Investigation of the Laws of Traversals\",
by and ,
in /Mathematically - Structured Functional Programming/ , 2012 , online at
-- <>.
--
-----------------------------------------------------------------------------
module Data.Traversable (
* The ' ' class
Traversable(..),
-- * Utility functions
for,
forM,
mapAccumL,
mapAccumR,
-- * General definitions for superclass methods
fmapDefault,
foldMapDefault,
) where
-- It is convenient to use 'Const' here but this means we must
define a few instances here which really belong in Control . Applicative
import Control.Applicative ( Const(..), ZipList(..) )
import Data.Either ( Either(..) )
import Data.Foldable ( Foldable )
import Data.Functor
import Data.Monoid ( Dual(..), Sum(..), Product(..), First(..), Last(..) )
import Data.Proxy ( Proxy(..) )
import GHC.Arr
import GHC.Base ( Applicative(..), Monad(..), Monoid, Maybe(..),
($), (.), id, flip )
import GHC.Generics
import qualified GHC.List as List ( foldr )
-- | Functors representing data structures that can be traversed from
-- left to right.
--
-- A definition of 'traverse' must satisfy the following laws:
--
-- [/naturality/]
-- @t . 'traverse' f = 'traverse' (t . f)@
-- for every applicative transformation @t@
--
-- [/identity/]
@'traverse ' Identity = Identity@
--
-- [/composition/]
@'traverse ' ( Compose . ' fmap ' g . f ) = Compose . ' fmap ' ( ' traverse ' g ) . ' traverse ' f@
--
-- A definition of 'sequenceA' must satisfy the following laws:
--
-- [/naturality/]
@t . ' sequenceA ' = ' sequenceA ' . ' fmap ' t@
-- for every applicative transformation @t@
--
-- [/identity/]
-- @'sequenceA' . 'fmap' Identity = Identity@
--
-- [/composition/]
-- @'sequenceA' . 'fmap' Compose = Compose . 'fmap' 'sequenceA' . 'sequenceA'@
--
-- where an /applicative transformation/ is a function
--
-- @t :: (Applicative f, Applicative g) => f a -> g a@
--
-- preserving the 'Applicative' operations, i.e.
--
* @t ( ' pure ' x ) = ' pure '
--
-- * @t (x '<*>' y) = t x '<*>' t y@
--
and the identity functor @Identity@ and composition of functors @Compose@
-- are defined as
--
-- > newtype Identity a = Identity a
-- >
> instance Functor Identity where
-- > fmap f (Identity x) = Identity (f x)
-- >
> instance Applicative Identity where
-- > pure x = Identity x
-- > Identity f <*> Identity x = Identity (f x)
-- >
-- > newtype Compose f g a = Compose (f (g a))
-- >
> instance ( Functor f , ) = > Functor ( Compose f g ) where
-- > fmap f (Compose x) = Compose (fmap (fmap f) x)
-- >
-- > instance (Applicative f, Applicative g) => Applicative (Compose f g) where
-- > pure x = Compose (pure (pure x))
-- > Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)
--
-- (The naturality law is implied by parametricity.)
--
-- Instances are similar to 'Functor', e.g. given a data type
--
-- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--
-- a suitable instance would be
--
> instance where
-- > traverse f Empty = pure Empty
-- > traverse f (Leaf x) = Leaf <$> f x
-- > traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
--
-- This is suitable even for abstract types, as the laws for '<*>'
-- imply a form of associativity.
--
-- The superclass instances should satisfy the following:
--
-- * In the 'Functor' instance, 'fmap' should be equivalent to traversal
-- with the identity applicative functor ('fmapDefault').
--
-- * In the 'Foldable' instance, 'Data.Foldable.foldMap' should be
-- equivalent to traversal with a constant applicative functor
-- ('foldMapDefault').
--
class (Functor t, Foldable t) => Traversable t where
# MINIMAL traverse | sequenceA #
-- | Map each element of a structure to an action, evaluate these actions
-- from left to right, and collect the results. For a version that ignores
-- the results see 'Data.Foldable.traverse_'.
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
traverse f = sequenceA . fmap f
-- | Evaluate each action in the structure from left to right, and
-- and collect the results. For a version that ignores the results
-- see 'Data.Foldable.sequenceA_'.
sequenceA :: Applicative f => t (f a) -> f (t a)
sequenceA = traverse id
-- | Map each element of a structure to a monadic action, evaluate
-- these actions from left to right, and collect the results. For
-- a version that ignores the results see 'Data.Foldable.mapM_'.
mapM :: Monad m => (a -> m b) -> t a -> m (t b)
mapM = traverse
-- | Evaluate each monadic action in the structure from left to
-- right, and collect the results. For a version that ignores the
-- results see 'Data.Foldable.sequence_'.
sequence :: Monad m => t (m a) -> m (t a)
sequence = sequenceA
instances for Prelude types
instance Traversable Maybe where
traverse _ Nothing = pure Nothing
traverse f (Just x) = Just <$> f x
instance Traversable [] where
{-# INLINE traverse #-} -- so that traverse can fuse
traverse f = List.foldr cons_f (pure [])
where cons_f x ys = (:) <$> f x <*> ys
instance Traversable (Either a) where
traverse _ (Left x) = pure (Left x)
traverse f (Right y) = Right <$> f y
instance Traversable ((,) a) where
traverse f (x, y) = (,) x <$> f y
instance Ix i => Traversable (Array i) where
traverse f arr = listArray (bounds arr) `fmap` traverse f (elems arr)
instance Traversable Proxy where
traverse _ _ = pure Proxy
{-# INLINE traverse #-}
sequenceA _ = pure Proxy
# INLINE sequenceA #
mapM _ _ = pure Proxy
# INLINE mapM #
sequence _ = pure Proxy
# INLINE sequence #
instance Traversable (Const m) where
traverse _ (Const m) = pure $ Const m
instance Traversable Dual where
traverse f (Dual x) = Dual <$> f x
instance Traversable Sum where
traverse f (Sum x) = Sum <$> f x
instance Traversable Product where
traverse f (Product x) = Product <$> f x
instance Traversable First where
traverse f (First x) = First <$> traverse f x
instance Traversable Last where
traverse f (Last x) = Last <$> traverse f x
instance Traversable ZipList where
traverse f (ZipList x) = ZipList <$> traverse f x
-- Instances for GHC.Generics
instance Traversable U1 where
traverse _ _ = pure U1
{-# INLINE traverse #-}
sequenceA _ = pure U1
# INLINE sequenceA #
mapM _ _ = pure U1
# INLINE mapM #
sequence _ = pure U1
# INLINE sequence #
deriving instance Traversable V1
deriving instance Traversable Par1
deriving instance Traversable f => Traversable (Rec1 f)
deriving instance Traversable (K1 i c)
deriving instance Traversable f => Traversable (M1 i c f)
deriving instance (Traversable f, Traversable g) => Traversable (f :+: g)
deriving instance (Traversable f, Traversable g) => Traversable (f :*: g)
deriving instance (Traversable f, Traversable g) => Traversable (f :.: g)
deriving instance Traversable UAddr
deriving instance Traversable UChar
deriving instance Traversable UDouble
deriving instance Traversable UFloat
deriving instance Traversable UInt
deriving instance Traversable UWord
-- general functions
-- | 'for' is 'traverse' with its arguments flipped. For a version
-- that ignores the results see 'Data.Foldable.for_'.
for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
{-# INLINE for #-}
for = flip traverse
-- | 'forM' is 'mapM' with its arguments flipped. For a version that
-- ignores the results see 'Data.Foldable.forM_'.
forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
# INLINE forM #
forM = flip mapM
-- left-to-right state transformer
newtype StateL s a = StateL { runStateL :: s -> (s, a) }
instance Functor (StateL s) where
fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v)
instance Applicative (StateL s) where
pure x = StateL (\ s -> (s, x))
StateL kf <*> StateL kv = StateL $ \ s ->
let (s', f) = kf s
(s'', v) = kv s'
in (s'', f v)
-- |The 'mapAccumL' function behaves like a combination of 'fmap'
-- and 'foldl'; it applies a function to each element of a structure,
-- passing an accumulating parameter from left to right, and returning
-- a final value of this accumulator together with the new structure.
mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
mapAccumL f s t = runStateL (traverse (StateL . flip f) t) s
-- right-to-left state transformer
newtype StateR s a = StateR { runStateR :: s -> (s, a) }
instance Functor (StateR s) where
fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v)
instance Applicative (StateR s) where
pure x = StateR (\ s -> (s, x))
StateR kf <*> StateR kv = StateR $ \ s ->
let (s', v) = kv s
(s'', f) = kf s'
in (s'', f v)
-- |The 'mapAccumR' function behaves like a combination of 'fmap'
-- and 'foldr'; it applies a function to each element of a structure,
-- passing an accumulating parameter from right to left, and returning
-- a final value of this accumulator together with the new structure.
mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
mapAccumR f s t = runStateR (traverse (StateR . flip f) t) s
-- | This function may be used as a value for `fmap` in a `Functor`
-- instance, provided that 'traverse' is defined. (Using
` fmapDefault ` with a ` ` instance defined only by
-- 'sequenceA' will result in infinite recursion.)
fmapDefault :: Traversable t => (a -> b) -> t a -> t b
# INLINE fmapDefault #
fmapDefault f = getId . traverse (Id . f)
-- | This function may be used as a value for `Data.Foldable.foldMap`
-- in a `Foldable` instance.
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m
foldMapDefault f = getConst . traverse (Const . f)
-- local instances
newtype Id a = Id { getId :: a }
instance Functor Id where
fmap f (Id x) = Id (f x)
instance Applicative Id where
pure = Id
Id f <*> Id x = Id (f x)
| null | https://raw.githubusercontent.com/tolysz/prepare-ghcjs/8499e14e27854a366e98f89fab0af355056cf055/spec-lts8/base-pure/Data/Traversable.hs | haskell | # LANGUAGE DeriveTraversable #
---------------------------------------------------------------------------
|
License : BSD-style (see the LICENSE file in the distribution)
Maintainer :
Stability : experimental
Portability : portable
Class of data structures that can be traversed from left to right,
performing an action on each element.
See also
* \"Applicative Programming with Effects\",
</~ross/papers/Applicative.html>.
* \"The Essence of the Iterator Pattern\",
</#iterator>.
* \"An Investigation of the Laws of Traversals\",
<>.
---------------------------------------------------------------------------
* Utility functions
* General definitions for superclass methods
It is convenient to use 'Const' here but this means we must
| Functors representing data structures that can be traversed from
left to right.
A definition of 'traverse' must satisfy the following laws:
[/naturality/]
@t . 'traverse' f = 'traverse' (t . f)@
for every applicative transformation @t@
[/identity/]
[/composition/]
A definition of 'sequenceA' must satisfy the following laws:
[/naturality/]
for every applicative transformation @t@
[/identity/]
@'sequenceA' . 'fmap' Identity = Identity@
[/composition/]
@'sequenceA' . 'fmap' Compose = Compose . 'fmap' 'sequenceA' . 'sequenceA'@
where an /applicative transformation/ is a function
@t :: (Applicative f, Applicative g) => f a -> g a@
preserving the 'Applicative' operations, i.e.
* @t (x '<*>' y) = t x '<*>' t y@
are defined as
> newtype Identity a = Identity a
>
> fmap f (Identity x) = Identity (f x)
>
> pure x = Identity x
> Identity f <*> Identity x = Identity (f x)
>
> newtype Compose f g a = Compose (f (g a))
>
> fmap f (Compose x) = Compose (fmap (fmap f) x)
>
> instance (Applicative f, Applicative g) => Applicative (Compose f g) where
> pure x = Compose (pure (pure x))
> Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)
(The naturality law is implied by parametricity.)
Instances are similar to 'Functor', e.g. given a data type
> data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
a suitable instance would be
> traverse f Empty = pure Empty
> traverse f (Leaf x) = Leaf <$> f x
> traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
This is suitable even for abstract types, as the laws for '<*>'
imply a form of associativity.
The superclass instances should satisfy the following:
* In the 'Functor' instance, 'fmap' should be equivalent to traversal
with the identity applicative functor ('fmapDefault').
* In the 'Foldable' instance, 'Data.Foldable.foldMap' should be
equivalent to traversal with a constant applicative functor
('foldMapDefault').
| Map each element of a structure to an action, evaluate these actions
from left to right, and collect the results. For a version that ignores
the results see 'Data.Foldable.traverse_'.
| Evaluate each action in the structure from left to right, and
and collect the results. For a version that ignores the results
see 'Data.Foldable.sequenceA_'.
| Map each element of a structure to a monadic action, evaluate
these actions from left to right, and collect the results. For
a version that ignores the results see 'Data.Foldable.mapM_'.
| Evaluate each monadic action in the structure from left to
right, and collect the results. For a version that ignores the
results see 'Data.Foldable.sequence_'.
# INLINE traverse #
so that traverse can fuse
# INLINE traverse #
Instances for GHC.Generics
# INLINE traverse #
general functions
| 'for' is 'traverse' with its arguments flipped. For a version
that ignores the results see 'Data.Foldable.for_'.
# INLINE for #
| 'forM' is 'mapM' with its arguments flipped. For a version that
ignores the results see 'Data.Foldable.forM_'.
left-to-right state transformer
|The 'mapAccumL' function behaves like a combination of 'fmap'
and 'foldl'; it applies a function to each element of a structure,
passing an accumulating parameter from left to right, and returning
a final value of this accumulator together with the new structure.
right-to-left state transformer
|The 'mapAccumR' function behaves like a combination of 'fmap'
and 'foldr'; it applies a function to each element of a structure,
passing an accumulating parameter from right to left, and returning
a final value of this accumulator together with the new structure.
| This function may be used as a value for `fmap` in a `Functor`
instance, provided that 'traverse' is defined. (Using
'sequenceA' will result in infinite recursion.)
| This function may be used as a value for `Data.Foldable.foldMap`
in a `Foldable` instance.
local instances | # LANGUAGE FlexibleInstances #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE StandaloneDeriving #
# LANGUAGE Trustworthy #
# LANGUAGE TypeOperators #
Module : Data .
Copyright : and 2005
by and ,
/Journal of Functional Programming/ 18:1 ( 2008 ) 1 - 13 , online at
by and ,
in /Mathematically - Structured Functional Programming/ , 2006 , online at
by and ,
in /Mathematically - Structured Functional Programming/ , 2012 , online at
module Data.Traversable (
* The ' ' class
Traversable(..),
for,
forM,
mapAccumL,
mapAccumR,
fmapDefault,
foldMapDefault,
) where
define a few instances here which really belong in Control . Applicative
import Control.Applicative ( Const(..), ZipList(..) )
import Data.Either ( Either(..) )
import Data.Foldable ( Foldable )
import Data.Functor
import Data.Monoid ( Dual(..), Sum(..), Product(..), First(..), Last(..) )
import Data.Proxy ( Proxy(..) )
import GHC.Arr
import GHC.Base ( Applicative(..), Monad(..), Monoid, Maybe(..),
($), (.), id, flip )
import GHC.Generics
import qualified GHC.List as List ( foldr )
@'traverse ' Identity = Identity@
@'traverse ' ( Compose . ' fmap ' g . f ) = Compose . ' fmap ' ( ' traverse ' g ) . ' traverse ' f@
@t . ' sequenceA ' = ' sequenceA ' . ' fmap ' t@
* @t ( ' pure ' x ) = ' pure '
and the identity functor @Identity@ and composition of functors @Compose@
> instance Functor Identity where
> instance Applicative Identity where
> instance ( Functor f , ) = > Functor ( Compose f g ) where
> instance where
class (Functor t, Foldable t) => Traversable t where
# MINIMAL traverse | sequenceA #
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
traverse f = sequenceA . fmap f
sequenceA :: Applicative f => t (f a) -> f (t a)
sequenceA = traverse id
mapM :: Monad m => (a -> m b) -> t a -> m (t b)
mapM = traverse
sequence :: Monad m => t (m a) -> m (t a)
sequence = sequenceA
instances for Prelude types
instance Traversable Maybe where
traverse _ Nothing = pure Nothing
traverse f (Just x) = Just <$> f x
instance Traversable [] where
traverse f = List.foldr cons_f (pure [])
where cons_f x ys = (:) <$> f x <*> ys
instance Traversable (Either a) where
traverse _ (Left x) = pure (Left x)
traverse f (Right y) = Right <$> f y
instance Traversable ((,) a) where
traverse f (x, y) = (,) x <$> f y
instance Ix i => Traversable (Array i) where
traverse f arr = listArray (bounds arr) `fmap` traverse f (elems arr)
instance Traversable Proxy where
traverse _ _ = pure Proxy
sequenceA _ = pure Proxy
# INLINE sequenceA #
mapM _ _ = pure Proxy
# INLINE mapM #
sequence _ = pure Proxy
# INLINE sequence #
instance Traversable (Const m) where
traverse _ (Const m) = pure $ Const m
instance Traversable Dual where
traverse f (Dual x) = Dual <$> f x
instance Traversable Sum where
traverse f (Sum x) = Sum <$> f x
instance Traversable Product where
traverse f (Product x) = Product <$> f x
instance Traversable First where
traverse f (First x) = First <$> traverse f x
instance Traversable Last where
traverse f (Last x) = Last <$> traverse f x
instance Traversable ZipList where
traverse f (ZipList x) = ZipList <$> traverse f x
instance Traversable U1 where
traverse _ _ = pure U1
sequenceA _ = pure U1
# INLINE sequenceA #
mapM _ _ = pure U1
# INLINE mapM #
sequence _ = pure U1
# INLINE sequence #
deriving instance Traversable V1
deriving instance Traversable Par1
deriving instance Traversable f => Traversable (Rec1 f)
deriving instance Traversable (K1 i c)
deriving instance Traversable f => Traversable (M1 i c f)
deriving instance (Traversable f, Traversable g) => Traversable (f :+: g)
deriving instance (Traversable f, Traversable g) => Traversable (f :*: g)
deriving instance (Traversable f, Traversable g) => Traversable (f :.: g)
deriving instance Traversable UAddr
deriving instance Traversable UChar
deriving instance Traversable UDouble
deriving instance Traversable UFloat
deriving instance Traversable UInt
deriving instance Traversable UWord
for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
for = flip traverse
forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
# INLINE forM #
forM = flip mapM
newtype StateL s a = StateL { runStateL :: s -> (s, a) }
instance Functor (StateL s) where
fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v)
instance Applicative (StateL s) where
pure x = StateL (\ s -> (s, x))
StateL kf <*> StateL kv = StateL $ \ s ->
let (s', f) = kf s
(s'', v) = kv s'
in (s'', f v)
mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
mapAccumL f s t = runStateL (traverse (StateL . flip f) t) s
newtype StateR s a = StateR { runStateR :: s -> (s, a) }
instance Functor (StateR s) where
fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v)
instance Applicative (StateR s) where
pure x = StateR (\ s -> (s, x))
StateR kf <*> StateR kv = StateR $ \ s ->
let (s', v) = kv s
(s'', f) = kf s'
in (s'', f v)
mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
mapAccumR f s t = runStateR (traverse (StateR . flip f) t) s
` fmapDefault ` with a ` ` instance defined only by
fmapDefault :: Traversable t => (a -> b) -> t a -> t b
# INLINE fmapDefault #
fmapDefault f = getId . traverse (Id . f)
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m
foldMapDefault f = getConst . traverse (Const . f)
newtype Id a = Id { getId :: a }
instance Functor Id where
fmap f (Id x) = Id (f x)
instance Applicative Id where
pure = Id
Id f <*> Id x = Id (f x)
|
1232729714ceed7712595b8f0d90a346a36a418ce69eb6a22c05fa2c0c3264b4 | r0man/netcdf-clj | location_test.clj | (ns netcdf.location-test
(:import (ucar.unidata.geoloc LatLonPointImpl LatLonPoint))
(:use clojure.test
netcdf.location))
(def berlin (make-location 52.523 13.411))
(def paris (make-location 48.857 2.351))
(def vienna (make-location 48.209 16.373))
(deftest test-to-location
(testing "LatLonPoint"
(let [location (to-location (LatLonPointImpl. 52.523 13.411))]
(instance? LatLonPoint location)
(is (= 52.523 (.getLatitude location)))
(is (= 13.411 (.getLongitude location)))))
(testing "hash map"
(let [location (to-location {:latitude 52.523 :longitude 13.411})]
(instance? LatLonPoint location)
(is (= 52.523 (.getLatitude location)))
(is (= 13.411 (.getLongitude location)))))
(testing "string"
(let [location (to-location "52.523,13.411")]
(instance? LatLonPoint location)
(is (= 52.523 (.getLatitude location)))
(is (= 13.411 (.getLongitude location))))))
(deftest test-make-location
(let [location (make-location 52.523 13.411)]
(is (= (latitude location) 52.523))
(is (= (longitude location) 13.411)))
(let [location (make-location {:latitude 52.523 :longitude 13.411})]
(is (= (latitude location) 52.523))
(is (= (longitude location) 13.411)))
(let [location (make-location "52.523" "13.411")]
(is (= (latitude location) 52.523))
(is (= (longitude location) 13.411))))
(deftest test-location?
(is (location? (make-location 1 2)))
(is (not (location? nil))))
(deftest test-parse-latitude
(are [longitude]
(is (thrown? IllegalArgumentException (parse-latitude latitude)))
nil "" "x")
(are [latitude expected]
(is (= expected (parse-latitude latitude :junk-allowed true)))
nil nil
"" nil
"1" 1.0
"1.0" 1.0
1 1))
(deftest test-parse-longitude
(are [longitude]
(is (thrown? IllegalArgumentException (parse-longitude longitude)))
nil "" "x")
(are [longitude expected]
(is (= expected (parse-longitude longitude :junk-allowed true)))
nil nil
"" nil
"1" 1.0
"1.0" 1.0
1 1))
(deftest test-parse-location
(are [location]
(is (thrown? IllegalArgumentException (parse-location location)))
nil "" "x")
(let [location (parse-location "52.52,13.41")]
(is (= (latitude location) 52.52))
(is (= (longitude location) 13.41)))
(let [location (parse-location "52.52;13.41")]
(is (= (latitude location) 52.52))
(is (= (longitude location) 13.41)))
(let [location (parse-location "52.52\t13.41")]
(is (= (latitude location) 52.52))
(is (= (longitude location) 13.41)))
(let [location (parse-location "51° 28' 40.12\" N, 000° 00' 0.531\" W")]
(is (= (latitude location) 51.57811111111111))
(is (= (longitude location) -0.0014750000000000002))))
;; (deftest test-destination-point
;; (let [location (destination-point berlin 30 100)]
( is (= ( latitude location ) 53.298866294161215 ) )
( is (= ( longitude location ) 14.16092284183496 ) ) ) )
(deftest test-distance
(is (= 0.0 (distance berlin berlin)))
(is (= 880.2565917803378 (distance berlin paris))))
(deftest test-north?
(is (north? berlin paris))
(is (north? paris vienna))
(is (not (north? berlin berlin)))
(is (not (north? (make-location (dec (latitude berlin)) (longitude berlin)) berlin)))
(is (north? (make-location (inc (latitude berlin)) (longitude berlin)) berlin)))
(deftest test-east?
(is (east? berlin paris))
(is (east? vienna berlin))
(is (not (east? berlin berlin)))
(is (not (east? (make-location (latitude berlin) (dec (longitude berlin))) berlin)))
(is (east? (make-location (latitude berlin) (inc (longitude berlin))) berlin)))
(deftest test-south?
(is (south? paris berlin))
(is (south? vienna berlin))
(is (not (south? berlin berlin)))
(is (not (south? (make-location (inc (latitude berlin)) (longitude berlin)) berlin)))
(is (south? (make-location (dec (latitude berlin)) (longitude berlin)) berlin)))
(deftest test-west?
(is (west? paris berlin))
(is (west? paris vienna ))
(is (not (west? berlin berlin)))
(is (not (west? (make-location (latitude berlin) (inc (longitude berlin))) berlin)))
(is (west? (make-location (latitude berlin) (dec (longitude berlin))) berlin)))
(deftest test-north-east?
(is (north-east? berlin paris))
(is (not (north-east? paris berlin)))
(is (not (north-east? berlin berlin))))
(deftest test-south-east?
(is (south-east? vienna berlin))
(is (not (south-east? berlin vienna)))
(is (not (south-east? berlin berlin))))
(deftest test-south-west?
(is (south-west? paris berlin))
(is (not (south-west? berlin paris)))
(is (not (south-west? vienna berlin))))
(deftest test-north-west?
(is (north-west? paris vienna))
(is (not (north-west? vienna paris)))
(is (not (north-west? paris paris))))
(deftest test-latitude-distance
(is (= (latitude-distance berlin berlin) 0.0))
(is (= (latitude-distance berlin paris) -3.666000000000004))
(is (= (latitude-distance paris berlin) 3.666000000000004)))
(deftest test-longitude-distance
(is (= (longitude-distance berlin berlin) 0.0))
(is (= (longitude-distance berlin paris) -11.059999999999999))
(is (= (longitude-distance paris berlin ) 11.059999999999999)))
(deftest test-latitude-range
(is (empty? (latitude-range 0 0)))
(is (= (latitude-range 0 1) [0]))
(is (= (latitude-range 0 1 0.5) [0.0]))
(let [range (latitude-range 0 90)]
(is (= (count range) 90))
(is (= (first range) -89))
(is (= (last range) 0))))
(deftest test-longitude-range
(is (empty? (longitude-range 0 0)))
(is (= (longitude-range 0 1) [0]))
(is (= (longitude-range 0 1 0.5) [0]))
(let [range (longitude-range 0 180)]
(is (= (count range) 180))
(is (= (first range) 0))
(is (= (last range) 179))))
(deftest test-location-range
(is (empty? (location-range (make-location 0 0) (make-location 0 0))))
(is (= (location-range (make-location 0 0) (make-location 1 1))
[(make-location 0 0)]))
(is (= (location-range (make-location 0 0) (make-location 1 1) :lat-step 0.5)
[(make-location 0 0)]))
(is (= (location-range (make-location 0 0) (make-location 1 1) :lon-step 0.5)
[(make-location 0 0)]))
(is (= (location-range (make-location 0 0) (make-location 2 1) :lon-step 0.5)
[(make-location -1 0) (make-location 0 0)]))
(let [range (location-range (make-location 0 0) (make-location 2 2))]
(is (= (count range) 4))
(is (= (first range) (make-location -1 0)))
(is (= (nth range 1) (make-location -1 1)))
(is (= (nth range 2) (make-location 0 0)))
(is (= (last range) (make-location 0 1)))))
(deftest test-location->array
(is (= (location->array (make-location 78 0)) [78.0 0.0])))
(deftest test-location-rect
(is (empty? (location-rect (make-location 0 0) :width 0)))
(is (empty? (location-rect (make-location 0 0) :height 0)))
(is (= (location-rect (make-location 0 0)) [(make-location 0 0)]))
(is (= (location-rect (make-location 0 0) :width 2)
[(make-location 0 0) (make-location 0 1) (make-location -1 0) (make-location -1 1)]))
(is (= (location-rect (make-location 0 0) :width 2 :height 1)
[(make-location 0 0) (make-location 0 1)])))
(deftest test-location->map
(is (= {:latitude 1.0 :longitude 2.0}
(location->map (make-location 1 2)))))
(deftest test-parse-dms
(are [string result]
(is (= (parse-dms string) result))
"51° 28' 40.12\" n" 51.57811111111111
"51° 28' 40.12\" N" 51.57811111111111
"000° 00' 0.531\" w" -0.0014750000000000002
"000° 00' 0.531\" W" -0.0014750000000000002
"8° 44.707' S" -8.745116666666666
"115° 9.019' E" 115.15031666666667))
(deftest test-print-method
(is (= {:latitude 1.0 :longitude 2.0}
(read-string (prn-str (make-location 1 2)))))
(is (= {:latitude 1.1 :longitude 2.2}
(read-string (prn-str (make-location 1.1 2.2))))))
| null | https://raw.githubusercontent.com/r0man/netcdf-clj/90f40ab958d3ebc16a4fcfc882c9cd7ef469d054/test/netcdf/location_test.clj | clojure | (deftest test-destination-point
(let [location (destination-point berlin 30 100)] | (ns netcdf.location-test
(:import (ucar.unidata.geoloc LatLonPointImpl LatLonPoint))
(:use clojure.test
netcdf.location))
(def berlin (make-location 52.523 13.411))
(def paris (make-location 48.857 2.351))
(def vienna (make-location 48.209 16.373))
(deftest test-to-location
(testing "LatLonPoint"
(let [location (to-location (LatLonPointImpl. 52.523 13.411))]
(instance? LatLonPoint location)
(is (= 52.523 (.getLatitude location)))
(is (= 13.411 (.getLongitude location)))))
(testing "hash map"
(let [location (to-location {:latitude 52.523 :longitude 13.411})]
(instance? LatLonPoint location)
(is (= 52.523 (.getLatitude location)))
(is (= 13.411 (.getLongitude location)))))
(testing "string"
(let [location (to-location "52.523,13.411")]
(instance? LatLonPoint location)
(is (= 52.523 (.getLatitude location)))
(is (= 13.411 (.getLongitude location))))))
(deftest test-make-location
(let [location (make-location 52.523 13.411)]
(is (= (latitude location) 52.523))
(is (= (longitude location) 13.411)))
(let [location (make-location {:latitude 52.523 :longitude 13.411})]
(is (= (latitude location) 52.523))
(is (= (longitude location) 13.411)))
(let [location (make-location "52.523" "13.411")]
(is (= (latitude location) 52.523))
(is (= (longitude location) 13.411))))
(deftest test-location?
(is (location? (make-location 1 2)))
(is (not (location? nil))))
(deftest test-parse-latitude
(are [longitude]
(is (thrown? IllegalArgumentException (parse-latitude latitude)))
nil "" "x")
(are [latitude expected]
(is (= expected (parse-latitude latitude :junk-allowed true)))
nil nil
"" nil
"1" 1.0
"1.0" 1.0
1 1))
(deftest test-parse-longitude
(are [longitude]
(is (thrown? IllegalArgumentException (parse-longitude longitude)))
nil "" "x")
(are [longitude expected]
(is (= expected (parse-longitude longitude :junk-allowed true)))
nil nil
"" nil
"1" 1.0
"1.0" 1.0
1 1))
(deftest test-parse-location
(are [location]
(is (thrown? IllegalArgumentException (parse-location location)))
nil "" "x")
(let [location (parse-location "52.52,13.41")]
(is (= (latitude location) 52.52))
(is (= (longitude location) 13.41)))
(let [location (parse-location "52.52;13.41")]
(is (= (latitude location) 52.52))
(is (= (longitude location) 13.41)))
(let [location (parse-location "52.52\t13.41")]
(is (= (latitude location) 52.52))
(is (= (longitude location) 13.41)))
(let [location (parse-location "51° 28' 40.12\" N, 000° 00' 0.531\" W")]
(is (= (latitude location) 51.57811111111111))
(is (= (longitude location) -0.0014750000000000002))))
( is (= ( latitude location ) 53.298866294161215 ) )
( is (= ( longitude location ) 14.16092284183496 ) ) ) )
(deftest test-distance
(is (= 0.0 (distance berlin berlin)))
(is (= 880.2565917803378 (distance berlin paris))))
(deftest test-north?
(is (north? berlin paris))
(is (north? paris vienna))
(is (not (north? berlin berlin)))
(is (not (north? (make-location (dec (latitude berlin)) (longitude berlin)) berlin)))
(is (north? (make-location (inc (latitude berlin)) (longitude berlin)) berlin)))
(deftest test-east?
(is (east? berlin paris))
(is (east? vienna berlin))
(is (not (east? berlin berlin)))
(is (not (east? (make-location (latitude berlin) (dec (longitude berlin))) berlin)))
(is (east? (make-location (latitude berlin) (inc (longitude berlin))) berlin)))
(deftest test-south?
(is (south? paris berlin))
(is (south? vienna berlin))
(is (not (south? berlin berlin)))
(is (not (south? (make-location (inc (latitude berlin)) (longitude berlin)) berlin)))
(is (south? (make-location (dec (latitude berlin)) (longitude berlin)) berlin)))
(deftest test-west?
(is (west? paris berlin))
(is (west? paris vienna ))
(is (not (west? berlin berlin)))
(is (not (west? (make-location (latitude berlin) (inc (longitude berlin))) berlin)))
(is (west? (make-location (latitude berlin) (dec (longitude berlin))) berlin)))
(deftest test-north-east?
(is (north-east? berlin paris))
(is (not (north-east? paris berlin)))
(is (not (north-east? berlin berlin))))
(deftest test-south-east?
(is (south-east? vienna berlin))
(is (not (south-east? berlin vienna)))
(is (not (south-east? berlin berlin))))
(deftest test-south-west?
(is (south-west? paris berlin))
(is (not (south-west? berlin paris)))
(is (not (south-west? vienna berlin))))
(deftest test-north-west?
(is (north-west? paris vienna))
(is (not (north-west? vienna paris)))
(is (not (north-west? paris paris))))
(deftest test-latitude-distance
(is (= (latitude-distance berlin berlin) 0.0))
(is (= (latitude-distance berlin paris) -3.666000000000004))
(is (= (latitude-distance paris berlin) 3.666000000000004)))
(deftest test-longitude-distance
(is (= (longitude-distance berlin berlin) 0.0))
(is (= (longitude-distance berlin paris) -11.059999999999999))
(is (= (longitude-distance paris berlin ) 11.059999999999999)))
(deftest test-latitude-range
(is (empty? (latitude-range 0 0)))
(is (= (latitude-range 0 1) [0]))
(is (= (latitude-range 0 1 0.5) [0.0]))
(let [range (latitude-range 0 90)]
(is (= (count range) 90))
(is (= (first range) -89))
(is (= (last range) 0))))
(deftest test-longitude-range
(is (empty? (longitude-range 0 0)))
(is (= (longitude-range 0 1) [0]))
(is (= (longitude-range 0 1 0.5) [0]))
(let [range (longitude-range 0 180)]
(is (= (count range) 180))
(is (= (first range) 0))
(is (= (last range) 179))))
(deftest test-location-range
(is (empty? (location-range (make-location 0 0) (make-location 0 0))))
(is (= (location-range (make-location 0 0) (make-location 1 1))
[(make-location 0 0)]))
(is (= (location-range (make-location 0 0) (make-location 1 1) :lat-step 0.5)
[(make-location 0 0)]))
(is (= (location-range (make-location 0 0) (make-location 1 1) :lon-step 0.5)
[(make-location 0 0)]))
(is (= (location-range (make-location 0 0) (make-location 2 1) :lon-step 0.5)
[(make-location -1 0) (make-location 0 0)]))
(let [range (location-range (make-location 0 0) (make-location 2 2))]
(is (= (count range) 4))
(is (= (first range) (make-location -1 0)))
(is (= (nth range 1) (make-location -1 1)))
(is (= (nth range 2) (make-location 0 0)))
(is (= (last range) (make-location 0 1)))))
(deftest test-location->array
(is (= (location->array (make-location 78 0)) [78.0 0.0])))
(deftest test-location-rect
(is (empty? (location-rect (make-location 0 0) :width 0)))
(is (empty? (location-rect (make-location 0 0) :height 0)))
(is (= (location-rect (make-location 0 0)) [(make-location 0 0)]))
(is (= (location-rect (make-location 0 0) :width 2)
[(make-location 0 0) (make-location 0 1) (make-location -1 0) (make-location -1 1)]))
(is (= (location-rect (make-location 0 0) :width 2 :height 1)
[(make-location 0 0) (make-location 0 1)])))
(deftest test-location->map
(is (= {:latitude 1.0 :longitude 2.0}
(location->map (make-location 1 2)))))
(deftest test-parse-dms
(are [string result]
(is (= (parse-dms string) result))
"51° 28' 40.12\" n" 51.57811111111111
"51° 28' 40.12\" N" 51.57811111111111
"000° 00' 0.531\" w" -0.0014750000000000002
"000° 00' 0.531\" W" -0.0014750000000000002
"8° 44.707' S" -8.745116666666666
"115° 9.019' E" 115.15031666666667))
(deftest test-print-method
(is (= {:latitude 1.0 :longitude 2.0}
(read-string (prn-str (make-location 1 2)))))
(is (= {:latitude 1.1 :longitude 2.2}
(read-string (prn-str (make-location 1.1 2.2))))))
|
1da3856817e5eb00e3d8dcbccb2a6b6d66601f66674d2e3177dd26b27eb8975b | sulami/spielwiese | Set3.hs | # LANGUAGE MonadComprehensions #
# LANGUAGE RebindableSyntax #
module Set3 where
import MCPrelude
301
allPairs :: [a] -> [b] -> [(a,b)]
allPairs l0 l1 = concatMap (\e -> zip (repeat e) l1) l0
302
data Card = Card Int String
instance Show Card where
show (Card x y) = show x ++ y
allCards :: [Int] -> [String] -> [Card]
allCards rs ss = concatMap (\r -> map (Card r) ss) rs
303
allPerms :: (a -> b -> c) -> [a] -> [b] -> [c]
allPerms fn l0 l1 = concatMap (\e -> map (fn e) l1) l0
allPairs2 :: [a] -> [b] -> [(a,b)]
allPairs2 = allPerms (,)
allCards2 :: [Int] -> [String] -> [Card]
allCards2 = allPerms Card
304
allPerms3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
allPerms3 fn l0 l1 l2 = concatMap (\e0 ->
concatMap (\e1 ->
map (fn e0 e1) l2
) l1
) l0
305
permStep :: [a -> b] -> [a] -> [b]
permStep fns xs = concatMap (`map` xs) fns
ap :: (a -> b -> c) -> [a] -> [b] -> [c]
ap fn = permStep . map fn
ap3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
ap3 fn l0 = permStep . ap fn l0
ap4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]
ap4 fn l0 l1 = permStep . ap3 fn l0 l1
| null | https://raw.githubusercontent.com/sulami/spielwiese/da354aa112d43d7ec5f258f4b5afafd7a88c8aa8/mc/Set3.hs | haskell | # LANGUAGE MonadComprehensions #
# LANGUAGE RebindableSyntax #
module Set3 where
import MCPrelude
301
allPairs :: [a] -> [b] -> [(a,b)]
allPairs l0 l1 = concatMap (\e -> zip (repeat e) l1) l0
302
data Card = Card Int String
instance Show Card where
show (Card x y) = show x ++ y
allCards :: [Int] -> [String] -> [Card]
allCards rs ss = concatMap (\r -> map (Card r) ss) rs
303
allPerms :: (a -> b -> c) -> [a] -> [b] -> [c]
allPerms fn l0 l1 = concatMap (\e -> map (fn e) l1) l0
allPairs2 :: [a] -> [b] -> [(a,b)]
allPairs2 = allPerms (,)
allCards2 :: [Int] -> [String] -> [Card]
allCards2 = allPerms Card
304
allPerms3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
allPerms3 fn l0 l1 l2 = concatMap (\e0 ->
concatMap (\e1 ->
map (fn e0 e1) l2
) l1
) l0
305
permStep :: [a -> b] -> [a] -> [b]
permStep fns xs = concatMap (`map` xs) fns
ap :: (a -> b -> c) -> [a] -> [b] -> [c]
ap fn = permStep . map fn
ap3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
ap3 fn l0 = permStep . ap fn l0
ap4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]
ap4 fn l0 l1 = permStep . ap3 fn l0 l1
|
|
4b7f27416aa3266ecfeccb3d655405684bbf50d77d7844c33a1dc18de3945342 | pavlobaron/ErlangOTPBookSamples | wk_build.erl | -module(wk_build).
-export([all/0, compile/0, dialyzer/0, test1/0, test2/0, doc/0]).
all() ->
compile(),
dialyzer(),
test1(),
test2(),
doc(),
cprof(),
% perf_kursinfo1(),
% perf_kursinfo2(),
cover().
files() ->
["wechselkurs_server.erl" ,
"wechselkurs_client.erl",
"wechselkurs_client_rpc.erl",
"wechselkurs_worker.erl",
"wechselkurs_tests.erl",
"wechselkurs_more_tests.erl",
"wechselkurs_db.erl"].
doc_files() ->
["wechselkurs_server.erl" ,
"wechselkurs_worker.erl",
"wechselkurs_db.erl"].
compile() ->
io:format("COMPILE MODULES ...\n"),
lists:foreach(fun(File) -> c:c(File, [debug_info]), io:format("Module ~p compiled \n", [File]) end, files()),
io:format("...\n\n\n").
dialyzer() ->
os:cmd("dialyzer --src -r .").
test1() ->
io:format("RUN TESTS ...\n"),
eunit:test(wechselkurs_tests, [verbose]),
io:format("...\n\n\n").
test2() ->
io:format("RUN MORE TESTS ...\n"),
wechselkurs_server:start(),
eunit:test(wechselkurs_more_tests, [verbose]),
wechselkurs_server:stop(),
io:format("...\n\n\n").
doc() ->
io:format("CREATE DOCS ...\n"),
edoc:files(doc_files(), [{dir, "../doc"}, {todo, true}]),
io:format("...\n\n\n").
perf_kursinfo1() ->
io:format("FPROF ...\n"),
wechselkurs_server:start(),
fprof:trace(start),
wechselkurs_client:kursinfo(),
fprof:trace(stop),
wechselkurs_server:stop(),
fprof:profile(),
fprof:analyse(),
io:format("...\n\n\n").
perf_kursinfo2() ->
io:format("FPROF ...\n"),
wechselkurs_server:start(),
[ fprof:apply(wechselkurs_client, kursinfo, []) || _P <- lists:seq(1,50)],
wechselkurs_server:stop(),
fprof:profile(),
fprof:analyse(),
io:format("...\n\n\n").
cprof() ->
io:format("CPROF ...\n"),
wechselkurs_server:start(),
cprof:start(wechselkurs_server, kursinfo, 3),
[ wechselkurs_client:kursinfo() || _P <- lists:seq(1,50)],
cprof:pause(),
Result=cprof:analyse(wechselkurs_server),
cprof:stop(),
wechselkurs_server:stop(),
io:format("~p \n", [Result]),
io:format("...\n\n\n").
cover() ->
io:format("COVER ... \n"),
cover:start(),
cover:compile(wechselkurs_server),
wechselkurs_server:start(),
[ wechselkurs_client:kursinfo() || _P <- lists:seq(1,10)],
[ wechselkurs_client:umrechnung() || _P <- lists:seq(1,10)],
cover:analyse_to_file(wechselkurs_server),
wechselkurs_server:stop(),
cover:stop(),
io:format("...\n\n\n").
| null | https://raw.githubusercontent.com/pavlobaron/ErlangOTPBookSamples/50094964ad814932760174914490e49618b2b8c2/entwicklung/chapex/src/wk_build.erl | erlang | perf_kursinfo1(),
perf_kursinfo2(),
| -module(wk_build).
-export([all/0, compile/0, dialyzer/0, test1/0, test2/0, doc/0]).
all() ->
compile(),
dialyzer(),
test1(),
test2(),
doc(),
cprof(),
cover().
files() ->
["wechselkurs_server.erl" ,
"wechselkurs_client.erl",
"wechselkurs_client_rpc.erl",
"wechselkurs_worker.erl",
"wechselkurs_tests.erl",
"wechselkurs_more_tests.erl",
"wechselkurs_db.erl"].
doc_files() ->
["wechselkurs_server.erl" ,
"wechselkurs_worker.erl",
"wechselkurs_db.erl"].
compile() ->
io:format("COMPILE MODULES ...\n"),
lists:foreach(fun(File) -> c:c(File, [debug_info]), io:format("Module ~p compiled \n", [File]) end, files()),
io:format("...\n\n\n").
dialyzer() ->
os:cmd("dialyzer --src -r .").
test1() ->
io:format("RUN TESTS ...\n"),
eunit:test(wechselkurs_tests, [verbose]),
io:format("...\n\n\n").
test2() ->
io:format("RUN MORE TESTS ...\n"),
wechselkurs_server:start(),
eunit:test(wechselkurs_more_tests, [verbose]),
wechselkurs_server:stop(),
io:format("...\n\n\n").
doc() ->
io:format("CREATE DOCS ...\n"),
edoc:files(doc_files(), [{dir, "../doc"}, {todo, true}]),
io:format("...\n\n\n").
perf_kursinfo1() ->
io:format("FPROF ...\n"),
wechselkurs_server:start(),
fprof:trace(start),
wechselkurs_client:kursinfo(),
fprof:trace(stop),
wechselkurs_server:stop(),
fprof:profile(),
fprof:analyse(),
io:format("...\n\n\n").
perf_kursinfo2() ->
io:format("FPROF ...\n"),
wechselkurs_server:start(),
[ fprof:apply(wechselkurs_client, kursinfo, []) || _P <- lists:seq(1,50)],
wechselkurs_server:stop(),
fprof:profile(),
fprof:analyse(),
io:format("...\n\n\n").
cprof() ->
io:format("CPROF ...\n"),
wechselkurs_server:start(),
cprof:start(wechselkurs_server, kursinfo, 3),
[ wechselkurs_client:kursinfo() || _P <- lists:seq(1,50)],
cprof:pause(),
Result=cprof:analyse(wechselkurs_server),
cprof:stop(),
wechselkurs_server:stop(),
io:format("~p \n", [Result]),
io:format("...\n\n\n").
cover() ->
io:format("COVER ... \n"),
cover:start(),
cover:compile(wechselkurs_server),
wechselkurs_server:start(),
[ wechselkurs_client:kursinfo() || _P <- lists:seq(1,10)],
[ wechselkurs_client:umrechnung() || _P <- lists:seq(1,10)],
cover:analyse_to_file(wechselkurs_server),
wechselkurs_server:stop(),
cover:stop(),
io:format("...\n\n\n").
|
c929a473d396a2b21c7bd37178166b1f50ee6305d1ade6e065c77246079a1003 | dcos/lashup | lashup_app.erl | -module(lashup_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
lashup_sup:start_link().
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/dcos/lashup/a0661006c38237147252ebe0b98cc2c29352c976/src/lashup_app.erl | erlang | -module(lashup_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
lashup_sup:start_link().
stop(_State) ->
ok.
|
|
89c655ab01cec72a0b1775cce745c74cce93f0ca2e678ec0479ba19c1721c8e6 | ds-wizard/engine-backend | List_GET.hs | module Wizard.Specs.API.Submission.List_GET (
list_GET,
) where
import Data.Aeson (encode)
import Network.HTTP.Types
import Network.Wai (Application)
import Test.Hspec
import Test.Hspec.Wai hiding (shouldRespondWith)
import Test.Hspec.Wai.Matcher
import Shared.Api.Resource.Error.ErrorJM ()
import Shared.Localization.Messages.Public
import Shared.Model.Error.Error
import Wizard.Api.Resource.Submission.SubmissionJM ()
import Wizard.Database.DAO.Document.DocumentDAO
import Wizard.Database.DAO.Questionnaire.QuestionnaireDAO
import Wizard.Database.Migration.Development.Document.Data.Documents
import qualified Wizard.Database.Migration.Development.Document.DocumentMigration as DOC_Migration
import qualified Wizard.Database.Migration.Development.DocumentTemplate.DocumentTemplateMigration as TML_Migration
import Wizard.Database.Migration.Development.Questionnaire.Data.Questionnaires
import qualified Wizard.Database.Migration.Development.Questionnaire.QuestionnaireMigration as QTN_Migration
import Wizard.Database.Migration.Development.Submission.Data.Submissions
import qualified Wizard.Database.Migration.Development.Submission.SubmissionMigration as SUB_Migration
import qualified Wizard.Database.Migration.Development.User.UserMigration as U_Migration
import Wizard.Model.Context.AppContext
import Wizard.Model.Document.Document
import Wizard.Model.Questionnaire.Questionnaire
import SharedTest.Specs.API.Common
import Wizard.Specs.API.Common
import Wizard.Specs.Common
-- ------------------------------------------------------------------------
-- POST /documents/{docUuid}/submissions
-- ------------------------------------------------------------------------
list_GET :: AppContext -> SpecWith ((), Application)
list_GET appContext =
describe "GET /documents/{docUuid}/submissions" $ do
test_200 appContext
test_401 appContext
test_403 appContext
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
reqMethod = methodGet
reqUrl = "/documents/264ca352-1a99-4ffd-860e-32aee9a98428/submissions"
reqHeadersT authHeader = reqCtHeader : authHeader
reqBody = ""
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_200 appContext = do
create_test_200 "HTTP 200 OK (Owner, Private)" appContext questionnaire1 [reqAuthHeader]
create_test_200 "HTTP 200 OK (Non-Owner, VisibleEdit)" appContext questionnaire3 [reqNonAdminAuthHeader]
create_test_200 "HTTP 200 OK (Non-Owner, VisibleView)" appContext questionnaire2 [reqNonAdminAuthHeader]
create_test_200 title appContext qtn authHeader =
it title $
-- GIVEN: Prepare request
do
let reqHeaders = reqHeadersT authHeader
-- AND: Prepare expectation
let expStatus = 200
let expHeaders = resCtHeader : resCorsHeaders
let expDto = [submission1Dto]
let expBody = encode expDto
-- AND: Run migrations
runInContextIO U_Migration.runMigration appContext
runInContextIO TML_Migration.runMigration appContext
runInContextIO QTN_Migration.runMigration appContext
runInContextIO (insertQuestionnaire questionnaire10) appContext
runInContextIO DOC_Migration.runMigration appContext
runInContextIO (deleteDocumentByUuid doc1.uuid) appContext
runInContextIO (insertDocument (doc1 {questionnaireUuid = qtn.uuid})) appContext
runInContextIO SUB_Migration.runMigration appContext
-- WHEN: Call API
response <- request reqMethod reqUrl reqHeaders reqBody
-- THEN: Compare response with expectation
let responseMatcher =
ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody}
response `shouldRespondWith` responseMatcher
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_401 appContext = createAuthTest reqMethod reqUrl [reqCtHeader] reqBody
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_403 appContext =
create_test_403
"HTTP 403 FORBIDDEN (Non-Owner, Private)"
appContext
questionnaire1
[reqNonAdminAuthHeader]
(_ERROR_VALIDATION__FORBIDDEN "View Questionnaire")
create_test_403 title appContext qtn authHeader errorMessage =
it title $
-- GIVEN: Prepare request
do
let reqHeaders = reqHeadersT authHeader
-- AND: Prepare expectation
let expStatus = 403
let expHeaders = resCtHeader : resCorsHeaders
let expDto = ForbiddenError errorMessage
let expBody = encode expDto
-- AND: Run migrations
runInContextIO U_Migration.runMigration appContext
runInContextIO TML_Migration.runMigration appContext
runInContextIO QTN_Migration.runMigration appContext
runInContextIO (insertQuestionnaire questionnaire7) appContext
runInContextIO DOC_Migration.runMigration appContext
runInContextIO (deleteDocumentByUuid doc1.uuid) appContext
runInContextIO (insertDocument (doc1 {questionnaireUuid = qtn.uuid})) appContext
-- WHEN: Call API
response <- request reqMethod reqUrl reqHeaders reqBody
-- THEN: Compare response with expectation
let responseMatcher =
ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody}
response `shouldRespondWith` responseMatcher
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/test/Wizard/Specs/API/Submission/List_GET.hs | haskell | ------------------------------------------------------------------------
POST /documents/{docUuid}/submissions
------------------------------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
GIVEN: Prepare request
AND: Prepare expectation
AND: Run migrations
WHEN: Call API
THEN: Compare response with expectation
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
GIVEN: Prepare request
AND: Prepare expectation
AND: Run migrations
WHEN: Call API
THEN: Compare response with expectation | module Wizard.Specs.API.Submission.List_GET (
list_GET,
) where
import Data.Aeson (encode)
import Network.HTTP.Types
import Network.Wai (Application)
import Test.Hspec
import Test.Hspec.Wai hiding (shouldRespondWith)
import Test.Hspec.Wai.Matcher
import Shared.Api.Resource.Error.ErrorJM ()
import Shared.Localization.Messages.Public
import Shared.Model.Error.Error
import Wizard.Api.Resource.Submission.SubmissionJM ()
import Wizard.Database.DAO.Document.DocumentDAO
import Wizard.Database.DAO.Questionnaire.QuestionnaireDAO
import Wizard.Database.Migration.Development.Document.Data.Documents
import qualified Wizard.Database.Migration.Development.Document.DocumentMigration as DOC_Migration
import qualified Wizard.Database.Migration.Development.DocumentTemplate.DocumentTemplateMigration as TML_Migration
import Wizard.Database.Migration.Development.Questionnaire.Data.Questionnaires
import qualified Wizard.Database.Migration.Development.Questionnaire.QuestionnaireMigration as QTN_Migration
import Wizard.Database.Migration.Development.Submission.Data.Submissions
import qualified Wizard.Database.Migration.Development.Submission.SubmissionMigration as SUB_Migration
import qualified Wizard.Database.Migration.Development.User.UserMigration as U_Migration
import Wizard.Model.Context.AppContext
import Wizard.Model.Document.Document
import Wizard.Model.Questionnaire.Questionnaire
import SharedTest.Specs.API.Common
import Wizard.Specs.API.Common
import Wizard.Specs.Common
list_GET :: AppContext -> SpecWith ((), Application)
list_GET appContext =
describe "GET /documents/{docUuid}/submissions" $ do
test_200 appContext
test_401 appContext
test_403 appContext
reqMethod = methodGet
reqUrl = "/documents/264ca352-1a99-4ffd-860e-32aee9a98428/submissions"
reqHeadersT authHeader = reqCtHeader : authHeader
reqBody = ""
test_200 appContext = do
create_test_200 "HTTP 200 OK (Owner, Private)" appContext questionnaire1 [reqAuthHeader]
create_test_200 "HTTP 200 OK (Non-Owner, VisibleEdit)" appContext questionnaire3 [reqNonAdminAuthHeader]
create_test_200 "HTTP 200 OK (Non-Owner, VisibleView)" appContext questionnaire2 [reqNonAdminAuthHeader]
create_test_200 title appContext qtn authHeader =
it title $
do
let reqHeaders = reqHeadersT authHeader
let expStatus = 200
let expHeaders = resCtHeader : resCorsHeaders
let expDto = [submission1Dto]
let expBody = encode expDto
runInContextIO U_Migration.runMigration appContext
runInContextIO TML_Migration.runMigration appContext
runInContextIO QTN_Migration.runMigration appContext
runInContextIO (insertQuestionnaire questionnaire10) appContext
runInContextIO DOC_Migration.runMigration appContext
runInContextIO (deleteDocumentByUuid doc1.uuid) appContext
runInContextIO (insertDocument (doc1 {questionnaireUuid = qtn.uuid})) appContext
runInContextIO SUB_Migration.runMigration appContext
response <- request reqMethod reqUrl reqHeaders reqBody
let responseMatcher =
ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody}
response `shouldRespondWith` responseMatcher
test_401 appContext = createAuthTest reqMethod reqUrl [reqCtHeader] reqBody
test_403 appContext =
create_test_403
"HTTP 403 FORBIDDEN (Non-Owner, Private)"
appContext
questionnaire1
[reqNonAdminAuthHeader]
(_ERROR_VALIDATION__FORBIDDEN "View Questionnaire")
create_test_403 title appContext qtn authHeader errorMessage =
it title $
do
let reqHeaders = reqHeadersT authHeader
let expStatus = 403
let expHeaders = resCtHeader : resCorsHeaders
let expDto = ForbiddenError errorMessage
let expBody = encode expDto
runInContextIO U_Migration.runMigration appContext
runInContextIO TML_Migration.runMigration appContext
runInContextIO QTN_Migration.runMigration appContext
runInContextIO (insertQuestionnaire questionnaire7) appContext
runInContextIO DOC_Migration.runMigration appContext
runInContextIO (deleteDocumentByUuid doc1.uuid) appContext
runInContextIO (insertDocument (doc1 {questionnaireUuid = qtn.uuid})) appContext
response <- request reqMethod reqUrl reqHeaders reqBody
let responseMatcher =
ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody}
response `shouldRespondWith` responseMatcher
|
091149cc87e9a1a82b7f96f45f2f33e972cd8b1a17536fe1972432321678d2cc | willdonnelly/dyre | configCheckTestA.hs | import Lib
main = configCheckTest "custom-a"
| null | https://raw.githubusercontent.com/willdonnelly/dyre/f1ebc1592fb188fa173f8c1baa325fc61f527825/Tests/config-check/configCheckTestA.hs | haskell | import Lib
main = configCheckTest "custom-a"
|
|
4c91c919a733021ad9dbc2a82dda4c12e12f6c2e8b08539c514b8574c57e0e86 | duo-lang/duo-lang | Primitives.hs | module TypeInference.GenerateConstraints.Primitives where
import Syntax.RST.Terms (PrimitiveOp(..))
import Syntax.CST.Types (PrdCnsRep(..))
import Syntax.RST.Types
( LinearContext,
PrdCnsType(PrdCnsType),
Typ(TyString, TyI64, TyF64, TyChar)
, Polarity(..)
, PolarityRep(..)
)
import Loc ( defaultLoc )
i64PrimBinOp :: LinearContext Neg
i64PrimBinOp = [PrdCnsType PrdRep (TyI64 defaultLoc NegRep), PrdCnsType PrdRep (TyI64 defaultLoc NegRep), PrdCnsType CnsRep (TyI64 defaultLoc PosRep)]
f64PrimBinOp :: LinearContext Neg
f64PrimBinOp = [PrdCnsType PrdRep (TyF64 defaultLoc NegRep), PrdCnsType PrdRep (TyF64 defaultLoc NegRep), PrdCnsType CnsRep (TyF64 defaultLoc PosRep)]
stringPrimBinOp :: LinearContext Neg
stringPrimBinOp = [PrdCnsType PrdRep (TyString defaultLoc NegRep), PrdCnsType PrdRep (TyString defaultLoc NegRep), PrdCnsType CnsRep (TyString defaultLoc PosRep)]
charPrimBinOp :: LinearContext Neg
charPrimBinOp = [PrdCnsType PrdRep (TyChar defaultLoc NegRep), PrdCnsType PrdRep (TyString defaultLoc NegRep), PrdCnsType CnsRep (TyString defaultLoc PosRep)]
-- | Primitive operations and their signatures
primOps :: PrimitiveOp -> LinearContext Neg
-- I64
primOps I64Add = i64PrimBinOp
primOps I64Sub = i64PrimBinOp
primOps I64Mul = i64PrimBinOp
primOps I64Div = i64PrimBinOp
primOps I64Mod = i64PrimBinOp
-- F64
primOps F64Add = f64PrimBinOp
primOps F64Sub = f64PrimBinOp
primOps F64Mul = f64PrimBinOp
primOps F64Div = f64PrimBinOp
-- Char
primOps CharPrepend = charPrimBinOp
-- String
primOps StringAppend = stringPrimBinOp
| null | https://raw.githubusercontent.com/duo-lang/duo-lang/326a8776d36ae702786f7a22c71289d7bf98717d/src/TypeInference/GenerateConstraints/Primitives.hs | haskell | | Primitive operations and their signatures
I64
F64
Char
String | module TypeInference.GenerateConstraints.Primitives where
import Syntax.RST.Terms (PrimitiveOp(..))
import Syntax.CST.Types (PrdCnsRep(..))
import Syntax.RST.Types
( LinearContext,
PrdCnsType(PrdCnsType),
Typ(TyString, TyI64, TyF64, TyChar)
, Polarity(..)
, PolarityRep(..)
)
import Loc ( defaultLoc )
i64PrimBinOp :: LinearContext Neg
i64PrimBinOp = [PrdCnsType PrdRep (TyI64 defaultLoc NegRep), PrdCnsType PrdRep (TyI64 defaultLoc NegRep), PrdCnsType CnsRep (TyI64 defaultLoc PosRep)]
f64PrimBinOp :: LinearContext Neg
f64PrimBinOp = [PrdCnsType PrdRep (TyF64 defaultLoc NegRep), PrdCnsType PrdRep (TyF64 defaultLoc NegRep), PrdCnsType CnsRep (TyF64 defaultLoc PosRep)]
stringPrimBinOp :: LinearContext Neg
stringPrimBinOp = [PrdCnsType PrdRep (TyString defaultLoc NegRep), PrdCnsType PrdRep (TyString defaultLoc NegRep), PrdCnsType CnsRep (TyString defaultLoc PosRep)]
charPrimBinOp :: LinearContext Neg
charPrimBinOp = [PrdCnsType PrdRep (TyChar defaultLoc NegRep), PrdCnsType PrdRep (TyString defaultLoc NegRep), PrdCnsType CnsRep (TyString defaultLoc PosRep)]
primOps :: PrimitiveOp -> LinearContext Neg
primOps I64Add = i64PrimBinOp
primOps I64Sub = i64PrimBinOp
primOps I64Mul = i64PrimBinOp
primOps I64Div = i64PrimBinOp
primOps I64Mod = i64PrimBinOp
primOps F64Add = f64PrimBinOp
primOps F64Sub = f64PrimBinOp
primOps F64Mul = f64PrimBinOp
primOps F64Div = f64PrimBinOp
primOps CharPrepend = charPrimBinOp
primOps StringAppend = stringPrimBinOp
|
ac50287bf074264d2459626bc578759349ab2dfd27a5a4cd72adcdb5fae596c2 | morpheusgraphql/morpheus-graphql | Schema.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeFamilies #
module Client.Schema where
import Data.Morpheus.Client.CodeGen.Internal
import Globals.GQLScalars (Euro)
newtype Bird = Bird
{ name :: Maybe String
}
deriving (Generic, Show, Eq)
instance ToJSON Bird where
toJSON (Bird birdName) =
omitNulls
[ "name" .= birdName
]
newtype Cat = Cat
{ name :: String
}
deriving (Generic, Show, Eq)
instance ToJSON Cat where
toJSON (Cat catName) =
omitNulls
[ "name" .= catName
]
data CityID
= CityIDParis
| CityIDBLN
| CityIDHH
deriving (Generic, Show, Eq)
instance FromJSON CityID where
parseJSON = \case
"Paris" -> pure CityIDParis
"BLN" -> pure CityIDBLN
"HH" -> pure CityIDHH
v -> invalidConstructorError v
instance ToJSON CityID where
toJSON = \case
CityIDParis -> "Paris"
CityIDBLN -> "BLN"
CityIDHH -> "HH"
data Coordinates = Coordinates
{ latitude :: Euro,
longitude :: [Maybe [[UniqueID]]]
}
deriving (Generic, Show, Eq)
instance ToJSON Coordinates where
toJSON (Coordinates coordinatesLatitude coordinatesLongitude) =
omitNulls
[ "latitude" .= coordinatesLatitude,
"longitude" .= coordinatesLongitude
]
newtype Dog = Dog
{ name :: String
}
deriving (Generic, Show, Eq)
instance ToJSON Dog where
toJSON (Dog dogName) =
omitNulls
[ "name" .= dogName
]
data Power
= PowerShapeshifting
| PowerThunderbolt
| PowerLightning
| PowerTeleportation
| PowerOmniscience
deriving (Generic, Show, Eq)
instance FromJSON Power where
parseJSON = \case
"Shapeshifting" -> pure PowerShapeshifting
"Thunderbolt" -> pure PowerThunderbolt
"Lightning" -> pure PowerLightning
"Teleportation" -> pure PowerTeleportation
"Omniscience" -> pure PowerOmniscience
v -> invalidConstructorError v
instance ToJSON Power where
toJSON = \case
PowerShapeshifting -> "Shapeshifting"
PowerThunderbolt -> "Thunderbolt"
PowerLightning -> "Lightning"
PowerTeleportation -> "Teleportation"
PowerOmniscience -> "Omniscience"
data UniqueID = UniqueID
{ name :: Maybe String,
id :: String,
rec :: Maybe UniqueID
}
deriving (Generic, Show, Eq)
instance ToJSON UniqueID where
toJSON (UniqueID uniqueIDName uniqueIDId uniqueIDRec) =
omitNulls
[ "name" .= uniqueIDName,
"id" .= uniqueIDId,
"rec" .= uniqueIDRec
]
| null | https://raw.githubusercontent.com/morpheusgraphql/morpheus-graphql/1d3ab7e3bc723e29ef8bd2a0c818a03ae82ce8ad/examples/code-gen/src/Client/Schema.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE LambdaCase #
# LANGUAGE TypeFamilies #
module Client.Schema where
import Data.Morpheus.Client.CodeGen.Internal
import Globals.GQLScalars (Euro)
newtype Bird = Bird
{ name :: Maybe String
}
deriving (Generic, Show, Eq)
instance ToJSON Bird where
toJSON (Bird birdName) =
omitNulls
[ "name" .= birdName
]
newtype Cat = Cat
{ name :: String
}
deriving (Generic, Show, Eq)
instance ToJSON Cat where
toJSON (Cat catName) =
omitNulls
[ "name" .= catName
]
data CityID
= CityIDParis
| CityIDBLN
| CityIDHH
deriving (Generic, Show, Eq)
instance FromJSON CityID where
parseJSON = \case
"Paris" -> pure CityIDParis
"BLN" -> pure CityIDBLN
"HH" -> pure CityIDHH
v -> invalidConstructorError v
instance ToJSON CityID where
toJSON = \case
CityIDParis -> "Paris"
CityIDBLN -> "BLN"
CityIDHH -> "HH"
data Coordinates = Coordinates
{ latitude :: Euro,
longitude :: [Maybe [[UniqueID]]]
}
deriving (Generic, Show, Eq)
instance ToJSON Coordinates where
toJSON (Coordinates coordinatesLatitude coordinatesLongitude) =
omitNulls
[ "latitude" .= coordinatesLatitude,
"longitude" .= coordinatesLongitude
]
newtype Dog = Dog
{ name :: String
}
deriving (Generic, Show, Eq)
instance ToJSON Dog where
toJSON (Dog dogName) =
omitNulls
[ "name" .= dogName
]
data Power
= PowerShapeshifting
| PowerThunderbolt
| PowerLightning
| PowerTeleportation
| PowerOmniscience
deriving (Generic, Show, Eq)
instance FromJSON Power where
parseJSON = \case
"Shapeshifting" -> pure PowerShapeshifting
"Thunderbolt" -> pure PowerThunderbolt
"Lightning" -> pure PowerLightning
"Teleportation" -> pure PowerTeleportation
"Omniscience" -> pure PowerOmniscience
v -> invalidConstructorError v
instance ToJSON Power where
toJSON = \case
PowerShapeshifting -> "Shapeshifting"
PowerThunderbolt -> "Thunderbolt"
PowerLightning -> "Lightning"
PowerTeleportation -> "Teleportation"
PowerOmniscience -> "Omniscience"
data UniqueID = UniqueID
{ name :: Maybe String,
id :: String,
rec :: Maybe UniqueID
}
deriving (Generic, Show, Eq)
instance ToJSON UniqueID where
toJSON (UniqueID uniqueIDName uniqueIDId uniqueIDRec) =
omitNulls
[ "name" .= uniqueIDName,
"id" .= uniqueIDId,
"rec" .= uniqueIDRec
]
|
b7e6784e55850c6bd105921ab354953e95b24b83ddf9772d51e6bcff0b503d9a | moonlightdrive/ocaml-ec2 | myocamlbuild.ml | OASIS_START
DO NOT EDIT ( digest : 8d562c7396a91e74254b267b11879a01 )
module OASISGettext = struct
# 22 " src / oasis / OASISGettext.ml "
let ns_ str =
str
let s_ str =
str
let f_ (str: ('a, 'b, 'c, 'd) format4) =
str
let fn_ fmt1 fmt2 n =
if n = 1 then
fmt1^^""
else
fmt2^^""
let init =
[]
end
module OASISExpr = struct
# 22 " src / oasis / OASISExpr.ml "
open OASISGettext
type test = string
type flag = string
type t =
| EBool of bool
| ENot of t
| EAnd of t * t
| EOr of t * t
| EFlag of flag
| ETest of test * string
type 'a choices = (t * 'a) list
let eval var_get t =
let rec eval' =
function
| EBool b ->
b
| ENot e ->
not (eval' e)
| EAnd (e1, e2) ->
(eval' e1) && (eval' e2)
| EOr (e1, e2) ->
(eval' e1) || (eval' e2)
| EFlag nm ->
let v =
var_get nm
in
assert(v = "true" || v = "false");
(v = "true")
| ETest (nm, vl) ->
let v =
var_get nm
in
(v = vl)
in
eval' t
let choose ?printer ?name var_get lst =
let rec choose_aux =
function
| (cond, vl) :: tl ->
if eval var_get cond then
vl
else
choose_aux tl
| [] ->
let str_lst =
if lst = [] then
s_ "<empty>"
else
String.concat
(s_ ", ")
(List.map
(fun (cond, vl) ->
match printer with
| Some p -> p vl
| None -> s_ "<no printer>")
lst)
in
match name with
| Some nm ->
failwith
(Printf.sprintf
(f_ "No result for the choice list '%s': %s")
nm str_lst)
| None ->
failwith
(Printf.sprintf
(f_ "No result for a choice list: %s")
str_lst)
in
choose_aux (List.rev lst)
end
# 132 "myocamlbuild.ml"
module BaseEnvLight = struct
# 22 " src / base / BaseEnvLight.ml "
module MapString = Map.Make(String)
type t = string MapString.t
let default_filename =
Filename.concat
(Sys.getcwd ())
"setup.data"
let load ?(allow_empty=false) ?(filename=default_filename) () =
if Sys.file_exists filename then
begin
let chn =
open_in_bin filename
in
let st =
Stream.of_channel chn
in
let line =
ref 1
in
let st_line =
Stream.from
(fun _ ->
try
match Stream.next st with
| '\n' -> incr line; Some '\n'
| c -> Some c
with Stream.Failure -> None)
in
let lexer =
Genlex.make_lexer ["="] st_line
in
let rec read_file mp =
match Stream.npeek 3 lexer with
| [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] ->
Stream.junk lexer;
Stream.junk lexer;
Stream.junk lexer;
read_file (MapString.add nm value mp)
| [] ->
mp
| _ ->
failwith
(Printf.sprintf
"Malformed data file '%s' line %d"
filename !line)
in
let mp =
read_file MapString.empty
in
close_in chn;
mp
end
else if allow_empty then
begin
MapString.empty
end
else
begin
failwith
(Printf.sprintf
"Unable to load environment, the file '%s' doesn't exist."
filename)
end
let rec var_expand str env =
let buff =
Buffer.create ((String.length str) * 2)
in
Buffer.add_substitute
buff
(fun var ->
try
var_expand (MapString.find var env) env
with Not_found ->
failwith
(Printf.sprintf
"No variable %s defined when trying to expand %S."
var
str))
str;
Buffer.contents buff
let var_get name env =
var_expand (MapString.find name env) env
let var_choose lst env =
OASISExpr.choose
(fun nm -> var_get nm env)
lst
end
# 237 "myocamlbuild.ml"
module MyOCamlbuildFindlib = struct
# 22 " src / plugins / ocamlbuild / MyOCamlbuildFindlib.ml "
* extension , copied from
*
* by and others
*
* Updated on 2009/02/28
*
* Modified by
*
* by N. Pouillard and others
*
* Updated on 2009/02/28
*
* Modified by Sylvain Le Gall
*)
open Ocamlbuild_plugin
type conf =
{ no_automatic_syntax: bool;
}
(* these functions are not really officially exported *)
let run_and_read =
Ocamlbuild_pack.My_unix.run_and_read
let blank_sep_strings =
Ocamlbuild_pack.Lexers.blank_sep_strings
let exec_from_conf exec =
let exec =
let env_filename = Pathname.basename BaseEnvLight.default_filename in
let env = BaseEnvLight.load ~filename:env_filename ~allow_empty:true () in
try
BaseEnvLight.var_get exec env
with Not_found ->
Printf.eprintf "W: Cannot get variable %s\n" exec;
exec
in
let fix_win32 str =
if Sys.os_type = "Win32" then begin
let buff = Buffer.create (String.length str) in
Adapt for windowsi , ocamlbuild + win32 has a hard time to handle ' \\ ' .
*)
String.iter
(fun c -> Buffer.add_char buff (if c = '\\' then '/' else c))
str;
Buffer.contents buff
end else begin
str
end
in
fix_win32 exec
let split s ch =
let buf = Buffer.create 13 in
let x = ref [] in
let flush () =
x := (Buffer.contents buf) :: !x;
Buffer.clear buf
in
String.iter
(fun c ->
if c = ch then
flush ()
else
Buffer.add_char buf c)
s;
flush ();
List.rev !x
let split_nl s = split s '\n'
let before_space s =
try
String.before s (String.index s ' ')
with Not_found -> s
(* ocamlfind command *)
let ocamlfind x = S[Sh (exec_from_conf "ocamlfind"); x]
(* This lists all supported packages. *)
let find_packages () =
List.map before_space (split_nl & run_and_read (exec_from_conf "ocamlfind" ^ " list"))
(* Mock to list available syntaxes. *)
let find_syntaxes () = ["camlp4o"; "camlp4r"]
let well_known_syntax = [
"camlp4.quotations.o";
"camlp4.quotations.r";
"camlp4.exceptiontracer";
"camlp4.extend";
"camlp4.foldgenerator";
"camlp4.listcomprehension";
"camlp4.locationstripper";
"camlp4.macro";
"camlp4.mapgenerator";
"camlp4.metagenerator";
"camlp4.profiler";
"camlp4.tracer"
]
let dispatch conf =
function
| After_options ->
(* By using Before_options one let command line options have an higher
* priority on the contrary using After_options will guarantee to have
* the higher priority override default commands by ocamlfind ones *)
Options.ocamlc := ocamlfind & A"ocamlc";
Options.ocamlopt := ocamlfind & A"ocamlopt";
Options.ocamldep := ocamlfind & A"ocamldep";
Options.ocamldoc := ocamlfind & A"ocamldoc";
Options.ocamlmktop := ocamlfind & A"ocamlmktop";
Options.ocamlmklib := ocamlfind & A"ocamlmklib"
| After_rules ->
When one link an OCaml library / binary / package , one should use
* -linkpkg
* -linkpkg *)
flag ["ocaml"; "link"; "program"] & A"-linkpkg";
if not (conf.no_automatic_syntax) then begin
For each ocamlfind package one inject the -package option when
* compiling , computing dependencies , generating documentation and
* linking .
* compiling, computing dependencies, generating documentation and
* linking. *)
List.iter
begin fun pkg ->
let base_args = [A"-package"; A pkg] in
TODO : consider how to really choose camlp4o or camlp4r .
let syn_args = [A"-syntax"; A "camlp4o"] in
let (args, pargs) =
(* Heuristic to identify syntax extensions: whether they end in
".syntax"; some might not.
*)
if Filename.check_suffix pkg "syntax" ||
List.mem pkg well_known_syntax then
(syn_args @ base_args, syn_args)
else
(base_args, [])
in
flag ["ocaml"; "compile"; "pkg_"^pkg] & S args;
flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S args;
flag ["ocaml"; "doc"; "pkg_"^pkg] & S args;
flag ["ocaml"; "link"; "pkg_"^pkg] & S base_args;
flag ["ocaml"; "infer_interface"; "pkg_"^pkg] & S args;
TODO : Check if this is allowed for OCaml < 3.12.1
flag ["ocaml"; "compile"; "package("^pkg^")"] & S pargs;
flag ["ocaml"; "ocamldep"; "package("^pkg^")"] & S pargs;
flag ["ocaml"; "doc"; "package("^pkg^")"] & S pargs;
flag ["ocaml"; "infer_interface"; "package("^pkg^")"] & S pargs;
end
(find_packages ());
end;
Like -package but for extensions syntax . -syntax is useless
* when linking .
* when linking. *)
List.iter begin fun syntax ->
flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "infer_interface"; "syntax_"^syntax] &
S[A"-syntax"; A syntax];
end (find_syntaxes ());
The default " thread " tag is not compatible with ocamlfind .
* Indeed , the default rules add the " threads.cma " or " threads.cmxa "
* options when using this tag . When using the " -linkpkg " option with
* ocamlfind , this module will then be added twice on the command line .
*
* To solve this , one approach is to add the " -thread " option when using
* the " threads " package using the previous plugin .
* Indeed, the default rules add the "threads.cma" or "threads.cmxa"
* options when using this tag. When using the "-linkpkg" option with
* ocamlfind, this module will then be added twice on the command line.
*
* To solve this, one approach is to add the "-thread" option when using
* the "threads" package using the previous plugin.
*)
flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]);
flag ["ocaml"; "pkg_threads"; "doc"] (S[A "-I"; A "+threads"]);
flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]);
flag ["ocaml"; "pkg_threads"; "infer_interface"] (S[A "-thread"]);
flag ["ocaml"; "package(threads)"; "compile"] (S[A "-thread"]);
flag ["ocaml"; "package(threads)"; "doc"] (S[A "-I"; A "+threads"]);
flag ["ocaml"; "package(threads)"; "link"] (S[A "-thread"]);
flag ["ocaml"; "package(threads)"; "infer_interface"] (S[A "-thread"]);
| _ ->
()
end
module MyOCamlbuildBase = struct
# 22 " src / plugins / ocamlbuild / MyOCamlbuildBase.ml "
* Base functions for writing myocamlbuild.ml
@author
@author Sylvain Le Gall
*)
open Ocamlbuild_plugin
module OC = Ocamlbuild_pack.Ocaml_compiler
type dir = string
type file = string
type name = string
type tag = string
# 62 " src / plugins / ocamlbuild / MyOCamlbuildBase.ml "
type t =
{
lib_ocaml: (name * dir list * string list) list;
lib_c: (name * dir * file list) list;
flags: (tag list * (spec OASISExpr.choices)) list;
(* Replace the 'dir: include' from _tags by a precise interdepends in
* directory.
*)
includes: (dir * dir list) list;
}
let env_filename =
Pathname.basename
BaseEnvLight.default_filename
let dispatch_combine lst =
fun e ->
List.iter
(fun dispatch -> dispatch e)
lst
let tag_libstubs nm =
"use_lib"^nm^"_stubs"
let nm_libstubs nm =
nm^"_stubs"
let dispatch t e =
let env =
BaseEnvLight.load
~filename:env_filename
~allow_empty:true
()
in
match e with
| Before_options ->
let no_trailing_dot s =
if String.length s >= 1 && s.[0] = '.' then
String.sub s 1 ((String.length s) - 1)
else
s
in
List.iter
(fun (opt, var) ->
try
opt := no_trailing_dot (BaseEnvLight.var_get var env)
with Not_found ->
Printf.eprintf "W: Cannot get variable %s\n" var)
[
Options.ext_obj, "ext_obj";
Options.ext_lib, "ext_lib";
Options.ext_dll, "ext_dll";
]
| After_rules ->
(* Declare OCaml libraries *)
List.iter
(function
| nm, [], intf_modules ->
ocaml_lib nm;
let cmis =
List.map (fun m -> (String.uncapitalize m) ^ ".cmi")
intf_modules in
dep ["ocaml"; "link"; "library"; "file:"^nm^".cma"] cmis
| nm, dir :: tl, intf_modules ->
ocaml_lib ~dir:dir (dir^"/"^nm);
List.iter
(fun dir ->
List.iter
(fun str ->
flag ["ocaml"; "use_"^nm; str] (S[A"-I"; P dir]))
["compile"; "infer_interface"; "doc"])
tl;
let cmis =
List.map (fun m -> dir^"/"^(String.uncapitalize m)^".cmi")
intf_modules in
dep ["ocaml"; "link"; "library"; "file:"^dir^"/"^nm^".cma"]
cmis)
t.lib_ocaml;
(* Declare directories dependencies, replace "include" in _tags. *)
List.iter
(fun (dir, include_dirs) ->
Pathname.define_context dir include_dirs)
t.includes;
(* Declare C libraries *)
List.iter
(fun (lib, dir, headers) ->
(* Handle C part of library *)
flag ["link"; "library"; "ocaml"; "byte"; tag_libstubs lib]
(S[A"-dllib"; A("-l"^(nm_libstubs lib)); A"-cclib";
A("-l"^(nm_libstubs lib))]);
flag ["link"; "library"; "ocaml"; "native"; tag_libstubs lib]
(S[A"-cclib"; A("-l"^(nm_libstubs lib))]);
flag ["link"; "program"; "ocaml"; "byte"; tag_libstubs lib]
(S[A"-dllib"; A("dll"^(nm_libstubs lib))]);
When ocaml link something that use the C library , then one
need that file to be up to date .
This holds both for programs and for libraries .
need that file to be up to date.
This holds both for programs and for libraries.
*)
dep ["link"; "ocaml"; tag_libstubs lib]
[dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)];
dep ["compile"; "ocaml"; tag_libstubs lib]
[dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)];
(* TODO: be more specific about what depends on headers *)
(* Depends on .h files *)
dep ["compile"; "c"]
headers;
(* Setup search path for lib *)
flag ["link"; "ocaml"; "use_"^lib]
(S[A"-I"; P(dir)]);
)
t.lib_c;
(* Add flags *)
List.iter
(fun (tags, cond_specs) ->
let spec = BaseEnvLight.var_choose cond_specs env in
let rec eval_specs =
function
| S lst -> S (List.map eval_specs lst)
| A str -> A (BaseEnvLight.var_expand str env)
| spec -> spec
in
flag tags & (eval_specs spec))
t.flags
| _ ->
()
let dispatch_default conf t =
dispatch_combine
[
dispatch t;
MyOCamlbuildFindlib.dispatch conf;
]
end
# 606 "myocamlbuild.ml"
open Ocamlbuild_plugin;;
let package_default =
{
MyOCamlbuildBase.lib_ocaml =
[("ec2", ["lib"], []); ("ec2-ami", ["ami"], [])];
lib_c = [];
flags = [];
includes =
[("lib_test", ["lib"]); ("examples", ["ami"; "lib"]); ("ami", ["lib"])
]
}
;;
let conf = {MyOCamlbuildFindlib.no_automatic_syntax = false}
let dispatch_default = MyOCamlbuildBase.dispatch_default conf package_default;;
# 625 "myocamlbuild.ml"
OASIS_STOP
Ocamlbuild_plugin.dispatch dispatch_default;;
| null | https://raw.githubusercontent.com/moonlightdrive/ocaml-ec2/06df35a4a29f1b51416013ddf126eeb43587dc11/myocamlbuild.ml | ocaml | these functions are not really officially exported
ocamlfind command
This lists all supported packages.
Mock to list available syntaxes.
By using Before_options one let command line options have an higher
* priority on the contrary using After_options will guarantee to have
* the higher priority override default commands by ocamlfind ones
Heuristic to identify syntax extensions: whether they end in
".syntax"; some might not.
Replace the 'dir: include' from _tags by a precise interdepends in
* directory.
Declare OCaml libraries
Declare directories dependencies, replace "include" in _tags.
Declare C libraries
Handle C part of library
TODO: be more specific about what depends on headers
Depends on .h files
Setup search path for lib
Add flags | OASIS_START
DO NOT EDIT ( digest : 8d562c7396a91e74254b267b11879a01 )
module OASISGettext = struct
# 22 " src / oasis / OASISGettext.ml "
let ns_ str =
str
let s_ str =
str
let f_ (str: ('a, 'b, 'c, 'd) format4) =
str
let fn_ fmt1 fmt2 n =
if n = 1 then
fmt1^^""
else
fmt2^^""
let init =
[]
end
module OASISExpr = struct
# 22 " src / oasis / OASISExpr.ml "
open OASISGettext
type test = string
type flag = string
type t =
| EBool of bool
| ENot of t
| EAnd of t * t
| EOr of t * t
| EFlag of flag
| ETest of test * string
type 'a choices = (t * 'a) list
let eval var_get t =
let rec eval' =
function
| EBool b ->
b
| ENot e ->
not (eval' e)
| EAnd (e1, e2) ->
(eval' e1) && (eval' e2)
| EOr (e1, e2) ->
(eval' e1) || (eval' e2)
| EFlag nm ->
let v =
var_get nm
in
assert(v = "true" || v = "false");
(v = "true")
| ETest (nm, vl) ->
let v =
var_get nm
in
(v = vl)
in
eval' t
let choose ?printer ?name var_get lst =
let rec choose_aux =
function
| (cond, vl) :: tl ->
if eval var_get cond then
vl
else
choose_aux tl
| [] ->
let str_lst =
if lst = [] then
s_ "<empty>"
else
String.concat
(s_ ", ")
(List.map
(fun (cond, vl) ->
match printer with
| Some p -> p vl
| None -> s_ "<no printer>")
lst)
in
match name with
| Some nm ->
failwith
(Printf.sprintf
(f_ "No result for the choice list '%s': %s")
nm str_lst)
| None ->
failwith
(Printf.sprintf
(f_ "No result for a choice list: %s")
str_lst)
in
choose_aux (List.rev lst)
end
# 132 "myocamlbuild.ml"
module BaseEnvLight = struct
# 22 " src / base / BaseEnvLight.ml "
module MapString = Map.Make(String)
type t = string MapString.t
let default_filename =
Filename.concat
(Sys.getcwd ())
"setup.data"
let load ?(allow_empty=false) ?(filename=default_filename) () =
if Sys.file_exists filename then
begin
let chn =
open_in_bin filename
in
let st =
Stream.of_channel chn
in
let line =
ref 1
in
let st_line =
Stream.from
(fun _ ->
try
match Stream.next st with
| '\n' -> incr line; Some '\n'
| c -> Some c
with Stream.Failure -> None)
in
let lexer =
Genlex.make_lexer ["="] st_line
in
let rec read_file mp =
match Stream.npeek 3 lexer with
| [Genlex.Ident nm; Genlex.Kwd "="; Genlex.String value] ->
Stream.junk lexer;
Stream.junk lexer;
Stream.junk lexer;
read_file (MapString.add nm value mp)
| [] ->
mp
| _ ->
failwith
(Printf.sprintf
"Malformed data file '%s' line %d"
filename !line)
in
let mp =
read_file MapString.empty
in
close_in chn;
mp
end
else if allow_empty then
begin
MapString.empty
end
else
begin
failwith
(Printf.sprintf
"Unable to load environment, the file '%s' doesn't exist."
filename)
end
let rec var_expand str env =
let buff =
Buffer.create ((String.length str) * 2)
in
Buffer.add_substitute
buff
(fun var ->
try
var_expand (MapString.find var env) env
with Not_found ->
failwith
(Printf.sprintf
"No variable %s defined when trying to expand %S."
var
str))
str;
Buffer.contents buff
let var_get name env =
var_expand (MapString.find name env) env
let var_choose lst env =
OASISExpr.choose
(fun nm -> var_get nm env)
lst
end
# 237 "myocamlbuild.ml"
module MyOCamlbuildFindlib = struct
# 22 " src / plugins / ocamlbuild / MyOCamlbuildFindlib.ml "
* extension , copied from
*
* by and others
*
* Updated on 2009/02/28
*
* Modified by
*
* by N. Pouillard and others
*
* Updated on 2009/02/28
*
* Modified by Sylvain Le Gall
*)
open Ocamlbuild_plugin
type conf =
{ no_automatic_syntax: bool;
}
let run_and_read =
Ocamlbuild_pack.My_unix.run_and_read
let blank_sep_strings =
Ocamlbuild_pack.Lexers.blank_sep_strings
let exec_from_conf exec =
let exec =
let env_filename = Pathname.basename BaseEnvLight.default_filename in
let env = BaseEnvLight.load ~filename:env_filename ~allow_empty:true () in
try
BaseEnvLight.var_get exec env
with Not_found ->
Printf.eprintf "W: Cannot get variable %s\n" exec;
exec
in
let fix_win32 str =
if Sys.os_type = "Win32" then begin
let buff = Buffer.create (String.length str) in
Adapt for windowsi , ocamlbuild + win32 has a hard time to handle ' \\ ' .
*)
String.iter
(fun c -> Buffer.add_char buff (if c = '\\' then '/' else c))
str;
Buffer.contents buff
end else begin
str
end
in
fix_win32 exec
let split s ch =
let buf = Buffer.create 13 in
let x = ref [] in
let flush () =
x := (Buffer.contents buf) :: !x;
Buffer.clear buf
in
String.iter
(fun c ->
if c = ch then
flush ()
else
Buffer.add_char buf c)
s;
flush ();
List.rev !x
let split_nl s = split s '\n'
let before_space s =
try
String.before s (String.index s ' ')
with Not_found -> s
let ocamlfind x = S[Sh (exec_from_conf "ocamlfind"); x]
let find_packages () =
List.map before_space (split_nl & run_and_read (exec_from_conf "ocamlfind" ^ " list"))
let find_syntaxes () = ["camlp4o"; "camlp4r"]
let well_known_syntax = [
"camlp4.quotations.o";
"camlp4.quotations.r";
"camlp4.exceptiontracer";
"camlp4.extend";
"camlp4.foldgenerator";
"camlp4.listcomprehension";
"camlp4.locationstripper";
"camlp4.macro";
"camlp4.mapgenerator";
"camlp4.metagenerator";
"camlp4.profiler";
"camlp4.tracer"
]
let dispatch conf =
function
| After_options ->
Options.ocamlc := ocamlfind & A"ocamlc";
Options.ocamlopt := ocamlfind & A"ocamlopt";
Options.ocamldep := ocamlfind & A"ocamldep";
Options.ocamldoc := ocamlfind & A"ocamldoc";
Options.ocamlmktop := ocamlfind & A"ocamlmktop";
Options.ocamlmklib := ocamlfind & A"ocamlmklib"
| After_rules ->
When one link an OCaml library / binary / package , one should use
* -linkpkg
* -linkpkg *)
flag ["ocaml"; "link"; "program"] & A"-linkpkg";
if not (conf.no_automatic_syntax) then begin
For each ocamlfind package one inject the -package option when
* compiling , computing dependencies , generating documentation and
* linking .
* compiling, computing dependencies, generating documentation and
* linking. *)
List.iter
begin fun pkg ->
let base_args = [A"-package"; A pkg] in
TODO : consider how to really choose camlp4o or camlp4r .
let syn_args = [A"-syntax"; A "camlp4o"] in
let (args, pargs) =
if Filename.check_suffix pkg "syntax" ||
List.mem pkg well_known_syntax then
(syn_args @ base_args, syn_args)
else
(base_args, [])
in
flag ["ocaml"; "compile"; "pkg_"^pkg] & S args;
flag ["ocaml"; "ocamldep"; "pkg_"^pkg] & S args;
flag ["ocaml"; "doc"; "pkg_"^pkg] & S args;
flag ["ocaml"; "link"; "pkg_"^pkg] & S base_args;
flag ["ocaml"; "infer_interface"; "pkg_"^pkg] & S args;
TODO : Check if this is allowed for OCaml < 3.12.1
flag ["ocaml"; "compile"; "package("^pkg^")"] & S pargs;
flag ["ocaml"; "ocamldep"; "package("^pkg^")"] & S pargs;
flag ["ocaml"; "doc"; "package("^pkg^")"] & S pargs;
flag ["ocaml"; "infer_interface"; "package("^pkg^")"] & S pargs;
end
(find_packages ());
end;
Like -package but for extensions syntax . -syntax is useless
* when linking .
* when linking. *)
List.iter begin fun syntax ->
flag ["ocaml"; "compile"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "ocamldep"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "doc"; "syntax_"^syntax] & S[A"-syntax"; A syntax];
flag ["ocaml"; "infer_interface"; "syntax_"^syntax] &
S[A"-syntax"; A syntax];
end (find_syntaxes ());
The default " thread " tag is not compatible with ocamlfind .
* Indeed , the default rules add the " threads.cma " or " threads.cmxa "
* options when using this tag . When using the " -linkpkg " option with
* ocamlfind , this module will then be added twice on the command line .
*
* To solve this , one approach is to add the " -thread " option when using
* the " threads " package using the previous plugin .
* Indeed, the default rules add the "threads.cma" or "threads.cmxa"
* options when using this tag. When using the "-linkpkg" option with
* ocamlfind, this module will then be added twice on the command line.
*
* To solve this, one approach is to add the "-thread" option when using
* the "threads" package using the previous plugin.
*)
flag ["ocaml"; "pkg_threads"; "compile"] (S[A "-thread"]);
flag ["ocaml"; "pkg_threads"; "doc"] (S[A "-I"; A "+threads"]);
flag ["ocaml"; "pkg_threads"; "link"] (S[A "-thread"]);
flag ["ocaml"; "pkg_threads"; "infer_interface"] (S[A "-thread"]);
flag ["ocaml"; "package(threads)"; "compile"] (S[A "-thread"]);
flag ["ocaml"; "package(threads)"; "doc"] (S[A "-I"; A "+threads"]);
flag ["ocaml"; "package(threads)"; "link"] (S[A "-thread"]);
flag ["ocaml"; "package(threads)"; "infer_interface"] (S[A "-thread"]);
| _ ->
()
end
module MyOCamlbuildBase = struct
# 22 " src / plugins / ocamlbuild / MyOCamlbuildBase.ml "
* Base functions for writing myocamlbuild.ml
@author
@author Sylvain Le Gall
*)
open Ocamlbuild_plugin
module OC = Ocamlbuild_pack.Ocaml_compiler
type dir = string
type file = string
type name = string
type tag = string
# 62 " src / plugins / ocamlbuild / MyOCamlbuildBase.ml "
type t =
{
lib_ocaml: (name * dir list * string list) list;
lib_c: (name * dir * file list) list;
flags: (tag list * (spec OASISExpr.choices)) list;
includes: (dir * dir list) list;
}
let env_filename =
Pathname.basename
BaseEnvLight.default_filename
let dispatch_combine lst =
fun e ->
List.iter
(fun dispatch -> dispatch e)
lst
let tag_libstubs nm =
"use_lib"^nm^"_stubs"
let nm_libstubs nm =
nm^"_stubs"
let dispatch t e =
let env =
BaseEnvLight.load
~filename:env_filename
~allow_empty:true
()
in
match e with
| Before_options ->
let no_trailing_dot s =
if String.length s >= 1 && s.[0] = '.' then
String.sub s 1 ((String.length s) - 1)
else
s
in
List.iter
(fun (opt, var) ->
try
opt := no_trailing_dot (BaseEnvLight.var_get var env)
with Not_found ->
Printf.eprintf "W: Cannot get variable %s\n" var)
[
Options.ext_obj, "ext_obj";
Options.ext_lib, "ext_lib";
Options.ext_dll, "ext_dll";
]
| After_rules ->
List.iter
(function
| nm, [], intf_modules ->
ocaml_lib nm;
let cmis =
List.map (fun m -> (String.uncapitalize m) ^ ".cmi")
intf_modules in
dep ["ocaml"; "link"; "library"; "file:"^nm^".cma"] cmis
| nm, dir :: tl, intf_modules ->
ocaml_lib ~dir:dir (dir^"/"^nm);
List.iter
(fun dir ->
List.iter
(fun str ->
flag ["ocaml"; "use_"^nm; str] (S[A"-I"; P dir]))
["compile"; "infer_interface"; "doc"])
tl;
let cmis =
List.map (fun m -> dir^"/"^(String.uncapitalize m)^".cmi")
intf_modules in
dep ["ocaml"; "link"; "library"; "file:"^dir^"/"^nm^".cma"]
cmis)
t.lib_ocaml;
List.iter
(fun (dir, include_dirs) ->
Pathname.define_context dir include_dirs)
t.includes;
List.iter
(fun (lib, dir, headers) ->
flag ["link"; "library"; "ocaml"; "byte"; tag_libstubs lib]
(S[A"-dllib"; A("-l"^(nm_libstubs lib)); A"-cclib";
A("-l"^(nm_libstubs lib))]);
flag ["link"; "library"; "ocaml"; "native"; tag_libstubs lib]
(S[A"-cclib"; A("-l"^(nm_libstubs lib))]);
flag ["link"; "program"; "ocaml"; "byte"; tag_libstubs lib]
(S[A"-dllib"; A("dll"^(nm_libstubs lib))]);
When ocaml link something that use the C library , then one
need that file to be up to date .
This holds both for programs and for libraries .
need that file to be up to date.
This holds both for programs and for libraries.
*)
dep ["link"; "ocaml"; tag_libstubs lib]
[dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)];
dep ["compile"; "ocaml"; tag_libstubs lib]
[dir/"lib"^(nm_libstubs lib)^"."^(!Options.ext_lib)];
dep ["compile"; "c"]
headers;
flag ["link"; "ocaml"; "use_"^lib]
(S[A"-I"; P(dir)]);
)
t.lib_c;
List.iter
(fun (tags, cond_specs) ->
let spec = BaseEnvLight.var_choose cond_specs env in
let rec eval_specs =
function
| S lst -> S (List.map eval_specs lst)
| A str -> A (BaseEnvLight.var_expand str env)
| spec -> spec
in
flag tags & (eval_specs spec))
t.flags
| _ ->
()
let dispatch_default conf t =
dispatch_combine
[
dispatch t;
MyOCamlbuildFindlib.dispatch conf;
]
end
# 606 "myocamlbuild.ml"
open Ocamlbuild_plugin;;
let package_default =
{
MyOCamlbuildBase.lib_ocaml =
[("ec2", ["lib"], []); ("ec2-ami", ["ami"], [])];
lib_c = [];
flags = [];
includes =
[("lib_test", ["lib"]); ("examples", ["ami"; "lib"]); ("ami", ["lib"])
]
}
;;
let conf = {MyOCamlbuildFindlib.no_automatic_syntax = false}
let dispatch_default = MyOCamlbuildBase.dispatch_default conf package_default;;
# 625 "myocamlbuild.ml"
OASIS_STOP
Ocamlbuild_plugin.dispatch dispatch_default;;
|
b87a7f00fce20660711add6c46c88553b46ef96bb91067768c25d38aecac9804 | findmyway/reinforcement-learning-an-introduction | infinite_variance.clj | gorilla-repl.fileformat = 1
;; @@
(ns rl.chapter05.infinite-variance
(:require [incanter.stats :refer [sample-binomial]]
[clojure.core.matrix :as m])
(:use [plotly-clj.core]))
;; @@
;; =>
;;; {"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"}
;; <=
;; @@
(online-init)
;; @@
;; =>
;;; {"type":"html","content":"<script src=\"-latest.min.js\" type=\"text/javascript\"></script>","value":"pr'ed value"}
;; <=
;; @@
(defn behavior-policy [] (if (zero? (sample-binomial 1)) :end :back))
(defn target-policy [] :back)
(defn play
[]
(loop [trajectory []]
(let [a (behavior-policy)
trajectory (conj trajectory a)]
(cond
(= a :end) [0 trajectory]
(zero? (sample-binomial 1 :prob 0.9)) [1 trajectory]
:else (recur trajectory)))))
(defn one-round
[n-episodes]
(let [get-ratio (fn [trajectory]
(if (= (last trajectory) :end)
0
(Math/pow 2 (count trajectory))))]
(m/div (->> (repeatedly n-episodes play)
(map (fn [[r t]] (* r (get-ratio t))))
(reductions +))
(range 1 (inc n-episodes)))))
;; @@
;; =>
{ " type":"html","content":"<span class='clj - var'>#'rl.chapter05.infinite - variance / one - round</span>","value":"#'rl.chapter05.infinite - variance / one - round " }
;; <=
;; @@
(let [n 10000]
(-> (plotly)
(plot-seq
(for [_ (range 10)]
#(add-scatter % :x (range 1 (inc n)) :y (one-round n) :type "scattergl")))
(set-layout :xaxis {:title "Episonde" :type "log"} :showlegend false)
(plot "RL-figure-5-5" :fileopt "overwrite")
embed-url))
;; @@
;; =>
;;; {"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/128.embed\" width=\"800\"></iframe>","value":"pr'ed value"}
;; <=
;; @@
;; @@
| null | https://raw.githubusercontent.com/findmyway/reinforcement-learning-an-introduction/6911efbe7a6478658b188022ebad542751146ddd/src/rl/chapter05/infinite_variance.clj | clojure | @@
@@
=>
{"type":"html","content":"<span class='clj-nil'>nil</span>","value":"nil"}
<=
@@
@@
=>
{"type":"html","content":"<script src=\"-latest.min.js\" type=\"text/javascript\"></script>","value":"pr'ed value"}
<=
@@
@@
=>
<=
@@
@@
=>
{"type":"html","content":"<iframe height=\"600\" src=\"//plot.ly/~findmyway/128.embed\" width=\"800\"></iframe>","value":"pr'ed value"}
<=
@@
@@ | gorilla-repl.fileformat = 1
(ns rl.chapter05.infinite-variance
(:require [incanter.stats :refer [sample-binomial]]
[clojure.core.matrix :as m])
(:use [plotly-clj.core]))
(online-init)
(defn behavior-policy [] (if (zero? (sample-binomial 1)) :end :back))
(defn target-policy [] :back)
(defn play
[]
(loop [trajectory []]
(let [a (behavior-policy)
trajectory (conj trajectory a)]
(cond
(= a :end) [0 trajectory]
(zero? (sample-binomial 1 :prob 0.9)) [1 trajectory]
:else (recur trajectory)))))
(defn one-round
[n-episodes]
(let [get-ratio (fn [trajectory]
(if (= (last trajectory) :end)
0
(Math/pow 2 (count trajectory))))]
(m/div (->> (repeatedly n-episodes play)
(map (fn [[r t]] (* r (get-ratio t))))
(reductions +))
(range 1 (inc n-episodes)))))
{ " type":"html","content":"<span class='clj - var'>#'rl.chapter05.infinite - variance / one - round</span>","value":"#'rl.chapter05.infinite - variance / one - round " }
(let [n 10000]
(-> (plotly)
(plot-seq
(for [_ (range 10)]
#(add-scatter % :x (range 1 (inc n)) :y (one-round n) :type "scattergl")))
(set-layout :xaxis {:title "Episonde" :type "log"} :showlegend false)
(plot "RL-figure-5-5" :fileopt "overwrite")
embed-url))
|
a4f2d8d5b66dc209b16ceed191f0e2cb86c8efbfedcdfd70a5d79f42df01f9a0 | haskell-mafia/mismi | Amazonka.hs | # LANGUAGE NoImplicitPrelude #
module Mismi.EC2.Amazonka (
module AWS
) where
import Network.AWS.EC2 as AWS
| null | https://raw.githubusercontent.com/haskell-mafia/mismi/f6df07a52c6c8b1cf195b58d20ef109e390be014/mismi-ec2/src/Mismi/EC2/Amazonka.hs | haskell | # LANGUAGE NoImplicitPrelude #
module Mismi.EC2.Amazonka (
module AWS
) where
import Network.AWS.EC2 as AWS
|
|
3877174ef166b78f753ac27ccaa7073f01f4ed6f020b5c48b5ff55d9fa969524 | troydm/edda | ShipyardV1.hs | {-# LANGUAGE OverloadedStrings #-}
module EDDA.Schema.ShipyardV1 where
import EDDA.Types
import EDDA.Schema.Util
import Data.Aeson
import Data.Aeson.Types
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
getShips :: Value -> ConfigT (Maybe [Str])
getShips v = return $ getStrArray v "ships"
parseShipyard :: Value -> ConfigT (Maybe MessageInfo)
parseShipyard v = do
ships <- getShips v
return $ do
systemName <- getStr v "systemName"
stationName <- getStr v "stationName"
timestamp <- getTimestamp v "timestamp"
s <- ships
Just $ ShipyardInfo { shipyardInfoSystemName = systemName,
shipyardInfoStationName = stationName,
shipyardInfoTimestamp = timestamp,
shipyardInfoShips = HS.fromList s }
| null | https://raw.githubusercontent.com/troydm/edda/710856d5bc3bf70c1061c50ae159107ca51c15f0/src/EDDA/Schema/ShipyardV1.hs | haskell | # LANGUAGE OverloadedStrings # | module EDDA.Schema.ShipyardV1 where
import EDDA.Types
import EDDA.Schema.Util
import Data.Aeson
import Data.Aeson.Types
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
getShips :: Value -> ConfigT (Maybe [Str])
getShips v = return $ getStrArray v "ships"
parseShipyard :: Value -> ConfigT (Maybe MessageInfo)
parseShipyard v = do
ships <- getShips v
return $ do
systemName <- getStr v "systemName"
stationName <- getStr v "stationName"
timestamp <- getTimestamp v "timestamp"
s <- ships
Just $ ShipyardInfo { shipyardInfoSystemName = systemName,
shipyardInfoStationName = stationName,
shipyardInfoTimestamp = timestamp,
shipyardInfoShips = HS.fromList s }
|
ec8967d7527af2fd46f5c6404adb1021251390dfa3bae27695a83386e2cc6477 | dom8509/logseq-to-markdown | config.cljs | (ns logseq-to-markdown.config
(:refer-clojure :exclude [set]))
(def exporter-config-data (atom {}))
(defn set
[config-data]
(reset! exporter-config-data config-data))
(defn entry
[key]
(get @exporter-config-data key))
| null | https://raw.githubusercontent.com/dom8509/logseq-to-markdown/de0988f700cb1a31207ee9167187bf690dbd8af6/src/logseq_to_markdown/config.cljs | clojure | (ns logseq-to-markdown.config
(:refer-clojure :exclude [set]))
(def exporter-config-data (atom {}))
(defn set
[config-data]
(reset! exporter-config-data config-data))
(defn entry
[key]
(get @exporter-config-data key))
|
|
48698170544400fa1add6733bd156dd2ac654acf9ac417cd62e20808b437b1be | tonyg/kali-scheme | mini-package.scm | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING .
; Miniature package system. This links mini-eval up to the output of
; the package reifier.
Reified package
(lambda (name)
(let loop ((i (- (vector-length names) 1)))
(if (< i 0)
(error "unbound" name)
(if (eq? name (vector-ref names i))
(contents (get-location (vector-ref locs i)))
(loop (- i 1)))))))
(define (make-simple-package opens foo1 foo2 name)
(define bindings
(list (cons '%%define%%
(lambda (name val)
(set! bindings (cons (cons name val) bindings))))))
(lambda (name)
(let ((probe (assq name bindings)))
(if probe
(cdr probe)
(let loop ((opens opens))
(if (null? opens)
(error "unbound" name)
(if (memq name (structure-interface (car opens)))
((structure-package (car opens)) name)
(loop (cdr opens)))))))))
; Structures
(define (make-structure package interface . name-option)
(cons package (vector->list interface)))
(define structure-interface cdr)
(define structure-package car)
; Things used by reification forms
(define (operator name type-exp)
`(operator ,name ,type-exp))
(define (simple-interface names type) names)
; Etc.
(define (transform . rest) (cons 'transform rest))
(define (usual-transform . rest)
(cons 'usual-transform rest))
(define (transform-for-structure-ref . rest)
(cons 'transform-for-structure-ref rest))
(define (inline-transform . rest)
(cons 'inline-transform rest))
(define (primop . rest)
(cons 'primop rest))
(define (package-define-static! package name op) 'lose)
; --------------------
; ???
; (define (integrate-all-primitives! . rest) 'lose)
( define ( package - lookup p name )
; ((p '%%lookup-operator%%) name))
;(define (package-ensure-defined! p name)
; (package-define! p name (make-location 'defined name)))
| null | https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/debug/mini-package.scm | scheme | Miniature package system. This links mini-eval up to the output of
the package reifier.
Structures
Things used by reification forms
Etc.
--------------------
???
(define (integrate-all-primitives! . rest) 'lose)
((p '%%lookup-operator%%) name))
(define (package-ensure-defined! p name)
(package-define! p name (make-location 'defined name))) | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING .
Reified package
(lambda (name)
(let loop ((i (- (vector-length names) 1)))
(if (< i 0)
(error "unbound" name)
(if (eq? name (vector-ref names i))
(contents (get-location (vector-ref locs i)))
(loop (- i 1)))))))
(define (make-simple-package opens foo1 foo2 name)
(define bindings
(list (cons '%%define%%
(lambda (name val)
(set! bindings (cons (cons name val) bindings))))))
(lambda (name)
(let ((probe (assq name bindings)))
(if probe
(cdr probe)
(let loop ((opens opens))
(if (null? opens)
(error "unbound" name)
(if (memq name (structure-interface (car opens)))
((structure-package (car opens)) name)
(loop (cdr opens)))))))))
(define (make-structure package interface . name-option)
(cons package (vector->list interface)))
(define structure-interface cdr)
(define structure-package car)
(define (operator name type-exp)
`(operator ,name ,type-exp))
(define (simple-interface names type) names)
(define (transform . rest) (cons 'transform rest))
(define (usual-transform . rest)
(cons 'usual-transform rest))
(define (transform-for-structure-ref . rest)
(cons 'transform-for-structure-ref rest))
(define (inline-transform . rest)
(cons 'inline-transform rest))
(define (primop . rest)
(cons 'primop rest))
(define (package-define-static! package name op) 'lose)
( define ( package - lookup p name )
|
e2db1b8f1f00ac9a9b0fe5ab0c47e55662c828cbe9cb05f559366cd3bee89ffd | skanev/playground | 22-tests.scm | (require rackunit rackunit/text-ui)
(load "../22.scm")
(define sicp-3.22-tests
(test-suite
"Tests for SICP exercise 3.22"
(test-begin "empty-queue?"
(check-true (empty-queue? (make-queue))))
(test-begin "insert-queue!"
(define q (make-queue))
(insert-queue! q 'a)
(check-equal? 'a (front-queue q)))
(test-begin "delete-queue!"
(define q (make-queue))
(insert-queue! q 'a)
(insert-queue! q 'b)
(check-equal? 'a (front-queue q))
(delete-queue! q)
(check-equal? 'b (front-queue q)))
))
(run-tests sicp-3.22-tests)
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/03/tests/22-tests.scm | scheme | (require rackunit rackunit/text-ui)
(load "../22.scm")
(define sicp-3.22-tests
(test-suite
"Tests for SICP exercise 3.22"
(test-begin "empty-queue?"
(check-true (empty-queue? (make-queue))))
(test-begin "insert-queue!"
(define q (make-queue))
(insert-queue! q 'a)
(check-equal? 'a (front-queue q)))
(test-begin "delete-queue!"
(define q (make-queue))
(insert-queue! q 'a)
(insert-queue! q 'b)
(check-equal? 'a (front-queue q))
(delete-queue! q)
(check-equal? 'b (front-queue q)))
))
(run-tests sicp-3.22-tests)
|
|
2cb2f90a3414b45aeb60414983a5f0d5b52c0e7f3f4812bd2896d54b3a95c8c5 | nubank/k8s-api | auth_test.clj | (ns kubernetes-api.interceptors.auth-test
(:require [clojure.test :refer :all]
[kubernetes-api.interceptors.auth :as interceptors.auth]
[matcher-combinators.matchers :as m]
[matcher-combinators.test]
[mockfn.core :refer [providing]]))
(deftest auth-test
(testing "request with basic-auth"
(is (match? {:request {:basic-auth "floki:freya1234"}}
((:enter (interceptors.auth/new {:username "floki"
:password "freya1234"})) {}))))
(testing "request with client certificate"
(providing [(#'interceptors.auth/new-ssl-engine {:client-cert "/some/client.crt"
:client-key "/some/client.key"
:ca-cert "/some/ca-cert.crt"}) 'SSLEngine]
(is (match? {:request {:sslengine #(= 'SSLEngine %)}}
((:enter (interceptors.auth/new {:client-cert "/some/client.crt"
:client-key "/some/client.key"
:ca-cert "/some/ca-cert.crt"})) {})))))
(testing "request with token"
(is (match? {:request {:oauth-token "TOKEN"}}
((:enter (interceptors.auth/new {:token "TOKEN"})) {}))))
(testing "request with token-fn"
(is (match? {:request {:oauth-token "TOKEN"}}
((:enter (interceptors.auth/new {:token-fn (constantly "TOKEN")})) {})))))
| null | https://raw.githubusercontent.com/nubank/k8s-api/5d8fb2e3ef789222f98092d48af454d297a41bc7/test/kubernetes_api/interceptors/auth_test.clj | clojure | (ns kubernetes-api.interceptors.auth-test
(:require [clojure.test :refer :all]
[kubernetes-api.interceptors.auth :as interceptors.auth]
[matcher-combinators.matchers :as m]
[matcher-combinators.test]
[mockfn.core :refer [providing]]))
(deftest auth-test
(testing "request with basic-auth"
(is (match? {:request {:basic-auth "floki:freya1234"}}
((:enter (interceptors.auth/new {:username "floki"
:password "freya1234"})) {}))))
(testing "request with client certificate"
(providing [(#'interceptors.auth/new-ssl-engine {:client-cert "/some/client.crt"
:client-key "/some/client.key"
:ca-cert "/some/ca-cert.crt"}) 'SSLEngine]
(is (match? {:request {:sslengine #(= 'SSLEngine %)}}
((:enter (interceptors.auth/new {:client-cert "/some/client.crt"
:client-key "/some/client.key"
:ca-cert "/some/ca-cert.crt"})) {})))))
(testing "request with token"
(is (match? {:request {:oauth-token "TOKEN"}}
((:enter (interceptors.auth/new {:token "TOKEN"})) {}))))
(testing "request with token-fn"
(is (match? {:request {:oauth-token "TOKEN"}}
((:enter (interceptors.auth/new {:token-fn (constantly "TOKEN")})) {})))))
|
|
d021ae65b0e6a5062ddabd6630737cbbc97bf14e44e4656ffcce2ba5d14a4baf | discus-lang/salt | Base.hs |
module Salt.LSP.Task.Diagnostics.Base where
import Salt.Data.Location
-- | Severity of a diagnostic.
data Severity
= SeverityError
| SeverityWarning
| SeverityInformation
| SeverityHint
deriving (Eq, Show)
-- | Get the numeric code of a severity level.
codeOfSeverity :: Severity -> Int
codeOfSeverity sv
= case sv of
SeverityError -> 1
SeverityWarning -> 2
SeverityInformation -> 3
SeverityHint -> 4
| Munge a range to work with VSCode
The ranges that Inchworm attaches to tokens are from the first character
to the last character in the token . VSCode wants from first character
-- to just after where to put the red wiggle.
mungeRangeForVSCode :: Range Location -> Range Location
mungeRangeForVSCode range'@(Range locStart locEnd)
| Location lStart cStart <- locStart
, Location lEnd cEnd <- locEnd
, lStart == lEnd, cEnd - cStart > 1
= Range locStart (Location lEnd (cEnd + 1))
| otherwise = range'
| null | https://raw.githubusercontent.com/discus-lang/salt/33c14414ac7e238fdbd8161971b8b8ac67fff569/src/salt/Salt/LSP/Task/Diagnostics/Base.hs | haskell | | Severity of a diagnostic.
| Get the numeric code of a severity level.
to just after where to put the red wiggle. |
module Salt.LSP.Task.Diagnostics.Base where
import Salt.Data.Location
data Severity
= SeverityError
| SeverityWarning
| SeverityInformation
| SeverityHint
deriving (Eq, Show)
codeOfSeverity :: Severity -> Int
codeOfSeverity sv
= case sv of
SeverityError -> 1
SeverityWarning -> 2
SeverityInformation -> 3
SeverityHint -> 4
| Munge a range to work with VSCode
The ranges that Inchworm attaches to tokens are from the first character
to the last character in the token . VSCode wants from first character
mungeRangeForVSCode :: Range Location -> Range Location
mungeRangeForVSCode range'@(Range locStart locEnd)
| Location lStart cStart <- locStart
, Location lEnd cEnd <- locEnd
, lStart == lEnd, cEnd - cStart > 1
= Range locStart (Location lEnd (cEnd + 1))
| otherwise = range'
|
c08bb3f01a4e808dd83d42be73d3a919c42c6df84b860ef78094ad2477baac2a | hanshuebner/bknr-web | url-handlers.lisp | (in-package :bknr-user)
(enable-interpol-syntax)
(defmethod object-url ((url url))
(format nil "/url/~A"
(store-object-id url)))
(defclass url-handler (object-handler)
())
(defmethod object-handler-get-object ((handler url-handler))
(find-store-object (parse-url) :class 'url))
(defmethod handle-object ((handler url-handler) (url (eql nil)))
(redirect "/url-page"))
(defmethod handle-object ((handler url-handler) url)
(let ((submissions (sort (group-on (url-submissions url)
:key #'(lambda (submission)
(get-daytime (url-submission-date submission))))
#'> :key #'car)))
(with-bknr-page (:title #?"url page for $((url-url url))")
(:p "keywords: "
(mapc #'url-keyword-link (url-keywords url)))
(:p (url-submissions-page submissions :full t)))))
(defclass url-redirect-handler (url-handler)
())
(defmethod handle-object ((handler url-redirect-handler) url)
(if url
(redirect (url-url url))
(redirect "/url-page")))
(defclass url-page-handler (object-date-list-handler)
())
(defmethod object-list-handler-title ((handler url-page-handler)
object)
"bknr urls")
(defmethod object-list-handler-rss-link ((handler url-page-handler)
object)
"/url-rss")
(defmethod object-list-handler-get-objects ((handler url-page-handler) object)
(mapcar #'url-latest-submission (all-urls)))
(defmethod object-date-list-handler-grouped-objects ((handler url-page-handler)
object)
(let* ((date (next-day 1 :start (object-date-list-handler-date handler object)))
(submissions (remove-if #'(lambda (submission)
(> (url-submission-date submission) date))
(object-list-handler-get-objects handler object))))
(sort (group-on submissions
:key #'(lambda (submission)
(get-daytime (url-submission-date submission))))
#'> :key #'car)))
(defmethod handle-object ((handler url-page-handler) object)
(let ((submissions (object-date-list-handler-grouped-objects handler object)))
(with-bknr-page (:title (object-list-handler-title
handler object))
(:p "random keywords: " (url-random-keywords))
(:p ((:a :href (object-list-handler-rss-link handler object)) "rss")
" "
((:a :href "/submit-url") "submit an url"))
(url-submissions-page
submissions
:start-date (object-date-list-handler-date handler object)))))
(defclass url-submitter-handler (url-page-handler)
())
(defmethod object-handler-get-object ((handler url-submitter-handler))
(find-store-object (parse-url) :class 'user
:query-function #'find-user))
(defmethod object-list-handler-get-objects ((handler url-submitter-handler)
user)
(copy-list (get-user-url-submissions user)))
(defmethod object-list-handler-title ((handler url-submitter-handler)
user)
(format nil "bknr urls submitted by ~a" (user-full-name user)))
(defmethod object-list-handler-rss-link ((handler url-submitter-handler)
user)
(format nil "/url-submitter-rss/~A"
(user-login user)))
(defmethod handle-object ((handler url-submitter-handler) user)
(let ((submissions (object-date-list-handler-grouped-objects handler user)))
(with-bknr-page (:title (object-list-handler-title
handler user))
((:a :href (object-list-handler-rss-link handler user)) "rss")
(url-submissions-page submissions
:start-date (object-date-list-handler-date
handler user)
:url (format nil "/url-submitter/~A"
(user-login user))))))
(defclass url-keyword-handler (url-page-handler keyword-handler)
())
(defmethod object-list-handler-get-objects ((handler url-keyword-handler)
keyword)
(mapcar #'url-latest-submission (get-keyword-urls keyword)))
(defmethod handle-object ((handler url-keyword-handler)
(keyword (eql nil)))
(with-bknr-page (:title "all-url-keywords")
(:ul (dolist (keyword (all-url-keywords))
(html (:li (url-keyword-link keyword)))))))
(defmethod object-list-handler-title ((handler url-keyword-handler)
keyword)
(format nil "bknr keyword urls: ~a" keyword))
(defmethod object-list-handler-rss-link ((handler url-keyword-handler)
keyword)
(format nil "/url-keyword-rss/~A"
(string-downcase (symbol-name keyword))))
(defclass url-union-handler (url-page-handler keywords-handler)
())
(defmethod object-list-handler-get-objects ((handler url-union-handler)
keywords)
(mapcar #'url-latest-submission (get-keywords-union-urls keywords)))
(defmethod object-list-handler-title ((handler url-union-handler)
keywords)
(format nil "bknr union keyword urls: ~a" keywords))
(defmethod object-list-handler-rss-link ((handler url-union-handler)
keyword)
(format nil "/url-union-rss/~A"
(parse-url)))
(defclass url-intersection-handler (url-page-handler keywords-handler)
())
(defmethod object-list-handler-get-objects ((handler url-intersection-handler)
keywords)
(mapcar #'url-latest-submission (get-keywords-intersection-urls keywords)))
(defmethod object-list-handler-title ((handler url-intersection-handler)
keywords)
(format nil "bknr intersection keyword urls: ~a" keywords))
(defmethod object-list-handler-rss-link ((handler url-intersection-handler)
keyword)
(format nil "/url-intersection-rss/~A"
(parse-url)))
| null | https://raw.githubusercontent.com/hanshuebner/bknr-web/5c30b61818a2f02f6f2e5dc69fd77396ec3afc51/modules/url/url-handlers.lisp | lisp | (in-package :bknr-user)
(enable-interpol-syntax)
(defmethod object-url ((url url))
(format nil "/url/~A"
(store-object-id url)))
(defclass url-handler (object-handler)
())
(defmethod object-handler-get-object ((handler url-handler))
(find-store-object (parse-url) :class 'url))
(defmethod handle-object ((handler url-handler) (url (eql nil)))
(redirect "/url-page"))
(defmethod handle-object ((handler url-handler) url)
(let ((submissions (sort (group-on (url-submissions url)
:key #'(lambda (submission)
(get-daytime (url-submission-date submission))))
#'> :key #'car)))
(with-bknr-page (:title #?"url page for $((url-url url))")
(:p "keywords: "
(mapc #'url-keyword-link (url-keywords url)))
(:p (url-submissions-page submissions :full t)))))
(defclass url-redirect-handler (url-handler)
())
(defmethod handle-object ((handler url-redirect-handler) url)
(if url
(redirect (url-url url))
(redirect "/url-page")))
(defclass url-page-handler (object-date-list-handler)
())
(defmethod object-list-handler-title ((handler url-page-handler)
object)
"bknr urls")
(defmethod object-list-handler-rss-link ((handler url-page-handler)
object)
"/url-rss")
(defmethod object-list-handler-get-objects ((handler url-page-handler) object)
(mapcar #'url-latest-submission (all-urls)))
(defmethod object-date-list-handler-grouped-objects ((handler url-page-handler)
object)
(let* ((date (next-day 1 :start (object-date-list-handler-date handler object)))
(submissions (remove-if #'(lambda (submission)
(> (url-submission-date submission) date))
(object-list-handler-get-objects handler object))))
(sort (group-on submissions
:key #'(lambda (submission)
(get-daytime (url-submission-date submission))))
#'> :key #'car)))
(defmethod handle-object ((handler url-page-handler) object)
(let ((submissions (object-date-list-handler-grouped-objects handler object)))
(with-bknr-page (:title (object-list-handler-title
handler object))
(:p "random keywords: " (url-random-keywords))
(:p ((:a :href (object-list-handler-rss-link handler object)) "rss")
" "
((:a :href "/submit-url") "submit an url"))
(url-submissions-page
submissions
:start-date (object-date-list-handler-date handler object)))))
(defclass url-submitter-handler (url-page-handler)
())
(defmethod object-handler-get-object ((handler url-submitter-handler))
(find-store-object (parse-url) :class 'user
:query-function #'find-user))
(defmethod object-list-handler-get-objects ((handler url-submitter-handler)
user)
(copy-list (get-user-url-submissions user)))
(defmethod object-list-handler-title ((handler url-submitter-handler)
user)
(format nil "bknr urls submitted by ~a" (user-full-name user)))
(defmethod object-list-handler-rss-link ((handler url-submitter-handler)
user)
(format nil "/url-submitter-rss/~A"
(user-login user)))
(defmethod handle-object ((handler url-submitter-handler) user)
(let ((submissions (object-date-list-handler-grouped-objects handler user)))
(with-bknr-page (:title (object-list-handler-title
handler user))
((:a :href (object-list-handler-rss-link handler user)) "rss")
(url-submissions-page submissions
:start-date (object-date-list-handler-date
handler user)
:url (format nil "/url-submitter/~A"
(user-login user))))))
(defclass url-keyword-handler (url-page-handler keyword-handler)
())
(defmethod object-list-handler-get-objects ((handler url-keyword-handler)
keyword)
(mapcar #'url-latest-submission (get-keyword-urls keyword)))
(defmethod handle-object ((handler url-keyword-handler)
(keyword (eql nil)))
(with-bknr-page (:title "all-url-keywords")
(:ul (dolist (keyword (all-url-keywords))
(html (:li (url-keyword-link keyword)))))))
(defmethod object-list-handler-title ((handler url-keyword-handler)
keyword)
(format nil "bknr keyword urls: ~a" keyword))
(defmethod object-list-handler-rss-link ((handler url-keyword-handler)
keyword)
(format nil "/url-keyword-rss/~A"
(string-downcase (symbol-name keyword))))
(defclass url-union-handler (url-page-handler keywords-handler)
())
(defmethod object-list-handler-get-objects ((handler url-union-handler)
keywords)
(mapcar #'url-latest-submission (get-keywords-union-urls keywords)))
(defmethod object-list-handler-title ((handler url-union-handler)
keywords)
(format nil "bknr union keyword urls: ~a" keywords))
(defmethod object-list-handler-rss-link ((handler url-union-handler)
keyword)
(format nil "/url-union-rss/~A"
(parse-url)))
(defclass url-intersection-handler (url-page-handler keywords-handler)
())
(defmethod object-list-handler-get-objects ((handler url-intersection-handler)
keywords)
(mapcar #'url-latest-submission (get-keywords-intersection-urls keywords)))
(defmethod object-list-handler-title ((handler url-intersection-handler)
keywords)
(format nil "bknr intersection keyword urls: ~a" keywords))
(defmethod object-list-handler-rss-link ((handler url-intersection-handler)
keyword)
(format nil "/url-intersection-rss/~A"
(parse-url)))
|
|
211380b0db148980b5ac4aa56b98d3c7dbab934db82ef7b6bef9f106860b354f | craigfe/sink | tuple.ml | $
let alpha i = Char.chr ( i + 96 )
let rec interleave ~sep = function
| ( [ ] | [ _ ] ) as l - > l
| h1 : : ( _ : : _ as tl ) - > h1 : : sep : : interleave ~sep tl
type component = { fmap : string ; proj : string }
let component = function
| 1 - > { fmap = " first " ; proj = " p1 " }
| 2 - > { fmap = " second " ; proj = " p2 " }
| 3 - > { fmap = " third " ; proj = " p3 " }
| 4 - > { fmap = " fourth " ; proj = " p4 " }
| 5 - > { fmap = " fifth " ; proj = " p5 " }
| _ - > assert false
let pp_tuple ~typ ? ( cs = [ ] ) ( ) ppf n =
let component i =
match List.assoc_opt i cs with
| Some s - > s
| None - > String.make 1 ( alpha i )
in
( match typ with ` - > Format.fprintf ppf " ( " | ` Sig - > ( ) ) ;
for i = 1 to n - 1 do
Format.fprintf ppf
( match typ with ` Str - > " % s , " | ` Sig - > " ' % s * " )
( component i )
done ;
Format.fprintf ( match typ with ` Str - > " % s ) " | ` Sig - > " ' % s " )
( component n )
let print_const ? ( cs = [ ] ) ( ) ppf n =
let component i =
match List.assoc_opt i cs with
| Some s - > s
| None - > " ' " ^ String.make 1 ( alpha i )
in
Format.fprintf ppf " ( " ;
for i = 1 to n - 1 do
Format.fprintf ppf " % s , " ( component i )
done ;
Format.fprintf ppf " % s ) t " ( component n )
let pp_projections ~typ ppf n =
match typ with
| ` Sig - >
Format.fprintf ppf
" ( * * Projecting each component from the tuple :
let alpha i = Char.chr (i + 96)
let rec interleave ~sep = function
| ([] | [ _ ]) as l -> l
| h1 :: (_ :: _ as tl) -> h1 :: sep :: interleave ~sep tl
type component = { fmap : string; proj : string }
let component = function
| 1 -> { fmap = "first "; proj = "p1" }
| 2 -> { fmap = "second"; proj = "p2" }
| 3 -> { fmap = "third "; proj = "p3" }
| 4 -> { fmap = "fourth"; proj = "p4" }
| 5 -> { fmap = "fifth "; proj = "p5" }
| _ -> assert false
let pp_tuple ~typ ?(cs = []) () ppf n =
let component i =
match List.assoc_opt i cs with
| Some s -> s
| None -> String.make 1 (alpha i)
in
(match typ with `Str -> Format.fprintf ppf "(" | `Sig -> ());
for i = 1 to n - 1 do
Format.fprintf ppf
(match typ with `Str -> "%s, " | `Sig -> "'%s * ")
(component i)
done;
Format.fprintf ppf
(match typ with `Str -> "%s)" | `Sig -> "'%s")
(component n)
let print_const ?(cs = []) () ppf n =
let component i =
match List.assoc_opt i cs with
| Some s -> s
| None -> "'" ^ String.make 1 (alpha i)
in
Format.fprintf ppf "(";
for i = 1 to n - 1 do
Format.fprintf ppf "%s, " (component i)
done;
Format.fprintf ppf "%s) t" (component n)
let pp_projections ~typ ppf n =
match typ with
| `Sig ->
Format.fprintf ppf
" (** Projecting each component from the tuple: *)\n";
for i = 1 to n do
let cs =
List.init n (function
| j when j + 1 = i -> (j + 1, "'" ^ String.make 1 (alpha (j + 1)))
| j -> (j + 1, "_"))
in
Format.fprintf ppf " val %s : %a -> '%c\n" (component i).proj
(print_const ~cs ()) n (alpha i)
done
| `Str ->
for i = 1 to n do
let cs =
List.init n (function
| j when j + 1 = i -> (j + 1, String.make 1 (alpha (j + 1)))
| j -> (j + 1, "_"))
in
Format.fprintf ppf " let %s %a = %c\n" (component i).proj
(pp_tuple ~typ:`Str ~cs ())
n (alpha i)
done
let pp_mono ~typ ppf n =
match typ with
| `Sig ->
let xs = List.init n (fun j -> (j + 1, "'a")) in
let ys = List.init n (fun j -> (j + 1, "'b")) in
Format.fprintf ppf " val map : ('a -> 'b) -> %a -> %a\n"
(print_const ~cs:xs ()) n (print_const ~cs:ys ()) n;
Format.fprintf ppf " val equal : ord:'a Ord.t -> %a -> %a -> bool\n"
(print_const ~cs:xs ()) n (print_const ~cs:xs ()) n;
Format.fprintf ppf " val minimum : ord:'a Ord.t -> %a -> 'a\n"
(print_const ~cs:xs ()) n;
Format.fprintf ppf
" val minimum_on : ord:'b Ord.t -> ('a -> 'b) -> %a -> 'a\n"
(print_const ~cs:xs ()) n;
Format.fprintf ppf " val maximum : ord:'a Ord.t -> %a -> 'a\n"
(print_const ~cs:xs ()) n;
Format.fprintf ppf
" val maximum_on : ord:'b Ord.t -> ('a -> 'b) -> %a -> 'a\n"
(print_const ~cs:xs ()) n
| `Str ->
Format.fprintf ppf " let map f %a = %a\n"
(pp_tuple ~typ:`Str ())
n
(pp_tuple ~typ:`Str
~cs:
(List.init n (fun i ->
(i + 1, Format.sprintf "f %c" (alpha (i + 1)))))
())
n;
let cs =
List.init n (fun j -> (j + 1, Format.sprintf "%c" (alpha (j + 1))))
in
let xs =
List.init n (fun j -> (j + 1, Format.sprintf "%c1" (alpha (j + 1))))
in
let ys =
List.init n (fun j -> (j + 1, Format.sprintf "%c2" (alpha (j + 1))))
in
let equals =
List.init n (fun j ->
Format.sprintf "ord.equal %c1 %c2" (alpha (j + 1)) (alpha (j + 1)))
|> String.concat "\n && "
in
Format.fprintf ppf
" let equal (type o) ~(ord : o Ord.t) %a %a =\n %s\n\n"
(pp_tuple ~typ:`Str ~cs:xs ())
n
(pp_tuple ~typ:`Str ~cs:ys ())
n equals;
let rec fold_left ~f ppf xs =
let rec inner ~acc = function
| [] -> Format.fprintf ppf " acc"
| x :: xs ->
Format.fprintf ppf " let acc = %s in\n" (f acc x);
inner ~acc:"acc" xs
in
inner ~acc:(List.hd xs) (List.tl xs)
in
Format.fprintf ppf
" let minimum (type o) ~(ord : o Ord.t) %a =\n%a\n\n"
(pp_tuple ~typ:`Str ~cs ())
n
(fold_left ~f:(Format.sprintf "ord.min %s %s"))
(List.map snd cs);
Format.fprintf ppf
" let maximum (type o) ~(ord : o Ord.t) %a =\n%a\n\n"
(pp_tuple ~typ:`Str ~cs ())
n
(fold_left ~f:(Format.sprintf "ord.max %s %s"))
(List.map snd cs);
let f a b =
Format.sprintf
"match ord.compare (f %s) (f %s) with Lt | Eq -> %s | Gt -> %s" a b
a b
in
Format.fprintf ppf
" let minimum_on (type o) ~(ord : o Ord.t) f %a =\n%a\n\n"
(pp_tuple ~typ:`Str ~cs ())
n (fold_left ~f) (List.map snd cs);
let f a b =
Format.sprintf
"match ord.compare (f %s) (f %s) with Gt | Eq -> %s | Lt -> %s" a b
a b
in
Format.fprintf ppf
" let maximum_on (type o) ~(ord : o Ord.t) f %a =\n%a\n\n"
(pp_tuple ~typ:`Str ~cs ())
n (fold_left ~f) (List.map snd cs)
let pp_maps ~typ ppf n =
match typ with
| `Sig ->
Format.fprintf ppf
" (** Functor instances on each of the components: *)\n";
for i = 1 to n do
Format.fprintf ppf " val %s : ('%c1 -> '%c2) -> %a -> %a\n"
(component i).fmap (alpha i) (alpha i)
(print_const ~cs:[ (i, Format.sprintf "'%c1" (alpha i)) ] ())
n
(print_const ~cs:[ (i, Format.sprintf "'%c2" (alpha i)) ] ())
n
done
| `Str ->
for i = 1 to n do
Format.fprintf ppf " let %s f %a = %a\n" (component i).fmap
(pp_tuple ~typ:`Str ())
n
(pp_tuple ~typ:`Str ~cs:[ (i, Format.sprintf "f %c" (alpha i)) ] ())
n
done
let pp_typ ppf n =
Format.printf "type %a = %a" (print_const ()) n (pp_tuple ~typ:`Sig ()) n
let pp_sig ppf n =
Format.fprintf ppf " %a [@implements Eq.S]\n" pp_typ n;
Format.fprintf ppf "\n%a" (pp_projections ~typ:`Sig) n;
Format.fprintf ppf "\n%a" (pp_mono ~typ:`Sig) n;
Format.fprintf ppf "\n%a" (pp_maps ~typ:`Sig) n;
()
let pp_struct ppf n =
Format.fprintf ppf " %a\n" pp_typ n;
Format.fprintf ppf "\n%a" (pp_projections ~typ:`Str) n;
Format.fprintf ppf "\n%a" (pp_mono ~typ:`Str) n;
Format.fprintf ppf "\n%a" (pp_maps ~typ:`Str) n;
()
let print_module n =
Format.printf "\nmodule T%d : sig\n%a\nend = struct\n%aend\n" n pp_sig n
pp_struct n
;;
for i = 2 to 5 do
print_module i
done
*)
module T2 : sig
type ('a, 'b) t = 'a * 'b [@implements Eq.S]
(** Projecting each component from the tuple: *)
val p1 : ('a, _) t -> 'a
val p2 : (_, 'b) t -> 'b
val map : ('a -> 'b) -> ('a, 'a) t -> ('b, 'b) t
val equal : ord:'a Ord.t -> ('a, 'a) t -> ('a, 'a) t -> bool
val minimum : ord:'a Ord.t -> ('a, 'a) t -> 'a
val minimum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a) t -> 'a
val maximum : ord:'a Ord.t -> ('a, 'a) t -> 'a
val maximum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a) t -> 'a
(** Functor instances on each of the components: *)
val first : ('a1 -> 'a2) -> ('a1, 'b) t -> ('a2, 'b) t
val second : ('b1 -> 'b2) -> ('a, 'b1) t -> ('a, 'b2) t
end = struct
type ('a, 'b) t = 'a * 'b
let p1 (a, _) = a
let p2 (_, b) = b
let map f (a, b) = (f a, f b)
let equal (type o) ~(ord : o Ord.t) (a1, b1) (a2, b2) =
ord.equal a1 a2
&& ord.equal b1 b2
let minimum (type o) ~(ord : o Ord.t) (a, b) =
let acc = ord.min a b in
acc
let maximum (type o) ~(ord : o Ord.t) (a, b) =
let acc = ord.max a b in
acc
let minimum_on (type o) ~(ord : o Ord.t) f (a, b) =
let acc = match ord.compare (f a) (f b) with Lt | Eq -> a | Gt -> b in
acc
let maximum_on (type o) ~(ord : o Ord.t) f (a, b) =
let acc = match ord.compare (f a) (f b) with Gt | Eq -> a | Lt -> b in
acc
let first f (a, b) = (f a, b)
let second f (a, b) = (a, f b)
end
module T3 : sig
type ('a, 'b, 'c) t = 'a * 'b * 'c [@implements Eq.S]
(** Projecting each component from the tuple: *)
val p1 : ('a, _, _) t -> 'a
val p2 : (_, 'b, _) t -> 'b
val p3 : (_, _, 'c) t -> 'c
val map : ('a -> 'b) -> ('a, 'a, 'a) t -> ('b, 'b, 'b) t
val equal : ord:'a Ord.t -> ('a, 'a, 'a) t -> ('a, 'a, 'a) t -> bool
val minimum : ord:'a Ord.t -> ('a, 'a, 'a) t -> 'a
val minimum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a) t -> 'a
val maximum : ord:'a Ord.t -> ('a, 'a, 'a) t -> 'a
val maximum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a) t -> 'a
(** Functor instances on each of the components: *)
val first : ('a1 -> 'a2) -> ('a1, 'b, 'c) t -> ('a2, 'b, 'c) t
val second : ('b1 -> 'b2) -> ('a, 'b1, 'c) t -> ('a, 'b2, 'c) t
val third : ('c1 -> 'c2) -> ('a, 'b, 'c1) t -> ('a, 'b, 'c2) t
end = struct
type ('a, 'b, 'c) t = 'a * 'b * 'c
let p1 (a, _, _) = a
let p2 (_, b, _) = b
let p3 (_, _, c) = c
let map f (a, b, c) = (f a, f b, f c)
let equal (type o) ~(ord : o Ord.t) (a1, b1, c1) (a2, b2, c2) =
ord.equal a1 a2
&& ord.equal b1 b2
&& ord.equal c1 c2
let minimum (type o) ~(ord : o Ord.t) (a, b, c) =
let acc = ord.min a b in
let acc = ord.min acc c in
acc
let maximum (type o) ~(ord : o Ord.t) (a, b, c) =
let acc = ord.max a b in
let acc = ord.max acc c in
acc
let minimum_on (type o) ~(ord : o Ord.t) f (a, b, c) =
let acc = match ord.compare (f a) (f b) with Lt | Eq -> a | Gt -> b in
let acc = match ord.compare (f acc) (f c) with Lt | Eq -> acc | Gt -> c in
acc
let maximum_on (type o) ~(ord : o Ord.t) f (a, b, c) =
let acc = match ord.compare (f a) (f b) with Gt | Eq -> a | Lt -> b in
let acc = match ord.compare (f acc) (f c) with Gt | Eq -> acc | Lt -> c in
acc
let first f (a, b, c) = (f a, b, c)
let second f (a, b, c) = (a, f b, c)
let third f (a, b, c) = (a, b, f c)
end
module T4 : sig
type ('a, 'b, 'c, 'd) t = 'a * 'b * 'c * 'd [@implements Eq.S]
(** Projecting each component from the tuple: *)
val p1 : ('a, _, _, _) t -> 'a
val p2 : (_, 'b, _, _) t -> 'b
val p3 : (_, _, 'c, _) t -> 'c
val p4 : (_, _, _, 'd) t -> 'd
val map : ('a -> 'b) -> ('a, 'a, 'a, 'a) t -> ('b, 'b, 'b, 'b) t
val equal : ord:'a Ord.t -> ('a, 'a, 'a, 'a) t -> ('a, 'a, 'a, 'a) t -> bool
val minimum : ord:'a Ord.t -> ('a, 'a, 'a, 'a) t -> 'a
val minimum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a, 'a) t -> 'a
val maximum : ord:'a Ord.t -> ('a, 'a, 'a, 'a) t -> 'a
val maximum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a, 'a) t -> 'a
(** Functor instances on each of the components: *)
val first : ('a1 -> 'a2) -> ('a1, 'b, 'c, 'd) t -> ('a2, 'b, 'c, 'd) t
val second : ('b1 -> 'b2) -> ('a, 'b1, 'c, 'd) t -> ('a, 'b2, 'c, 'd) t
val third : ('c1 -> 'c2) -> ('a, 'b, 'c1, 'd) t -> ('a, 'b, 'c2, 'd) t
val fourth : ('d1 -> 'd2) -> ('a, 'b, 'c, 'd1) t -> ('a, 'b, 'c, 'd2) t
end = struct
type ('a, 'b, 'c, 'd) t = 'a * 'b * 'c * 'd
let p1 (a, _, _, _) = a
let p2 (_, b, _, _) = b
let p3 (_, _, c, _) = c
let p4 (_, _, _, d) = d
let map f (a, b, c, d) = (f a, f b, f c, f d)
let equal (type o) ~(ord : o Ord.t) (a1, b1, c1, d1) (a2, b2, c2, d2) =
ord.equal a1 a2
&& ord.equal b1 b2
&& ord.equal c1 c2
&& ord.equal d1 d2
let minimum (type o) ~(ord : o Ord.t) (a, b, c, d) =
let acc = ord.min a b in
let acc = ord.min acc c in
let acc = ord.min acc d in
acc
let maximum (type o) ~(ord : o Ord.t) (a, b, c, d) =
let acc = ord.max a b in
let acc = ord.max acc c in
let acc = ord.max acc d in
acc
let minimum_on (type o) ~(ord : o Ord.t) f (a, b, c, d) =
let acc = match ord.compare (f a) (f b) with Lt | Eq -> a | Gt -> b in
let acc = match ord.compare (f acc) (f c) with Lt | Eq -> acc | Gt -> c in
let acc = match ord.compare (f acc) (f d) with Lt | Eq -> acc | Gt -> d in
acc
let maximum_on (type o) ~(ord : o Ord.t) f (a, b, c, d) =
let acc = match ord.compare (f a) (f b) with Gt | Eq -> a | Lt -> b in
let acc = match ord.compare (f acc) (f c) with Gt | Eq -> acc | Lt -> c in
let acc = match ord.compare (f acc) (f d) with Gt | Eq -> acc | Lt -> d in
acc
let first f (a, b, c, d) = (f a, b, c, d)
let second f (a, b, c, d) = (a, f b, c, d)
let third f (a, b, c, d) = (a, b, f c, d)
let fourth f (a, b, c, d) = (a, b, c, f d)
end
module T5 : sig
type ('a, 'b, 'c, 'd, 'e) t = 'a * 'b * 'c * 'd * 'e [@implements Eq.S]
(** Projecting each component from the tuple: *)
val p1 : ('a, _, _, _, _) t -> 'a
val p2 : (_, 'b, _, _, _) t -> 'b
val p3 : (_, _, 'c, _, _) t -> 'c
val p4 : (_, _, _, 'd, _) t -> 'd
val p5 : (_, _, _, _, 'e) t -> 'e
val map : ('a -> 'b) -> ('a, 'a, 'a, 'a, 'a) t -> ('b, 'b, 'b, 'b, 'b) t
val equal : ord:'a Ord.t -> ('a, 'a, 'a, 'a, 'a) t -> ('a, 'a, 'a, 'a, 'a) t -> bool
val minimum : ord:'a Ord.t -> ('a, 'a, 'a, 'a, 'a) t -> 'a
val minimum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a, 'a, 'a) t -> 'a
val maximum : ord:'a Ord.t -> ('a, 'a, 'a, 'a, 'a) t -> 'a
val maximum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a, 'a, 'a) t -> 'a
(** Functor instances on each of the components: *)
val first : ('a1 -> 'a2) -> ('a1, 'b, 'c, 'd, 'e) t -> ('a2, 'b, 'c, 'd, 'e) t
val second : ('b1 -> 'b2) -> ('a, 'b1, 'c, 'd, 'e) t -> ('a, 'b2, 'c, 'd, 'e) t
val third : ('c1 -> 'c2) -> ('a, 'b, 'c1, 'd, 'e) t -> ('a, 'b, 'c2, 'd, 'e) t
val fourth : ('d1 -> 'd2) -> ('a, 'b, 'c, 'd1, 'e) t -> ('a, 'b, 'c, 'd2, 'e) t
val fifth : ('e1 -> 'e2) -> ('a, 'b, 'c, 'd, 'e1) t -> ('a, 'b, 'c, 'd, 'e2) t
end = struct
type ('a, 'b, 'c, 'd, 'e) t = 'a * 'b * 'c * 'd * 'e
let p1 (a, _, _, _, _) = a
let p2 (_, b, _, _, _) = b
let p3 (_, _, c, _, _) = c
let p4 (_, _, _, d, _) = d
let p5 (_, _, _, _, e) = e
let map f (a, b, c, d, e) = (f a, f b, f c, f d, f e)
let equal (type o) ~(ord : o Ord.t) (a1, b1, c1, d1, e1) (a2, b2, c2, d2, e2) =
ord.equal a1 a2
&& ord.equal b1 b2
&& ord.equal c1 c2
&& ord.equal d1 d2
&& ord.equal e1 e2
let minimum (type o) ~(ord : o Ord.t) (a, b, c, d, e) =
let acc = ord.min a b in
let acc = ord.min acc c in
let acc = ord.min acc d in
let acc = ord.min acc e in
acc
let maximum (type o) ~(ord : o Ord.t) (a, b, c, d, e) =
let acc = ord.max a b in
let acc = ord.max acc c in
let acc = ord.max acc d in
let acc = ord.max acc e in
acc
let minimum_on (type o) ~(ord : o Ord.t) f (a, b, c, d, e) =
let acc = match ord.compare (f a) (f b) with Lt | Eq -> a | Gt -> b in
let acc = match ord.compare (f acc) (f c) with Lt | Eq -> acc | Gt -> c in
let acc = match ord.compare (f acc) (f d) with Lt | Eq -> acc | Gt -> d in
let acc = match ord.compare (f acc) (f e) with Lt | Eq -> acc | Gt -> e in
acc
let maximum_on (type o) ~(ord : o Ord.t) f (a, b, c, d, e) =
let acc = match ord.compare (f a) (f b) with Gt | Eq -> a | Lt -> b in
let acc = match ord.compare (f acc) (f c) with Gt | Eq -> acc | Lt -> c in
let acc = match ord.compare (f acc) (f d) with Gt | Eq -> acc | Lt -> d in
let acc = match ord.compare (f acc) (f e) with Gt | Eq -> acc | Lt -> e in
acc
let first f (a, b, c, d, e) = (f a, b, c, d, e)
let second f (a, b, c, d, e) = (a, f b, c, d, e)
let third f (a, b, c, d, e) = (a, b, f c, d, e)
let fourth f (a, b, c, d, e) = (a, b, c, f d, e)
let fifth f (a, b, c, d, e) = (a, b, c, d, f e)
end
(*$*)
| null | https://raw.githubusercontent.com/craigfe/sink/c5431edfa1b06f1a09845a481c4afcb3e92f0667/src/sink/tuple.ml | ocaml | * Projecting each component from the tuple:
* Functor instances on each of the components:
* Projecting each component from the tuple:
* Functor instances on each of the components:
* Projecting each component from the tuple:
* Functor instances on each of the components:
* Projecting each component from the tuple:
* Functor instances on each of the components:
$ | $
let alpha i = Char.chr ( i + 96 )
let rec interleave ~sep = function
| ( [ ] | [ _ ] ) as l - > l
| h1 : : ( _ : : _ as tl ) - > h1 : : sep : : interleave ~sep tl
type component = { fmap : string ; proj : string }
let component = function
| 1 - > { fmap = " first " ; proj = " p1 " }
| 2 - > { fmap = " second " ; proj = " p2 " }
| 3 - > { fmap = " third " ; proj = " p3 " }
| 4 - > { fmap = " fourth " ; proj = " p4 " }
| 5 - > { fmap = " fifth " ; proj = " p5 " }
| _ - > assert false
let pp_tuple ~typ ? ( cs = [ ] ) ( ) ppf n =
let component i =
match List.assoc_opt i cs with
| Some s - > s
| None - > String.make 1 ( alpha i )
in
( match typ with ` - > Format.fprintf ppf " ( " | ` Sig - > ( ) ) ;
for i = 1 to n - 1 do
Format.fprintf ppf
( match typ with ` Str - > " % s , " | ` Sig - > " ' % s * " )
( component i )
done ;
Format.fprintf ( match typ with ` Str - > " % s ) " | ` Sig - > " ' % s " )
( component n )
let print_const ? ( cs = [ ] ) ( ) ppf n =
let component i =
match List.assoc_opt i cs with
| Some s - > s
| None - > " ' " ^ String.make 1 ( alpha i )
in
Format.fprintf ppf " ( " ;
for i = 1 to n - 1 do
Format.fprintf ppf " % s , " ( component i )
done ;
Format.fprintf ppf " % s ) t " ( component n )
let pp_projections ~typ ppf n =
match typ with
| ` Sig - >
Format.fprintf ppf
" ( * * Projecting each component from the tuple :
let alpha i = Char.chr (i + 96)
let rec interleave ~sep = function
| ([] | [ _ ]) as l -> l
| h1 :: (_ :: _ as tl) -> h1 :: sep :: interleave ~sep tl
type component = { fmap : string; proj : string }
let component = function
| 1 -> { fmap = "first "; proj = "p1" }
| 2 -> { fmap = "second"; proj = "p2" }
| 3 -> { fmap = "third "; proj = "p3" }
| 4 -> { fmap = "fourth"; proj = "p4" }
| 5 -> { fmap = "fifth "; proj = "p5" }
| _ -> assert false
let pp_tuple ~typ ?(cs = []) () ppf n =
let component i =
match List.assoc_opt i cs with
| Some s -> s
| None -> String.make 1 (alpha i)
in
(match typ with `Str -> Format.fprintf ppf "(" | `Sig -> ());
for i = 1 to n - 1 do
Format.fprintf ppf
(match typ with `Str -> "%s, " | `Sig -> "'%s * ")
(component i)
done;
Format.fprintf ppf
(match typ with `Str -> "%s)" | `Sig -> "'%s")
(component n)
let print_const ?(cs = []) () ppf n =
let component i =
match List.assoc_opt i cs with
| Some s -> s
| None -> "'" ^ String.make 1 (alpha i)
in
Format.fprintf ppf "(";
for i = 1 to n - 1 do
Format.fprintf ppf "%s, " (component i)
done;
Format.fprintf ppf "%s) t" (component n)
let pp_projections ~typ ppf n =
match typ with
| `Sig ->
Format.fprintf ppf
" (** Projecting each component from the tuple: *)\n";
for i = 1 to n do
let cs =
List.init n (function
| j when j + 1 = i -> (j + 1, "'" ^ String.make 1 (alpha (j + 1)))
| j -> (j + 1, "_"))
in
Format.fprintf ppf " val %s : %a -> '%c\n" (component i).proj
(print_const ~cs ()) n (alpha i)
done
| `Str ->
for i = 1 to n do
let cs =
List.init n (function
| j when j + 1 = i -> (j + 1, String.make 1 (alpha (j + 1)))
| j -> (j + 1, "_"))
in
Format.fprintf ppf " let %s %a = %c\n" (component i).proj
(pp_tuple ~typ:`Str ~cs ())
n (alpha i)
done
let pp_mono ~typ ppf n =
match typ with
| `Sig ->
let xs = List.init n (fun j -> (j + 1, "'a")) in
let ys = List.init n (fun j -> (j + 1, "'b")) in
Format.fprintf ppf " val map : ('a -> 'b) -> %a -> %a\n"
(print_const ~cs:xs ()) n (print_const ~cs:ys ()) n;
Format.fprintf ppf " val equal : ord:'a Ord.t -> %a -> %a -> bool\n"
(print_const ~cs:xs ()) n (print_const ~cs:xs ()) n;
Format.fprintf ppf " val minimum : ord:'a Ord.t -> %a -> 'a\n"
(print_const ~cs:xs ()) n;
Format.fprintf ppf
" val minimum_on : ord:'b Ord.t -> ('a -> 'b) -> %a -> 'a\n"
(print_const ~cs:xs ()) n;
Format.fprintf ppf " val maximum : ord:'a Ord.t -> %a -> 'a\n"
(print_const ~cs:xs ()) n;
Format.fprintf ppf
" val maximum_on : ord:'b Ord.t -> ('a -> 'b) -> %a -> 'a\n"
(print_const ~cs:xs ()) n
| `Str ->
Format.fprintf ppf " let map f %a = %a\n"
(pp_tuple ~typ:`Str ())
n
(pp_tuple ~typ:`Str
~cs:
(List.init n (fun i ->
(i + 1, Format.sprintf "f %c" (alpha (i + 1)))))
())
n;
let cs =
List.init n (fun j -> (j + 1, Format.sprintf "%c" (alpha (j + 1))))
in
let xs =
List.init n (fun j -> (j + 1, Format.sprintf "%c1" (alpha (j + 1))))
in
let ys =
List.init n (fun j -> (j + 1, Format.sprintf "%c2" (alpha (j + 1))))
in
let equals =
List.init n (fun j ->
Format.sprintf "ord.equal %c1 %c2" (alpha (j + 1)) (alpha (j + 1)))
|> String.concat "\n && "
in
Format.fprintf ppf
" let equal (type o) ~(ord : o Ord.t) %a %a =\n %s\n\n"
(pp_tuple ~typ:`Str ~cs:xs ())
n
(pp_tuple ~typ:`Str ~cs:ys ())
n equals;
let rec fold_left ~f ppf xs =
let rec inner ~acc = function
| [] -> Format.fprintf ppf " acc"
| x :: xs ->
Format.fprintf ppf " let acc = %s in\n" (f acc x);
inner ~acc:"acc" xs
in
inner ~acc:(List.hd xs) (List.tl xs)
in
Format.fprintf ppf
" let minimum (type o) ~(ord : o Ord.t) %a =\n%a\n\n"
(pp_tuple ~typ:`Str ~cs ())
n
(fold_left ~f:(Format.sprintf "ord.min %s %s"))
(List.map snd cs);
Format.fprintf ppf
" let maximum (type o) ~(ord : o Ord.t) %a =\n%a\n\n"
(pp_tuple ~typ:`Str ~cs ())
n
(fold_left ~f:(Format.sprintf "ord.max %s %s"))
(List.map snd cs);
let f a b =
Format.sprintf
"match ord.compare (f %s) (f %s) with Lt | Eq -> %s | Gt -> %s" a b
a b
in
Format.fprintf ppf
" let minimum_on (type o) ~(ord : o Ord.t) f %a =\n%a\n\n"
(pp_tuple ~typ:`Str ~cs ())
n (fold_left ~f) (List.map snd cs);
let f a b =
Format.sprintf
"match ord.compare (f %s) (f %s) with Gt | Eq -> %s | Lt -> %s" a b
a b
in
Format.fprintf ppf
" let maximum_on (type o) ~(ord : o Ord.t) f %a =\n%a\n\n"
(pp_tuple ~typ:`Str ~cs ())
n (fold_left ~f) (List.map snd cs)
let pp_maps ~typ ppf n =
match typ with
| `Sig ->
Format.fprintf ppf
" (** Functor instances on each of the components: *)\n";
for i = 1 to n do
Format.fprintf ppf " val %s : ('%c1 -> '%c2) -> %a -> %a\n"
(component i).fmap (alpha i) (alpha i)
(print_const ~cs:[ (i, Format.sprintf "'%c1" (alpha i)) ] ())
n
(print_const ~cs:[ (i, Format.sprintf "'%c2" (alpha i)) ] ())
n
done
| `Str ->
for i = 1 to n do
Format.fprintf ppf " let %s f %a = %a\n" (component i).fmap
(pp_tuple ~typ:`Str ())
n
(pp_tuple ~typ:`Str ~cs:[ (i, Format.sprintf "f %c" (alpha i)) ] ())
n
done
let pp_typ ppf n =
Format.printf "type %a = %a" (print_const ()) n (pp_tuple ~typ:`Sig ()) n
let pp_sig ppf n =
Format.fprintf ppf " %a [@implements Eq.S]\n" pp_typ n;
Format.fprintf ppf "\n%a" (pp_projections ~typ:`Sig) n;
Format.fprintf ppf "\n%a" (pp_mono ~typ:`Sig) n;
Format.fprintf ppf "\n%a" (pp_maps ~typ:`Sig) n;
()
let pp_struct ppf n =
Format.fprintf ppf " %a\n" pp_typ n;
Format.fprintf ppf "\n%a" (pp_projections ~typ:`Str) n;
Format.fprintf ppf "\n%a" (pp_mono ~typ:`Str) n;
Format.fprintf ppf "\n%a" (pp_maps ~typ:`Str) n;
()
let print_module n =
Format.printf "\nmodule T%d : sig\n%a\nend = struct\n%aend\n" n pp_sig n
pp_struct n
;;
for i = 2 to 5 do
print_module i
done
*)
module T2 : sig
type ('a, 'b) t = 'a * 'b [@implements Eq.S]
val p1 : ('a, _) t -> 'a
val p2 : (_, 'b) t -> 'b
val map : ('a -> 'b) -> ('a, 'a) t -> ('b, 'b) t
val equal : ord:'a Ord.t -> ('a, 'a) t -> ('a, 'a) t -> bool
val minimum : ord:'a Ord.t -> ('a, 'a) t -> 'a
val minimum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a) t -> 'a
val maximum : ord:'a Ord.t -> ('a, 'a) t -> 'a
val maximum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a) t -> 'a
val first : ('a1 -> 'a2) -> ('a1, 'b) t -> ('a2, 'b) t
val second : ('b1 -> 'b2) -> ('a, 'b1) t -> ('a, 'b2) t
end = struct
type ('a, 'b) t = 'a * 'b
let p1 (a, _) = a
let p2 (_, b) = b
let map f (a, b) = (f a, f b)
let equal (type o) ~(ord : o Ord.t) (a1, b1) (a2, b2) =
ord.equal a1 a2
&& ord.equal b1 b2
let minimum (type o) ~(ord : o Ord.t) (a, b) =
let acc = ord.min a b in
acc
let maximum (type o) ~(ord : o Ord.t) (a, b) =
let acc = ord.max a b in
acc
let minimum_on (type o) ~(ord : o Ord.t) f (a, b) =
let acc = match ord.compare (f a) (f b) with Lt | Eq -> a | Gt -> b in
acc
let maximum_on (type o) ~(ord : o Ord.t) f (a, b) =
let acc = match ord.compare (f a) (f b) with Gt | Eq -> a | Lt -> b in
acc
let first f (a, b) = (f a, b)
let second f (a, b) = (a, f b)
end
module T3 : sig
type ('a, 'b, 'c) t = 'a * 'b * 'c [@implements Eq.S]
val p1 : ('a, _, _) t -> 'a
val p2 : (_, 'b, _) t -> 'b
val p3 : (_, _, 'c) t -> 'c
val map : ('a -> 'b) -> ('a, 'a, 'a) t -> ('b, 'b, 'b) t
val equal : ord:'a Ord.t -> ('a, 'a, 'a) t -> ('a, 'a, 'a) t -> bool
val minimum : ord:'a Ord.t -> ('a, 'a, 'a) t -> 'a
val minimum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a) t -> 'a
val maximum : ord:'a Ord.t -> ('a, 'a, 'a) t -> 'a
val maximum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a) t -> 'a
val first : ('a1 -> 'a2) -> ('a1, 'b, 'c) t -> ('a2, 'b, 'c) t
val second : ('b1 -> 'b2) -> ('a, 'b1, 'c) t -> ('a, 'b2, 'c) t
val third : ('c1 -> 'c2) -> ('a, 'b, 'c1) t -> ('a, 'b, 'c2) t
end = struct
type ('a, 'b, 'c) t = 'a * 'b * 'c
let p1 (a, _, _) = a
let p2 (_, b, _) = b
let p3 (_, _, c) = c
let map f (a, b, c) = (f a, f b, f c)
let equal (type o) ~(ord : o Ord.t) (a1, b1, c1) (a2, b2, c2) =
ord.equal a1 a2
&& ord.equal b1 b2
&& ord.equal c1 c2
let minimum (type o) ~(ord : o Ord.t) (a, b, c) =
let acc = ord.min a b in
let acc = ord.min acc c in
acc
let maximum (type o) ~(ord : o Ord.t) (a, b, c) =
let acc = ord.max a b in
let acc = ord.max acc c in
acc
let minimum_on (type o) ~(ord : o Ord.t) f (a, b, c) =
let acc = match ord.compare (f a) (f b) with Lt | Eq -> a | Gt -> b in
let acc = match ord.compare (f acc) (f c) with Lt | Eq -> acc | Gt -> c in
acc
let maximum_on (type o) ~(ord : o Ord.t) f (a, b, c) =
let acc = match ord.compare (f a) (f b) with Gt | Eq -> a | Lt -> b in
let acc = match ord.compare (f acc) (f c) with Gt | Eq -> acc | Lt -> c in
acc
let first f (a, b, c) = (f a, b, c)
let second f (a, b, c) = (a, f b, c)
let third f (a, b, c) = (a, b, f c)
end
module T4 : sig
type ('a, 'b, 'c, 'd) t = 'a * 'b * 'c * 'd [@implements Eq.S]
val p1 : ('a, _, _, _) t -> 'a
val p2 : (_, 'b, _, _) t -> 'b
val p3 : (_, _, 'c, _) t -> 'c
val p4 : (_, _, _, 'd) t -> 'd
val map : ('a -> 'b) -> ('a, 'a, 'a, 'a) t -> ('b, 'b, 'b, 'b) t
val equal : ord:'a Ord.t -> ('a, 'a, 'a, 'a) t -> ('a, 'a, 'a, 'a) t -> bool
val minimum : ord:'a Ord.t -> ('a, 'a, 'a, 'a) t -> 'a
val minimum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a, 'a) t -> 'a
val maximum : ord:'a Ord.t -> ('a, 'a, 'a, 'a) t -> 'a
val maximum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a, 'a) t -> 'a
val first : ('a1 -> 'a2) -> ('a1, 'b, 'c, 'd) t -> ('a2, 'b, 'c, 'd) t
val second : ('b1 -> 'b2) -> ('a, 'b1, 'c, 'd) t -> ('a, 'b2, 'c, 'd) t
val third : ('c1 -> 'c2) -> ('a, 'b, 'c1, 'd) t -> ('a, 'b, 'c2, 'd) t
val fourth : ('d1 -> 'd2) -> ('a, 'b, 'c, 'd1) t -> ('a, 'b, 'c, 'd2) t
end = struct
type ('a, 'b, 'c, 'd) t = 'a * 'b * 'c * 'd
let p1 (a, _, _, _) = a
let p2 (_, b, _, _) = b
let p3 (_, _, c, _) = c
let p4 (_, _, _, d) = d
let map f (a, b, c, d) = (f a, f b, f c, f d)
let equal (type o) ~(ord : o Ord.t) (a1, b1, c1, d1) (a2, b2, c2, d2) =
ord.equal a1 a2
&& ord.equal b1 b2
&& ord.equal c1 c2
&& ord.equal d1 d2
let minimum (type o) ~(ord : o Ord.t) (a, b, c, d) =
let acc = ord.min a b in
let acc = ord.min acc c in
let acc = ord.min acc d in
acc
let maximum (type o) ~(ord : o Ord.t) (a, b, c, d) =
let acc = ord.max a b in
let acc = ord.max acc c in
let acc = ord.max acc d in
acc
let minimum_on (type o) ~(ord : o Ord.t) f (a, b, c, d) =
let acc = match ord.compare (f a) (f b) with Lt | Eq -> a | Gt -> b in
let acc = match ord.compare (f acc) (f c) with Lt | Eq -> acc | Gt -> c in
let acc = match ord.compare (f acc) (f d) with Lt | Eq -> acc | Gt -> d in
acc
let maximum_on (type o) ~(ord : o Ord.t) f (a, b, c, d) =
let acc = match ord.compare (f a) (f b) with Gt | Eq -> a | Lt -> b in
let acc = match ord.compare (f acc) (f c) with Gt | Eq -> acc | Lt -> c in
let acc = match ord.compare (f acc) (f d) with Gt | Eq -> acc | Lt -> d in
acc
let first f (a, b, c, d) = (f a, b, c, d)
let second f (a, b, c, d) = (a, f b, c, d)
let third f (a, b, c, d) = (a, b, f c, d)
let fourth f (a, b, c, d) = (a, b, c, f d)
end
module T5 : sig
type ('a, 'b, 'c, 'd, 'e) t = 'a * 'b * 'c * 'd * 'e [@implements Eq.S]
val p1 : ('a, _, _, _, _) t -> 'a
val p2 : (_, 'b, _, _, _) t -> 'b
val p3 : (_, _, 'c, _, _) t -> 'c
val p4 : (_, _, _, 'd, _) t -> 'd
val p5 : (_, _, _, _, 'e) t -> 'e
val map : ('a -> 'b) -> ('a, 'a, 'a, 'a, 'a) t -> ('b, 'b, 'b, 'b, 'b) t
val equal : ord:'a Ord.t -> ('a, 'a, 'a, 'a, 'a) t -> ('a, 'a, 'a, 'a, 'a) t -> bool
val minimum : ord:'a Ord.t -> ('a, 'a, 'a, 'a, 'a) t -> 'a
val minimum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a, 'a, 'a) t -> 'a
val maximum : ord:'a Ord.t -> ('a, 'a, 'a, 'a, 'a) t -> 'a
val maximum_on : ord:'b Ord.t -> ('a -> 'b) -> ('a, 'a, 'a, 'a, 'a) t -> 'a
val first : ('a1 -> 'a2) -> ('a1, 'b, 'c, 'd, 'e) t -> ('a2, 'b, 'c, 'd, 'e) t
val second : ('b1 -> 'b2) -> ('a, 'b1, 'c, 'd, 'e) t -> ('a, 'b2, 'c, 'd, 'e) t
val third : ('c1 -> 'c2) -> ('a, 'b, 'c1, 'd, 'e) t -> ('a, 'b, 'c2, 'd, 'e) t
val fourth : ('d1 -> 'd2) -> ('a, 'b, 'c, 'd1, 'e) t -> ('a, 'b, 'c, 'd2, 'e) t
val fifth : ('e1 -> 'e2) -> ('a, 'b, 'c, 'd, 'e1) t -> ('a, 'b, 'c, 'd, 'e2) t
end = struct
type ('a, 'b, 'c, 'd, 'e) t = 'a * 'b * 'c * 'd * 'e
let p1 (a, _, _, _, _) = a
let p2 (_, b, _, _, _) = b
let p3 (_, _, c, _, _) = c
let p4 (_, _, _, d, _) = d
let p5 (_, _, _, _, e) = e
let map f (a, b, c, d, e) = (f a, f b, f c, f d, f e)
let equal (type o) ~(ord : o Ord.t) (a1, b1, c1, d1, e1) (a2, b2, c2, d2, e2) =
ord.equal a1 a2
&& ord.equal b1 b2
&& ord.equal c1 c2
&& ord.equal d1 d2
&& ord.equal e1 e2
let minimum (type o) ~(ord : o Ord.t) (a, b, c, d, e) =
let acc = ord.min a b in
let acc = ord.min acc c in
let acc = ord.min acc d in
let acc = ord.min acc e in
acc
let maximum (type o) ~(ord : o Ord.t) (a, b, c, d, e) =
let acc = ord.max a b in
let acc = ord.max acc c in
let acc = ord.max acc d in
let acc = ord.max acc e in
acc
let minimum_on (type o) ~(ord : o Ord.t) f (a, b, c, d, e) =
let acc = match ord.compare (f a) (f b) with Lt | Eq -> a | Gt -> b in
let acc = match ord.compare (f acc) (f c) with Lt | Eq -> acc | Gt -> c in
let acc = match ord.compare (f acc) (f d) with Lt | Eq -> acc | Gt -> d in
let acc = match ord.compare (f acc) (f e) with Lt | Eq -> acc | Gt -> e in
acc
let maximum_on (type o) ~(ord : o Ord.t) f (a, b, c, d, e) =
let acc = match ord.compare (f a) (f b) with Gt | Eq -> a | Lt -> b in
let acc = match ord.compare (f acc) (f c) with Gt | Eq -> acc | Lt -> c in
let acc = match ord.compare (f acc) (f d) with Gt | Eq -> acc | Lt -> d in
let acc = match ord.compare (f acc) (f e) with Gt | Eq -> acc | Lt -> e in
acc
let first f (a, b, c, d, e) = (f a, b, c, d, e)
let second f (a, b, c, d, e) = (a, f b, c, d, e)
let third f (a, b, c, d, e) = (a, b, f c, d, e)
let fourth f (a, b, c, d, e) = (a, b, c, f d, e)
let fifth f (a, b, c, d, e) = (a, b, c, d, f e)
end
|
6859e6f8309ab495399d23eb4910bb2f583a4237958c84759c6becf1c6404020 | shayan-najd/NativeMetaprogramming | DList.hs | module DList where
newtype DList a = DList ([a] -> [a])
snoc :: DList a -> a -> DList a
DList f `snoc` x = DList (f . (x:))
toList :: DList a -> [a]
toList (DList f) = f []
instance Monoid (DList a) where
mempty = DList id
DList a `mappend` DList b = DList (a . b)
| null | https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/utils/mkUserGuidePart/DList.hs | haskell | module DList where
newtype DList a = DList ([a] -> [a])
snoc :: DList a -> a -> DList a
DList f `snoc` x = DList (f . (x:))
toList :: DList a -> [a]
toList (DList f) = f []
instance Monoid (DList a) where
mempty = DList id
DList a `mappend` DList b = DList (a . b)
|
|
7f9365b7a760d3b0d9cf16ff3c755fb2836dfaa0e32db62894f3a2026621f863 | jyh/metaprl | itt_singleton.mli |
declare singleton{'a;'A}
| null | https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/itt/core/itt_singleton.mli | ocaml |
declare singleton{'a;'A}
|
|
fef32e6f44bd926ca60e2594ac46853f93c849195d980719fe392fd1a825262c | ericdrgn/drgn.nyxt | init.lisp | (in-package #:nyxt-user)
;;loading of config files
;;add theme here
(nyxt::load-lisp "~/.config/nyxt/themes/standard-dark.lisp")
;;base
(nyxt::load-lisp "~/.config/nyxt/base/keybindings.lisp")
(nyxt::load-lisp "~/.config/nyxt/base/urlprompt.lisp")
(nyxt::load-lisp "~/.config/nyxt/base/commands.lisp")
(nyxt::load-lisp "~/.config/nyxt/base/glyphs.lisp")
;;extending
(nyxt::load-lisp "~/.config/nyxt/ex/specificurl.lisp")
;;configuration for browser
(define-configuration browser
((session-restore-prompt :never-restore)))
;;configuration for buffer and nosave buffer to have reduce tracking by default
(define-configuration (web-buffer nosave-buffer)
((default-modes `(reduce-tracking-mode
,@%slot-default%))))
;;setting new buffer url and having nyxt start full screen
(defmethod nyxt::startup ((browser browser) urls)
"Home"
(window-make browser)
(let ((window (current-window)))
(window-set-buffer window (make-buffer :url (quri:uri "/")))
(toggle-fullscreen window)))
;;when reloading init.lisp file shows in message bar once finished
(echo "Loaded config.")
| null | https://raw.githubusercontent.com/ericdrgn/drgn.nyxt/f7cc9a5351b9fa3e002fe56d870f1c7cef22cafb/init.lisp | lisp | loading of config files
add theme here
base
extending
configuration for browser
configuration for buffer and nosave buffer to have reduce tracking by default
setting new buffer url and having nyxt start full screen
when reloading init.lisp file shows in message bar once finished | (in-package #:nyxt-user)
(nyxt::load-lisp "~/.config/nyxt/themes/standard-dark.lisp")
(nyxt::load-lisp "~/.config/nyxt/base/keybindings.lisp")
(nyxt::load-lisp "~/.config/nyxt/base/urlprompt.lisp")
(nyxt::load-lisp "~/.config/nyxt/base/commands.lisp")
(nyxt::load-lisp "~/.config/nyxt/base/glyphs.lisp")
(nyxt::load-lisp "~/.config/nyxt/ex/specificurl.lisp")
(define-configuration browser
((session-restore-prompt :never-restore)))
(define-configuration (web-buffer nosave-buffer)
((default-modes `(reduce-tracking-mode
,@%slot-default%))))
(defmethod nyxt::startup ((browser browser) urls)
"Home"
(window-make browser)
(let ((window (current-window)))
(window-set-buffer window (make-buffer :url (quri:uri "/")))
(toggle-fullscreen window)))
(echo "Loaded config.")
|
e72f94735dbca3a7b36110f301f28644a7135344dbd87c57647fd470aee11b46 | roburio/albatross | albatross_console.ml | ( c ) 2017 , all rights reserved
(* the process responsible for buffering console IO *)
communication channel is a single unix domain socket . The following commands
can be issued :
- Add name ( by ) -- > creates a new console slurper for name ,
and starts a read_console task
- Attach name -- > attaches console of name : send existing stuff to client ,
and record the requesting socket to receive further messages . A potential
earlier subscriber to the same console is closed .
can be issued:
- Add name (by vmmd) --> creates a new console slurper for name,
and starts a read_console task
- Attach name --> attaches console of name: send existing stuff to client,
and record the requesting socket to receive further messages. A potential
earlier subscriber to the same console is closed. *)
open Lwt.Infix
let pp_unix_error ppf e = Fmt.string ppf (Unix.error_message e)
let active = ref Vmm_core.String_map.empty
let read_console id name ring fd =
Lwt.catch (fun () ->
Lwt_unix.wait_read fd >>= fun () ->
let channel = Lwt_io.of_fd ~mode:Lwt_io.Input fd in
let rec loop () =
Lwt_io.read_line channel >>= fun line ->
Logs.debug (fun m -> m "read %s" line) ;
let t = Ptime_clock.now () in
Vmm_ring.write ring (t, line) ;
(match Vmm_core.String_map.find_opt name !active with
| None -> Lwt.return_unit
| Some (version, fd) ->
let header = Vmm_commands.header ~version id in
Vmm_lwt.write_wire fd (header, `Data (`Console_data (t, line))) >>= function
| Error _ ->
Vmm_lwt.safe_close fd >|= fun () ->
active := Vmm_core.String_map.remove name !active
| Ok () -> Lwt.return_unit) >>=
loop
in
loop ())
(fun e ->
begin match e with
| Unix.Unix_error (e, f, _) ->
Logs.err (fun m -> m "%s error in %s: %a" name f pp_unix_error e)
| End_of_file ->
Logs.debug (fun m -> m "%s end of file while reading" name)
| exn ->
Logs.err (fun m -> m "%s error while reading %s" name (Printexc.to_string exn))
end ;
Vmm_lwt.safe_close fd)
let open_fifo name =
let fifo = Vmm_core.Name.fifo_file name in
Lwt.catch (fun () ->
Logs.debug (fun m -> m "opening %a for reading" Fpath.pp fifo) ;
Lwt_unix.openfile (Fpath.to_string fifo) [Lwt_unix.O_RDONLY; Lwt_unix.O_NONBLOCK] 0 >>= fun fd ->
Lwt.return (Some fd))
(function
| Unix.Unix_error (e, f, _) ->
Logs.err (fun m -> m "%a error in %s: %a" Fpath.pp fifo f pp_unix_error e) ;
Lwt.return None
| exn ->
Logs.err (fun m -> m "%a error while reading %s" Fpath.pp fifo (Printexc.to_string exn)) ;
Lwt.return None)
let t = ref Vmm_core.String_map.empty
let fifos = Vmm_core.conn_metrics "fifo"
let add_fifo id =
let name = Vmm_core.Name.to_string id in
open_fifo id >|= function
| None -> Error (`Msg "opening")
| Some f ->
let ring = match Vmm_core.String_map.find_opt name !t with
| None ->
let ring = Vmm_ring.create "" () in
let map = Vmm_core.String_map.add name ring !t in
t := map ;
ring
| Some ring -> ring
in
fifos `Open;
Lwt.async (fun () -> read_console id name ring f >|= fun () -> fifos `Close) ;
Ok ()
let subscribe s version id =
let name = Vmm_core.Name.to_string id in
Logs.debug (fun m -> m "attempting to subscribe %a" Vmm_core.Name.pp id) ;
match Vmm_core.String_map.find_opt name !t with
| None ->
active := Vmm_core.String_map.add name (version, s) !active ;
Lwt.return (None, "waiting for VM")
| Some r ->
(match Vmm_core.String_map.find_opt name !active with
| None -> Lwt.return_unit
| Some (_, s) -> Vmm_lwt.safe_close s) >|= fun () ->
active := Vmm_core.String_map.add name (version, s) !active ;
(Some r, "subscribed")
let send_history s version r id since =
let entries =
match since with
| `Count n -> Vmm_ring.read_last r n
| `Since ts -> Vmm_ring.read_history r ts
in
Logs.debug (fun m -> m "%a found %d history" Vmm_core.Name.pp id (List.length entries)) ;
Lwt_list.iter_s (fun (i, v) ->
let header = Vmm_commands.header ~version id in
Vmm_lwt.write_wire s (header, `Data (`Console_data (i, v))) >>= function
| Ok () -> Lwt.return_unit
| Error _ -> Vmm_lwt.safe_close s)
entries
let handle s addr =
Logs.info (fun m -> m "handling connection %a" Vmm_lwt.pp_sockaddr addr) ;
let rec loop () =
Vmm_lwt.read_wire s >>= function
| Error _ ->
Logs.err (fun m -> m "exception while reading") ;
Lwt.return_unit
| Ok (header, `Command (`Console_cmd cmd)) ->
begin
let name = header.Vmm_commands.name in
match cmd with
| `Console_add ->
begin
add_fifo name >>= fun res ->
let reply = match res with
| Ok () -> `Success `Empty
| Error (`Msg msg) -> `Failure msg
in
Vmm_lwt.write_wire s (header, reply) >>= function
| Ok () -> loop ()
| Error _ ->
Logs.err (fun m -> m "error while writing") ;
Lwt.return_unit
end
| `Console_subscribe ts ->
subscribe s header.Vmm_commands.version name >>= fun (ring, res) ->
Vmm_lwt.write_wire s (header, `Success (`String res)) >>= function
| Error _ -> Vmm_lwt.safe_close s
| Ok () ->
(match ring with
| None -> Lwt.return_unit
| Some r -> send_history s header.Vmm_commands.version r name ts) >>= fun () ->
(* now we wait for the next read and terminate*)
Vmm_lwt.read_wire s >|= fun _ -> ()
end
| Ok wire ->
Logs.err (fun m -> m "unexpected wire %a"
(Vmm_commands.pp_wire ~verbose:false) wire) ;
Lwt.return ()
in
loop () >>= fun () ->
Vmm_lwt.safe_close s >|= fun () ->
Logs.warn (fun m -> m "disconnected")
let m = Vmm_core.conn_metrics "unix"
let jump _ systemd influx tmpdir =
Sys.(set_signal sigpipe Signal_ignore) ;
Albatross_cli.set_tmpdir tmpdir;
let socket () =
if systemd then Vmm_lwt.systemd_socket ()
else Vmm_lwt.service_socket `Console
in
Lwt_main.run
(Albatross_cli.init_influx "albatross_console" influx;
socket () >>= fun s ->
let rec loop () =
Lwt_unix.accept s >>= fun (cs, addr) ->
m `Open;
Lwt.async (fun () -> handle cs addr >|= fun () -> m `Close) ;
loop ()
in
loop ())
open Cmdliner
open Albatross_cli
let cmd =
let term =
Term.(term_result (const jump $ setup_log $ systemd_socket_activation $ influx $ tmpdir))
and info = Cmd.info "albatross-console" ~version
in
Cmd.v info term
let () = exit (Cmd.eval cmd)
| null | https://raw.githubusercontent.com/roburio/albatross/99d7dad34e71120b673d040b1edc2ff55872c61a/daemon/albatross_console.ml | ocaml | the process responsible for buffering console IO
now we wait for the next read and terminate | ( c ) 2017 , all rights reserved
communication channel is a single unix domain socket . The following commands
can be issued :
- Add name ( by ) -- > creates a new console slurper for name ,
and starts a read_console task
- Attach name -- > attaches console of name : send existing stuff to client ,
and record the requesting socket to receive further messages . A potential
earlier subscriber to the same console is closed .
can be issued:
- Add name (by vmmd) --> creates a new console slurper for name,
and starts a read_console task
- Attach name --> attaches console of name: send existing stuff to client,
and record the requesting socket to receive further messages. A potential
earlier subscriber to the same console is closed. *)
open Lwt.Infix
let pp_unix_error ppf e = Fmt.string ppf (Unix.error_message e)
let active = ref Vmm_core.String_map.empty
let read_console id name ring fd =
Lwt.catch (fun () ->
Lwt_unix.wait_read fd >>= fun () ->
let channel = Lwt_io.of_fd ~mode:Lwt_io.Input fd in
let rec loop () =
Lwt_io.read_line channel >>= fun line ->
Logs.debug (fun m -> m "read %s" line) ;
let t = Ptime_clock.now () in
Vmm_ring.write ring (t, line) ;
(match Vmm_core.String_map.find_opt name !active with
| None -> Lwt.return_unit
| Some (version, fd) ->
let header = Vmm_commands.header ~version id in
Vmm_lwt.write_wire fd (header, `Data (`Console_data (t, line))) >>= function
| Error _ ->
Vmm_lwt.safe_close fd >|= fun () ->
active := Vmm_core.String_map.remove name !active
| Ok () -> Lwt.return_unit) >>=
loop
in
loop ())
(fun e ->
begin match e with
| Unix.Unix_error (e, f, _) ->
Logs.err (fun m -> m "%s error in %s: %a" name f pp_unix_error e)
| End_of_file ->
Logs.debug (fun m -> m "%s end of file while reading" name)
| exn ->
Logs.err (fun m -> m "%s error while reading %s" name (Printexc.to_string exn))
end ;
Vmm_lwt.safe_close fd)
let open_fifo name =
let fifo = Vmm_core.Name.fifo_file name in
Lwt.catch (fun () ->
Logs.debug (fun m -> m "opening %a for reading" Fpath.pp fifo) ;
Lwt_unix.openfile (Fpath.to_string fifo) [Lwt_unix.O_RDONLY; Lwt_unix.O_NONBLOCK] 0 >>= fun fd ->
Lwt.return (Some fd))
(function
| Unix.Unix_error (e, f, _) ->
Logs.err (fun m -> m "%a error in %s: %a" Fpath.pp fifo f pp_unix_error e) ;
Lwt.return None
| exn ->
Logs.err (fun m -> m "%a error while reading %s" Fpath.pp fifo (Printexc.to_string exn)) ;
Lwt.return None)
let t = ref Vmm_core.String_map.empty
let fifos = Vmm_core.conn_metrics "fifo"
let add_fifo id =
let name = Vmm_core.Name.to_string id in
open_fifo id >|= function
| None -> Error (`Msg "opening")
| Some f ->
let ring = match Vmm_core.String_map.find_opt name !t with
| None ->
let ring = Vmm_ring.create "" () in
let map = Vmm_core.String_map.add name ring !t in
t := map ;
ring
| Some ring -> ring
in
fifos `Open;
Lwt.async (fun () -> read_console id name ring f >|= fun () -> fifos `Close) ;
Ok ()
let subscribe s version id =
let name = Vmm_core.Name.to_string id in
Logs.debug (fun m -> m "attempting to subscribe %a" Vmm_core.Name.pp id) ;
match Vmm_core.String_map.find_opt name !t with
| None ->
active := Vmm_core.String_map.add name (version, s) !active ;
Lwt.return (None, "waiting for VM")
| Some r ->
(match Vmm_core.String_map.find_opt name !active with
| None -> Lwt.return_unit
| Some (_, s) -> Vmm_lwt.safe_close s) >|= fun () ->
active := Vmm_core.String_map.add name (version, s) !active ;
(Some r, "subscribed")
let send_history s version r id since =
let entries =
match since with
| `Count n -> Vmm_ring.read_last r n
| `Since ts -> Vmm_ring.read_history r ts
in
Logs.debug (fun m -> m "%a found %d history" Vmm_core.Name.pp id (List.length entries)) ;
Lwt_list.iter_s (fun (i, v) ->
let header = Vmm_commands.header ~version id in
Vmm_lwt.write_wire s (header, `Data (`Console_data (i, v))) >>= function
| Ok () -> Lwt.return_unit
| Error _ -> Vmm_lwt.safe_close s)
entries
let handle s addr =
Logs.info (fun m -> m "handling connection %a" Vmm_lwt.pp_sockaddr addr) ;
let rec loop () =
Vmm_lwt.read_wire s >>= function
| Error _ ->
Logs.err (fun m -> m "exception while reading") ;
Lwt.return_unit
| Ok (header, `Command (`Console_cmd cmd)) ->
begin
let name = header.Vmm_commands.name in
match cmd with
| `Console_add ->
begin
add_fifo name >>= fun res ->
let reply = match res with
| Ok () -> `Success `Empty
| Error (`Msg msg) -> `Failure msg
in
Vmm_lwt.write_wire s (header, reply) >>= function
| Ok () -> loop ()
| Error _ ->
Logs.err (fun m -> m "error while writing") ;
Lwt.return_unit
end
| `Console_subscribe ts ->
subscribe s header.Vmm_commands.version name >>= fun (ring, res) ->
Vmm_lwt.write_wire s (header, `Success (`String res)) >>= function
| Error _ -> Vmm_lwt.safe_close s
| Ok () ->
(match ring with
| None -> Lwt.return_unit
| Some r -> send_history s header.Vmm_commands.version r name ts) >>= fun () ->
Vmm_lwt.read_wire s >|= fun _ -> ()
end
| Ok wire ->
Logs.err (fun m -> m "unexpected wire %a"
(Vmm_commands.pp_wire ~verbose:false) wire) ;
Lwt.return ()
in
loop () >>= fun () ->
Vmm_lwt.safe_close s >|= fun () ->
Logs.warn (fun m -> m "disconnected")
let m = Vmm_core.conn_metrics "unix"
let jump _ systemd influx tmpdir =
Sys.(set_signal sigpipe Signal_ignore) ;
Albatross_cli.set_tmpdir tmpdir;
let socket () =
if systemd then Vmm_lwt.systemd_socket ()
else Vmm_lwt.service_socket `Console
in
Lwt_main.run
(Albatross_cli.init_influx "albatross_console" influx;
socket () >>= fun s ->
let rec loop () =
Lwt_unix.accept s >>= fun (cs, addr) ->
m `Open;
Lwt.async (fun () -> handle cs addr >|= fun () -> m `Close) ;
loop ()
in
loop ())
open Cmdliner
open Albatross_cli
let cmd =
let term =
Term.(term_result (const jump $ setup_log $ systemd_socket_activation $ influx $ tmpdir))
and info = Cmd.info "albatross-console" ~version
in
Cmd.v info term
let () = exit (Cmd.eval cmd)
|
84cdb58c169320d6e154a9682d1506df8b30fde1096d3f1f528e9d81525a8087 | rururu/r4f-pro | core_test.clj | (ns r4f-pro.core-test
(:require [clojure.test :refer :all]
[r4f-pro.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/rururu/r4f-pro/c472b902049f620e25b36a197a42f07f5796620d/test/r4f_pro/core_test.clj | clojure | (ns r4f-pro.core-test
(:require [clojure.test :refer :all]
[r4f-pro.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
|
|
5f891b0df414ed1688e904930ddf29d8389877eff0f66ff28ee3a4d0bc41fbe9 | ku-fpg/sunroof-compiler | JQuery.hs | # LANGUAGE DataKinds #
| This module provides parts of the JQuery API ( < / > ) .
module Language.Sunroof.JS.JQuery
(
-- * General JQuery API
dollar
, jQuery, jq
-- * DOM
, append
, html, setHtml
, text, setText
-- * CSS
, css, setCss
, addClass, removeClass
-- * Attributes
, attribute, attr'
, setAttr
, removeAttr
-- * Event Handling
, on
-- * Manipulation
, innerWidth
, innerHeight
, outerWidth, outerWidth'
, outerHeight, outerHeight'
, clone, clone'
) where
import Language.Sunroof.Classes
( SunroofArgument(..)
)
import Language.Sunroof.Types
import Language.Sunroof.JS.Object ( JSObject )
import Language.Sunroof.JS.String ( JSString )
import Language.Sunroof.JS.Number ( JSNumber )
import Language.Sunroof.JS.Bool ( JSBool )
-- -----------------------------------------------------------------------
-- JQuery interface
-- -----------------------------------------------------------------------
-- | The dollar function.
-- See </>.
dollar :: JSFunction JSString JSObject
dollar = fun "$"
-- | Calls the JQuery dollar function.
-- See </>.
jQuery :: JSString -> JS t JSObject
jQuery nm = dollar `apply` nm
-- | Short-hand for 'jQuery'.
jq :: JSString -> JS t JSObject
jq = jQuery
-- -----------------------------------------------------------------------
-- Manipulation > DOM
-- -----------------------------------------------------------------------
-- | See </>.
append :: JSObject -> JSObject -> JS t ()
append x = invoke "append" x
-- | See @.html()@ at </>.
html :: JSObject -> JS t JSObject
html = invoke "html" ()
-- | See @.html(htmlString)@ at </>.
setHtml :: JSString -> JSObject -> JS t JSObject
setHtml s = invoke "html" s
-- | See @.text()@ at </>.
text :: JSObject -> JS t JSObject
text = invoke "text" ()
-- | See @.text(textString)@ at </>.
setText :: JSString -> JSObject -> JS t JSObject
setText s = invoke "text" s
-- -------------------------------------------------------------
-- CSS
-- -------------------------------------------------------------
-- | See @.css(propertyName)@ at </>.
css :: JSString -> JSObject -> JS t JSString
css prop = invoke "css" prop
-- | See @.css(propertyName, value)@ at </>.
setCss :: JSString -> JSString -> JSObject -> JS t JSString
setCss prop v = invoke "css" (prop, v)
-- | See </>.
addClass :: JSString -> JSObject -> JS t ()
addClass = invoke "addClass"
-- | See </>.
removeClass :: JSString -> JSObject -> JS t ()
removeClass = invoke "removeClass"
-- -------------------------------------------------------------
-- Attributes
-- -------------------------------------------------------------
-- | See @.attr(attributeName)@ at </>.
This binding does not have the original Javascript name ,
-- because of the 'attr' function.
attribute :: JSString -> JSObject -> JS t JSString
attribute a = invoke "attr" a
-- | See @.attr(attributeName)@ at </>.
This binding does not have the original Javascript name ,
-- because of the 'attr' function.
attr' :: JSString -> JSObject -> JS t JSString
attr' = attribute
-- | See @.attr(attributeName, value)@ at </>.
setAttr :: JSString -> JSString -> JSObject -> JS t JSString
setAttr a v = invoke "attr" (a, v)
-- | See: </>
removeAttr :: JSString -> JSObject -> JS t JSObject
removeAttr attrName = invoke "removeAttr" attrName
-- -------------------------------------------------------------
-- Event Handling
-- -------------------------------------------------------------
-- | See </>.
on :: (SunroofArgument a) => JSString -> JSString -> (a -> JS 'B ()) -> JSObject -> JS t ()
on nm sel f o = do
callback <- continuation f
o # invoke "on" (nm,sel,callback)
-- -------------------------------------------------------------
Manipulation > Style Properties
-- -------------------------------------------------------------
-- | See </>.
innerWidth :: JSObject -> JS t JSNumber
innerWidth = invoke "innerWidth" ()
-- | See </>.
innerHeight :: JSObject -> JS t JSNumber
innerHeight = invoke "innerHeight" ()
-- | See </>.
outerWidth :: JSObject -> JS t JSNumber
outerWidth = invoke "outerWidth" ()
-- | See </>.
outerWidth' :: JSBool -> JSObject -> JS t JSNumber
outerWidth' includeMargin = invoke "outerWidth" includeMargin
-- | See </>.
outerHeight :: JSObject -> JS t JSNumber
outerHeight = invoke "outerHeight" ()
-- | See </>.
outerHeight' :: JSBool -> JSObject -> JS t JSNumber
outerHeight' includeMargin = invoke "outerHeight" includeMargin
-- | See @.clone()@ at </>.
clone :: JSObject -> JS t JSObject
clone = invoke "clone" ()
| See @.clone(withDataAndEvents , deepWithDataAndEvents)@ at < / > .
clone' :: JSBool -> JSBool -> JSObject -> JS t JSObject
clone' withDataAndEvents deepWithDataAndEvents =
invoke "clone" (withDataAndEvents, deepWithDataAndEvents)
| null | https://raw.githubusercontent.com/ku-fpg/sunroof-compiler/5d8edafea515c4c2b4e7631799f35d8df977e289/Language/Sunroof/JS/JQuery.hs | haskell | * General JQuery API
* DOM
* CSS
* Attributes
* Event Handling
* Manipulation
-----------------------------------------------------------------------
JQuery interface
-----------------------------------------------------------------------
| The dollar function.
See </>.
| Calls the JQuery dollar function.
See </>.
| Short-hand for 'jQuery'.
-----------------------------------------------------------------------
Manipulation > DOM
-----------------------------------------------------------------------
| See </>.
| See @.html()@ at </>.
| See @.html(htmlString)@ at </>.
| See @.text()@ at </>.
| See @.text(textString)@ at </>.
-------------------------------------------------------------
CSS
-------------------------------------------------------------
| See @.css(propertyName)@ at </>.
| See @.css(propertyName, value)@ at </>.
| See </>.
| See </>.
-------------------------------------------------------------
Attributes
-------------------------------------------------------------
| See @.attr(attributeName)@ at </>.
because of the 'attr' function.
| See @.attr(attributeName)@ at </>.
because of the 'attr' function.
| See @.attr(attributeName, value)@ at </>.
| See: </>
-------------------------------------------------------------
Event Handling
-------------------------------------------------------------
| See </>.
-------------------------------------------------------------
-------------------------------------------------------------
| See </>.
| See </>.
| See </>.
| See </>.
| See </>.
| See </>.
| See @.clone()@ at </>. | # LANGUAGE DataKinds #
| This module provides parts of the JQuery API ( < / > ) .
module Language.Sunroof.JS.JQuery
(
dollar
, jQuery, jq
, append
, html, setHtml
, text, setText
, css, setCss
, addClass, removeClass
, attribute, attr'
, setAttr
, removeAttr
, on
, innerWidth
, innerHeight
, outerWidth, outerWidth'
, outerHeight, outerHeight'
, clone, clone'
) where
import Language.Sunroof.Classes
( SunroofArgument(..)
)
import Language.Sunroof.Types
import Language.Sunroof.JS.Object ( JSObject )
import Language.Sunroof.JS.String ( JSString )
import Language.Sunroof.JS.Number ( JSNumber )
import Language.Sunroof.JS.Bool ( JSBool )
dollar :: JSFunction JSString JSObject
dollar = fun "$"
jQuery :: JSString -> JS t JSObject
jQuery nm = dollar `apply` nm
jq :: JSString -> JS t JSObject
jq = jQuery
append :: JSObject -> JSObject -> JS t ()
append x = invoke "append" x
html :: JSObject -> JS t JSObject
html = invoke "html" ()
setHtml :: JSString -> JSObject -> JS t JSObject
setHtml s = invoke "html" s
text :: JSObject -> JS t JSObject
text = invoke "text" ()
setText :: JSString -> JSObject -> JS t JSObject
setText s = invoke "text" s
css :: JSString -> JSObject -> JS t JSString
css prop = invoke "css" prop
setCss :: JSString -> JSString -> JSObject -> JS t JSString
setCss prop v = invoke "css" (prop, v)
addClass :: JSString -> JSObject -> JS t ()
addClass = invoke "addClass"
removeClass :: JSString -> JSObject -> JS t ()
removeClass = invoke "removeClass"
This binding does not have the original Javascript name ,
attribute :: JSString -> JSObject -> JS t JSString
attribute a = invoke "attr" a
This binding does not have the original Javascript name ,
attr' :: JSString -> JSObject -> JS t JSString
attr' = attribute
setAttr :: JSString -> JSString -> JSObject -> JS t JSString
setAttr a v = invoke "attr" (a, v)
removeAttr :: JSString -> JSObject -> JS t JSObject
removeAttr attrName = invoke "removeAttr" attrName
on :: (SunroofArgument a) => JSString -> JSString -> (a -> JS 'B ()) -> JSObject -> JS t ()
on nm sel f o = do
callback <- continuation f
o # invoke "on" (nm,sel,callback)
Manipulation > Style Properties
innerWidth :: JSObject -> JS t JSNumber
innerWidth = invoke "innerWidth" ()
innerHeight :: JSObject -> JS t JSNumber
innerHeight = invoke "innerHeight" ()
outerWidth :: JSObject -> JS t JSNumber
outerWidth = invoke "outerWidth" ()
outerWidth' :: JSBool -> JSObject -> JS t JSNumber
outerWidth' includeMargin = invoke "outerWidth" includeMargin
outerHeight :: JSObject -> JS t JSNumber
outerHeight = invoke "outerHeight" ()
outerHeight' :: JSBool -> JSObject -> JS t JSNumber
outerHeight' includeMargin = invoke "outerHeight" includeMargin
clone :: JSObject -> JS t JSObject
clone = invoke "clone" ()
| See @.clone(withDataAndEvents , deepWithDataAndEvents)@ at < / > .
clone' :: JSBool -> JSBool -> JSObject -> JS t JSObject
clone' withDataAndEvents deepWithDataAndEvents =
invoke "clone" (withDataAndEvents, deepWithDataAndEvents)
|
73c60a1102105010e3829a760a7102c107e7a60e962ef83dcc46ef5bdd928a49 | alanz/ghc-exactprint | ExpandSynsFail1.hs | type Foo = Int
type Bar = Bool
main = print $ (1 :: Foo) == (False :: Bar)
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/ExpandSynsFail1.hs | haskell | type Foo = Int
type Bar = Bool
main = print $ (1 :: Foo) == (False :: Bar)
|
|
573dcc71998ade4e011cf5b569a50659206f439fc58dddb0d7603bc83e40b547 | altsun/My-Lisps | (FLEX) [FlexSpline] Ve duong luon song.lsp | FlexSpline . LSP [ Command name : FLEX ]
;;; To draw a Spline approximation of a sine wave Centered on a path, such as is used by many
;;; to represent flexible duct or conduit. [Not a precisely accurate sine-wave shape, but close.]
;;; Draws continuous Spline along fit points zig-zagging across center of path object.
[ Non - tangent changes in direction in paths , or overly tight curves relative to wave
;;; width in various entity types, will yield quirky results. Allows selecting or drawing planar
3D Polyline , " because it can , " however unlikely that one would want to because of this ; if 3D
is fully collinear , will pick a UCS related to current one . Forbids 3D Spline . ]
Divides path length into half - wave - length increments to make waves end at path ends ; forces
an even number of half - waves for closed paths so that result is complete S - waves continuous
;;; across start/end point.
;;; Draws on current Layer, unless Deleting pre-Existing path; if so, draws on its Layer, assuming
;;; the intent is to replace it (i.e. to replace something drawn only to establish path), but pre-drawn
;;; path is not necessary -- User can create path within command.
;;; Under select-Existing option, asks User to select again if nothing is selected, or if selected object
;;; is an inappropriate entity type.
Accounts for different Coordinate Systems of selected existing path objects .
;;; Remembers option choices and offers them as defaults on subsequent use.
;;; Options:
1 . draw new within routine , or select pre - Existing , path of any planar finite type with linearity ;
2 . if selected Existing object is on locked Layer , whether to unlock it and Proceed , or Quit ;
3 . PRevious = redraw along prior path ( whether retained or deleted ) allowing different choices ;
4 . Retain or Delete base path ( whether new or selected Existing ) ;
5 . sine - wave ( overall / outer ) ;
6 . sine - wave full - S - cycle approximate Length as ratio of width ( actual length will be adjusted to
fit overall path length ) , offering same value as ( ratio of 1.0 ) as initial default .
, last edited 17 July 2015
(vl-load-com)
(defun flexreset ()
(mapcar 'setvar svnames svvals)
(vla-endundomark doc)
); defun -- flexreset
(defun C:FLEX
(/ *error* doc svnames svvals pathent pathdata pathtype 3DP u3p1 u3p2
u3p3pt u3p3 ptno ucschanged pathlength hwsegs steplength ptdist)
(defun *error* (errmsg)
(if (not (wcmatch errmsg "Function cancelled,quit / exit abort,console break"))
(princ (strcat "\nError: " errmsg))
); if
(if ucschanged (vl-cmdf "_.ucs" "_prev"))
^ i.e. do n't go back unless routine reached UCS change but did n't change it back
(flexreset)
); defun -- *error*
(setq doc (vla-get-activedocument (vlax-get-acad-object)))
(vla-startundomark doc)
(setq
svnames '(cmdecho osmode blipmode ucsfollow clayer)
svvals (mapcar 'getvar svnames); current System Variable values
); setq
(initget
(strcat
"Existing Line Arc Circle Pline ELlipse Spline 3dpoly"
add PR option only if not first use
); strcat
); initget
(setq *flextype*
(cond
( (getkword
(strcat
"\nPath type [Existing or draw Line(single)/Arc/Circle/Pline(2D)/ELlipse/Spline/3dpoly"
offer PR option if not first use
"] <"
(cond (*flextype*) ("Line")); prior choice default if present; otherwise Line
">: "
); strcat
); getkword
); User option condition
(*flextype*); Enter with prior choice
Enter on first use
); cond & *flextype*
); setq
(cond ; re-establish/select/make path
((= *flextype* "PRevious")
(if (= *flexdel* "Delete")
(progn ; then
(if *isLocked* (command "_.layer" "_unlock" *pathlay* ""))
; unlock layer w/o asking [Proceed option chosen before] so it can:
(entdel *flexpath*); bring back previous path
); progn
); if
(entdel *flex*); delete previous result
; under Retain-path option where it draws on current Layer, not that of path object,
; will fail IF current Layer is locked [not accounted for as being highly unlikely];
; under Delete-path option where it draws on object's Layer, already unlocked above
); PRevious-path condition
((= *flextype* "Existing")
(while
(not
(and
(setq
pathent (car (entsel "\nSelect object to draw sine-wave along an Existing path: "))
pathdata (if pathent (entget pathent))
pathtype (if pathent (substr (cdr (assoc 100 (reverse pathdata))) 5))
^ = entity type from second ( assoc 100 ) without " AcDb " prefix ; using this because
( assoc 0 ) value is the same for 2D & 3D Polylines ; 2D OK , but 3D only if planar ( if
; not, result would be flattened in current CS
); setq
(or
other types than Spline/3DPoly
(and (wcmatch pathtype "Spline,3dPolyline") (vlax-curve-isPlanar pathent)); only if flat
); or
); and
); not
(prompt "\nNothing selected, or not a finite planar path type; try again:")
); while
); Existing-object condition
((= *flextype* "Line") (command "_.line" pause pause "")); only single Line
((/= *flextype* "PRevious"); all other draw-new entity types
(command (strcat "_." *flextype*)); start drawing command
(while (> (getvar 'cmdactive) 0) (command pause)); complete it
); draw-new condition
); cond
(mapcar 'setvar svnames '(0 0 0 0)); turn off System Variables after path selected/drawn
(setq
*flexpath* ; set object as base path [not localized, so it can be brought back if PR and D options]
(cond
((= *flextype* "Existing") pathent); selected object
((= *flextype* "PRevious") *flexpath*); keep the same
((entlast)); otherwise, newly drawn path
); cond & *flexpath*
pathdata (entget *flexpath*)
pathtype (substr (cdr (assoc 100 (reverse pathdata))) 5)
); setq
(if
User drew Spline or 3DPolyline that is not planar
(or
(= pathtype "Spline")
separately from Spline , for UCS alignment
); or
(not (vlax-curve-isPlanar *flexpath*))
); and
(progn ; then
(prompt "\nCannot use non-planar Spline/3DPolyline.")
(flexreset) (quit)
); progn -- then [no else]
); if
(setq
*pathlay* (cdr (assoc 8 pathdata))
; ^ not localized, so that under PRevious option, knows what layer to unlock if needed
*isLocked* ; not localized, so that under PRevious option, don't need to ask again
(if (and (= *flextype* "PRevious") *isLocked*)
T ; keep with PR if previous object was on locked layer [will be unlocked by now]
(= (logand (cdr (assoc 70 (tblsearch "layer" *pathlay*))) 4) 4)
other types : 0 = Unlocked [ nil ] ; 4 = Locked [ T ]
); if & *isLocked*
); setq
(initget "Retain Delete")
(setq *flexdel*
(cond
( (getkword
(strcat
"\nRetain or Delete base path [R/D] <"
prior choice default , Delete on first use
">: "
); strcat
); getkword
); User-input condition
(*flexdel*); Enter with prior choice
Enter on first use
); cond & *flexdel*
); setq
(if (and *isLocked* (= *flexdel* "Delete"))
(if (/= *flextype* "PRevious"); then -- check for not redoing on previous object
(progn ; then -- ask whether to unlock
(initget "Proceed Quit")
(setq *flexunlk*
(cond
( (getkword
(strcat
"\nLayer is locked; temporarily unlock and Proceed, or Quit? [P/Q] <"
prior choice default , Proceed on first use
">: "
); strcat
); getkword
); User-input condition
(*flexunlk*); Enter with prior choice
Enter on first use
); cond & *flexunlk*
); setq
(if (= *flexunlk* "Proceed")
(command "_.layer" "_unlock" *pathlay* ""); then
(progn (flexreset) (quit)); else
); if
progn & inner then argument
); inner if & outer then argument
); outer if -- no else argument [no issue if not on locked layer with Delete option]
no zero , no negative , no Enter on first use
(setq *flexwid*
(cond
( (getdist
(strcat
"\nWidth (overall) of sine wave"
default only if not first use
; EDIT to add mode & precision above if current Units settings not desired
": "
); strcat
); getdist
); User-input condition
(*flexwid*); Enter with prior value
); cond & *flexwid*
); setq
no zero , no negative
(setq *flexlenratio* ; LENgth of full wave as RATIO of width
(cond
( (getreal
(strcat
"\nFull-S cycle length as ratio of width <"
(if *flexlenratio* (rtos *flexlenratio* 2 3) "1.0"); EDIT precision as desired
prior as default only if present ; 1 as default on first use
">: "
); strcat
); getreal
); User-input condition
(*flexlenratio*); Enter with prior value
Enter on first use
); cond & *flexlenratio*
); setq
(if 3DP
then -- 3DPolyline does n't define UCS under object option , so :
(setq
u3p1 (trans (vlax-curve-getStartPoint *flexpath*) 0 1); first vertex
second
u3p3pt (vlax-curve-getPointAtParam *flexpath* (setq ptno 2))
third [ if present ] -- WCS point only , un - translated [ ( trans ) fails if nil ]
); setq
at least 3 vertices
(progn ; then
(while
(and
u3p3pt ; still a remaining vertex
collinear with first 2 vertices
); and
will usually finish at 3rd vertex ; if first 3 are collinear , will look further
until it finds one not collinear with 1st & 2nd
(setq u3p3pt (vlax-curve-getPointAtParam *flexpath* (setq ptno (1+ ptno))))
; next vertex [finally nil if all collinear to end]
); while
(if (not u3p3pt); reached end without finding non-collinear point
accept offered default for 3rd point [ UCS will be parallel to current UCS ]
); if
); progn -- then
else [ single - segment ] -- accept offered default for 3rd point [ as above ]
if [ 3 or more vertices vs. 2 ]
use vertices to define UCS
progn -- then [ 3DP ]
else [ other types ] -- set UCS to match object
); if
(setq
marker for * error * to reset UCS if routine does n't get to it
starting value for intermediate point multiplier [ replace prior use if 3DP ]
); setq
(setq
pathlength (vlax-curve-getDistAtParam *flexpath* (vlax-curve-getEndParam *flexpath*))
closed path needs even number of Half - Wave SEGmentS ; open can have odd number
(if (vlax-curve-isClosed *flexpath*)
(* (fix (+ (/ pathlength *flexwid* *flexlenratio*) 0.5)) 2); then -- round to nearest *even* number
(fix (+ (/ pathlength *flexwid* *flexlenratio* 0.5) 0.5)); else -- round to nearest *whole* number
); if & hwsegs
steplength (/ pathlength hwsegs 2)
); setq
(if (and (wcmatch *flextype* "Existing,PRevious") (= *flexdel* "Delete")) (setvar 'clayer *pathlay*))
; if Deleting Existing/PRevious path, draw on same Layer [already will for new path]
(command "_.spline" (trans (vlax-curve-getStartPoint *flexpath*) 0 1)); [leave in Spline command]
for Fit Points not including final at end
(command ; feed out to Spline command:
(polar
(trans
(vlax-curve-getPointAtDist ; advance point along path
*flexpath*
(setq ptdist (* (setq ptno (1+ ptno)) steplength))
getPointAtDist
0 1 ; from World coordinates to object's coordinates
); trans
(+ ; localized angle of offset
(angle
'(0 0 0)
(trans
(vlax-curve-getFirstDeriv
*flexpath*
(vlax-curve-getParamAtDist *flexpath* ptdist)
); getFirstDeriv
world to current CS , as displacement
); trans
); angle
(/ pi 2); perpendicular to center-line path [sine +/- gives left/right]
); +
(* *flexwid* 0.5 (sin (* (/ pi 2) (rem ptno 4))))
proportion of sine - wave width [ alternates between + /- 0.5 & 0 ]
); polar
); command
); repeat
(if (vlax-curve-isClosed *flexpath*); finish Spline
; (command "_close" ""); then
; Close option used because end-at-path's-end 'else' line below results in "kinked"
; start/end on most closed paths. Using plain Close line above, accepting default
; for tangent direction, though start/end "flows" across, result has noticeable variance
; there from typical wave shape elsewhere. Following is a compromise tangent-
; direction determination, better than default above but slightly too steep in some
; situations and not steep enough in others. There is no universal ideal -- it would
differ depending on degrees of curvature within first & last wavelengths of path .
(command ; then [closed path]
"_close"
(polar ; tangent-direction found as before, but farther out from last 'ptno' location
(trans
(vlax-curve-getPointAtDist
*flexpath*
(setq ptdist (* ptno steplength)); re-use from last wave-crest fit point
getPointAtDist
0 1
); trans
(+
(angle
'(0 0 0)
(trans
(vlax-curve-getFirstDeriv
*flexpath*
(vlax-curve-getParamAtDist *flexpath* ptdist)
); getFirstDeriv
0 1 T
); trans
); angle
(/ pi 2)
); +
(* *flexwid* (sin (* (/ pi 2) (rem ptno 4)))); tangent-direction defining point:
outboard of last wave crest , twice as far from path , for compromise location
); polar
); command
(command (trans (vlax-curve-getEndPoint *flexpath*) 0 1) "" "" ""); else [open-ended]
); if
(command "_.ucs" "_prev")
(setq
eliminate UCS reset in * error * since routine did it already
*flex* (entlast); save result in case of recall of routine with PRevious option
); setq
(if (= *flexdel* "Delete") (entdel *flexpath*)); remove base path under Delete option
(if *isLocked* (command "_.layer" "_lock" *pathlay* "")); re-lock layer if appropriate
(flexreset)
(princ)
); defun -- FLEX
(prompt "Type FLEX to draw sine-wave-approximation Spline centered along path.") | null | https://raw.githubusercontent.com/altsun/My-Lisps/85476bb09b79ef5e966402cc5158978d1cebd7eb/Other/(FLEX)%20%5BFlexSpline%5D%20Ve%20duong%20luon%20song.lsp | lisp | To draw a Spline approximation of a sine wave Centered on a path, such as is used by many
to represent flexible duct or conduit. [Not a precisely accurate sine-wave shape, but close.]
Draws continuous Spline along fit points zig-zagging across center of path object.
width in various entity types, will yield quirky results. Allows selecting or drawing planar
if 3D
forces
across start/end point.
Draws on current Layer, unless Deleting pre-Existing path; if so, draws on its Layer, assuming
the intent is to replace it (i.e. to replace something drawn only to establish path), but pre-drawn
path is not necessary -- User can create path within command.
Under select-Existing option, asks User to select again if nothing is selected, or if selected object
is an inappropriate entity type.
Remembers option choices and offers them as defaults on subsequent use.
Options:
defun -- flexreset
if
defun -- *error*
current System Variable values
setq
strcat
initget
prior choice default if present; otherwise Line
strcat
getkword
User option condition
Enter with prior choice
cond & *flextype*
setq
re-establish/select/make path
then
unlock layer w/o asking [Proceed option chosen before] so it can:
bring back previous path
progn
if
delete previous result
under Retain-path option where it draws on current Layer, not that of path object,
will fail IF current Layer is locked [not accounted for as being highly unlikely];
under Delete-path option where it draws on object's Layer, already unlocked above
PRevious-path condition
using this because
2D OK , but 3D only if planar ( if
not, result would be flattened in current CS
setq
only if flat
or
and
not
while
Existing-object condition
only single Line
all other draw-new entity types
start drawing command
complete it
draw-new condition
cond
turn off System Variables after path selected/drawn
set object as base path [not localized, so it can be brought back if PR and D options]
selected object
keep the same
otherwise, newly drawn path
cond & *flexpath*
setq
or
and
then
progn -- then [no else]
if
^ not localized, so that under PRevious option, knows what layer to unlock if needed
not localized, so that under PRevious option, don't need to ask again
keep with PR if previous object was on locked layer [will be unlocked by now]
4 = Locked [ T ]
if & *isLocked*
setq
strcat
getkword
User-input condition
Enter with prior choice
cond & *flexdel*
setq
then -- check for not redoing on previous object
then -- ask whether to unlock
strcat
getkword
User-input condition
Enter with prior choice
cond & *flexunlk*
setq
then
else
if
inner if & outer then argument
outer if -- no else argument [no issue if not on locked layer with Delete option]
EDIT to add mode & precision above if current Units settings not desired
strcat
getdist
User-input condition
Enter with prior value
cond & *flexwid*
setq
LENgth of full wave as RATIO of width
EDIT precision as desired
1 as default on first use
strcat
getreal
User-input condition
Enter with prior value
cond & *flexlenratio*
setq
first vertex
setq
then
still a remaining vertex
and
if first 3 are collinear , will look further
next vertex [finally nil if all collinear to end]
while
reached end without finding non-collinear point
if
progn -- then
if
setq
open can have odd number
then -- round to nearest *even* number
else -- round to nearest *whole* number
if & hwsegs
setq
if Deleting Existing/PRevious path, draw on same Layer [already will for new path]
[leave in Spline command]
feed out to Spline command:
advance point along path
from World coordinates to object's coordinates
trans
localized angle of offset
getFirstDeriv
trans
angle
perpendicular to center-line path [sine +/- gives left/right]
+
polar
command
repeat
finish Spline
(command "_close" ""); then
Close option used because end-at-path's-end 'else' line below results in "kinked"
start/end on most closed paths. Using plain Close line above, accepting default
for tangent direction, though start/end "flows" across, result has noticeable variance
there from typical wave shape elsewhere. Following is a compromise tangent-
direction determination, better than default above but slightly too steep in some
situations and not steep enough in others. There is no universal ideal -- it would
then [closed path]
tangent-direction found as before, but farther out from last 'ptno' location
re-use from last wave-crest fit point
trans
getFirstDeriv
trans
angle
+
tangent-direction defining point:
polar
command
else [open-ended]
if
save result in case of recall of routine with PRevious option
setq
remove base path under Delete option
re-lock layer if appropriate
defun -- FLEX | FlexSpline . LSP [ Command name : FLEX ]
[ Non - tangent changes in direction in paths , or overly tight curves relative to wave
is fully collinear , will pick a UCS related to current one . Forbids 3D Spline . ]
an even number of half - waves for closed paths so that result is complete S - waves continuous
Accounts for different Coordinate Systems of selected existing path objects .
6 . sine - wave full - S - cycle approximate Length as ratio of width ( actual length will be adjusted to
fit overall path length ) , offering same value as ( ratio of 1.0 ) as initial default .
, last edited 17 July 2015
(vl-load-com)
(defun flexreset ()
(mapcar 'setvar svnames svvals)
(vla-endundomark doc)
(defun C:FLEX
(/ *error* doc svnames svvals pathent pathdata pathtype 3DP u3p1 u3p2
u3p3pt u3p3 ptno ucschanged pathlength hwsegs steplength ptdist)
(defun *error* (errmsg)
(if (not (wcmatch errmsg "Function cancelled,quit / exit abort,console break"))
(princ (strcat "\nError: " errmsg))
(if ucschanged (vl-cmdf "_.ucs" "_prev"))
^ i.e. do n't go back unless routine reached UCS change but did n't change it back
(flexreset)
(setq doc (vla-get-activedocument (vlax-get-acad-object)))
(vla-startundomark doc)
(setq
svnames '(cmdecho osmode blipmode ucsfollow clayer)
(initget
(strcat
"Existing Line Arc Circle Pline ELlipse Spline 3dpoly"
add PR option only if not first use
(setq *flextype*
(cond
( (getkword
(strcat
"\nPath type [Existing or draw Line(single)/Arc/Circle/Pline(2D)/ELlipse/Spline/3dpoly"
offer PR option if not first use
"] <"
">: "
Enter on first use
((= *flextype* "PRevious")
(if (= *flexdel* "Delete")
(if *isLocked* (command "_.layer" "_unlock" *pathlay* ""))
((= *flextype* "Existing")
(while
(not
(and
(setq
pathent (car (entsel "\nSelect object to draw sine-wave along an Existing path: "))
pathdata (if pathent (entget pathent))
pathtype (if pathent (substr (cdr (assoc 100 (reverse pathdata))) 5))
(or
other types than Spline/3DPoly
(prompt "\nNothing selected, or not a finite planar path type; try again:")
(setq
(cond
pathdata (entget *flexpath*)
pathtype (substr (cdr (assoc 100 (reverse pathdata))) 5)
(if
User drew Spline or 3DPolyline that is not planar
(or
(= pathtype "Spline")
separately from Spline , for UCS alignment
(not (vlax-curve-isPlanar *flexpath*))
(prompt "\nCannot use non-planar Spline/3DPolyline.")
(flexreset) (quit)
(setq
*pathlay* (cdr (assoc 8 pathdata))
(if (and (= *flextype* "PRevious") *isLocked*)
(= (logand (cdr (assoc 70 (tblsearch "layer" *pathlay*))) 4) 4)
(initget "Retain Delete")
(setq *flexdel*
(cond
( (getkword
(strcat
"\nRetain or Delete base path [R/D] <"
prior choice default , Delete on first use
">: "
Enter on first use
(if (and *isLocked* (= *flexdel* "Delete"))
(initget "Proceed Quit")
(setq *flexunlk*
(cond
( (getkword
(strcat
"\nLayer is locked; temporarily unlock and Proceed, or Quit? [P/Q] <"
prior choice default , Proceed on first use
">: "
Enter on first use
(if (= *flexunlk* "Proceed")
progn & inner then argument
no zero , no negative , no Enter on first use
(setq *flexwid*
(cond
( (getdist
(strcat
"\nWidth (overall) of sine wave"
default only if not first use
": "
no zero , no negative
(cond
( (getreal
(strcat
"\nFull-S cycle length as ratio of width <"
">: "
Enter on first use
(if 3DP
then -- 3DPolyline does n't define UCS under object option , so :
(setq
second
u3p3pt (vlax-curve-getPointAtParam *flexpath* (setq ptno 2))
third [ if present ] -- WCS point only , un - translated [ ( trans ) fails if nil ]
at least 3 vertices
(while
(and
collinear with first 2 vertices
until it finds one not collinear with 1st & 2nd
(setq u3p3pt (vlax-curve-getPointAtParam *flexpath* (setq ptno (1+ ptno))))
accept offered default for 3rd point [ UCS will be parallel to current UCS ]
else [ single - segment ] -- accept offered default for 3rd point [ as above ]
if [ 3 or more vertices vs. 2 ]
use vertices to define UCS
progn -- then [ 3DP ]
else [ other types ] -- set UCS to match object
(setq
marker for * error * to reset UCS if routine does n't get to it
starting value for intermediate point multiplier [ replace prior use if 3DP ]
(setq
pathlength (vlax-curve-getDistAtParam *flexpath* (vlax-curve-getEndParam *flexpath*))
(if (vlax-curve-isClosed *flexpath*)
steplength (/ pathlength hwsegs 2)
(if (and (wcmatch *flextype* "Existing,PRevious") (= *flexdel* "Delete")) (setvar 'clayer *pathlay*))
for Fit Points not including final at end
(polar
(trans
*flexpath*
(setq ptdist (* (setq ptno (1+ ptno)) steplength))
getPointAtDist
(angle
'(0 0 0)
(trans
(vlax-curve-getFirstDeriv
*flexpath*
(vlax-curve-getParamAtDist *flexpath* ptdist)
world to current CS , as displacement
(* *flexwid* 0.5 (sin (* (/ pi 2) (rem ptno 4))))
proportion of sine - wave width [ alternates between + /- 0.5 & 0 ]
differ depending on degrees of curvature within first & last wavelengths of path .
"_close"
(trans
(vlax-curve-getPointAtDist
*flexpath*
getPointAtDist
0 1
(+
(angle
'(0 0 0)
(trans
(vlax-curve-getFirstDeriv
*flexpath*
(vlax-curve-getParamAtDist *flexpath* ptdist)
0 1 T
(/ pi 2)
outboard of last wave crest , twice as far from path , for compromise location
(command "_.ucs" "_prev")
(setq
eliminate UCS reset in * error * since routine did it already
(flexreset)
(princ)
(prompt "Type FLEX to draw sine-wave-approximation Spline centered along path.") |
ae739dd15b82d8080ba0ff900440e2efb403b3c952c8e081af65cb32701de51c | tylerholien/milena | tests.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Functor
import Data.Either (isRight, isLeft)
import qualified Data.List.NonEmpty as NE
import Control.Lens
import Control.Monad.Except (catchError, throwError)
import Control.Monad.Trans (liftIO)
import Network.Kafka
import Network.Kafka.Consumer
import Network.Kafka.Producer
import Network.Kafka.Protocol (ProduceResponse(..), KafkaError(..), CompressionCodec(..))
import Test.Tasty
import Test.Tasty.Hspec
import Test.Tasty.QuickCheck
import qualified Data.ByteString.Char8 as B
import Prelude
main :: IO ()
main = testSpec "the specs" specs >>= defaultMain
specs :: Spec
specs = do
let topic = "milena-test"
run = runKafka $ mkKafkaState "milena-test-client" ("localhost", 9092)
requireAllAcks = do
stateRequiredAcks .= -1
stateWaitSize .= 1
stateWaitTime .= 1000
byteMessages = fmap (TopicAndMessage topic . makeMessage . B.pack)
describe "can talk to local Kafka server" $ do
prop "can produce messages" $ \ms -> do
result <- run . produceMessages $ byteMessages ms
result `shouldSatisfy` isRight
prop "can produce compressed messages" $ \ms -> do
result <- run . produceCompressedMessages Gzip $ byteMessages ms
result `shouldSatisfy` isRight
prop "can produce multiple messages" $ \(ms, ms', ms'') -> do
result <- run $ do
r1 <- produceMessages $ byteMessages ms
r2 <- produceMessages $ byteMessages ms'
r3 <- produceCompressedMessages Gzip $ byteMessages ms''
return $ r1 ++ r2 ++ r3
result `shouldSatisfy` isRight
prop "can fetch messages" $ do
result <- run $ do
offset <- getLastOffset EarliestTime 0 topic
withAnyHandle (\handle -> fetch' handle =<< fetchRequest offset 0 topic)
result `shouldSatisfy` isRight
prop "can roundtrip messages" $ \ms key -> do
let messages = byteMessages ms
result <- run $ do
requireAllAcks
info <- brokerPartitionInfo topic
case getPartitionByKey (B.pack key) info of
Just PartitionAndLeader { _palLeader = leader, _palPartition = partition } -> do
let payload = [(TopicAndPartition topic partition, groupMessagesToSet NoCompression messages)]
s = stateBrokers . at leader
[(_topicName, [(_, NoError, offset)])] <- _produceResponseFields <$> send leader payload
broker <- findMetadataOrElse [topic] s (KafkaInvalidBroker leader)
resp <- withBrokerHandle broker (\handle -> fetch' handle =<< fetchRequest offset partition topic)
return $ fmap tamPayload . fetchMessages $ resp
Nothing -> fail "Could not deduce partition"
result `shouldBe` Right (tamPayload <$> messages)
prop "can roundtrip compressed messages" $ \(NonEmpty ms) -> do
let messages = byteMessages ms
result <- run $ do
requireAllAcks
produceResps <- produceCompressedMessages Gzip messages
case map _produceResponseFields produceResps of
[[(_topicName, [(partition, NoError, offset)])]] -> do
resp <- fetch offset partition topic
return $ fmap tamPayload . fetchMessages $ resp
_ -> fail "Unexpected produce response"
result `shouldBe` Right (tamPayload <$> messages)
prop "can roundtrip keyed messages" $ \(NonEmpty ms) key -> do
let keyBytes = B.pack key
messages = fmap (TopicAndMessage topic . makeKeyedMessage keyBytes . B.pack) ms
result <- run $ do
requireAllAcks
produceResps <- produceMessages messages
case map _produceResponseFields produceResps of
[[(_topicName, [(partition, NoError, offset)])]] -> do
resp <- fetch offset partition topic
return $ fmap tamPayload . fetchMessages $ resp
_ -> fail "Unexpected produce response"
result `shouldBe` Right (tamPayload <$> messages)
describe "withAddressHandle" $ do
it "turns 'IOException's into 'KafkaClientError's" $ do
result <- run $ withAddressHandle ("localhost", 9092) (\_ -> liftIO $ ioError $ userError "SOMETHING WENT WRONG!") :: IO (Either KafkaClientError ())
result `shouldSatisfy` isLeft
it "discards monadic effects when exceptions are thrown" $ do
result <- run $ do
stateName .= "expected"
_ <- flip catchError (return . Left) $ withAddressHandle ("localhost", 9092) $ \_ -> do
stateName .= "changed"
_ <- throwError KafkaFailedToFetchMetadata
n <- use stateName
return (Right n)
use stateName
result `shouldBe` Right "expected"
describe "updateMetadatas" $
it "de-dupes _stateAddresses" $ do
result <- run $ do
stateAddresses %= NE.cons ("localhost", 9092)
updateMetadatas []
use stateAddresses
result `shouldBe` fmap NE.nub result
prop :: Testable prop => String -> prop -> SpecWith ()
prop s = it s . property
| null | https://raw.githubusercontent.com/tylerholien/milena/5b46dccfb35017a0c6705db525b4b09f8b48139d/test/tests.hs | haskell | # LANGUAGE OverloadedStrings # |
module Main where
import Data.Functor
import Data.Either (isRight, isLeft)
import qualified Data.List.NonEmpty as NE
import Control.Lens
import Control.Monad.Except (catchError, throwError)
import Control.Monad.Trans (liftIO)
import Network.Kafka
import Network.Kafka.Consumer
import Network.Kafka.Producer
import Network.Kafka.Protocol (ProduceResponse(..), KafkaError(..), CompressionCodec(..))
import Test.Tasty
import Test.Tasty.Hspec
import Test.Tasty.QuickCheck
import qualified Data.ByteString.Char8 as B
import Prelude
main :: IO ()
main = testSpec "the specs" specs >>= defaultMain
specs :: Spec
specs = do
let topic = "milena-test"
run = runKafka $ mkKafkaState "milena-test-client" ("localhost", 9092)
requireAllAcks = do
stateRequiredAcks .= -1
stateWaitSize .= 1
stateWaitTime .= 1000
byteMessages = fmap (TopicAndMessage topic . makeMessage . B.pack)
describe "can talk to local Kafka server" $ do
prop "can produce messages" $ \ms -> do
result <- run . produceMessages $ byteMessages ms
result `shouldSatisfy` isRight
prop "can produce compressed messages" $ \ms -> do
result <- run . produceCompressedMessages Gzip $ byteMessages ms
result `shouldSatisfy` isRight
prop "can produce multiple messages" $ \(ms, ms', ms'') -> do
result <- run $ do
r1 <- produceMessages $ byteMessages ms
r2 <- produceMessages $ byteMessages ms'
r3 <- produceCompressedMessages Gzip $ byteMessages ms''
return $ r1 ++ r2 ++ r3
result `shouldSatisfy` isRight
prop "can fetch messages" $ do
result <- run $ do
offset <- getLastOffset EarliestTime 0 topic
withAnyHandle (\handle -> fetch' handle =<< fetchRequest offset 0 topic)
result `shouldSatisfy` isRight
prop "can roundtrip messages" $ \ms key -> do
let messages = byteMessages ms
result <- run $ do
requireAllAcks
info <- brokerPartitionInfo topic
case getPartitionByKey (B.pack key) info of
Just PartitionAndLeader { _palLeader = leader, _palPartition = partition } -> do
let payload = [(TopicAndPartition topic partition, groupMessagesToSet NoCompression messages)]
s = stateBrokers . at leader
[(_topicName, [(_, NoError, offset)])] <- _produceResponseFields <$> send leader payload
broker <- findMetadataOrElse [topic] s (KafkaInvalidBroker leader)
resp <- withBrokerHandle broker (\handle -> fetch' handle =<< fetchRequest offset partition topic)
return $ fmap tamPayload . fetchMessages $ resp
Nothing -> fail "Could not deduce partition"
result `shouldBe` Right (tamPayload <$> messages)
prop "can roundtrip compressed messages" $ \(NonEmpty ms) -> do
let messages = byteMessages ms
result <- run $ do
requireAllAcks
produceResps <- produceCompressedMessages Gzip messages
case map _produceResponseFields produceResps of
[[(_topicName, [(partition, NoError, offset)])]] -> do
resp <- fetch offset partition topic
return $ fmap tamPayload . fetchMessages $ resp
_ -> fail "Unexpected produce response"
result `shouldBe` Right (tamPayload <$> messages)
prop "can roundtrip keyed messages" $ \(NonEmpty ms) key -> do
let keyBytes = B.pack key
messages = fmap (TopicAndMessage topic . makeKeyedMessage keyBytes . B.pack) ms
result <- run $ do
requireAllAcks
produceResps <- produceMessages messages
case map _produceResponseFields produceResps of
[[(_topicName, [(partition, NoError, offset)])]] -> do
resp <- fetch offset partition topic
return $ fmap tamPayload . fetchMessages $ resp
_ -> fail "Unexpected produce response"
result `shouldBe` Right (tamPayload <$> messages)
describe "withAddressHandle" $ do
it "turns 'IOException's into 'KafkaClientError's" $ do
result <- run $ withAddressHandle ("localhost", 9092) (\_ -> liftIO $ ioError $ userError "SOMETHING WENT WRONG!") :: IO (Either KafkaClientError ())
result `shouldSatisfy` isLeft
it "discards monadic effects when exceptions are thrown" $ do
result <- run $ do
stateName .= "expected"
_ <- flip catchError (return . Left) $ withAddressHandle ("localhost", 9092) $ \_ -> do
stateName .= "changed"
_ <- throwError KafkaFailedToFetchMetadata
n <- use stateName
return (Right n)
use stateName
result `shouldBe` Right "expected"
describe "updateMetadatas" $
it "de-dupes _stateAddresses" $ do
result <- run $ do
stateAddresses %= NE.cons ("localhost", 9092)
updateMetadatas []
use stateAddresses
result `shouldBe` fmap NE.nub result
prop :: Testable prop => String -> prop -> SpecWith ()
prop s = it s . property
|
63eeccbc211e8f6e8bf8558ab9920d13b5af2acb4b7a0d12c620d641f4313be8 | peterholko/pax_server | map.erl | %% -------------------------------------------------------------------
Author :
%%% Description :
%%%
Created : June 23 , 2010
%%% -------------------------------------------------------------------
-module(map).
-behaviour(gen_server).
%% --------------------------------------------------------------------
%% Include files
%% --------------------------------------------------------------------
-include("schema.hrl").
-include("common.hrl").
%% --------------------------------------------------------------------
%% External exports
-export([start/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([load/0, get_tile/2, get_tile_type/2, get_explored_map/1, get_surrounding_tiles/2]).
-export([get_tile_info/1, harvest_resource/3, is_tile_explored/2]).
-export([convert_coords/1, convert_coords/2]).
-record(module_data, {}).
%% ====================================================================
%% External functions
%% ====================================================================
start() ->
gen_server:start({global, map}, map, [], []).
load() ->
gen_server:call({global, map}, load).
get_tile(X, Y) ->
TileIndex = convert_coords(X,Y),
gen_server:call({global, map}, {'GET_TILE', TileIndex}).
get_tile_info(TileIndex) ->
gen_server:call({global, map}, {'GET_TILE_INFO', TileIndex}).
get_tile_type(X, Y) ->
TileIndex = convert_coords(X,Y),
gen_server:call({global, map}, {'GET_TILE_TYPE', TileIndex}).
get_explored_map(TileIndexList) ->
gen_server:call({global, map}, {'GET_EXPLORED_MAP', TileIndexList}).
get_surrounding_tiles(X, Y) ->
Tiles2D = surrounding_tiles_2D(X, Y, 1),
TileList = surrounding_tiles(Tiles2D),
TileList.
harvest_resource(TileIndex, ResourceType, Amount) ->
gen_server:call({global, map}, {'HARVEST_RESOURCE', TileIndex, ResourceType, Amount}).
is_tile_explored(TileIndex, ExploredMap) ->
case lists:keyfind(TileIndex, 1, ExploredMap) of
false ->
Result = false;
{_Tile, _TileType} ->
Result = true
end,
Result.
%% ====================================================================
%% Server functions
%% ====================================================================
init([]) ->
Data = #module_data{},
{ok, Data}.
handle_cast(none, Data) ->
{noreply, Data};
handle_cast(stop, Data) ->
{stop, normal, Data}.
handle_call(load, _From, Data) ->
io:fwrite("Loading map...~n"),
case file:open("tiles.bin", read) of
{ok, TilesFileRef} ->
load_tiles(TilesFileRef, false, 0),
case file:open("resourceList.txt", read) of
{ok, ResourceListFileRef} ->
Time = util:get_time_seconds(),
load_resources(ResourceListFileRef, Time, false, 0);
Any ->
io:fwrite("Failed to open resourceList.txt - ~w", [Any])
end;
{error, Reason} ->
io:fwrite("Failed to open tiles.bin - ~w", [Reason]);
_ ->
?ERROR("System limit reache")
end,
{reply, ok, Data};
handle_call({'GET_EXPLORED_MAP', TileIndexList}, _From, Data) ->
MapTiles = get_map_tiles(TileIndexList, []),
{reply, MapTiles, Data};
handle_call({'GET_TILE', TileIndex}, _From, Data) ->
Tile = db:dirty_read(tile, TileIndex),
{reply, Tile, Data};
handle_call({'GET_TILE_INFO', TileIndex}, _From, Data) ->
case db:dirty_read(tile, TileIndex) of
[Tile] ->
TileType = Tile#tile.type,
Resources = get_resources(Tile#tile.resources, []);
_ ->
TileType = -1,
Resources = [],
log4erl:error("~w: Could not find tile ~w", [?MODULE, TileIndex]),
erlang:error("Could not find tile.")
end,
{reply, {TileType, Resources}, Data};
handle_call({'GET_TILE_TYPE', TileIndex}, _From, Data) ->
[Tile] = db:dirty_read(tile, TileIndex),
{reply, Tile#tile.type, Data};
handle_call({'HARVEST_RESOURCE', TileIndex, ResourceType, Amount}, _From, Data) ->
[Tile] = db:dirty_read(tile, TileIndex),
?INFO("Resources: ", Tile#tile.resources),
Resource list is contains the resource tuple , { ResourceId , ResourceType }
case lists:keyfind(ResourceType, 2, Tile#tile.resources) of
false ->
HarvestAmount = 0,
log4erl:error("{~w}: Could not find resource type ~w", [?MODULE, ResourceType]),
erlang:error("Could not find resource type.");
{ResourceId, _ResType} ->
HarvestAmount = get_harvest_amount(ResourceId, Amount)
end,
{reply, HarvestAmount, Data};
handle_call(Event, From, Data) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Event},
{from, From}
]),
{noreply, Data}.
handle_info(Info, Data) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Info}]),
{noreply, Data}.
code_change(_OldVsn, Data, _Extra) ->
{ok, Data}.
terminate(_Reason, _) ->
ok.
%% --------------------------------------------------------------------
Internal functions
load_tiles(_FileRef, true, _TileIndex) ->
?INFO("loading tiles done"),
done;
load_tiles(FileRef, false, TileIndex) ->
case file:read(FileRef, 1) of
{ok, Data} ->
[TileType] = Data,
Tile = #tile {index = TileIndex, type = TileType, resources = []},
db:dirty_write(Tile),
EOF = false;
eof ->
EOF = true
end,
load_tiles(FileRef, EOF, TileIndex + 1).
load_resources(_ResourceListFileRef, _Time, true, _TileIndex) ->
?INFO("Loading resources done"),
done;
load_resources(ResourceListFileRef, Time, _, TileIndex) ->
case io:get_line(ResourceListFileRef, '') of
eof ->
EOF = true;
Data ->
ResourceFileName = re:split(Data,"[\n]",[{return,list},trim]),
case file:open(ResourceFileName, read) of
{ok, ResourceFileRef} ->
[FileName] = ResourceFileName,
[ResourceName, _Ext] = re:split(FileName, "[.]", [{return, list}, trim]),
case db:dirty_match_object({resource_type, '_', ResourceName}) of
[ResourceType] ->
load_resource_regen(ResourceFileRef,
ResourceType#resource_type.id,
Time,
false,
0);
_ ->
?ERROR("Invalid resource type")
end;
Any ->
io:fwrite("Failed to open ResourceFileName: ~w - ~w", [ResourceFileName, Any])
end,
EOF = false
end,
load_resources(ResourceListFileRef, Time, EOF, TileIndex + 1).
load_resource_regen(_ResourceFileRef, _ResourceType, _Time, true, _TileIndex) ->
done;
load_resource_regen(ResourceFileRef, ResourceType, Time, _, TileIndex) ->
case file:read(ResourceFileRef, 1) of
{ok, Data} ->
[ResourceRegen] = Data,
case ResourceRegen > 0 of
true ->
ResourceId = counter:increment(resource),
[Tile] = db:dirty_read(tile, TileIndex),
NewResources = [{ResourceId, ResourceType} | Tile#tile.resources],
NewTile = Tile#tile { resources = NewResources},
Resource = #resource {id = ResourceId,
type = ResourceType,
total = 0,
regen_rate = ResourceRegen,
last_update = Time},
db:dirty_write(NewTile),
db:dirty_write(Resource);
false ->
skip_resource
end,
EOF = false;
eof ->
EOF = true
end,
load_resource_regen(ResourceFileRef, ResourceType, Time, EOF, TileIndex + 1).
get_harvest_amount(ResourceId, Amount) ->
case db:dirty_read(resource, ResourceId) of
[Resource] ->
HarvestAmount = update_resource(Resource, Amount);
_ ->
HarvestAmount = 0
end,
HarvestAmount.
update_resource(Resource, Amount) ->
CurrentTime = util:get_time_seconds(),
DiffTime = CurrentTime - Resource#resource.last_update,
Total = Resource#resource.total,
ResourceGrowth = erlang:round(DiffTime / 10) * Resource#resource.regen_rate,
?INFO("ResourceGrowth: ", ResourceGrowth),
?INFO("Total: ", Total),
?INFO("Amount: ", Amount),
case (Total + ResourceGrowth - Amount) < 0 of
true ->
HarvestAmount = (Total + ResourceGrowth),
NewTotal = 0;
false ->
HarvestAmount = Amount,
NewTotal = Total + ResourceGrowth - Amount
end,
?INFO("HarvestAmount: ", HarvestAmount),
NewResource = Resource#resource {total = NewTotal,
last_update = CurrentTime},
?INFO("NewResource: ", NewResource),
db:dirty_write(NewResource),
%Return harvested amount
HarvestAmount.
get_resources([], NewResources) ->
NewResources;
get_resources([{ResourceId, _ResourceType} | Rest], Resources) ->
case db:dirty_read(resource, ResourceId) of
[Resource] ->
NewResource = update_resource(Resource),
NewResources = [NewResource | Resources];
_ ->
NewResources = Resources,
log4erl:error("~w: Could not find resource id ~w", [?MODULE, ResourceId]),
erlang:error("Could not find resource id.")
end,
get_resources(Rest, NewResources).
update_resource(Resource) ->
CurrentTime = util:get_time_seconds(),
DiffTime = CurrentTime - Resource#resource.last_update,
log4erl:info("~w", [DiffTime]),
log4erl:info("{~w} Resource Total ~w", [?MODULE, Resource#resource.total]),
ResourceGrowth = erlang:round(DiffTime / 10) * Resource#resource.regen_rate,
NewTotal = Resource#resource.total + ResourceGrowth,
NewResource = Resource#resource {total = NewTotal,
last_update = CurrentTime},
log4erl:info("{~w} New Resource Total ~w", [?MODULE, NewResource#resource.total]),
db:dirty_write(NewResource),
{NewResource#resource.id,
NewResource#resource.type,
NewResource#resource.total,
NewResource#resource.regen_rate}.
get_map_tiles([], MapList) ->
MapList;
get_map_tiles(TileIndexList, MapList) ->
[TileIndex | Rest] = TileIndexList,
if
TileIndex >= 0 ->
[Tile] = db:dirty_read(tile, TileIndex),
NewMapList = [{TileIndex, Tile#tile.type} | MapList];
true ->
NewMapList = MapList
end,
get_map_tiles(Rest, NewMapList).
convert_coords(X, Y) ->
Y * ?MAP_HEIGHT + X.
convert_coords(TileIndex) ->
TileX = TileIndex rem ?MAP_WIDTH,
TileY = TileIndex div ?MAP_HEIGHT,
{TileX , TileY}.
is_valid_coords(X, Y) ->
GuardX = (X >= 0) and (X < ?MAP_WIDTH),
GuardY = (Y >= 0) and (Y < ?MAP_HEIGHT),
if
(GuardX and GuardY) ->
Result = true;
true ->
Result = false
end,
Result.
surrounding_tiles_2D(X, Y, ViewRange) ->
MinX = X - ViewRange,
MinY = Y - ViewRange,
MaxX = X + ViewRange + 1,
MaxY = Y + ViewRange + 1,
tiles_y_2D(MinX, MinY, MaxX, MaxY, []).
tiles_y_2D(_, MaxY, _, MaxY, Tiles) ->
Tiles;
tiles_y_2D(X, Y, MaxX, MaxY, Tiles) ->
io : : ~w y : ~w MaxX : ~w MaxY : ~w Tiles : ~w ~ n " , [ X , Y , MaxX , MaxY , Tiles ] ) ,
NewTiles = tiles_x_2D(X, Y, MaxX, MaxY, Tiles),
tiles_y_2D(X, Y + 1, MaxX, MaxY, NewTiles).
tiles_x_2D(MaxX, _, MaxX, _, Tiles) ->
Tiles;
tiles_x_2D(X, Y, MaxX, MaxY, Tiles) ->
Tile = {X, Y},
NewTiles = [Tile | Tiles],
io : fwrite("tiles_x_2D - x : ~w y : ~w MaxX : ~w MaxY : ~w NewTiles : ~w ~ n " , [ X , Y , MaxX , MaxY , NewTiles ] ) ,
tiles_x_2D(X + 1, Y, MaxX, MaxY, NewTiles).
%% TODO: Combine with above tiles x,y looping
surrounding_tiles(Tiles2D) ->
F = fun(Tile2D, Tiles) ->
{X, Y} = Tile2D,
ValidTile = is_valid_coords(X, Y),
if
ValidTile ->
Tile = convert_coords(X, Y),
NewTiles = [Tile | Tiles];
true ->
NewTiles = Tiles
end,
NewTiles
end,
lists:foldl(F, [], Tiles2D).
| null | https://raw.githubusercontent.com/peterholko/pax_server/62b2ec1fae195ff915d19af06e56a7c4567fd4b8/src/map.erl | erlang | -------------------------------------------------------------------
Description :
-------------------------------------------------------------------
--------------------------------------------------------------------
Include files
--------------------------------------------------------------------
--------------------------------------------------------------------
External exports
====================================================================
External functions
====================================================================
====================================================================
Server functions
====================================================================
--------------------------------------------------------------------
Return harvested amount
TODO: Combine with above tiles x,y looping | Author :
Created : June 23 , 2010
-module(map).
-behaviour(gen_server).
-include("schema.hrl").
-include("common.hrl").
-export([start/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([load/0, get_tile/2, get_tile_type/2, get_explored_map/1, get_surrounding_tiles/2]).
-export([get_tile_info/1, harvest_resource/3, is_tile_explored/2]).
-export([convert_coords/1, convert_coords/2]).
-record(module_data, {}).
start() ->
gen_server:start({global, map}, map, [], []).
load() ->
gen_server:call({global, map}, load).
get_tile(X, Y) ->
TileIndex = convert_coords(X,Y),
gen_server:call({global, map}, {'GET_TILE', TileIndex}).
get_tile_info(TileIndex) ->
gen_server:call({global, map}, {'GET_TILE_INFO', TileIndex}).
get_tile_type(X, Y) ->
TileIndex = convert_coords(X,Y),
gen_server:call({global, map}, {'GET_TILE_TYPE', TileIndex}).
get_explored_map(TileIndexList) ->
gen_server:call({global, map}, {'GET_EXPLORED_MAP', TileIndexList}).
get_surrounding_tiles(X, Y) ->
Tiles2D = surrounding_tiles_2D(X, Y, 1),
TileList = surrounding_tiles(Tiles2D),
TileList.
harvest_resource(TileIndex, ResourceType, Amount) ->
gen_server:call({global, map}, {'HARVEST_RESOURCE', TileIndex, ResourceType, Amount}).
is_tile_explored(TileIndex, ExploredMap) ->
case lists:keyfind(TileIndex, 1, ExploredMap) of
false ->
Result = false;
{_Tile, _TileType} ->
Result = true
end,
Result.
init([]) ->
Data = #module_data{},
{ok, Data}.
handle_cast(none, Data) ->
{noreply, Data};
handle_cast(stop, Data) ->
{stop, normal, Data}.
handle_call(load, _From, Data) ->
io:fwrite("Loading map...~n"),
case file:open("tiles.bin", read) of
{ok, TilesFileRef} ->
load_tiles(TilesFileRef, false, 0),
case file:open("resourceList.txt", read) of
{ok, ResourceListFileRef} ->
Time = util:get_time_seconds(),
load_resources(ResourceListFileRef, Time, false, 0);
Any ->
io:fwrite("Failed to open resourceList.txt - ~w", [Any])
end;
{error, Reason} ->
io:fwrite("Failed to open tiles.bin - ~w", [Reason]);
_ ->
?ERROR("System limit reache")
end,
{reply, ok, Data};
handle_call({'GET_EXPLORED_MAP', TileIndexList}, _From, Data) ->
MapTiles = get_map_tiles(TileIndexList, []),
{reply, MapTiles, Data};
handle_call({'GET_TILE', TileIndex}, _From, Data) ->
Tile = db:dirty_read(tile, TileIndex),
{reply, Tile, Data};
handle_call({'GET_TILE_INFO', TileIndex}, _From, Data) ->
case db:dirty_read(tile, TileIndex) of
[Tile] ->
TileType = Tile#tile.type,
Resources = get_resources(Tile#tile.resources, []);
_ ->
TileType = -1,
Resources = [],
log4erl:error("~w: Could not find tile ~w", [?MODULE, TileIndex]),
erlang:error("Could not find tile.")
end,
{reply, {TileType, Resources}, Data};
handle_call({'GET_TILE_TYPE', TileIndex}, _From, Data) ->
[Tile] = db:dirty_read(tile, TileIndex),
{reply, Tile#tile.type, Data};
handle_call({'HARVEST_RESOURCE', TileIndex, ResourceType, Amount}, _From, Data) ->
[Tile] = db:dirty_read(tile, TileIndex),
?INFO("Resources: ", Tile#tile.resources),
Resource list is contains the resource tuple , { ResourceId , ResourceType }
case lists:keyfind(ResourceType, 2, Tile#tile.resources) of
false ->
HarvestAmount = 0,
log4erl:error("{~w}: Could not find resource type ~w", [?MODULE, ResourceType]),
erlang:error("Could not find resource type.");
{ResourceId, _ResType} ->
HarvestAmount = get_harvest_amount(ResourceId, Amount)
end,
{reply, HarvestAmount, Data};
handle_call(Event, From, Data) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Event},
{from, From}
]),
{noreply, Data}.
handle_info(Info, Data) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Info}]),
{noreply, Data}.
code_change(_OldVsn, Data, _Extra) ->
{ok, Data}.
terminate(_Reason, _) ->
ok.
Internal functions
load_tiles(_FileRef, true, _TileIndex) ->
?INFO("loading tiles done"),
done;
load_tiles(FileRef, false, TileIndex) ->
case file:read(FileRef, 1) of
{ok, Data} ->
[TileType] = Data,
Tile = #tile {index = TileIndex, type = TileType, resources = []},
db:dirty_write(Tile),
EOF = false;
eof ->
EOF = true
end,
load_tiles(FileRef, EOF, TileIndex + 1).
load_resources(_ResourceListFileRef, _Time, true, _TileIndex) ->
?INFO("Loading resources done"),
done;
load_resources(ResourceListFileRef, Time, _, TileIndex) ->
case io:get_line(ResourceListFileRef, '') of
eof ->
EOF = true;
Data ->
ResourceFileName = re:split(Data,"[\n]",[{return,list},trim]),
case file:open(ResourceFileName, read) of
{ok, ResourceFileRef} ->
[FileName] = ResourceFileName,
[ResourceName, _Ext] = re:split(FileName, "[.]", [{return, list}, trim]),
case db:dirty_match_object({resource_type, '_', ResourceName}) of
[ResourceType] ->
load_resource_regen(ResourceFileRef,
ResourceType#resource_type.id,
Time,
false,
0);
_ ->
?ERROR("Invalid resource type")
end;
Any ->
io:fwrite("Failed to open ResourceFileName: ~w - ~w", [ResourceFileName, Any])
end,
EOF = false
end,
load_resources(ResourceListFileRef, Time, EOF, TileIndex + 1).
load_resource_regen(_ResourceFileRef, _ResourceType, _Time, true, _TileIndex) ->
done;
load_resource_regen(ResourceFileRef, ResourceType, Time, _, TileIndex) ->
case file:read(ResourceFileRef, 1) of
{ok, Data} ->
[ResourceRegen] = Data,
case ResourceRegen > 0 of
true ->
ResourceId = counter:increment(resource),
[Tile] = db:dirty_read(tile, TileIndex),
NewResources = [{ResourceId, ResourceType} | Tile#tile.resources],
NewTile = Tile#tile { resources = NewResources},
Resource = #resource {id = ResourceId,
type = ResourceType,
total = 0,
regen_rate = ResourceRegen,
last_update = Time},
db:dirty_write(NewTile),
db:dirty_write(Resource);
false ->
skip_resource
end,
EOF = false;
eof ->
EOF = true
end,
load_resource_regen(ResourceFileRef, ResourceType, Time, EOF, TileIndex + 1).
get_harvest_amount(ResourceId, Amount) ->
case db:dirty_read(resource, ResourceId) of
[Resource] ->
HarvestAmount = update_resource(Resource, Amount);
_ ->
HarvestAmount = 0
end,
HarvestAmount.
update_resource(Resource, Amount) ->
CurrentTime = util:get_time_seconds(),
DiffTime = CurrentTime - Resource#resource.last_update,
Total = Resource#resource.total,
ResourceGrowth = erlang:round(DiffTime / 10) * Resource#resource.regen_rate,
?INFO("ResourceGrowth: ", ResourceGrowth),
?INFO("Total: ", Total),
?INFO("Amount: ", Amount),
case (Total + ResourceGrowth - Amount) < 0 of
true ->
HarvestAmount = (Total + ResourceGrowth),
NewTotal = 0;
false ->
HarvestAmount = Amount,
NewTotal = Total + ResourceGrowth - Amount
end,
?INFO("HarvestAmount: ", HarvestAmount),
NewResource = Resource#resource {total = NewTotal,
last_update = CurrentTime},
?INFO("NewResource: ", NewResource),
db:dirty_write(NewResource),
HarvestAmount.
get_resources([], NewResources) ->
NewResources;
get_resources([{ResourceId, _ResourceType} | Rest], Resources) ->
case db:dirty_read(resource, ResourceId) of
[Resource] ->
NewResource = update_resource(Resource),
NewResources = [NewResource | Resources];
_ ->
NewResources = Resources,
log4erl:error("~w: Could not find resource id ~w", [?MODULE, ResourceId]),
erlang:error("Could not find resource id.")
end,
get_resources(Rest, NewResources).
update_resource(Resource) ->
CurrentTime = util:get_time_seconds(),
DiffTime = CurrentTime - Resource#resource.last_update,
log4erl:info("~w", [DiffTime]),
log4erl:info("{~w} Resource Total ~w", [?MODULE, Resource#resource.total]),
ResourceGrowth = erlang:round(DiffTime / 10) * Resource#resource.regen_rate,
NewTotal = Resource#resource.total + ResourceGrowth,
NewResource = Resource#resource {total = NewTotal,
last_update = CurrentTime},
log4erl:info("{~w} New Resource Total ~w", [?MODULE, NewResource#resource.total]),
db:dirty_write(NewResource),
{NewResource#resource.id,
NewResource#resource.type,
NewResource#resource.total,
NewResource#resource.regen_rate}.
get_map_tiles([], MapList) ->
MapList;
get_map_tiles(TileIndexList, MapList) ->
[TileIndex | Rest] = TileIndexList,
if
TileIndex >= 0 ->
[Tile] = db:dirty_read(tile, TileIndex),
NewMapList = [{TileIndex, Tile#tile.type} | MapList];
true ->
NewMapList = MapList
end,
get_map_tiles(Rest, NewMapList).
convert_coords(X, Y) ->
Y * ?MAP_HEIGHT + X.
convert_coords(TileIndex) ->
TileX = TileIndex rem ?MAP_WIDTH,
TileY = TileIndex div ?MAP_HEIGHT,
{TileX , TileY}.
is_valid_coords(X, Y) ->
GuardX = (X >= 0) and (X < ?MAP_WIDTH),
GuardY = (Y >= 0) and (Y < ?MAP_HEIGHT),
if
(GuardX and GuardY) ->
Result = true;
true ->
Result = false
end,
Result.
surrounding_tiles_2D(X, Y, ViewRange) ->
MinX = X - ViewRange,
MinY = Y - ViewRange,
MaxX = X + ViewRange + 1,
MaxY = Y + ViewRange + 1,
tiles_y_2D(MinX, MinY, MaxX, MaxY, []).
tiles_y_2D(_, MaxY, _, MaxY, Tiles) ->
Tiles;
tiles_y_2D(X, Y, MaxX, MaxY, Tiles) ->
io : : ~w y : ~w MaxX : ~w MaxY : ~w Tiles : ~w ~ n " , [ X , Y , MaxX , MaxY , Tiles ] ) ,
NewTiles = tiles_x_2D(X, Y, MaxX, MaxY, Tiles),
tiles_y_2D(X, Y + 1, MaxX, MaxY, NewTiles).
tiles_x_2D(MaxX, _, MaxX, _, Tiles) ->
Tiles;
tiles_x_2D(X, Y, MaxX, MaxY, Tiles) ->
Tile = {X, Y},
NewTiles = [Tile | Tiles],
io : fwrite("tiles_x_2D - x : ~w y : ~w MaxX : ~w MaxY : ~w NewTiles : ~w ~ n " , [ X , Y , MaxX , MaxY , NewTiles ] ) ,
tiles_x_2D(X + 1, Y, MaxX, MaxY, NewTiles).
surrounding_tiles(Tiles2D) ->
F = fun(Tile2D, Tiles) ->
{X, Y} = Tile2D,
ValidTile = is_valid_coords(X, Y),
if
ValidTile ->
Tile = convert_coords(X, Y),
NewTiles = [Tile | Tiles];
true ->
NewTiles = Tiles
end,
NewTiles
end,
lists:foldl(F, [], Tiles2D).
|
d3a15d301af594b9e05fd93523b39c955d9026f61299102bd9add73aab061609 | penpot/penpot | page.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.workspace.sidebar.options.page
"Page options menu entries."
(:require
[app.common.colors :as clr]
[app.main.data.workspace :as dw]
[app.main.data.workspace.undo :as dwu]
[app.main.refs :as refs]
[app.main.store :as st]
[app.main.ui.workspace.sidebar.options.rows.color-row :refer [color-row]]
[app.util.i18n :as i18n :refer [tr]]
[rumext.v2 :as mf]))
(mf/defc options
{::mf/wrap [mf/memo]}
[]
(let [options (mf/deref refs/workspace-page-options)
on-change
(fn [value]
(st/emit! (dw/change-canvas-color value)))
on-open
(fn []
(st/emit! (dwu/start-undo-transaction :options)))
on-close
(fn []
(st/emit! (dwu/commit-undo-transaction :options)))]
[:div.element-set
[:div.element-set-title (tr "workspace.options.canvas-background")]
[:div.element-set-content
[:& color-row {:disable-gradient true
:disable-opacity true
:title (tr "workspace.options.canvas-background")
:color {:color (get options :background clr/canvas)
:opacity 1}
:on-change on-change
:on-open on-open
:on-close on-close}]]]))
| null | https://raw.githubusercontent.com/penpot/penpot/694d90d485cc916ff104f1e845d1e6453ddacbaf/frontend/src/app/main/ui/workspace/sidebar/options/page.cljs | clojure |
Copyright (c) KALEIDOS INC | 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.workspace.sidebar.options.page
"Page options menu entries."
(:require
[app.common.colors :as clr]
[app.main.data.workspace :as dw]
[app.main.data.workspace.undo :as dwu]
[app.main.refs :as refs]
[app.main.store :as st]
[app.main.ui.workspace.sidebar.options.rows.color-row :refer [color-row]]
[app.util.i18n :as i18n :refer [tr]]
[rumext.v2 :as mf]))
(mf/defc options
{::mf/wrap [mf/memo]}
[]
(let [options (mf/deref refs/workspace-page-options)
on-change
(fn [value]
(st/emit! (dw/change-canvas-color value)))
on-open
(fn []
(st/emit! (dwu/start-undo-transaction :options)))
on-close
(fn []
(st/emit! (dwu/commit-undo-transaction :options)))]
[:div.element-set
[:div.element-set-title (tr "workspace.options.canvas-background")]
[:div.element-set-content
[:& color-row {:disable-gradient true
:disable-opacity true
:title (tr "workspace.options.canvas-background")
:color {:color (get options :background clr/canvas)
:opacity 1}
:on-change on-change
:on-open on-open
:on-close on-close}]]]))
|
ba990070841f7db67731f1643aad239df30ba49ddbc6ddbf0ba926f69b551860 | den1k/vimsical | core.cljc | (ns vimsical.common.core )
(defn =by
([f a]
(fn [b]
(= (f a) (f b))))
([f x y] (= (f x) (f y)))
([f g x y] (= (f x) (g y))))
(defn some-val
[f coll]
(some (fn [x] (when (f x) x)) coll))
| null | https://raw.githubusercontent.com/den1k/vimsical/1e4a1f1297849b1121baf24bdb7a0c6ba3558954/src/common/vimsical/common/core.cljc | clojure | (ns vimsical.common.core )
(defn =by
([f a]
(fn [b]
(= (f a) (f b))))
([f x y] (= (f x) (f y)))
([f g x y] (= (f x) (g y))))
(defn some-val
[f coll]
(some (fn [x] (when (f x) x)) coll))
|
|
59f33765bbeb839988290ee2a2b66701e090da50e98dc4bb306d3aaad848051c | dgiot/dgiot | dgiot_opc_channel.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 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_opc_channel).
-behavior(dgiot_channelx).
-define(TYPE, <<"DGIOTOPC">>).
-author("johnliu").
-include_lib("dgiot_bridge/include/dgiot_bridge.hrl").
-include_lib("dgiot/include/logger.hrl").
-record(state, {id, step, env = #{}}).
%% API
-export([start/2]).
-export([init/3, handle_event/3, handle_message/2, handle_init/1, stop/3]).
注册通道类型
-channel_type(#{
cType => ?TYPE,
type => ?PROTOCOL_CHL,
title => #{
zh => <<"OPC采集通道"/utf8>>
},
description => #{
zh => <<"OPC采集通道"/utf8>>
}
}).
%% 注册通道参数
-params(#{
<<"OPCSEVER">> => #{
order => 1,
type => string,
required => true,
default => <<"Kepware.KEPServerEX.V6"/utf8>>,
title => #{
zh => <<"OPC服务器"/utf8>>
},
description => #{
zh => <<"OPC服务器"/utf8>>
}
},
<<"OPCGROUP">> => #{
order => 2,
type => string,
required => true,
default => <<"group"/utf8>>,
title => #{
zh => <<"OPC分组"/utf8>>
},
description => #{
zh => <<"OPC分组"/utf8>>
}
},
<<"Topic">> => #{
order => 3,
type => string,
required => true,
default => <<"dgiot_opc_da"/utf8>>,
title => #{
zh => <<"订阅Topic"/utf8>>
},
description => #{
zh => <<"订阅Topic"/utf8>>
}
},
<<"ico">> => #{
order => 102,
type => string,
required => false,
default => <<"/dgiot_file/shuwa_tech/zh/product/dgiot/channel/OPC_ICO.png">>,
title => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
},
description => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
}
}
}).
start(ChannelId, ChannelArgs) ->
dgiot_channelx:add(?TYPE, ChannelId, ?MODULE, ChannelArgs#{
<<"Size">> => 1
}).
通道初始化
init(?TYPE, ChannelId, ChannelArgs) ->
{ProductId, Deviceinfo_list} = get_product(ChannelId), %Deviceinfo_list = [{DeviceId1,Devaddr1},{DeviceId2,Devaddr2}...]
State = #state{
id = ChannelId,
env = ChannelArgs#{
<<"productid">> => ProductId,
<<"deviceinfo_list">> => Deviceinfo_list
}
},
{ok, State}.
初始化池子
handle_init(State) ->
#state{env = #{<<"Topic">> := Topic}} = State,
Topic_ACK = binary:bin_to_list(Topic) ++ "_ack",
Topic_SCAN = binary:bin_to_list(Topic) ++ "_scan",
dgiot_mqtt:subscribe( erlang:list_to_binary(Topic_ACK)),
dgiot_mqtt:subscribe( erlang:list_to_binary(Topic_SCAN)),
erlang:send_after(1000 * 5, self(), scan_opc),
erlang:send_after(1000*60*10,self(),offline_jud),
{ok, State}.
通道消息处理 ,
handle_event(EventId, Event, _State) ->
?LOG(info, "channel ~p, ~p", [EventId, Event]),
ok.
设备下线状态修改
handle_message(offline_jud, #state{env = Env} = State) ->
erlang:send_after(1000*60*10,self(),offline_jud),
#{<<"deviceinfo_list">> := Deviceinfo_list} = Env,
[offline_modify(DeviceID) ||{DeviceID,_} <- Deviceinfo_list],
{ok, State};
handle_message({sync_parse, _Method, Args}, State) ->
?LOG(info,"sync_parse ~p", [Args]),
{ok, State};
handle_message(scan_opc, #state{env = Env} = State) ->
dgiot_opc:scan_opc(Env),
%% #{<<"Topic">> := Topic} = Env,
%% ?LOG(info,"------------------------Env:~p",[Topic]),
{ok, State#state{step = scan}};
{ " " , " opcserver " : " ControlEase . OPC.2 " , " group":"小闭式 " , " items " : " INSPEC.小闭式台位计测 . U_OPC , INSPEC.小闭式台位计测 . P_OPC ,
INSPEC.小闭式台位计测 . I_OPC , INSPEC.小闭式台位计测 . DJZS_OPC , INSPEC.小闭式台位计测 . SWD_OPC ,
INSPEC.小闭式台位计测 . , INSPEC.小闭式台位计测 . JKYL_OPC , INSPEC.小闭式台位计测 . CKYL_OPC","noitemid":"000 " }
handle_message(read_opc, #state{id = ChannelId, step = read_cycle ,env = #{<<"OPCSEVER">> := OpcServer,<<"Topic">> := Topic, <<"productid">> := ProductId,<<"deviceinfo_list">> := Deviceinfo_list}} = State) ->
{ok,#{<<"name">> :=ProductName}} = dgiot_parse:get_object(<<"Product">>,ProductId),
DeviceName_list = [get_DevAddr(X)|| X <- Deviceinfo_list],
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Properties}}} ->
Item2 = [maps:get(<<"identifier">>, H) || H <- Properties],
Identifier_item = [binary:bin_to_list(H) || H <- Item2],
Instruct = [binary:bin_to_list(ProductName) ++ "." ++ binary:bin_to_list(Y) ++ "." ++ X ++ "," || X <- Identifier_item,Y <- DeviceName_list],
Instruct1 = lists:droplast(lists:concat(Instruct)),
Instruct2 = erlang:list_to_binary(Instruct1),
dgiot_opc:read_opc(ChannelId, OpcServer,Topic,Instruct2);
_ ->
pass
end,
{ok, State#state{step = read}};
{ " status":0,"小闭式":{"INSPEC.小闭式台位计测 . . } }
handle_message({deliver, _Topic, Msg}, #state{id = ChannelId, step = scan, env = Env} = State) ->
#{<<"productid">> := ProductId,<<"Topic">> :=Topic} = Env,
Payload = dgiot_mqtt:get_payload(Msg),
#{<<"OPCSEVER">> := OpcServer,<<"OPCGROUP">> := Group } = Env,
dgiot_bridge:send_log(ChannelId, "from opc scan: ~p ", [Payload]),
case jsx:is_json(Payload) of
false ->
{ok, State};
true ->
dgiot_opc:scan_opc_ack(Payload,OpcServer,Topic, Group,ProductId),
{ok, State#state{step = pre_read}}
end;
handle_message({deliver, _Topic, Msg}, #state{ step = pre_read, env = Env} = State) ->
Payload = dgiot_mqtt:get_payload(Msg),
#{<<"productid">> := ProductId} = Env,
case jsx:is_json(Payload) of
false ->
pass;
true ->
case jsx:decode(Payload, [return_maps]) of
#{<<"status">> := 0} = Map0 ->
[Map1 | _] = maps:values(maps:without([<<"status">>], Map0)),
case maps:find(<<"status">>,Map1) of
{ok,_} ->
[Map2 | _] = maps:values(maps:without([<<"status">>], Map1));
error ->
Map2 = Map1
end,
Data = maps:fold(fun(K, V, Acc) ->
case binary:split(K, <<$.>>, [global, trim]) of
[_, _, Key1,Key2] ->
Key3 =erlang:list_to_binary(binary:bin_to_list(Key1) ++ binary:bin_to_list(Key2)),
Acc#{Key3 => V,Key1 =>Key1 };
[_,_,_] ->
Acc#{K => K};
_ -> Acc
end
end, #{}, Map2),
List_Data = maps:to_list(Data),
Need_update_list0 = dgiot_opc:create_changelist(List_Data),
Need_update_list =unique_1(Need_update_list0),
%% ?LOG(info,"--------------------Need_update_list:~p",[Need_update_list]),
Final_Properties = dgiot_opc:create_final_Properties(Need_update_list),
Topo_para=lists:zip(Need_update_list,dgiot_opc:create_x_y(erlang:length(Need_update_list))),
New_config = dgiot_opc:create_config(dgiot_opc:change_config(Topo_para)),
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Properties}}} ->
case erlang:length(Properties) of
0 ->
dgiot_parse:update_object(<<"Product">>, ProductId, #{<<"config">> => New_config}),
dgiot_parse:update_object(<<"Product">>, ProductId, #{<<"thing">> => #{<<"properties">> => Final_Properties}});
_ ->
pass
end
end,
{ok, State#state{step = read}}
end
end;
handle_message({deliver, _Topic, Msg}, #state{id = ChannelId, step = read, env = Env} = State) ->
Payload = dgiot_mqtt:get_payload(Msg),
#{<<"productid">> := ProductId, <<"deviceinfo_list">> := Deviceinfo_list} = Env, %Deviceinfo_list = [{DeviceId1,Devaddr1},{DeviceId2,Devaddr2}...]
dgiot_bridge:send_log(ChannelId, "from opc read: ~p ", [jsx:decode(Payload, [return_maps])]),
case jsx:is_json(Payload) of
false ->
pass;
true ->
[dgiot_opc:read_opc_ack(Payload, ProductId,X) || X<-Deviceinfo_list],
erlang:send_after(1000 * 10, self(), read_opc)
end,
{ok, State#state{step = read_cycle}};
handle_message(Message, State) ->
?LOG(info,"channel ~p", [Message]),
{ok, State}.
stop(ChannelType, ChannelId, _State) ->
?LOG(info,"channel stop ~p,~p", [ChannelType, ChannelId]),
ok.
get_product(ChannelId) ->
case dgiot_bridge:get_products(ChannelId) of
{ok, _, [ProductId | _]} ->
Filter = #{<<"where">> => #{<<"product">> => ProductId},<<"limit">> => 10},
case dgiot_parse:query_object(<<"Device">>, Filter) of
{ok, #{<<"results">> := Results}} ->
Deviceinfo_list = [get_deviceinfo(X)||X<-Results],
{ProductId, Deviceinfo_list};
_ ->
{<<>>, [{<<>>, <<>>}]}
end;
_ ->
{<<>>, [{<<>>, <<>>}]}
end.
get_deviceinfo(X) ->
#{<<"objectId">> := DeviceId, <<"devaddr">> := Devaddr} = X,
{DeviceId,Devaddr}.
get_DevAddr({_DeviceId,DevAddr}) ->
DevAddr.
unique_1(List)->
unique_1(List, []).
unique_1([H|L], ResultList) ->
case lists:member(H, ResultList) of
true -> unique_1(L, ResultList);
false -> unique_1(L, [H|ResultList])
end;
unique_1([], ResultList) -> ResultList.
offline_jud(DeviceID) ->
Url = "/" ++ dgiot_utils:to_list(DeviceID) ++ "?order=-createdAt&limit=1&skip=0" ,
AuthHeader = [{"authorization","Basic ZGdpb3RfYWRtaW46ZGdpb3RfYWRtaW4="}],
{ok,{_,_,Result1}} = httpc:request(get,{[Url],AuthHeader},[],[]),
timer:sleep(1000*60),
{ok,{_,_,Result2}} = httpc:request(get,{[Url],AuthHeader},[],[]),
case Result1 == Result2 of
true ->
true;
false ->
false
end.
offline_modify(DeviceID) ->
case offline_jud(DeviceID) of
true ->
dgiot_parse:update_object(<<"Device">>, DeviceID, #{<<"status">> => <<"OFFLINE">>});
false ->
pass
end.
| null | https://raw.githubusercontent.com/dgiot/dgiot/a6b816a094b1c9bd024ce40b8142375a0f0289d8/apps/dgiot_opc/src/dgiot_opc_channel.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.
--------------------------------------------------------------------
API
注册通道参数
Deviceinfo_list = [{DeviceId1,Devaddr1},{DeviceId2,Devaddr2}...]
#{<<"Topic">> := Topic} = Env,
?LOG(info,"------------------------Env:~p",[Topic]),
?LOG(info,"--------------------Need_update_list:~p",[Need_update_list]),
Deviceinfo_list = [{DeviceId1,Devaddr1},{DeviceId2,Devaddr2}...] | Copyright ( c ) 2020 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_opc_channel).
-behavior(dgiot_channelx).
-define(TYPE, <<"DGIOTOPC">>).
-author("johnliu").
-include_lib("dgiot_bridge/include/dgiot_bridge.hrl").
-include_lib("dgiot/include/logger.hrl").
-record(state, {id, step, env = #{}}).
-export([start/2]).
-export([init/3, handle_event/3, handle_message/2, handle_init/1, stop/3]).
注册通道类型
-channel_type(#{
cType => ?TYPE,
type => ?PROTOCOL_CHL,
title => #{
zh => <<"OPC采集通道"/utf8>>
},
description => #{
zh => <<"OPC采集通道"/utf8>>
}
}).
-params(#{
<<"OPCSEVER">> => #{
order => 1,
type => string,
required => true,
default => <<"Kepware.KEPServerEX.V6"/utf8>>,
title => #{
zh => <<"OPC服务器"/utf8>>
},
description => #{
zh => <<"OPC服务器"/utf8>>
}
},
<<"OPCGROUP">> => #{
order => 2,
type => string,
required => true,
default => <<"group"/utf8>>,
title => #{
zh => <<"OPC分组"/utf8>>
},
description => #{
zh => <<"OPC分组"/utf8>>
}
},
<<"Topic">> => #{
order => 3,
type => string,
required => true,
default => <<"dgiot_opc_da"/utf8>>,
title => #{
zh => <<"订阅Topic"/utf8>>
},
description => #{
zh => <<"订阅Topic"/utf8>>
}
},
<<"ico">> => #{
order => 102,
type => string,
required => false,
default => <<"/dgiot_file/shuwa_tech/zh/product/dgiot/channel/OPC_ICO.png">>,
title => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
},
description => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
}
}
}).
start(ChannelId, ChannelArgs) ->
dgiot_channelx:add(?TYPE, ChannelId, ?MODULE, ChannelArgs#{
<<"Size">> => 1
}).
通道初始化
init(?TYPE, ChannelId, ChannelArgs) ->
State = #state{
id = ChannelId,
env = ChannelArgs#{
<<"productid">> => ProductId,
<<"deviceinfo_list">> => Deviceinfo_list
}
},
{ok, State}.
初始化池子
handle_init(State) ->
#state{env = #{<<"Topic">> := Topic}} = State,
Topic_ACK = binary:bin_to_list(Topic) ++ "_ack",
Topic_SCAN = binary:bin_to_list(Topic) ++ "_scan",
dgiot_mqtt:subscribe( erlang:list_to_binary(Topic_ACK)),
dgiot_mqtt:subscribe( erlang:list_to_binary(Topic_SCAN)),
erlang:send_after(1000 * 5, self(), scan_opc),
erlang:send_after(1000*60*10,self(),offline_jud),
{ok, State}.
通道消息处理 ,
handle_event(EventId, Event, _State) ->
?LOG(info, "channel ~p, ~p", [EventId, Event]),
ok.
设备下线状态修改
handle_message(offline_jud, #state{env = Env} = State) ->
erlang:send_after(1000*60*10,self(),offline_jud),
#{<<"deviceinfo_list">> := Deviceinfo_list} = Env,
[offline_modify(DeviceID) ||{DeviceID,_} <- Deviceinfo_list],
{ok, State};
handle_message({sync_parse, _Method, Args}, State) ->
?LOG(info,"sync_parse ~p", [Args]),
{ok, State};
handle_message(scan_opc, #state{env = Env} = State) ->
dgiot_opc:scan_opc(Env),
{ok, State#state{step = scan}};
{ " " , " opcserver " : " ControlEase . OPC.2 " , " group":"小闭式 " , " items " : " INSPEC.小闭式台位计测 . U_OPC , INSPEC.小闭式台位计测 . P_OPC ,
INSPEC.小闭式台位计测 . I_OPC , INSPEC.小闭式台位计测 . DJZS_OPC , INSPEC.小闭式台位计测 . SWD_OPC ,
INSPEC.小闭式台位计测 . , INSPEC.小闭式台位计测 . JKYL_OPC , INSPEC.小闭式台位计测 . CKYL_OPC","noitemid":"000 " }
handle_message(read_opc, #state{id = ChannelId, step = read_cycle ,env = #{<<"OPCSEVER">> := OpcServer,<<"Topic">> := Topic, <<"productid">> := ProductId,<<"deviceinfo_list">> := Deviceinfo_list}} = State) ->
{ok,#{<<"name">> :=ProductName}} = dgiot_parse:get_object(<<"Product">>,ProductId),
DeviceName_list = [get_DevAddr(X)|| X <- Deviceinfo_list],
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Properties}}} ->
Item2 = [maps:get(<<"identifier">>, H) || H <- Properties],
Identifier_item = [binary:bin_to_list(H) || H <- Item2],
Instruct = [binary:bin_to_list(ProductName) ++ "." ++ binary:bin_to_list(Y) ++ "." ++ X ++ "," || X <- Identifier_item,Y <- DeviceName_list],
Instruct1 = lists:droplast(lists:concat(Instruct)),
Instruct2 = erlang:list_to_binary(Instruct1),
dgiot_opc:read_opc(ChannelId, OpcServer,Topic,Instruct2);
_ ->
pass
end,
{ok, State#state{step = read}};
{ " status":0,"小闭式":{"INSPEC.小闭式台位计测 . . } }
handle_message({deliver, _Topic, Msg}, #state{id = ChannelId, step = scan, env = Env} = State) ->
#{<<"productid">> := ProductId,<<"Topic">> :=Topic} = Env,
Payload = dgiot_mqtt:get_payload(Msg),
#{<<"OPCSEVER">> := OpcServer,<<"OPCGROUP">> := Group } = Env,
dgiot_bridge:send_log(ChannelId, "from opc scan: ~p ", [Payload]),
case jsx:is_json(Payload) of
false ->
{ok, State};
true ->
dgiot_opc:scan_opc_ack(Payload,OpcServer,Topic, Group,ProductId),
{ok, State#state{step = pre_read}}
end;
handle_message({deliver, _Topic, Msg}, #state{ step = pre_read, env = Env} = State) ->
Payload = dgiot_mqtt:get_payload(Msg),
#{<<"productid">> := ProductId} = Env,
case jsx:is_json(Payload) of
false ->
pass;
true ->
case jsx:decode(Payload, [return_maps]) of
#{<<"status">> := 0} = Map0 ->
[Map1 | _] = maps:values(maps:without([<<"status">>], Map0)),
case maps:find(<<"status">>,Map1) of
{ok,_} ->
[Map2 | _] = maps:values(maps:without([<<"status">>], Map1));
error ->
Map2 = Map1
end,
Data = maps:fold(fun(K, V, Acc) ->
case binary:split(K, <<$.>>, [global, trim]) of
[_, _, Key1,Key2] ->
Key3 =erlang:list_to_binary(binary:bin_to_list(Key1) ++ binary:bin_to_list(Key2)),
Acc#{Key3 => V,Key1 =>Key1 };
[_,_,_] ->
Acc#{K => K};
_ -> Acc
end
end, #{}, Map2),
List_Data = maps:to_list(Data),
Need_update_list0 = dgiot_opc:create_changelist(List_Data),
Need_update_list =unique_1(Need_update_list0),
Final_Properties = dgiot_opc:create_final_Properties(Need_update_list),
Topo_para=lists:zip(Need_update_list,dgiot_opc:create_x_y(erlang:length(Need_update_list))),
New_config = dgiot_opc:create_config(dgiot_opc:change_config(Topo_para)),
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"thing">> := #{<<"properties">> := Properties}}} ->
case erlang:length(Properties) of
0 ->
dgiot_parse:update_object(<<"Product">>, ProductId, #{<<"config">> => New_config}),
dgiot_parse:update_object(<<"Product">>, ProductId, #{<<"thing">> => #{<<"properties">> => Final_Properties}});
_ ->
pass
end
end,
{ok, State#state{step = read}}
end
end;
handle_message({deliver, _Topic, Msg}, #state{id = ChannelId, step = read, env = Env} = State) ->
Payload = dgiot_mqtt:get_payload(Msg),
dgiot_bridge:send_log(ChannelId, "from opc read: ~p ", [jsx:decode(Payload, [return_maps])]),
case jsx:is_json(Payload) of
false ->
pass;
true ->
[dgiot_opc:read_opc_ack(Payload, ProductId,X) || X<-Deviceinfo_list],
erlang:send_after(1000 * 10, self(), read_opc)
end,
{ok, State#state{step = read_cycle}};
handle_message(Message, State) ->
?LOG(info,"channel ~p", [Message]),
{ok, State}.
stop(ChannelType, ChannelId, _State) ->
?LOG(info,"channel stop ~p,~p", [ChannelType, ChannelId]),
ok.
get_product(ChannelId) ->
case dgiot_bridge:get_products(ChannelId) of
{ok, _, [ProductId | _]} ->
Filter = #{<<"where">> => #{<<"product">> => ProductId},<<"limit">> => 10},
case dgiot_parse:query_object(<<"Device">>, Filter) of
{ok, #{<<"results">> := Results}} ->
Deviceinfo_list = [get_deviceinfo(X)||X<-Results],
{ProductId, Deviceinfo_list};
_ ->
{<<>>, [{<<>>, <<>>}]}
end;
_ ->
{<<>>, [{<<>>, <<>>}]}
end.
get_deviceinfo(X) ->
#{<<"objectId">> := DeviceId, <<"devaddr">> := Devaddr} = X,
{DeviceId,Devaddr}.
get_DevAddr({_DeviceId,DevAddr}) ->
DevAddr.
unique_1(List)->
unique_1(List, []).
unique_1([H|L], ResultList) ->
case lists:member(H, ResultList) of
true -> unique_1(L, ResultList);
false -> unique_1(L, [H|ResultList])
end;
unique_1([], ResultList) -> ResultList.
offline_jud(DeviceID) ->
Url = "/" ++ dgiot_utils:to_list(DeviceID) ++ "?order=-createdAt&limit=1&skip=0" ,
AuthHeader = [{"authorization","Basic ZGdpb3RfYWRtaW46ZGdpb3RfYWRtaW4="}],
{ok,{_,_,Result1}} = httpc:request(get,{[Url],AuthHeader},[],[]),
timer:sleep(1000*60),
{ok,{_,_,Result2}} = httpc:request(get,{[Url],AuthHeader},[],[]),
case Result1 == Result2 of
true ->
true;
false ->
false
end.
offline_modify(DeviceID) ->
case offline_jud(DeviceID) of
true ->
dgiot_parse:update_object(<<"Device">>, DeviceID, #{<<"status">> => <<"OFFLINE">>});
false ->
pass
end.
|
54fe01c1d2a9962a86cf55428eccc69fbe5c077ccff34270394c57345fa425e5 | ulisses/Static-Code-Analyzer | ExtractValues.hs | {-#OPTIONS -XFlexibleInstances#-}
module ExtractValues where
import Data.List
import ProcessDirectory
{-
Here we have: (x,y,r)
where 'x' and 'y' are the coordinates and 'r' the radius
of the circular spot
-}
vals = [(1,2,1),(1,5,1),(1,8,1)]
fog = scan "/Users/ulissesaraujocosta/ulisses/univ/msc/el/pi/Static-Code-Analyzer/sample_app/data/concursos"
{-
getNameContests :: Disk Data -> [String]
getNameContests (File _) = []
getNameContests (Folder a l) | intersect (name a) "contest-" == "contest-" = name a : concat ( map getNameContests l)
| otherwise = concat $ map getNameContests l
-}
-- example : /Users/ulissesaraujocosta/ulisses/univ/msc/el/pi/Static-Code-Analyzer/sample_app/data/concursos/contest-1/en-1/user-1/tent-20110303163050
--con1 :: Disk Data -> [(Int,Int,Int)]
--con1 (Folder a l) =
type ContestName = String
getContestsName :: IO [ContestName]
getContestsName = fog >>= return . getContestsName_
where
getContestsName_ :: Disk Data -> [ContestName]
getContestsName_ (Folder a l) = getNamesFolders l
type AssignmentName = String
getAssignmentName :: ContestName -> IO [AssignmentName]
getAssignmentName c = fog >>= return . (getAssignmentName_ c)
where
getAssignmentName_ :: ContestName -> Disk Data -> [AssignmentName]
getAssignmentName_ c (Folder a l) | name a == c = getNamesFolders l
| otherwise = concat (fmap (getAssignmentName_ c) l)
type GroupName = String
--getGroupName :: ContestName -> AssignmentName -> IO [GroupName]
--getGroupName c assig = fog >>= return . (getGroupName_ c assig)
--getGroupName_ :: ContestName -> AssignmentName -> Disk Data -> [GroupName]
--getGroupName_ c as (Folder a l) |
getNamesFolders :: [Disk Data] -> [String]
getNamesFolders [] = []
getNamesFolders ((Folder fn _):t) = name fn : getNamesFolders t
| null | https://raw.githubusercontent.com/ulisses/Static-Code-Analyzer/4c3f6423d43e1bccb9d1cf04e74ae60d9170186f/Haskell/graphForContest/ExtractValues.hs | haskell | #OPTIONS -XFlexibleInstances#
Here we have: (x,y,r)
where 'x' and 'y' are the coordinates and 'r' the radius
of the circular spot
getNameContests :: Disk Data -> [String]
getNameContests (File _) = []
getNameContests (Folder a l) | intersect (name a) "contest-" == "contest-" = name a : concat ( map getNameContests l)
| otherwise = concat $ map getNameContests l
example : /Users/ulissesaraujocosta/ulisses/univ/msc/el/pi/Static-Code-Analyzer/sample_app/data/concursos/contest-1/en-1/user-1/tent-20110303163050
con1 :: Disk Data -> [(Int,Int,Int)]
con1 (Folder a l) =
getGroupName :: ContestName -> AssignmentName -> IO [GroupName]
getGroupName c assig = fog >>= return . (getGroupName_ c assig)
getGroupName_ :: ContestName -> AssignmentName -> Disk Data -> [GroupName]
getGroupName_ c as (Folder a l) | |
module ExtractValues where
import Data.List
import ProcessDirectory
vals = [(1,2,1),(1,5,1),(1,8,1)]
fog = scan "/Users/ulissesaraujocosta/ulisses/univ/msc/el/pi/Static-Code-Analyzer/sample_app/data/concursos"
type ContestName = String
getContestsName :: IO [ContestName]
getContestsName = fog >>= return . getContestsName_
where
getContestsName_ :: Disk Data -> [ContestName]
getContestsName_ (Folder a l) = getNamesFolders l
type AssignmentName = String
getAssignmentName :: ContestName -> IO [AssignmentName]
getAssignmentName c = fog >>= return . (getAssignmentName_ c)
where
getAssignmentName_ :: ContestName -> Disk Data -> [AssignmentName]
getAssignmentName_ c (Folder a l) | name a == c = getNamesFolders l
| otherwise = concat (fmap (getAssignmentName_ c) l)
type GroupName = String
getNamesFolders :: [Disk Data] -> [String]
getNamesFolders [] = []
getNamesFolders ((Folder fn _):t) = name fn : getNamesFolders t
|
2a09027b64501221181c7d70f1f3a1277a38a48616160a1aacc1ecb9bd3aa8e2 | retro/keechma-next-realworld-app | core_test.cljs | (ns router.core-test
(:require [cljs.test :refer-macros [deftest is use-fixtures testing are]]
[router.core :as router]
[router.util :refer [encode-query-params decode-query-params]]))
#_(use-fixtures :once {:before (fn [] (js/console.clear))})
(deftest route->parts
(is (= [":foo" "/" "bar" "/" ":baz"] (router/route->parts ":foo/bar/:baz")))
(is (= [":foo/bar" "/" "baz" "/" ":bar.qux/foo" "/" ":qux/baz"] (router/route->parts "{:foo/bar}/baz/{:bar.qux/foo}/{qux/baz}")))
(is (thrown? js/Error (router/route->parts "{:foo")))
(is (thrown? js/Error (router/route->parts "{f:oo}"))))
(deftest match-path []
(let [routes (router/expand-routes ["/:foo/bar/:baz"])
matched-path (router/match-path routes "one/bar/two")]
(is (= matched-path {:route ":foo/bar/:baz" :data {:foo "one" :baz "two"}}))))
(deftest url->map []
(let [routes (router/expand-routes [[":page" {:page "index"}]])
matched-1 (router/url->map routes "foo.Bar")
matched-2 (router/url->map routes "")
matched-3 (router/url->map routes "foo.Bar?where=there")]
(is (= matched-1 {:route ":page"
:data {:page "foo.Bar"}}))
(is (= matched-2 {:route ":page"
:data {:page "index"}}))
(is (= matched-3 {:route ":page"
:data {:page "foo.Bar"
:where "there"}})))
(let [routes (router/expand-routes [[":page/:bar" {:page "index" :bar "foo"}]])
matched (router/url->map routes "foo.Bar/?where=there")]
(is (= matched {:route ":page/:bar"
:data {:page "foo.Bar"
:bar "foo"
:where "there"}})))
(let [routes (router/expand-routes ["/:foo/bar/:baz"])
url "/one/bar/two?qux=1&test=success"
matched (router/url->map routes url)
expected-data {:foo "one" :baz "two" :qux "1" :test "success"}]
(is (= matched {:route ":foo/bar/:baz"
:data expected-data})))
(let [routes (router/expand-routes [":page"])]
(is (= (router/url->map routes "Hello%20World")
{:route ":page"
:data {:page "Hello World"}})))
(let [routes (router/expand-routes [":folder/:file.:ext"])]
(is (= {:route ":folder/:file.:ext" :data {:folder "desktop" :file "image", :ext "jpg"}}
(router/url->map routes "desktop/image.jpg")))))
(deftest url->map-invalid []
(let [routes (router/expand-routes [["pages/:var1/:var2/:var3"
{:var1 "default1"
:var2 "default2"
:var3 "default3"}]])
matched-1 (router/url->map routes "pages//")
matched-2 (router/url->map routes "pages/val1/val2/val3?invalid-param")]
(is (= matched-1 {:data {}}))
(is (= matched-2 {:route "pages/:var1/:var2/:var3"
:data {:var1 "val1"
:var2 "val2"
:var3 "val3"}}))))
(deftest url->map-only-query-string []
(let [routes []
url "?foo=bar&baz=qux"
matched-url (router/url->map routes url)]
(is (= matched-url {:data {:foo "bar" :baz "qux"}}))))
(deftest map->url []
(let [routes (router/expand-routes [["pages/:page" {:page "index"}]])
url-1 (router/map->url routes {:page "foo"})
url-2 (router/map->url routes {:page "foo" :index "bar"})]
(is (= url-1 "pages/foo"))
(is (= url-2 "pages/foo?index=bar")))
(let [routes (router/expand-routes [["pages/:page" {:page "index"}]
["pages/:page/:foo" {:page "index" :foo "bar"}]])
url (router/map->url routes {:page "foo" :foo "bar" :where "there"})]
(is (= url "pages/foo/?where=there")))
(let [url (router/map->url nil {:page "foo" :bar "baz" :where "there"})]
(is (= url "?page=foo&bar=baz&where=there"))))
(deftest symmetry []
(let [data {:page "=&[]" :nestedArray ["a"] :nested {:a "b"}}
url (router/map->url [] data)
back-data (router/url->map [] url)]
(is (= data (:data back-data)))))
(deftest light-param []
(let [routes (router/expand-routes [[":page", {:page "index"}]])
res (router/map->url routes {:page "index"})]
(is (= res "")))
(let [routes (router/expand-routes [["pages/:p1/:p2/:p3" {:p1 "index" :p2 "foo" :p3 "bar"}]])
res-1 (router/map->url routes {:p1 "index" :p2 "foo" :p3 "bar"})
res-2 (router/map->url routes {:p1 "index" :p2 "baz" :p3 "bar"})]
(is (= res-1 "pages///"))
(is (= res-2 "pages//baz/"))))
(deftest map->url-does-not-add-defaults []
(let [routes (router/expand-routes [["pages/:p1", {:p2 "foo"}]])]
(is (= (router/map->url routes {:p1 "index" :p2 "foo"}) "pages/index"))))
(deftest map->url-url->map []
(let [routes (router/expand-routes [
[":page/:type", {:page "index", :type "foo"}]])
data {:page "foo.Bar" :type "document" :bar "baz" :where "there"}
url (router/map->url routes data)
url-data (router/url->map routes url)
data-2 {:page "foo.Bar" :type "foo" :bar "baz" :where "there"}
url-2 (router/map->url routes data-2)
url-data-2 (router/url->map routes url-2)
data-3 {:page "index" :type "foo" :bar "baz" :where "there"}
url-3 (router/map->url routes data-3)
url-data-3 (router/url->map routes url-3)]
(is (= data (:data url-data)))
(is (= data-2 (:data url-data-2)))
(is (= data-3 (:data url-data-3))))
(let [data {:page "foo" :bar "baz" :where "there"}
url (router/map->url [] data)
url-data (router/url->map [] url)]
(is (= data (:data url-data))))
(let [routes (router/expand-routes [[":foo/:bar" {:foo 1 :bar 2}]])
url (router/map->url routes {:foo 1 :bar 2})
data (router/url->map routes "/")]
(is (= url ""))
(is (= {:foo 1 :bar 2} (:data data)))))
(deftest precedence []
(let [routes (router/expand-routes [[":who", {:who "index"}]
"search/:search"])
data-1 (router/url->map routes "foo.Bar")
data-2 (router/url->map routes "search/foo.Bar")
url-1 (router/map->url routes {:who "foo.Bar"})
url-2 (router/map->url routes {:search "foo.Bar"})]
(is (= (:data data-1) {:who "foo.Bar"}))
(is (= (:data data-2) {:search "foo.Bar"}))
(is (= url-1 "foo.Bar"))
(is (= url-2 "search/foo.Bar")))
(let [routes (router/expand-routes [[":type" , {:who "index"}]
":type/:id"])
data (router/url->map routes "foo/bar")
url (router/map->url routes {:type "foo" :id "bar"})]
(is (= (:data data) {:type "foo" :id "bar"}))
(is (= url "foo/bar"))))
(deftest namespaced-keys
(let [routes (router/expand-routes [["" {:page "homepage"}]
":page"
["blog" {:page "blog-index" :blog-posts/page 1}]
["blog/p/{:blog-posts/page}" {:page "blog-index"}]
["blog/{:blog-post/slug}" {:page "blog-post"}]
["users/list" {:page "users"}]
["users/{:user/id}" {:page "user-details"}]
["users/{:user/id}/{:user/page}"]])]
(is (= "" (router/map->url routes {:page "homepage"})))
(is (= "foo" (router/map->url routes {:page "foo"})))
(is (= "users/list" (router/map->url routes {:page "users"})))
(is (= "users/1" (router/map->url routes {:user/id 1})))
(is (= "users/1/details" (router/map->url routes {:user/id 1 :user/page "details"})))
(is (= "?foo/bar=1&foo.bar/baz=2&foo.bar.baz/qux[qux/foo]=bar&foo.bar.baz.qux/foo[bar.baz/qux]=foo"
(router/map->url routes {:foo/bar 1
:foo.bar/baz 2
:foo.bar.baz/qux {:qux/foo "bar"}
:foo.bar.baz.qux/foo {:bar.baz/qux "foo"}})))
(is (= {:page "homepage"} (:data (router/url->map routes ""))))
(is (= {:page "homepage"} (:data (router/url->map routes "homepage"))))
(is (= {:page "foo"} (:data (router/url->map routes "foo"))))
(is (= {:page "users"} (:data (router/url->map routes "users/list"))))
(is (= {:page "user-details" :user/id "1"} (:data (router/url->map routes "users/1"))))
(is (= {:user/id "1" :user/page "details"} (:data (router/url->map routes "users/1/details"))))
(is (= {:foo/bar "1"
:foo.bar/baz "2"
:foo.bar.baz/qux {:qux/foo "bar"}
:foo.bar.baz.qux/foo {:bar.baz/qux "foo"}
:page "homepage"}
(:data (router/url->map routes "?foo/bar=1&foo.bar/baz=2&foo.bar.baz/qux[qux/foo]=bar&foo.bar.baz.qux/foo[bar.baz/qux]=foo"))))))
(deftest splat-routes
(let [routes (router/expand-routes [["" {:page "homepage"}]
":page"
"fs/{:folders/*}/:file.:ext"
[":*" {:page "not-found"}]])]
(is (= {:page "homepage"} (:data (router/url->map routes ""))))
(is (= {:page "foo"} (:data (router/url->map routes "foo"))))
(is (= {:page "not-found" :* "foo/bar/baz"} (:data (router/url->map routes "foo/bar/baz"))))
(is (= {:folders/* "foo/bar/baz" :file "img" :ext "jpg"} (:data (router/url->map routes "fs/foo/bar/baz/img.jpg"))))
(is (= "fs/foo/bar/baz/img.jpg" (router/map->url routes {:folders/* "foo/bar/baz" :file "img" :ext "jpg"})))
(is (= "foo/bar" (router/map->url routes {:* "foo/bar"})))))
(deftest duplicate-placeholders
(is (thrown? js/Error (router/expand-routes [":foo/bar/:foo"]))))
(deftest trailing-slash
(let [routes (router/expand-routes [":page"])]
(is (= {:page "homepage"} (:data (router/url->map routes "homepage/"))))))
(deftest query-params-test
(testing "encodes query params"
(let [params {:id "kevin" :food "bacon"}
encoded (encode-query-params params)]
(is (= (decode-query-params encoded)
params)))
(are [x y] (= (encode-query-params x) y)
{:x [1 2]} "x[]=1&x[]=2"
{:a [{:b 1} {:b 2}]} "a[0][b]=1&a[1][b]=2"
{:a [{:b [1 2]} {:b [3 4]}]} "a[0][b][]=1&a[0][b][]=2&a[1][b][]=3&a[1][b][]=4"))
(testing "decodes query params"
(let [query-string "id=kevin&food=bacong"
decoded (decode-query-params query-string)
encoded (encode-query-params decoded)]
(is (re-find #"id=kevin" query-string))
(is (re-find #"food=bacon" query-string)))
(are [x y] (= (decode-query-params x) y)
"x[]=1&x[]=2" {:x ["1" "2"]}
"a[0][b]=1&a[1][b]=2" {:a [{:b "1"} {:b "2"}]}
"a[0][b][]=1&a[0][b][]=2&a[1][b][]=?3&a[1][b][]=4" {:a [{:b ["1" "2"]} {:b ["?3" "4"]}]})))
(defn mean [coll]
(let [sum (apply + coll)
count (count coll)]
(if (pos? count)
(/ sum count)
0)))
(defn median [coll]
(let [sorted (sort coll)
cnt (count sorted)
halfway (quot cnt 2)]
(if (odd? cnt)
( 1 )
(let [bottom (dec halfway)
bottom-val (nth sorted bottom)
top-val (nth sorted halfway)]
(mean [bottom-val top-val])))))
(defn standard-deviation [coll]
(let [avg (mean coll)
squares (for [x coll]
(let [x-avg (- x avg)]
(* x-avg x-avg)))
total (count coll)]
(-> (/ (apply + squares)
(- total 1))
(Math/sqrt))))
#_(deftest performance
(let [routes (router/expand-routes [["" {:page "homepage"}]
":page"
["blog" {:page "blog-index" :blog-posts/page 1}]
["blog/p/{:blog-posts/page}" {:page "blog-index"}]
["blog/{:blog-post/slug}" {:page "blog-post"}]
["users/list" {:page "users"}]
["users/{:user/id}" {:user/page "user-details"}]
["users/{:user/id}/{:user/page}"]])
measurements
(map
(fn [_]
(let [t (js/performance.now)]
(doseq [i (range 0 10000)]
(let [user-page (if (even? i) "user-details" "feed")]
(router/map->url routes {:user/id i :user/page user-page})))
(- (js/performance.now) t)))
(range 0 10))]
(println "Mean:" (mean measurements) "High:" (last (sort measurements)) "Low:" (first (sort measurements)))
(println "Median:" (median measurements))
(println "SD:" (standard-deviation measurements)))) | null | https://raw.githubusercontent.com/retro/keechma-next-realworld-app/47a14f4f3f6d56be229cd82f7806d7397e559ebe/classes/test/realworld-2/router/core_test.cljs | clojure | (ns router.core-test
(:require [cljs.test :refer-macros [deftest is use-fixtures testing are]]
[router.core :as router]
[router.util :refer [encode-query-params decode-query-params]]))
#_(use-fixtures :once {:before (fn [] (js/console.clear))})
(deftest route->parts
(is (= [":foo" "/" "bar" "/" ":baz"] (router/route->parts ":foo/bar/:baz")))
(is (= [":foo/bar" "/" "baz" "/" ":bar.qux/foo" "/" ":qux/baz"] (router/route->parts "{:foo/bar}/baz/{:bar.qux/foo}/{qux/baz}")))
(is (thrown? js/Error (router/route->parts "{:foo")))
(is (thrown? js/Error (router/route->parts "{f:oo}"))))
(deftest match-path []
(let [routes (router/expand-routes ["/:foo/bar/:baz"])
matched-path (router/match-path routes "one/bar/two")]
(is (= matched-path {:route ":foo/bar/:baz" :data {:foo "one" :baz "two"}}))))
(deftest url->map []
(let [routes (router/expand-routes [[":page" {:page "index"}]])
matched-1 (router/url->map routes "foo.Bar")
matched-2 (router/url->map routes "")
matched-3 (router/url->map routes "foo.Bar?where=there")]
(is (= matched-1 {:route ":page"
:data {:page "foo.Bar"}}))
(is (= matched-2 {:route ":page"
:data {:page "index"}}))
(is (= matched-3 {:route ":page"
:data {:page "foo.Bar"
:where "there"}})))
(let [routes (router/expand-routes [[":page/:bar" {:page "index" :bar "foo"}]])
matched (router/url->map routes "foo.Bar/?where=there")]
(is (= matched {:route ":page/:bar"
:data {:page "foo.Bar"
:bar "foo"
:where "there"}})))
(let [routes (router/expand-routes ["/:foo/bar/:baz"])
url "/one/bar/two?qux=1&test=success"
matched (router/url->map routes url)
expected-data {:foo "one" :baz "two" :qux "1" :test "success"}]
(is (= matched {:route ":foo/bar/:baz"
:data expected-data})))
(let [routes (router/expand-routes [":page"])]
(is (= (router/url->map routes "Hello%20World")
{:route ":page"
:data {:page "Hello World"}})))
(let [routes (router/expand-routes [":folder/:file.:ext"])]
(is (= {:route ":folder/:file.:ext" :data {:folder "desktop" :file "image", :ext "jpg"}}
(router/url->map routes "desktop/image.jpg")))))
(deftest url->map-invalid []
(let [routes (router/expand-routes [["pages/:var1/:var2/:var3"
{:var1 "default1"
:var2 "default2"
:var3 "default3"}]])
matched-1 (router/url->map routes "pages//")
matched-2 (router/url->map routes "pages/val1/val2/val3?invalid-param")]
(is (= matched-1 {:data {}}))
(is (= matched-2 {:route "pages/:var1/:var2/:var3"
:data {:var1 "val1"
:var2 "val2"
:var3 "val3"}}))))
(deftest url->map-only-query-string []
(let [routes []
url "?foo=bar&baz=qux"
matched-url (router/url->map routes url)]
(is (= matched-url {:data {:foo "bar" :baz "qux"}}))))
(deftest map->url []
(let [routes (router/expand-routes [["pages/:page" {:page "index"}]])
url-1 (router/map->url routes {:page "foo"})
url-2 (router/map->url routes {:page "foo" :index "bar"})]
(is (= url-1 "pages/foo"))
(is (= url-2 "pages/foo?index=bar")))
(let [routes (router/expand-routes [["pages/:page" {:page "index"}]
["pages/:page/:foo" {:page "index" :foo "bar"}]])
url (router/map->url routes {:page "foo" :foo "bar" :where "there"})]
(is (= url "pages/foo/?where=there")))
(let [url (router/map->url nil {:page "foo" :bar "baz" :where "there"})]
(is (= url "?page=foo&bar=baz&where=there"))))
(deftest symmetry []
(let [data {:page "=&[]" :nestedArray ["a"] :nested {:a "b"}}
url (router/map->url [] data)
back-data (router/url->map [] url)]
(is (= data (:data back-data)))))
(deftest light-param []
(let [routes (router/expand-routes [[":page", {:page "index"}]])
res (router/map->url routes {:page "index"})]
(is (= res "")))
(let [routes (router/expand-routes [["pages/:p1/:p2/:p3" {:p1 "index" :p2 "foo" :p3 "bar"}]])
res-1 (router/map->url routes {:p1 "index" :p2 "foo" :p3 "bar"})
res-2 (router/map->url routes {:p1 "index" :p2 "baz" :p3 "bar"})]
(is (= res-1 "pages///"))
(is (= res-2 "pages//baz/"))))
(deftest map->url-does-not-add-defaults []
(let [routes (router/expand-routes [["pages/:p1", {:p2 "foo"}]])]
(is (= (router/map->url routes {:p1 "index" :p2 "foo"}) "pages/index"))))
(deftest map->url-url->map []
(let [routes (router/expand-routes [
[":page/:type", {:page "index", :type "foo"}]])
data {:page "foo.Bar" :type "document" :bar "baz" :where "there"}
url (router/map->url routes data)
url-data (router/url->map routes url)
data-2 {:page "foo.Bar" :type "foo" :bar "baz" :where "there"}
url-2 (router/map->url routes data-2)
url-data-2 (router/url->map routes url-2)
data-3 {:page "index" :type "foo" :bar "baz" :where "there"}
url-3 (router/map->url routes data-3)
url-data-3 (router/url->map routes url-3)]
(is (= data (:data url-data)))
(is (= data-2 (:data url-data-2)))
(is (= data-3 (:data url-data-3))))
(let [data {:page "foo" :bar "baz" :where "there"}
url (router/map->url [] data)
url-data (router/url->map [] url)]
(is (= data (:data url-data))))
(let [routes (router/expand-routes [[":foo/:bar" {:foo 1 :bar 2}]])
url (router/map->url routes {:foo 1 :bar 2})
data (router/url->map routes "/")]
(is (= url ""))
(is (= {:foo 1 :bar 2} (:data data)))))
(deftest precedence []
(let [routes (router/expand-routes [[":who", {:who "index"}]
"search/:search"])
data-1 (router/url->map routes "foo.Bar")
data-2 (router/url->map routes "search/foo.Bar")
url-1 (router/map->url routes {:who "foo.Bar"})
url-2 (router/map->url routes {:search "foo.Bar"})]
(is (= (:data data-1) {:who "foo.Bar"}))
(is (= (:data data-2) {:search "foo.Bar"}))
(is (= url-1 "foo.Bar"))
(is (= url-2 "search/foo.Bar")))
(let [routes (router/expand-routes [[":type" , {:who "index"}]
":type/:id"])
data (router/url->map routes "foo/bar")
url (router/map->url routes {:type "foo" :id "bar"})]
(is (= (:data data) {:type "foo" :id "bar"}))
(is (= url "foo/bar"))))
(deftest namespaced-keys
(let [routes (router/expand-routes [["" {:page "homepage"}]
":page"
["blog" {:page "blog-index" :blog-posts/page 1}]
["blog/p/{:blog-posts/page}" {:page "blog-index"}]
["blog/{:blog-post/slug}" {:page "blog-post"}]
["users/list" {:page "users"}]
["users/{:user/id}" {:page "user-details"}]
["users/{:user/id}/{:user/page}"]])]
(is (= "" (router/map->url routes {:page "homepage"})))
(is (= "foo" (router/map->url routes {:page "foo"})))
(is (= "users/list" (router/map->url routes {:page "users"})))
(is (= "users/1" (router/map->url routes {:user/id 1})))
(is (= "users/1/details" (router/map->url routes {:user/id 1 :user/page "details"})))
(is (= "?foo/bar=1&foo.bar/baz=2&foo.bar.baz/qux[qux/foo]=bar&foo.bar.baz.qux/foo[bar.baz/qux]=foo"
(router/map->url routes {:foo/bar 1
:foo.bar/baz 2
:foo.bar.baz/qux {:qux/foo "bar"}
:foo.bar.baz.qux/foo {:bar.baz/qux "foo"}})))
(is (= {:page "homepage"} (:data (router/url->map routes ""))))
(is (= {:page "homepage"} (:data (router/url->map routes "homepage"))))
(is (= {:page "foo"} (:data (router/url->map routes "foo"))))
(is (= {:page "users"} (:data (router/url->map routes "users/list"))))
(is (= {:page "user-details" :user/id "1"} (:data (router/url->map routes "users/1"))))
(is (= {:user/id "1" :user/page "details"} (:data (router/url->map routes "users/1/details"))))
(is (= {:foo/bar "1"
:foo.bar/baz "2"
:foo.bar.baz/qux {:qux/foo "bar"}
:foo.bar.baz.qux/foo {:bar.baz/qux "foo"}
:page "homepage"}
(:data (router/url->map routes "?foo/bar=1&foo.bar/baz=2&foo.bar.baz/qux[qux/foo]=bar&foo.bar.baz.qux/foo[bar.baz/qux]=foo"))))))
(deftest splat-routes
(let [routes (router/expand-routes [["" {:page "homepage"}]
":page"
"fs/{:folders/*}/:file.:ext"
[":*" {:page "not-found"}]])]
(is (= {:page "homepage"} (:data (router/url->map routes ""))))
(is (= {:page "foo"} (:data (router/url->map routes "foo"))))
(is (= {:page "not-found" :* "foo/bar/baz"} (:data (router/url->map routes "foo/bar/baz"))))
(is (= {:folders/* "foo/bar/baz" :file "img" :ext "jpg"} (:data (router/url->map routes "fs/foo/bar/baz/img.jpg"))))
(is (= "fs/foo/bar/baz/img.jpg" (router/map->url routes {:folders/* "foo/bar/baz" :file "img" :ext "jpg"})))
(is (= "foo/bar" (router/map->url routes {:* "foo/bar"})))))
(deftest duplicate-placeholders
(is (thrown? js/Error (router/expand-routes [":foo/bar/:foo"]))))
(deftest trailing-slash
(let [routes (router/expand-routes [":page"])]
(is (= {:page "homepage"} (:data (router/url->map routes "homepage/"))))))
(deftest query-params-test
(testing "encodes query params"
(let [params {:id "kevin" :food "bacon"}
encoded (encode-query-params params)]
(is (= (decode-query-params encoded)
params)))
(are [x y] (= (encode-query-params x) y)
{:x [1 2]} "x[]=1&x[]=2"
{:a [{:b 1} {:b 2}]} "a[0][b]=1&a[1][b]=2"
{:a [{:b [1 2]} {:b [3 4]}]} "a[0][b][]=1&a[0][b][]=2&a[1][b][]=3&a[1][b][]=4"))
(testing "decodes query params"
(let [query-string "id=kevin&food=bacong"
decoded (decode-query-params query-string)
encoded (encode-query-params decoded)]
(is (re-find #"id=kevin" query-string))
(is (re-find #"food=bacon" query-string)))
(are [x y] (= (decode-query-params x) y)
"x[]=1&x[]=2" {:x ["1" "2"]}
"a[0][b]=1&a[1][b]=2" {:a [{:b "1"} {:b "2"}]}
"a[0][b][]=1&a[0][b][]=2&a[1][b][]=?3&a[1][b][]=4" {:a [{:b ["1" "2"]} {:b ["?3" "4"]}]})))
(defn mean [coll]
(let [sum (apply + coll)
count (count coll)]
(if (pos? count)
(/ sum count)
0)))
(defn median [coll]
(let [sorted (sort coll)
cnt (count sorted)
halfway (quot cnt 2)]
(if (odd? cnt)
( 1 )
(let [bottom (dec halfway)
bottom-val (nth sorted bottom)
top-val (nth sorted halfway)]
(mean [bottom-val top-val])))))
(defn standard-deviation [coll]
(let [avg (mean coll)
squares (for [x coll]
(let [x-avg (- x avg)]
(* x-avg x-avg)))
total (count coll)]
(-> (/ (apply + squares)
(- total 1))
(Math/sqrt))))
#_(deftest performance
(let [routes (router/expand-routes [["" {:page "homepage"}]
":page"
["blog" {:page "blog-index" :blog-posts/page 1}]
["blog/p/{:blog-posts/page}" {:page "blog-index"}]
["blog/{:blog-post/slug}" {:page "blog-post"}]
["users/list" {:page "users"}]
["users/{:user/id}" {:user/page "user-details"}]
["users/{:user/id}/{:user/page}"]])
measurements
(map
(fn [_]
(let [t (js/performance.now)]
(doseq [i (range 0 10000)]
(let [user-page (if (even? i) "user-details" "feed")]
(router/map->url routes {:user/id i :user/page user-page})))
(- (js/performance.now) t)))
(range 0 10))]
(println "Mean:" (mean measurements) "High:" (last (sort measurements)) "Low:" (first (sort measurements)))
(println "Median:" (median measurements))
(println "SD:" (standard-deviation measurements)))) |
|
399def629747ba150e4d541953de5eb30e91116821fc206c1031290018647d00 | jlongster/gambit-iphone-example | osx#.scm | " osx ffi types "
Defines c types for the osx ffi .
;;;; Cocoa
(c-define-type id (pointer (struct "objc_object") #f))
(c-define-type NSTimeInterval double)
(c-define-type NSArray "NSArray")
(c-define-type NSArray* (pointer NSArray))
(c-define-type NSSet "NSSet")
(c-define-type NSSet* (pointer NSSet))
(c-define-type NSString "NSString")
(c-define-type NSString* (pointer "NSString"))
(c-define-type NSBundle "NSBundle")
(c-define-type NSBundle* (pointer NSBundle))
(c-define-type NSImage "NSImage")
(c-define-type NSImage* (pointer NSImage))
Quartz
(c-define-type CGFloat float)
(c-define-type CGPoint "CGPoint")
(c-define-type CGPoint* (pointer CGPoint))
(c-define-type CGSize "CGSize")
(c-define-type CGSize* (pointer CGSize))
(c-define-type CGRect "CGRect")
(c-define-type CGRect* (pointer CGRect))
(c-define-type CGImageRef "CGImageRef")
| null | https://raw.githubusercontent.com/jlongster/gambit-iphone-example/e55d915180cb6c57312cbb683d81823ea455e14f/lib/ffi/osx%23.scm | scheme | Cocoa | " osx ffi types "
Defines c types for the osx ffi .
(c-define-type id (pointer (struct "objc_object") #f))
(c-define-type NSTimeInterval double)
(c-define-type NSArray "NSArray")
(c-define-type NSArray* (pointer NSArray))
(c-define-type NSSet "NSSet")
(c-define-type NSSet* (pointer NSSet))
(c-define-type NSString "NSString")
(c-define-type NSString* (pointer "NSString"))
(c-define-type NSBundle "NSBundle")
(c-define-type NSBundle* (pointer NSBundle))
(c-define-type NSImage "NSImage")
(c-define-type NSImage* (pointer NSImage))
Quartz
(c-define-type CGFloat float)
(c-define-type CGPoint "CGPoint")
(c-define-type CGPoint* (pointer CGPoint))
(c-define-type CGSize "CGSize")
(c-define-type CGSize* (pointer CGSize))
(c-define-type CGRect "CGRect")
(c-define-type CGRect* (pointer CGRect))
(c-define-type CGImageRef "CGImageRef")
|
c71a96047b62dde692d8dcaa515c9eb75548475d51ca290893834fda782b1e8f | reflectionalist/S9fES | programp.scm | Scheme 9 from Empty Space , Function Library
By , 2009
; Placed in the Public Domain
;
; (program? object) ==> boolean
;
; (load-from-library "programp.scm")
;
; Return #T, if OBJECT is a syntactically correct Scheme program.
This program does not implement all of R4RS . Caveat utilitor .
;
Example : ( program ? ' ( let ( ( x 1 ) ) ( cons x x ) ) ) = = > # t
(load-from-library "for-all.scm")
(define (program? x)
(define INF #f)
(define (list-of-programs? x)
(for-all program? x))
(define (of-length? min max x)
(let ((k (length x)))
(or (and (not max)
(<= min k))
(<= min k max))))
(define (argument-list? x)
(or (symbol? x)
(null? x)
(and (pair? x)
(symbol? (car x))
(argument-list? (cdr x)))))
(define (valid-and? x)
(list-of-programs? (cdr x)))
(define (valid-begin? x)
(list-of-programs? (cdr x)))
(define (valid-case? x)
(and (of-length? 2 INF x)
(program? (cadr x))
(for-all (lambda (x)
(and (list? x)
(or (list? (car x))
(eq? 'else (car x)))
(for-all program? (cdr x))))
(cddr x))))
(define (valid-cond? x)
(and (of-length? 2 INF x)
(for-all (lambda (x)
(and (list? x)
(for-all program? x)))
(cdr x))))
(define (valid-define? x)
(or (and (of-length? 3 INF x)
(pair? (cadr x))
(argument-list? (cadr x))
(for-all program? (cddr x)))
(and (of-length? 3 3 x)
(symbol? (cadr x))
(program? (caddr x)))))
(define (lambda-expression? x)
(and (list? x)
(not (null? x))
(eq? 'lambda (car x))
(valid-lambda? x)))
Not in R4RS
(define (valid-alt-define-syntax? x)
(and (of-length? 3 3 x)
(or (and (pair? (cadr x))
(argument-list? (cadr x))
(program? (caddr x)))
(and (symbol? (cadr x))
(program? (caddr x))))))
(define (valid-define-syntax? x)
(or (valid-alt-define-syntax? x)
(and (of-length? 3 3 x)
(symbol? (cadr x))
(list? (caddr x))
(let ((x (caddr x)))
(and (not (null? x))
(eq? 'syntax-rules (car x))
(list? (cadr x))
(for-all symbol? (cadr x))
(let ((clauses (cddr x)))
(for-all (lambda (x)
(and (list? x)
(of-length? 2 2 x)
(pair? (car x))
(symbol? (caar x))
(pair? (cdr x))))
clauses)))))))
(define (valid-delay? x)
(and (of-length? 1 1 (cdr x))
(program? (cadr x))))
(define (valid-do? x)
(and (of-length? 2 INF (cdr x))
(list? (cadr x))
(for-all (lambda (x)
(and (list? x)
(of-length? 2 3 x)
(symbol? (car x))
(for-all program? (cdr x))))
(cadr x))
(list? (caddr x))
(of-length? 1 INF (caddr x))
(for-all program? (caddr x))
(for-all program? (cdddr x))))
(define (valid-if? x)
(and (of-length? 2 3 (cdr x))
(list-of-programs? (cdr x))))
(define (valid-lambda? x)
(and (of-length? 2 INF (cdr x))
(argument-list? (cadr x))
(for-all program? (cddr x))))
(define (valid-let/*/rec? x named)
(and (of-length? 2 INF (cdr x))
(let* ((name (and named
(of-length? 3 INF (cdr x))
(symbol? (cadr x))))
(bind (if name
(caddr x)
(cadr x)))
(body (if name
(cdddr x)
(cddr x))))
(and (for-all (lambda (x)
(and (list? x)
(of-length? 2 2 x)
(symbol? (car x))
(program? (cadr x))))
bind)
(for-all program? body)))))
(define (valid-or? x)
(list-of-programs? (cdr x)))
(define (valid-quote? x)
(of-length? 1 1 (cdr x)))
(define (valid-set!? x)
(and (of-length? 2 2 (cdr x))
(symbol? (cadr x))
(program? (caddr x))))
(define (expression? x)
(and (list? x)
(not (null? x))
(case (car x)
((and) (valid-and? x))
((begin) (valid-begin? x))
((case) (valid-case? x))
((cond) (valid-cond? x))
((define) (valid-define? x))
((define-syntax) (valid-define-syntax? x))
((delay) (valid-delay? x))
((do) (valid-do? x))
((if) (valid-if? x))
((lambda) (valid-lambda? x))
((let) (valid-let/*/rec? x #t))
((let* letrec) (valid-let/*/rec? x #f))
((quote) (valid-quote? x))
((quasiquote) (valid-quote? x))
((or) (valid-or? x))
((set!) (valid-set!? x))
(else (and (or (expression? (car x))
(symbol? (car x)))
(for-all program? (cdr x)))))))
(or (symbol? x)
(boolean? x)
(number? x)
(char? x)
(string? x)
(procedure? x) ; not formally correct, but useful
(expression? x)))
| null | https://raw.githubusercontent.com/reflectionalist/S9fES/0ade11593cf35f112e197026886fc819042058dd/lib/programp.scm | scheme | Placed in the Public Domain
(program? object) ==> boolean
(load-from-library "programp.scm")
Return #T, if OBJECT is a syntactically correct Scheme program.
not formally correct, but useful | Scheme 9 from Empty Space , Function Library
By , 2009
This program does not implement all of R4RS . Caveat utilitor .
Example : ( program ? ' ( let ( ( x 1 ) ) ( cons x x ) ) ) = = > # t
(load-from-library "for-all.scm")
(define (program? x)
(define INF #f)
(define (list-of-programs? x)
(for-all program? x))
(define (of-length? min max x)
(let ((k (length x)))
(or (and (not max)
(<= min k))
(<= min k max))))
(define (argument-list? x)
(or (symbol? x)
(null? x)
(and (pair? x)
(symbol? (car x))
(argument-list? (cdr x)))))
(define (valid-and? x)
(list-of-programs? (cdr x)))
(define (valid-begin? x)
(list-of-programs? (cdr x)))
(define (valid-case? x)
(and (of-length? 2 INF x)
(program? (cadr x))
(for-all (lambda (x)
(and (list? x)
(or (list? (car x))
(eq? 'else (car x)))
(for-all program? (cdr x))))
(cddr x))))
(define (valid-cond? x)
(and (of-length? 2 INF x)
(for-all (lambda (x)
(and (list? x)
(for-all program? x)))
(cdr x))))
(define (valid-define? x)
(or (and (of-length? 3 INF x)
(pair? (cadr x))
(argument-list? (cadr x))
(for-all program? (cddr x)))
(and (of-length? 3 3 x)
(symbol? (cadr x))
(program? (caddr x)))))
(define (lambda-expression? x)
(and (list? x)
(not (null? x))
(eq? 'lambda (car x))
(valid-lambda? x)))
Not in R4RS
(define (valid-alt-define-syntax? x)
(and (of-length? 3 3 x)
(or (and (pair? (cadr x))
(argument-list? (cadr x))
(program? (caddr x)))
(and (symbol? (cadr x))
(program? (caddr x))))))
(define (valid-define-syntax? x)
(or (valid-alt-define-syntax? x)
(and (of-length? 3 3 x)
(symbol? (cadr x))
(list? (caddr x))
(let ((x (caddr x)))
(and (not (null? x))
(eq? 'syntax-rules (car x))
(list? (cadr x))
(for-all symbol? (cadr x))
(let ((clauses (cddr x)))
(for-all (lambda (x)
(and (list? x)
(of-length? 2 2 x)
(pair? (car x))
(symbol? (caar x))
(pair? (cdr x))))
clauses)))))))
(define (valid-delay? x)
(and (of-length? 1 1 (cdr x))
(program? (cadr x))))
(define (valid-do? x)
(and (of-length? 2 INF (cdr x))
(list? (cadr x))
(for-all (lambda (x)
(and (list? x)
(of-length? 2 3 x)
(symbol? (car x))
(for-all program? (cdr x))))
(cadr x))
(list? (caddr x))
(of-length? 1 INF (caddr x))
(for-all program? (caddr x))
(for-all program? (cdddr x))))
(define (valid-if? x)
(and (of-length? 2 3 (cdr x))
(list-of-programs? (cdr x))))
(define (valid-lambda? x)
(and (of-length? 2 INF (cdr x))
(argument-list? (cadr x))
(for-all program? (cddr x))))
(define (valid-let/*/rec? x named)
(and (of-length? 2 INF (cdr x))
(let* ((name (and named
(of-length? 3 INF (cdr x))
(symbol? (cadr x))))
(bind (if name
(caddr x)
(cadr x)))
(body (if name
(cdddr x)
(cddr x))))
(and (for-all (lambda (x)
(and (list? x)
(of-length? 2 2 x)
(symbol? (car x))
(program? (cadr x))))
bind)
(for-all program? body)))))
(define (valid-or? x)
(list-of-programs? (cdr x)))
(define (valid-quote? x)
(of-length? 1 1 (cdr x)))
(define (valid-set!? x)
(and (of-length? 2 2 (cdr x))
(symbol? (cadr x))
(program? (caddr x))))
(define (expression? x)
(and (list? x)
(not (null? x))
(case (car x)
((and) (valid-and? x))
((begin) (valid-begin? x))
((case) (valid-case? x))
((cond) (valid-cond? x))
((define) (valid-define? x))
((define-syntax) (valid-define-syntax? x))
((delay) (valid-delay? x))
((do) (valid-do? x))
((if) (valid-if? x))
((lambda) (valid-lambda? x))
((let) (valid-let/*/rec? x #t))
((let* letrec) (valid-let/*/rec? x #f))
((quote) (valid-quote? x))
((quasiquote) (valid-quote? x))
((or) (valid-or? x))
((set!) (valid-set!? x))
(else (and (or (expression? (car x))
(symbol? (car x)))
(for-all program? (cdr x)))))))
(or (symbol? x)
(boolean? x)
(number? x)
(char? x)
(string? x)
(expression? x)))
|
41ef354bad22def00ed6c022901b38bf4effc120d203ec6b9abd359ab892d155 | copton/ocram | DebugInfo.hs | # LANGUAGE TemplateHaskell , ViewPatterns #
module Ocram.Debug.DebugInfo
exports { { { 1
(
t2p_map, p2e_map, var_map, all_threads, non_critical_functions
) where
imports { { { 1
import Control.Applicative ((<$>), (<*>))
import Data.List (nub)
import Data.Maybe (mapMaybe)
import Language.C.Syntax.AST (CExternalDeclaration(CFDefExt))
import Ocram.Ruab (MapTP(..), MapPE, VarMap, TRow(..), PLocation(..), t2p_row, Scope(..), Thread(..))
import Ocram.Analysis (Analysis(anaNonCritical), CallGraph, start_functions, call_order)
import Ocram.Debug.Types (Breakpoints, Breakpoint(..), VarMap')
import Ocram.Symbols (symbol)
import Ocram.Util (abort, fromJust_s)
import Ocram.Names (tfunction)
import Text.Regex.Posix ((=~))
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map as M
{ { { 1
t2p_map tcode pcode
| BS.null pcode = MapTP 0 0 []
| BS.last pcode /= '\n' = $abort "pre-processed file should be terminated by a newline"
| otherwise = MapTP (trows) (prows - 1) (reverse ppm)
where
trows = TRow $ length $ BS.split '\n' tcode
(first:rest) = init $ BS.split '\n' pcode
(ppm, prows) = foldl go ([], 2) rest
mainFile = case match first of
(_, (BS.null -> True), _, _) -> $abort $ "unexpected first row in pre-processed file"
(_, _, _, (_:file:_)) -> file
x -> $abort $ "unexpected parameter: " ++ show x
match :: BS.ByteString -> (BS.ByteString, BS.ByteString, BS.ByteString, [BS.ByteString])
match txt = txt =~ "^# ([0-9]*) \"([^\"]+)\".*$" -- prefix, match, postfix, groups
go (ppm', row) line = case match line of
(_, (BS.null -> True), _, _ ) -> (ppm', row + 1)
(_, _, _, (row':file:_)) -> if file == mainFile
then (((TRow . read . BS.unpack) row', row) : ppm', row + 1)
else (ppm', row + 1)
x -> $abort $ "unexpected parameter:" ++ show x
{ { { 1
p2e_map mtp tfile = M.toList . foldr insert M.empty . nub . filter ((==(Just tfile)) . bpFile)
where
insert bp = M.alter (alter (bpERow bp)) (ploc bp)
alter erow Nothing = Just [erow]
alter erow (Just erows) = Just $ erow : erows
ploc = PLocation <$> bpThread <*> $fromJust_s . t2p_row mtp . bpTRow <*> bpBlocking
{ { { 1
var_map mtp = M.toList . foldr insert M.empty
where
t2p = $fromJust_s . t2p_row mtp
insert (var, (start, end), fqn) = M.alter (alter var fqn) (Scope (t2p start) (t2p end))
alter var fqn Nothing = Just [(var, fqn)]
alter var fqn (Just rm) = Just $ (var, fqn) : rm
{ { { 1
all_threads cg = zipWith create [0..] (start_functions cg)
where
co = $fromJust_s . call_order cg
create tid sf = Thread tid sf (tfunction tid) (co sf)
non_critical_functions :: Analysis -> [String]
non_critical_functions = mapMaybe funDef . anaNonCritical
where
funDef (CFDefExt fd) = Just (symbol fd)
funDef _ = Nothing
| null | https://raw.githubusercontent.com/copton/ocram/c7166eab0187868a52a61017c6d3687e5a1a6162/ocram/src/Ocram/Debug/DebugInfo.hs | haskell | prefix, match, postfix, groups | # LANGUAGE TemplateHaskell , ViewPatterns #
module Ocram.Debug.DebugInfo
exports { { { 1
(
t2p_map, p2e_map, var_map, all_threads, non_critical_functions
) where
imports { { { 1
import Control.Applicative ((<$>), (<*>))
import Data.List (nub)
import Data.Maybe (mapMaybe)
import Language.C.Syntax.AST (CExternalDeclaration(CFDefExt))
import Ocram.Ruab (MapTP(..), MapPE, VarMap, TRow(..), PLocation(..), t2p_row, Scope(..), Thread(..))
import Ocram.Analysis (Analysis(anaNonCritical), CallGraph, start_functions, call_order)
import Ocram.Debug.Types (Breakpoints, Breakpoint(..), VarMap')
import Ocram.Symbols (symbol)
import Ocram.Util (abort, fromJust_s)
import Ocram.Names (tfunction)
import Text.Regex.Posix ((=~))
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map as M
{ { { 1
t2p_map tcode pcode
| BS.null pcode = MapTP 0 0 []
| BS.last pcode /= '\n' = $abort "pre-processed file should be terminated by a newline"
| otherwise = MapTP (trows) (prows - 1) (reverse ppm)
where
trows = TRow $ length $ BS.split '\n' tcode
(first:rest) = init $ BS.split '\n' pcode
(ppm, prows) = foldl go ([], 2) rest
mainFile = case match first of
(_, (BS.null -> True), _, _) -> $abort $ "unexpected first row in pre-processed file"
(_, _, _, (_:file:_)) -> file
x -> $abort $ "unexpected parameter: " ++ show x
match :: BS.ByteString -> (BS.ByteString, BS.ByteString, BS.ByteString, [BS.ByteString])
go (ppm', row) line = case match line of
(_, (BS.null -> True), _, _ ) -> (ppm', row + 1)
(_, _, _, (row':file:_)) -> if file == mainFile
then (((TRow . read . BS.unpack) row', row) : ppm', row + 1)
else (ppm', row + 1)
x -> $abort $ "unexpected parameter:" ++ show x
{ { { 1
p2e_map mtp tfile = M.toList . foldr insert M.empty . nub . filter ((==(Just tfile)) . bpFile)
where
insert bp = M.alter (alter (bpERow bp)) (ploc bp)
alter erow Nothing = Just [erow]
alter erow (Just erows) = Just $ erow : erows
ploc = PLocation <$> bpThread <*> $fromJust_s . t2p_row mtp . bpTRow <*> bpBlocking
{ { { 1
var_map mtp = M.toList . foldr insert M.empty
where
t2p = $fromJust_s . t2p_row mtp
insert (var, (start, end), fqn) = M.alter (alter var fqn) (Scope (t2p start) (t2p end))
alter var fqn Nothing = Just [(var, fqn)]
alter var fqn (Just rm) = Just $ (var, fqn) : rm
{ { { 1
all_threads cg = zipWith create [0..] (start_functions cg)
where
co = $fromJust_s . call_order cg
create tid sf = Thread tid sf (tfunction tid) (co sf)
non_critical_functions :: Analysis -> [String]
non_critical_functions = mapMaybe funDef . anaNonCritical
where
funDef (CFDefExt fd) = Just (symbol fd)
funDef _ = Nothing
|
9ffac0258800020fb6f88a55e065688023d6bd4588b77ffe2ec12c48f5ac34c5 | katox/4clojure-solutions | project.clj | (defproject foreclojure-solutions "0.1.0-SNAPSHOT"
:description "My take on problems on "
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]])
| null | https://raw.githubusercontent.com/katox/4clojure-solutions/e7d9edc8af41934f2087c7a25b28799acac70374/project.clj | clojure | (defproject foreclojure-solutions "0.1.0-SNAPSHOT"
:description "My take on problems on "
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]])
|
|
83a2869143ba4de9fe1a0f7f666239a141dbabc5cffbc9ff75c12a42cb74f677 | graninas/Functional-Design-and-Architecture | ScenarioDSL4Advanced.hs | module ScenarioDSL4Advanced where
import Data.Time
type Name = String
type Duration = DiffTime
-- service function:
seconds s = secondsToDiffTime s
data Value = FloatValue Float
| IntValue Int
| StringValue String
deriving (Show, Read, Eq)
data Controller = Controller Name
deriving (Show, Read, Eq)
type Power = Float
data Status = Online | Offline
deriving (Show, Read, Eq)
data Parameter = Temperature | Pressure
deriving (Show, Read, Eq)
data Procedure
= Script [Procedure]
| Read Parameter Controller (Value -> Procedure)
| Report Value
| Store Value
| AskStatus Controller (Status -> Procedure)
| InitBoosters (Controller -> Procedure)
| HeatUpBoosters Power Duration
heatUpBoosters :: Controller -> Procedure
heatUpBoosters controller =
Read Temperature controller (\t1 ->
Script
[ Report t1
, Store t1
, HeatUpBoosters 1.0 (seconds 10)
, Read Temperature controller (\t2 ->
Script [ Report t2
, Store t2 ])
])
tryHeatUp :: Controller -> Procedure
tryHeatUp controller =
AskStatus controller (\status ->
if (status == Online)
then heatUpBoosters controller
else Script []
)
boostersHeatingUp :: Procedure
boostersHeatingUp = Script
[ InitBoosters tryHeatUp
, Report (StringValue "Script finished.") ]
someController = Controller "a00"
interpretMany :: [Procedure] -> IO ()
interpretMany [] = return ()
interpretMany (p:ps) = do
interpret p
interpretMany ps
interpret :: Procedure -> IO ()
--interpret (Script ps) = interpretMany ps
interpret (Script []) = return ()
interpret (Script (p:ps)) = do
interpret p
interpret (Script ps)
interpret (Read Temperature _ f) = do
print "Read temperature"
interpret (f $ FloatValue 0.0)
interpret (Read p _ f) = error $ "Not implemented: " ++ show p
interpret (Report v) = print $ "Report: " ++ show v
interpret (Store v) = print $ "Store: " ++ show v
interpret (AskStatus _ f) = do
print "Ask status"
interpret (f Online)
interpret (InitBoosters f) = do
print "Init boosters"
interpret (f (Controller "a00"))
interpret (HeatUpBoosters _ _) = print "Heat up boosters"
main = interpret boostersHeatingUp
| null | https://raw.githubusercontent.com/graninas/Functional-Design-and-Architecture/1736abc16d3e4917fc466010dcc182746af2fd0e/First-Edition/BookSamples/CH02/ScenarioDSL4Advanced.hs | haskell | service function:
interpret (Script ps) = interpretMany ps | module ScenarioDSL4Advanced where
import Data.Time
type Name = String
type Duration = DiffTime
seconds s = secondsToDiffTime s
data Value = FloatValue Float
| IntValue Int
| StringValue String
deriving (Show, Read, Eq)
data Controller = Controller Name
deriving (Show, Read, Eq)
type Power = Float
data Status = Online | Offline
deriving (Show, Read, Eq)
data Parameter = Temperature | Pressure
deriving (Show, Read, Eq)
data Procedure
= Script [Procedure]
| Read Parameter Controller (Value -> Procedure)
| Report Value
| Store Value
| AskStatus Controller (Status -> Procedure)
| InitBoosters (Controller -> Procedure)
| HeatUpBoosters Power Duration
heatUpBoosters :: Controller -> Procedure
heatUpBoosters controller =
Read Temperature controller (\t1 ->
Script
[ Report t1
, Store t1
, HeatUpBoosters 1.0 (seconds 10)
, Read Temperature controller (\t2 ->
Script [ Report t2
, Store t2 ])
])
tryHeatUp :: Controller -> Procedure
tryHeatUp controller =
AskStatus controller (\status ->
if (status == Online)
then heatUpBoosters controller
else Script []
)
boostersHeatingUp :: Procedure
boostersHeatingUp = Script
[ InitBoosters tryHeatUp
, Report (StringValue "Script finished.") ]
someController = Controller "a00"
interpretMany :: [Procedure] -> IO ()
interpretMany [] = return ()
interpretMany (p:ps) = do
interpret p
interpretMany ps
interpret :: Procedure -> IO ()
interpret (Script []) = return ()
interpret (Script (p:ps)) = do
interpret p
interpret (Script ps)
interpret (Read Temperature _ f) = do
print "Read temperature"
interpret (f $ FloatValue 0.0)
interpret (Read p _ f) = error $ "Not implemented: " ++ show p
interpret (Report v) = print $ "Report: " ++ show v
interpret (Store v) = print $ "Store: " ++ show v
interpret (AskStatus _ f) = do
print "Ask status"
interpret (f Online)
interpret (InitBoosters f) = do
print "Init boosters"
interpret (f (Controller "a00"))
interpret (HeatUpBoosters _ _) = print "Heat up boosters"
main = interpret boostersHeatingUp
|
0f931a75d8d0ecd67c4d978ec643b796f90709f0f26e202cd6b75b410449022c | fpco/stackage-server | ModuleForest.hs | -- Adopted from -server/blob/master/Distribution/Server/Packages/ModuleForest.hs
# LANGUAGE NoImplicitPrelude #
# LANGUAGE ViewPatterns #
module Distribution.Package.ModuleForest
( moduleName
, moduleForest
, ModuleTree(..)
, ModuleForest
, NameComponent
) where
import Distribution.ModuleName (ModuleName)
import qualified Distribution.ModuleName as ModuleName
import RIO
import RIO.Text (pack, unpack)
type NameComponent = Text
type ModuleForest = [ModuleTree]
data ModuleTree = Node { component :: NameComponent
, isModule :: Bool
, subModules :: ModuleForest
}
deriving (Show, Eq)
moduleName :: Text -> ModuleName
moduleName = ModuleName.fromString . unpack
moduleForest :: [ModuleName] -> ModuleForest
moduleForest = foldr (addToForest . map pack . ModuleName.components) []
addToForest :: [NameComponent] -> ModuleForest -> ModuleForest
addToForest [] trees = trees
addToForest comps [] = mkSubTree comps
addToForest comps@(comp1:cs) (t@(component -> comp2):ts) = case
compare comp1 comp2 of
GT -> t : addToForest comps ts
EQ -> Node comp2 (isModule t || null cs) (addToForest cs (subModules t)) : ts
LT -> mkSubTree comps ++ t : ts
mkSubTree :: [Text] -> ModuleForest
mkSubTree [] = []
mkSubTree (c:cs) = [Node c (null cs) (mkSubTree cs)]
| null | https://raw.githubusercontent.com/fpco/stackage-server/b707b5a0d72c44a3134a305b628c3f0b28db2697/src/Distribution/Package/ModuleForest.hs | haskell | Adopted from -server/blob/master/Distribution/Server/Packages/ModuleForest.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE ViewPatterns #
module Distribution.Package.ModuleForest
( moduleName
, moduleForest
, ModuleTree(..)
, ModuleForest
, NameComponent
) where
import Distribution.ModuleName (ModuleName)
import qualified Distribution.ModuleName as ModuleName
import RIO
import RIO.Text (pack, unpack)
type NameComponent = Text
type ModuleForest = [ModuleTree]
data ModuleTree = Node { component :: NameComponent
, isModule :: Bool
, subModules :: ModuleForest
}
deriving (Show, Eq)
moduleName :: Text -> ModuleName
moduleName = ModuleName.fromString . unpack
moduleForest :: [ModuleName] -> ModuleForest
moduleForest = foldr (addToForest . map pack . ModuleName.components) []
addToForest :: [NameComponent] -> ModuleForest -> ModuleForest
addToForest [] trees = trees
addToForest comps [] = mkSubTree comps
addToForest comps@(comp1:cs) (t@(component -> comp2):ts) = case
compare comp1 comp2 of
GT -> t : addToForest comps ts
EQ -> Node comp2 (isModule t || null cs) (addToForest cs (subModules t)) : ts
LT -> mkSubTree comps ++ t : ts
mkSubTree :: [Text] -> ModuleForest
mkSubTree [] = []
mkSubTree (c:cs) = [Node c (null cs) (mkSubTree cs)]
|
809dcf28169a56eea11d78c3b5e8e51bb4e79614b1c419406522e4014d8ded88 | cxphoe/SICP-solutions | environment.rkt | (load "expression.rkt")
; environment operations
(define (enclosing-environment env) (cdr env))
(define (first-frame env) (car env))
(define the-empty-environment '())
(define (make-frame variables values)
(cons variables values))
(define (frame-variables frame) (car frame))
(define (frame-values frame) (cdr frame))
(define (add-binding-to-frame! var val frame)
(set-car! frame (cons var (car frame)))
(set-cdr! frame (cons val (cdr frame))))
(define (extend-environment vars vals base-env)
(if (= (length vars) (length vals))
(cons (make-frame vars vals) base-env)
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
answer for question 4.12
(define (env-loop env var var-not-in-frame proc)
(define (scan vars vals)
(cond ((null? vars) (var-not-in-frame env))
((eq? var (car vars)) (proc vals))
(else
(scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(define (lookup-variable-value var env)
(define (var-not-in-frame env)
(lookup-variable-value var (enclosing-environment env)))
(env-loop env var var-not-in-frame car))
(define (set-val! val)
(lambda (vals) (set-car! vals val)))
(define (set-variable-value! var val env)
(define (var-not-in-frame env)
(set-variable-value! var val (enclosing-environment env)))
(env-loop env var var-not-in-frame (set-val! val)))
(define (define-variable! var val env)
(define (var-not-in-frame env)
(add-binding-to-frame! var val (first-frame env)))
(env-loop env var var-not-in-frame (set-val! val))) | null | https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%204-Metalinguistic%20Abstraction/1.The%20Meta-cycle%20Evaluator/environment.rkt | racket | environment operations | (load "expression.rkt")
(define (enclosing-environment env) (cdr env))
(define (first-frame env) (car env))
(define the-empty-environment '())
(define (make-frame variables values)
(cons variables values))
(define (frame-variables frame) (car frame))
(define (frame-values frame) (cdr frame))
(define (add-binding-to-frame! var val frame)
(set-car! frame (cons var (car frame)))
(set-cdr! frame (cons val (cdr frame))))
(define (extend-environment vars vals base-env)
(if (= (length vars) (length vals))
(cons (make-frame vars vals) base-env)
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
answer for question 4.12
(define (env-loop env var var-not-in-frame proc)
(define (scan vars vals)
(cond ((null? vars) (var-not-in-frame env))
((eq? var (car vars)) (proc vals))
(else
(scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(define (lookup-variable-value var env)
(define (var-not-in-frame env)
(lookup-variable-value var (enclosing-environment env)))
(env-loop env var var-not-in-frame car))
(define (set-val! val)
(lambda (vals) (set-car! vals val)))
(define (set-variable-value! var val env)
(define (var-not-in-frame env)
(set-variable-value! var val (enclosing-environment env)))
(env-loop env var var-not-in-frame (set-val! val)))
(define (define-variable! var val env)
(define (var-not-in-frame env)
(add-binding-to-frame! var val (first-frame env)))
(env-loop env var var-not-in-frame (set-val! val))) |
bddb79260b59ce37f822cfd4986a8972e572b9d37c7486be1848b41ba6caf6cf | nomnom-insights/nomnom.lockjaw | project.clj | (defproject nomnom/lockjaw "0.3.1"
:description "Postgres Advisory Locks as a Component"
:url "-insights/nomnom.lockjaw"
:license {:name "MIT License"
:url ""
:year 2018
:key "mit"}
:deploy-repositories {"clojars" {:sign-releases false
:username :env/clojars_username
:password :env/clojars_password}}
:dependencies [[org.clojure/clojure "1.10.3"]
[com.github.seancorfield/next.jdbc "1.2.761"]
[com.stuartsierra/component "1.0.0"]]
:profiles {:dev
{:resource-paths ["dev-resources"]
:dependencies [[ch.qos.logback/logback-classic "1.2.10"]
;; pulls in all the PG bits and a connection pool
;; component
[nomnom/utility-belt.sql "1.1.0"]
[org.clojure/tools.logging "1.2.4"]]}})
| null | https://raw.githubusercontent.com/nomnom-insights/nomnom.lockjaw/8d568d1ec36054ca25e798613ccd3e1d229c94cf/project.clj | clojure | pulls in all the PG bits and a connection pool
component | (defproject nomnom/lockjaw "0.3.1"
:description "Postgres Advisory Locks as a Component"
:url "-insights/nomnom.lockjaw"
:license {:name "MIT License"
:url ""
:year 2018
:key "mit"}
:deploy-repositories {"clojars" {:sign-releases false
:username :env/clojars_username
:password :env/clojars_password}}
:dependencies [[org.clojure/clojure "1.10.3"]
[com.github.seancorfield/next.jdbc "1.2.761"]
[com.stuartsierra/component "1.0.0"]]
:profiles {:dev
{:resource-paths ["dev-resources"]
:dependencies [[ch.qos.logback/logback-classic "1.2.10"]
[nomnom/utility-belt.sql "1.1.0"]
[org.clojure/tools.logging "1.2.4"]]}})
|
2cd8329ffe7241bd686898c6f77288bbf75f6991e06a73370b36cab6652d0e77 | chaw/r7rs-libs | red-line.sps |
(import (scheme base)
(srfi 42)
(rebottled pstk))
;; set up the graphical display
(let ((tk (tk-start)))
(tk/wm 'title tk "Example")
(tk 'configure 'width: 300 'height: 200)
(let ((canvas (tk 'create-widget 'canvas 'width: 300 'height: 200))
(image (tk/image 'create 'photo 'width: 300 'height: 200)))
; clear the image
(tk-eval (string-append image " blank"))
; draw a line across the centre
(do-ec (: i 300)
(tk-eval (string-append image
" put red -to "
(number->string i)
" 120")))
; place image in canvas
(canvas 'create 'image 0 0 'image: image 'anchor: 'nw)
; put canvas on window
(tk/pack canvas))
(tk-event-loop tk))
| null | https://raw.githubusercontent.com/chaw/r7rs-libs/b8b625c36b040ff3d4b723e4346629a8a0e8d6c2/rebottled-examples/pstk/red-line.sps | scheme | set up the graphical display
clear the image
draw a line across the centre
place image in canvas
put canvas on window |
(import (scheme base)
(srfi 42)
(rebottled pstk))
(let ((tk (tk-start)))
(tk/wm 'title tk "Example")
(tk 'configure 'width: 300 'height: 200)
(let ((canvas (tk 'create-widget 'canvas 'width: 300 'height: 200))
(image (tk/image 'create 'photo 'width: 300 'height: 200)))
(tk-eval (string-append image " blank"))
(do-ec (: i 300)
(tk-eval (string-append image
" put red -to "
(number->string i)
" 120")))
(canvas 'create 'image 0 0 'image: image 'anchor: 'nw)
(tk/pack canvas))
(tk-event-loop tk))
|
078c6c016f75d93d12350df6d650ee1eefdd539125a0554ab5dcb8596d68119c | portkey-cloud/aws-clj-sdk | _2012-10-29.clj | (ns portkey.aws.datapipeline.-2012-10-29 (:require [portkey.aws]))
(def
endpoints
'{"ap-northeast-1"
{:credential-scope
{:service "datapipeline", :region "ap-northeast-1"},
:ssl-common-name "datapipeline.ap-northeast-1.amazonaws.com",
:endpoint "-northeast-1.amazonaws.com",
:signature-version :v4},
"eu-west-1"
{:credential-scope {:service "datapipeline", :region "eu-west-1"},
:ssl-common-name "datapipeline.eu-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4},
"ap-southeast-2"
{:credential-scope
{:service "datapipeline", :region "ap-southeast-2"},
:ssl-common-name "datapipeline.ap-southeast-2.amazonaws.com",
:endpoint "-southeast-2.amazonaws.com",
:signature-version :v4},
"us-west-2"
{:credential-scope {:service "datapipeline", :region "us-west-2"},
:ssl-common-name "datapipeline.us-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-east-1"
{:credential-scope {:service "datapipeline", :region "us-east-1"},
:ssl-common-name "datapipeline.us-east-1.amazonaws.com",
:endpoint "-east-1.amazonaws.com",
:signature-version :v4}})
(comment TODO support "json")
| null | https://raw.githubusercontent.com/portkey-cloud/aws-clj-sdk/10623a5c86bd56c8b312f56b76ae5ff52c26a945/src/portkey/aws/datapipeline/_2012-10-29.clj | clojure | (ns portkey.aws.datapipeline.-2012-10-29 (:require [portkey.aws]))
(def
endpoints
'{"ap-northeast-1"
{:credential-scope
{:service "datapipeline", :region "ap-northeast-1"},
:ssl-common-name "datapipeline.ap-northeast-1.amazonaws.com",
:endpoint "-northeast-1.amazonaws.com",
:signature-version :v4},
"eu-west-1"
{:credential-scope {:service "datapipeline", :region "eu-west-1"},
:ssl-common-name "datapipeline.eu-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4},
"ap-southeast-2"
{:credential-scope
{:service "datapipeline", :region "ap-southeast-2"},
:ssl-common-name "datapipeline.ap-southeast-2.amazonaws.com",
:endpoint "-southeast-2.amazonaws.com",
:signature-version :v4},
"us-west-2"
{:credential-scope {:service "datapipeline", :region "us-west-2"},
:ssl-common-name "datapipeline.us-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-east-1"
{:credential-scope {:service "datapipeline", :region "us-east-1"},
:ssl-common-name "datapipeline.us-east-1.amazonaws.com",
:endpoint "-east-1.amazonaws.com",
:signature-version :v4}})
(comment TODO support "json")
|
|
c7a87a5d724e392674c11a1cd4d1cb075f7743565dac1b80e5ad01edd0662fc4 | xapi-project/xen-api | mime.ml |
* Copyright ( C ) 2006 - 2009 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) 2006-2009 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.
*)
(* MIME handling for HTTP responses *)
open Printf
(** Map extension to MIME type *)
type t = (string, string) Hashtbl.t
let lowercase = Astring.String.Ascii.lowercase
* an Apache - format mime.types file and return mime_t
let mime_of_file file =
let h = Hashtbl.create 1024 in
Xapi_stdext_unix.Unixext.readfile_line
(fun line ->
if not (Astring.String.is_prefix ~affix:"#" line) then
match Astring.String.fields ~empty:false line with
| [] | [_] ->
()
| mime :: exts ->
List.iter (fun e -> Hashtbl.add h (lowercase e) mime) exts
)
file ;
h
let string_of_mime m =
String.concat "," (Hashtbl.fold (fun k v a -> sprintf "{%s:%s}" k v :: a) m [])
let default_mime = "text/plain"
(** Map a file extension to a MIME type *)
let mime_of_ext mime ext =
try Hashtbl.find mime (lowercase ext) with Not_found -> default_mime
(** Figure out a mime type from a full filename *)
let mime_of_file_name mime fname =
(* split filename into dot components *)
let ext =
match Astring.String.cuts ~sep:"." fname with
| [] | [_] ->
""
| x ->
List.hd (List.rev x)
in
mime_of_ext mime ext
| null | https://raw.githubusercontent.com/xapi-project/xen-api/47fae74032aa6ade0fc12e867c530eaf2a96bf75/ocaml/libs/http-svr/mime.ml | ocaml | MIME handling for HTTP responses
* Map extension to MIME type
* Map a file extension to a MIME type
* Figure out a mime type from a full filename
split filename into dot components |
* Copyright ( C ) 2006 - 2009 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) 2006-2009 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 Printf
type t = (string, string) Hashtbl.t
let lowercase = Astring.String.Ascii.lowercase
* an Apache - format mime.types file and return mime_t
let mime_of_file file =
let h = Hashtbl.create 1024 in
Xapi_stdext_unix.Unixext.readfile_line
(fun line ->
if not (Astring.String.is_prefix ~affix:"#" line) then
match Astring.String.fields ~empty:false line with
| [] | [_] ->
()
| mime :: exts ->
List.iter (fun e -> Hashtbl.add h (lowercase e) mime) exts
)
file ;
h
let string_of_mime m =
String.concat "," (Hashtbl.fold (fun k v a -> sprintf "{%s:%s}" k v :: a) m [])
let default_mime = "text/plain"
let mime_of_ext mime ext =
try Hashtbl.find mime (lowercase ext) with Not_found -> default_mime
let mime_of_file_name mime fname =
let ext =
match Astring.String.cuts ~sep:"." fname with
| [] | [_] ->
""
| x ->
List.hd (List.rev x)
in
mime_of_ext mime ext
|
de1ad678bc30d4f9b8dbec3aa74f2a1bd955c9fe527ee446198d884059091da3 | djjolicoeur/datamaps | core_test.clj | (ns datamaps.core-test
(:require [clojure.test :refer :all]
[datamaps.core :refer :all]
[datamaps.facts :as df]
[datomic.api :as datomic]))
(def test-users
[{:firstname "Dan"
:lastname "Joli"
:cats ["islay" "zorro" "lily"]
:dogs ["ginny"]
:location {:city "Annapolis"
:state "MD"
:neighborhood {:name "Baltimore"
:zip 21224}}}
{:firstname "Casey"
:lastname "Joli"
:cats ["islay" "zorro" "lily"]
:dogs ["ginny"]
:location {:city "Salisbury"
:state "MD"
:neighborhood {:name "Cape"
:zip 21409}}}
{:firstname "Mike"
:lastname "Joli"
:dogs ["penny" "stokely"]
:location {:city "Annapolis"
:state "MD"
:neighborhood {:name "West Annapolis"
:zip 21401}}}
{:firstname "Katie"
:lastname "Joli"
:dogs ["penny" "stokely"]
:location {:city "Annapolis"
:state "MD"
:neighborhood {:name "West Annapolis"
:zip 21401}}}])
(defn west-annapolitans [facts]
(q '[:find [?f ...]
:where
[?e :firstname ?f]
[?e :location ?l]
[?l :neighborhood ?n]
[?n :zip 21401]]
facts))
(defn get-dan [facts]
(q '[:find ?e .
:where [?e :firstname "Dan"]]
facts))
(defn city [facts location-ref]
(q '[:find ?v .
:in $ ?loc
:where
[?loc :city ?v]]
facts location-ref))
(deftest entity-mapping []
(testing "Test map elements get mapped to entities"
(let [facts (facts test-users)
dan (get-dan facts)
dan-entity (entity facts dan)]
(is (= "Dan" (:firstname dan-entity)))
(is (= "Joli" (:lastname dan-entity)))
(is (= #{"lily" "zorro" "islay"} (set (:cats dan-entity))))
(is (= #{"ginny"} (set (:dogs dan-entity))))
(is (= "Annapolis" (get-in dan-entity [:location :city])))
(is (= 21224 (get-in dan-entity [:location :neighborhood :zip]))))))
(deftest queryable []
(testing "Test generated facts are queryable"
(let [facts (facts test-users)]
(is (= #{"Mike" "Katie"} (set (west-annapolitans facts)))))))
(def key-collisions
{:foo {:bar [{:foo [1 2 3]}] :baz {:bar 5}}})
(deftest test-collisions []
(testing "Keys are defined on a per-map basis"
(let [facts (facts key-collisions)
sub-id (q '[:find ?e .
:where
[?e :baz ?b]
[?b :bar 5]]
facts)
sub-ent (entity facts sub-id)
root-id (q '[:find ?e .
:where
[?e :foo ?f]
[?f :bar ?b]
[?b :foo 1]]
facts)
root-ent (entity facts root-id)]
(is (= 5 (get-in sub-ent [:baz :bar])))
(is (= 5 (get-in root-ent [:foo :baz :bar]))))))
(def dan-test-credits [100.0 100.0 200.0 200.0 1000.0 1000.0 157.66])
(def dan-test-debits [-500.0 -675.55])
(def casey-test-credits [1756.66 987.55 990.45 345.65])
(def casey-test-debits [-357.44 -432.11 -10.54])
(def bank-maps
[{:user "Dan"
:account [{:type :checking
:credits dan-test-credits
:debits dan-test-debits}]}
{:user "Casey"
:account [{:type :checking
:credits casey-test-credits
:debits casey-test-debits}]}])
(defn bank-credit-q [bank-facts user]
(q '[:find (sum ?c) .
:in $ ?u
:where
[?e :user ?u]
[?e :account ?a]
[?a :type :checking]
[?a :credits ?c]]
bank-facts user))
(defn bank-debit-q [bank-facts user]
(q '[:find (sum ?d) .
:in $ ?u
:where
[?e :user ?u]
[?e :account ?a]
[?a :type :checking]
[?a :debits ?d]]
bank-facts user))
(deftest collections-not-deduped []
(testing "Collections maintain all original elements"
(let [bank-facts (facts bank-maps)
dc (bank-credit-q bank-facts "Dan")
dd (bank-debit-q bank-facts "Dan")
cc (bank-credit-q bank-facts "Casey")
cd (bank-debit-q bank-facts "Casey")]
(is (= (apply + dan-test-credits) dc))
(is (= (apply + dan-test-debits) dd))
(is (= (apply + casey-test-credits) cc))
(is (= (apply + casey-test-debits) cd)))))
(deftest querying-across-fact-sets []
(testing "Test the ability to query across generated fact sets"
(let [user-facts (facts test-users)
bank-facts (facts bank-maps)
results (q '[:find ?tf ?bf ?c ?at
:in $1 $2
:where
[$1 ?tu :firstname ?tf]
[$2 ?bu :user ?bf]
[(= ?bf ?tf)]
[$1 ?tu :location ?l]
[$1 ?l :city ?c]
[$2 ?bu :account ?a]
[$2 ?a :type ?at]] user-facts bank-facts)
result-set (set results)]
(is (= #{["Dan" "Dan" "Annapolis" :checking]
["Casey" "Casey" "Salisbury" :checking]} result-set)))))
(deftest test-pull []
(testing "Test ability to pull"
(let [tfacts (facts test-users)
dan-id (get-dan tfacts)
pulled (pull tfacts '[* {:location [:city]}] dan-id)]
(is (= 1 (count (:location pulled))))
(is (= "Annapolis" (get-in pulled [:location :city]))))))
(def schema
[{:db/id #db/id[:db.part/db]
:db/ident :demo/firstname
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
{:db/id #db/id[:db.part/db]
:db/ident :demo/lastname
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}])
(def datomic-facts
[{:db/id #db/id[:db.part/user]
:demo/firstname "Dan"
:demo/lastname "Joli"}
{:db/id #db/id[:db.part/user]
:demo/firstname "Casey"
:demo/lastname "Joli"}])
(deftest datomic-integration []
(testing "Testing ability to integrate with datomic query engine"
(let [_ (datomic/create-database "datomic:mem-talk")
conn (datomic/connect "datomic:mem-talk")
_ @(datomic/transact conn schema)
_ @(datomic/transact conn datomic-facts)
tfacts (facts test-users)
results (datomic/q
'[:find ?datomic-firstname ?datomic-lastname ?map-firstname
?map-lastname ?map-city ?map-state
:in $1 $2
:where
[$1 ?e :demo/firstname ?datomic-firstname]
[$1 ?e :demo/lastname ?datomic-lastname]
[$2 ?fe :firstname ?map-firstname]
[$2 ?fe :lastname ?map-lastname]
[$2 ?fe :location ?l]
[$2 ?l :city ?map-city]
[$2 ?l :state ?map-state]
[(= ?datomic-firstname ?map-firstname)]
[(= ?datomic-lastname ?map-lastname)]]
(datomic/db conn) (df/fact-partition tfacts))
_ (datomic/delete-database "datomic:mem-talk")]
(is (= results
#{["Casey" "Joli" "Casey" "Joli" "Salisbury" "MD"]
["Dan" "Joli" "Dan" "Joli" "Annapolis" "MD"]})))))
| null | https://raw.githubusercontent.com/djjolicoeur/datamaps/f7523e83a87c5f790f492bbfcce8a23980ef0077/test/datamaps/core_test.clj | clojure | (ns datamaps.core-test
(:require [clojure.test :refer :all]
[datamaps.core :refer :all]
[datamaps.facts :as df]
[datomic.api :as datomic]))
(def test-users
[{:firstname "Dan"
:lastname "Joli"
:cats ["islay" "zorro" "lily"]
:dogs ["ginny"]
:location {:city "Annapolis"
:state "MD"
:neighborhood {:name "Baltimore"
:zip 21224}}}
{:firstname "Casey"
:lastname "Joli"
:cats ["islay" "zorro" "lily"]
:dogs ["ginny"]
:location {:city "Salisbury"
:state "MD"
:neighborhood {:name "Cape"
:zip 21409}}}
{:firstname "Mike"
:lastname "Joli"
:dogs ["penny" "stokely"]
:location {:city "Annapolis"
:state "MD"
:neighborhood {:name "West Annapolis"
:zip 21401}}}
{:firstname "Katie"
:lastname "Joli"
:dogs ["penny" "stokely"]
:location {:city "Annapolis"
:state "MD"
:neighborhood {:name "West Annapolis"
:zip 21401}}}])
(defn west-annapolitans [facts]
(q '[:find [?f ...]
:where
[?e :firstname ?f]
[?e :location ?l]
[?l :neighborhood ?n]
[?n :zip 21401]]
facts))
(defn get-dan [facts]
(q '[:find ?e .
:where [?e :firstname "Dan"]]
facts))
(defn city [facts location-ref]
(q '[:find ?v .
:in $ ?loc
:where
[?loc :city ?v]]
facts location-ref))
(deftest entity-mapping []
(testing "Test map elements get mapped to entities"
(let [facts (facts test-users)
dan (get-dan facts)
dan-entity (entity facts dan)]
(is (= "Dan" (:firstname dan-entity)))
(is (= "Joli" (:lastname dan-entity)))
(is (= #{"lily" "zorro" "islay"} (set (:cats dan-entity))))
(is (= #{"ginny"} (set (:dogs dan-entity))))
(is (= "Annapolis" (get-in dan-entity [:location :city])))
(is (= 21224 (get-in dan-entity [:location :neighborhood :zip]))))))
(deftest queryable []
(testing "Test generated facts are queryable"
(let [facts (facts test-users)]
(is (= #{"Mike" "Katie"} (set (west-annapolitans facts)))))))
(def key-collisions
{:foo {:bar [{:foo [1 2 3]}] :baz {:bar 5}}})
(deftest test-collisions []
(testing "Keys are defined on a per-map basis"
(let [facts (facts key-collisions)
sub-id (q '[:find ?e .
:where
[?e :baz ?b]
[?b :bar 5]]
facts)
sub-ent (entity facts sub-id)
root-id (q '[:find ?e .
:where
[?e :foo ?f]
[?f :bar ?b]
[?b :foo 1]]
facts)
root-ent (entity facts root-id)]
(is (= 5 (get-in sub-ent [:baz :bar])))
(is (= 5 (get-in root-ent [:foo :baz :bar]))))))
(def dan-test-credits [100.0 100.0 200.0 200.0 1000.0 1000.0 157.66])
(def dan-test-debits [-500.0 -675.55])
(def casey-test-credits [1756.66 987.55 990.45 345.65])
(def casey-test-debits [-357.44 -432.11 -10.54])
(def bank-maps
[{:user "Dan"
:account [{:type :checking
:credits dan-test-credits
:debits dan-test-debits}]}
{:user "Casey"
:account [{:type :checking
:credits casey-test-credits
:debits casey-test-debits}]}])
(defn bank-credit-q [bank-facts user]
(q '[:find (sum ?c) .
:in $ ?u
:where
[?e :user ?u]
[?e :account ?a]
[?a :type :checking]
[?a :credits ?c]]
bank-facts user))
(defn bank-debit-q [bank-facts user]
(q '[:find (sum ?d) .
:in $ ?u
:where
[?e :user ?u]
[?e :account ?a]
[?a :type :checking]
[?a :debits ?d]]
bank-facts user))
(deftest collections-not-deduped []
(testing "Collections maintain all original elements"
(let [bank-facts (facts bank-maps)
dc (bank-credit-q bank-facts "Dan")
dd (bank-debit-q bank-facts "Dan")
cc (bank-credit-q bank-facts "Casey")
cd (bank-debit-q bank-facts "Casey")]
(is (= (apply + dan-test-credits) dc))
(is (= (apply + dan-test-debits) dd))
(is (= (apply + casey-test-credits) cc))
(is (= (apply + casey-test-debits) cd)))))
(deftest querying-across-fact-sets []
(testing "Test the ability to query across generated fact sets"
(let [user-facts (facts test-users)
bank-facts (facts bank-maps)
results (q '[:find ?tf ?bf ?c ?at
:in $1 $2
:where
[$1 ?tu :firstname ?tf]
[$2 ?bu :user ?bf]
[(= ?bf ?tf)]
[$1 ?tu :location ?l]
[$1 ?l :city ?c]
[$2 ?bu :account ?a]
[$2 ?a :type ?at]] user-facts bank-facts)
result-set (set results)]
(is (= #{["Dan" "Dan" "Annapolis" :checking]
["Casey" "Casey" "Salisbury" :checking]} result-set)))))
(deftest test-pull []
(testing "Test ability to pull"
(let [tfacts (facts test-users)
dan-id (get-dan tfacts)
pulled (pull tfacts '[* {:location [:city]}] dan-id)]
(is (= 1 (count (:location pulled))))
(is (= "Annapolis" (get-in pulled [:location :city]))))))
(def schema
[{:db/id #db/id[:db.part/db]
:db/ident :demo/firstname
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
{:db/id #db/id[:db.part/db]
:db/ident :demo/lastname
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}])
(def datomic-facts
[{:db/id #db/id[:db.part/user]
:demo/firstname "Dan"
:demo/lastname "Joli"}
{:db/id #db/id[:db.part/user]
:demo/firstname "Casey"
:demo/lastname "Joli"}])
(deftest datomic-integration []
(testing "Testing ability to integrate with datomic query engine"
(let [_ (datomic/create-database "datomic:mem-talk")
conn (datomic/connect "datomic:mem-talk")
_ @(datomic/transact conn schema)
_ @(datomic/transact conn datomic-facts)
tfacts (facts test-users)
results (datomic/q
'[:find ?datomic-firstname ?datomic-lastname ?map-firstname
?map-lastname ?map-city ?map-state
:in $1 $2
:where
[$1 ?e :demo/firstname ?datomic-firstname]
[$1 ?e :demo/lastname ?datomic-lastname]
[$2 ?fe :firstname ?map-firstname]
[$2 ?fe :lastname ?map-lastname]
[$2 ?fe :location ?l]
[$2 ?l :city ?map-city]
[$2 ?l :state ?map-state]
[(= ?datomic-firstname ?map-firstname)]
[(= ?datomic-lastname ?map-lastname)]]
(datomic/db conn) (df/fact-partition tfacts))
_ (datomic/delete-database "datomic:mem-talk")]
(is (= results
#{["Casey" "Joli" "Casey" "Joli" "Salisbury" "MD"]
["Dan" "Joli" "Dan" "Joli" "Annapolis" "MD"]})))))
|
|
a81a30ff42dba7bec8cc664197effea1b1b2ce5effe548fb7e17c06630718cc3 | jrh13/hol-light | herbrand.ml | (* ========================================================================= *)
(* Refinement of canonical model theorem to consider ground terms only. *)
(* ========================================================================= *)
let herbase_RULES,herbase_INDUCT,herbase_CASES = new_inductive_definition
`(~(?c. (c,0) IN fns) ==> herbase fns (V 0)) /\
(!f l. (f,LENGTH l) IN fns /\ ALL (herbase fns) l
==> herbase fns (Fn f l))`;;
(* ------------------------------------------------------------------------- *)
(* Canonical model based on the language of a set of formulas. *)
(* ------------------------------------------------------------------------- *)
let herbrand = new_definition
`herbrand (L:(num#num->bool)#(num#num->bool)) M <=>
(Dom M = herbase (FST L)) /\
(!f. Fun(M) f = Fn f)`;;
(* ------------------------------------------------------------------------- *)
Lemmas .
(* ------------------------------------------------------------------------- *)
let HERBRAND_INTERPRETATION = prove
(`!L M. herbrand L M ==> interpretation L M`,
GEN_REWRITE_TAC I [FORALL_PAIR_THM] THEN
SIMP_TAC[herbrand; interpretation] THEN
REPEAT GEN_TAC THEN STRIP_TAC THEN REPEAT GEN_TAC THEN
DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN
REWRITE_TAC[IN] THEN CONV_TAC(ONCE_DEPTH_CONV ETA_CONV) THEN
ASM_SIMP_TAC[herbase_RULES]);;
let HERBASE_FUNCTIONS = prove
(`!fns t. t IN herbase fns ==> (functions_term t) SUBSET fns`,
GEN_TAC THEN REWRITE_TAC[IN] THEN MATCH_MP_TAC herbase_INDUCT THEN
REWRITE_TAC[functions_term; EMPTY_SUBSET] THEN
REWRITE_TAC[SUBSET; IN_INSERT; IN_LIST_UNION; GSYM ALL_MEM; GSYM EX_MEM;
MEM_MAP] THEN
MESON_TAC[]);;
let HERBASE_NONEMPTY = prove
(`!fns. ?t. t IN herbase fns`,
GEN_TAC THEN REWRITE_TAC[IN] THEN ONCE_REWRITE_TAC[herbase_CASES] THEN
MESON_TAC[ALL; LENGTH]);;
let HERBRAND_NONEMPTY = prove
(`!L M. herbrand L M ==> ~(Dom M = {})`,
SIMP_TAC[herbrand; Dom_DEF; EXTENSION; NOT_IN_EMPTY] THEN
REWRITE_TAC[NOT_FORALL_THM; HERBASE_NONEMPTY]);;
(* ------------------------------------------------------------------------- *)
(* Mappings between models and propositional valuations. *)
(* ------------------------------------------------------------------------- *)
let herbrand_of_prop = new_definition
`herbrand_of_prop (L:((num#num)->bool)#((num#num)->bool)) (d:form->bool) =
herbase(FST L),Fn,\p l. d(Atom p l)`;;
let PROP_OF_HERBRAND_OF_PROP = prove
(`!p l. prop_of_model (herbrand_of_prop L d) V (Atom p l) = d (Atom p l)`,
REWRITE_TAC[prop_of_model; herbrand_of_prop; holds; Pred_DEF] THEN
REPEAT GEN_TAC THEN REPEAT AP_TERM_TAC THEN
MATCH_MP_TAC MAP_EQ_DEGEN THEN
SPEC_TAC(`l:term list`,`l:term list`) THEN
LIST_INDUCT_TAC THEN ASM_REWRITE_TAC[ALL] THEN
SPEC_TAC(`h:term`,`t:term`) THEN
MATCH_MP_TAC term_INDUCT THEN
REWRITE_TAC[termval; Fun_DEF] THEN
REPEAT STRIP_TAC THEN AP_TERM_TAC THEN
MATCH_MP_TAC MAP_EQ_DEGEN THEN ASM_REWRITE_TAC[]);;
let HOLDS_HERBRAND_OF_PROP = prove
(`!p. qfree p ==> (holds (herbrand_of_prop L d) V p <=> pholds d p)`,
GEN_TAC THEN DISCH_THEN(fun th -> MP_TAC th THEN
REWRITE_TAC[GSYM(MATCH_MP PHOLDS_PROP_OF_MODEL th)]) THEN
SPEC_TAC(`p:form`,`p:form`) THEN
MATCH_MP_TAC form_INDUCTION THEN
REWRITE_TAC[pholds; qfree; PROP_OF_HERBRAND_OF_PROP] THEN
REPEAT GEN_TAC THEN STRIP_TAC THEN
DISCH_THEN(CONJUNCTS_THEN (ANTE_RES_THEN SUBST1_TAC)) THEN REFL_TAC);;
let HOLDS_HERBRAND_OF_PROP_GENERAL = prove
(`qfree p ==> (holds (herbrand_of_prop L d) v p <=> pholds d (formsubst v p))`,
DISCH_THEN(fun th -> MP_TAC th THEN
REWRITE_TAC[GSYM(MATCH_MP PHOLDS_PROP_OF_MODEL th)]) THEN
SPEC_TAC(`p:form`,`p:form`) THEN
MATCH_MP_TAC form_INDUCTION THEN
REWRITE_TAC[formsubst; pholds; qfree; PROP_OF_HERBRAND_OF_PROP] THEN
REPEAT GEN_TAC THEN STRIP_TAC THENL
[ALL_TAC;
REPEAT GEN_TAC THEN STRIP_TAC THEN
DISCH_THEN(CONJUNCTS_THEN (ANTE_RES_THEN SUBST1_TAC)) THEN
REFL_TAC] THEN
REPEAT GEN_TAC THEN REWRITE_TAC[prop_of_model; herbrand_of_prop; holds] THEN
REWRITE_TAC[Pred_DEF] THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN AP_THM_TAC THEN AP_TERM_TAC THEN
REWRITE_TAC[FUN_EQ_THM] THEN SIMP_TAC[GSYM TERMSUBST_TERMVAL; Fun_DEF]);;
let HERBRAND_HERBRAND_OF_PROP = prove
(`!d. herbrand L (herbrand_of_prop L d)`,
REWRITE_TAC[herbrand; herbrand_of_prop; Dom_DEF; Fun_DEF; FUN_EQ_THM]);;
let INTERPRETATION_HERBRAND_OF_PROP = prove
(`!L d. interpretation L (herbrand_of_prop L d)`,
REWRITE_TAC[FORALL_PAIR_THM; interpretation; herbrand_of_prop; Fun_DEF;
Dom_DEF; IN; ETA_AX] THEN
MESON_TAC[herbase_RULES; IN]);;
(* ------------------------------------------------------------------------- *)
(* Same thing for satisfiability. *)
(* ------------------------------------------------------------------------- *)
let PSATISFIES_HERBRAND_INSTANCES = prove
(`(!p. p IN s ==> qfree p) /\
d psatisfies {formsubst v p | (!x. v x IN herbase(FST L)) /\ p IN s}
==> (herbrand_of_prop L d) satisfies s`,
REWRITE_TAC[satisfies; psatisfies; IN_ELIM_THM; LEFT_IMP_EXISTS_THM] THEN
STRIP_TAC THEN
REPEAT GEN_TAC THEN GEN_REWRITE_TAC (LAND_CONV o TOP_DEPTH_CONV)
[herbrand_of_prop; Dom_DEF; valuation] THEN STRIP_TAC THEN
FIRST_X_ASSUM(MP_TAC o SPECL[`formsubst v p`; `v:num->term`; `p:form`]) THEN
ASM_REWRITE_TAC[] THEN DISCH_TAC THEN
SUBGOAL_THEN `holds (herbrand_of_prop L d) V (formsubst v p)` MP_TAC THENL
[ASM_MESON_TAC[HOLDS_HERBRAND_OF_PROP; QFREE_FORMSUBST]; ALL_TAC] THEN
SUBGOAL_THEN `holds (herbrand_of_prop L d) V (formsubst v p) <=>
holds (herbrand_of_prop L d)
(termval (herbrand_of_prop L d) V o v)
p`
SUBST1_TAC THENL
[REWRITE_TAC[HOLDS_FORMSUBST] THEN
ASM_MESON_TAC[INTER_EMPTY; QFREE_BV_EMPTY];
MATCH_MP_TAC EQ_IMP THEN AP_THM_TAC THEN
AP_TERM_TAC THEN REWRITE_TAC[FUN_EQ_THM; o_THM] THEN
GEN_TAC THEN SPEC_TAC(`(v:num->term) x`,`t:term`) THEN
MATCH_MP_TAC TERMVAL_TRIV THEN
REWRITE_TAC[herbrand_of_prop; Fun_DEF]]);;
(* ------------------------------------------------------------------------- *)
Hence the Herbrand theorem .
(* ------------------------------------------------------------------------- *)
let SATISFIES_SUBSET = prove
(`!M s t. s SUBSET t /\ M satisfies t ==> M satisfies s`,
REWRITE_TAC[satisfies; SUBSET] THEN MESON_TAC[]);;
let HERBASE_SUBSET_TERMS = prove
(`!t. t IN herbase fns ==> t IN terms fns`,
REWRITE_TAC[IN] THEN MATCH_MP_TAC herbase_INDUCT THEN
CONV_TAC(ONCE_DEPTH_CONV ETA_CONV) THEN REWRITE_TAC[terms_RULES]);;
let HERBRAND_THEOREM = prove
(`!s. (!p. p IN s ==> qfree p)
==> ((?M:(term->bool)#(num->term list->term)#(num->term list->bool).
interpretation (language s) M /\ ~(Dom M = {}) /\
M satisfies s) <=>
(?d. d psatisfies
{formsubst v p | (!x. v x IN herbase(functions s)) /\
p IN s}))`,
GEN_TAC THEN DISCH_TAC THEN EQ_TAC THEN STRIP_TAC THENL
[FIRST_ASSUM(X_CHOOSE_TAC `v:num->term` o MATCH_MP VALUATION_EXISTS) THEN
EXISTS_TAC `prop_of_model M (v:num->term)` THEN
MATCH_MP_TAC SATISFIES_PSATISFIES THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL
[ASM_SIMP_TAC[IN_ELIM_THM; LEFT_IMP_EXISTS_THM; QFREE_FORMSUBST];
FIRST_ASSUM(MP_TAC o MATCH_MP SATISFIES_INSTANCES) THEN
DISCH_THEN(MP_TAC o SPEC `s:form->bool`) THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ]
SATISFIES_SUBSET) THEN
REWRITE_TAC[SUBSET; IN_ELIM_THM; language] THEN
MESON_TAC[HERBASE_SUBSET_TERMS; SUBSET]];
EXISTS_TAC `herbrand_of_prop (language s) d` THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[INTERPRETATION_HERBRAND_OF_PROP];
REWRITE_TAC[herbrand_of_prop; Dom_DEF; language;
EXTENSION; NOT_IN_EMPTY] THEN
REWRITE_TAC[IN] THEN MESON_TAC[herbase_RULES; ALL; LENGTH];
ASM_SIMP_TAC[PSATISFIES_HERBRAND_INSTANCES; language]]]);;
| null | https://raw.githubusercontent.com/jrh13/hol-light/ea44a4cacd238d7fa5a397f043f3e3321eb66543/Logic/herbrand.ml | ocaml | =========================================================================
Refinement of canonical model theorem to consider ground terms only.
=========================================================================
-------------------------------------------------------------------------
Canonical model based on the language of a set of formulas.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Mappings between models and propositional valuations.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Same thing for satisfiability.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
------------------------------------------------------------------------- |
let herbase_RULES,herbase_INDUCT,herbase_CASES = new_inductive_definition
`(~(?c. (c,0) IN fns) ==> herbase fns (V 0)) /\
(!f l. (f,LENGTH l) IN fns /\ ALL (herbase fns) l
==> herbase fns (Fn f l))`;;
let herbrand = new_definition
`herbrand (L:(num#num->bool)#(num#num->bool)) M <=>
(Dom M = herbase (FST L)) /\
(!f. Fun(M) f = Fn f)`;;
Lemmas .
let HERBRAND_INTERPRETATION = prove
(`!L M. herbrand L M ==> interpretation L M`,
GEN_REWRITE_TAC I [FORALL_PAIR_THM] THEN
SIMP_TAC[herbrand; interpretation] THEN
REPEAT GEN_TAC THEN STRIP_TAC THEN REPEAT GEN_TAC THEN
DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN
REWRITE_TAC[IN] THEN CONV_TAC(ONCE_DEPTH_CONV ETA_CONV) THEN
ASM_SIMP_TAC[herbase_RULES]);;
let HERBASE_FUNCTIONS = prove
(`!fns t. t IN herbase fns ==> (functions_term t) SUBSET fns`,
GEN_TAC THEN REWRITE_TAC[IN] THEN MATCH_MP_TAC herbase_INDUCT THEN
REWRITE_TAC[functions_term; EMPTY_SUBSET] THEN
REWRITE_TAC[SUBSET; IN_INSERT; IN_LIST_UNION; GSYM ALL_MEM; GSYM EX_MEM;
MEM_MAP] THEN
MESON_TAC[]);;
let HERBASE_NONEMPTY = prove
(`!fns. ?t. t IN herbase fns`,
GEN_TAC THEN REWRITE_TAC[IN] THEN ONCE_REWRITE_TAC[herbase_CASES] THEN
MESON_TAC[ALL; LENGTH]);;
let HERBRAND_NONEMPTY = prove
(`!L M. herbrand L M ==> ~(Dom M = {})`,
SIMP_TAC[herbrand; Dom_DEF; EXTENSION; NOT_IN_EMPTY] THEN
REWRITE_TAC[NOT_FORALL_THM; HERBASE_NONEMPTY]);;
let herbrand_of_prop = new_definition
`herbrand_of_prop (L:((num#num)->bool)#((num#num)->bool)) (d:form->bool) =
herbase(FST L),Fn,\p l. d(Atom p l)`;;
let PROP_OF_HERBRAND_OF_PROP = prove
(`!p l. prop_of_model (herbrand_of_prop L d) V (Atom p l) = d (Atom p l)`,
REWRITE_TAC[prop_of_model; herbrand_of_prop; holds; Pred_DEF] THEN
REPEAT GEN_TAC THEN REPEAT AP_TERM_TAC THEN
MATCH_MP_TAC MAP_EQ_DEGEN THEN
SPEC_TAC(`l:term list`,`l:term list`) THEN
LIST_INDUCT_TAC THEN ASM_REWRITE_TAC[ALL] THEN
SPEC_TAC(`h:term`,`t:term`) THEN
MATCH_MP_TAC term_INDUCT THEN
REWRITE_TAC[termval; Fun_DEF] THEN
REPEAT STRIP_TAC THEN AP_TERM_TAC THEN
MATCH_MP_TAC MAP_EQ_DEGEN THEN ASM_REWRITE_TAC[]);;
let HOLDS_HERBRAND_OF_PROP = prove
(`!p. qfree p ==> (holds (herbrand_of_prop L d) V p <=> pholds d p)`,
GEN_TAC THEN DISCH_THEN(fun th -> MP_TAC th THEN
REWRITE_TAC[GSYM(MATCH_MP PHOLDS_PROP_OF_MODEL th)]) THEN
SPEC_TAC(`p:form`,`p:form`) THEN
MATCH_MP_TAC form_INDUCTION THEN
REWRITE_TAC[pholds; qfree; PROP_OF_HERBRAND_OF_PROP] THEN
REPEAT GEN_TAC THEN STRIP_TAC THEN
DISCH_THEN(CONJUNCTS_THEN (ANTE_RES_THEN SUBST1_TAC)) THEN REFL_TAC);;
let HOLDS_HERBRAND_OF_PROP_GENERAL = prove
(`qfree p ==> (holds (herbrand_of_prop L d) v p <=> pholds d (formsubst v p))`,
DISCH_THEN(fun th -> MP_TAC th THEN
REWRITE_TAC[GSYM(MATCH_MP PHOLDS_PROP_OF_MODEL th)]) THEN
SPEC_TAC(`p:form`,`p:form`) THEN
MATCH_MP_TAC form_INDUCTION THEN
REWRITE_TAC[formsubst; pholds; qfree; PROP_OF_HERBRAND_OF_PROP] THEN
REPEAT GEN_TAC THEN STRIP_TAC THENL
[ALL_TAC;
REPEAT GEN_TAC THEN STRIP_TAC THEN
DISCH_THEN(CONJUNCTS_THEN (ANTE_RES_THEN SUBST1_TAC)) THEN
REFL_TAC] THEN
REPEAT GEN_TAC THEN REWRITE_TAC[prop_of_model; herbrand_of_prop; holds] THEN
REWRITE_TAC[Pred_DEF] THEN
AP_TERM_TAC THEN AP_TERM_TAC THEN AP_THM_TAC THEN AP_TERM_TAC THEN
REWRITE_TAC[FUN_EQ_THM] THEN SIMP_TAC[GSYM TERMSUBST_TERMVAL; Fun_DEF]);;
let HERBRAND_HERBRAND_OF_PROP = prove
(`!d. herbrand L (herbrand_of_prop L d)`,
REWRITE_TAC[herbrand; herbrand_of_prop; Dom_DEF; Fun_DEF; FUN_EQ_THM]);;
let INTERPRETATION_HERBRAND_OF_PROP = prove
(`!L d. interpretation L (herbrand_of_prop L d)`,
REWRITE_TAC[FORALL_PAIR_THM; interpretation; herbrand_of_prop; Fun_DEF;
Dom_DEF; IN; ETA_AX] THEN
MESON_TAC[herbase_RULES; IN]);;
let PSATISFIES_HERBRAND_INSTANCES = prove
(`(!p. p IN s ==> qfree p) /\
d psatisfies {formsubst v p | (!x. v x IN herbase(FST L)) /\ p IN s}
==> (herbrand_of_prop L d) satisfies s`,
REWRITE_TAC[satisfies; psatisfies; IN_ELIM_THM; LEFT_IMP_EXISTS_THM] THEN
STRIP_TAC THEN
REPEAT GEN_TAC THEN GEN_REWRITE_TAC (LAND_CONV o TOP_DEPTH_CONV)
[herbrand_of_prop; Dom_DEF; valuation] THEN STRIP_TAC THEN
FIRST_X_ASSUM(MP_TAC o SPECL[`formsubst v p`; `v:num->term`; `p:form`]) THEN
ASM_REWRITE_TAC[] THEN DISCH_TAC THEN
SUBGOAL_THEN `holds (herbrand_of_prop L d) V (formsubst v p)` MP_TAC THENL
[ASM_MESON_TAC[HOLDS_HERBRAND_OF_PROP; QFREE_FORMSUBST]; ALL_TAC] THEN
SUBGOAL_THEN `holds (herbrand_of_prop L d) V (formsubst v p) <=>
holds (herbrand_of_prop L d)
(termval (herbrand_of_prop L d) V o v)
p`
SUBST1_TAC THENL
[REWRITE_TAC[HOLDS_FORMSUBST] THEN
ASM_MESON_TAC[INTER_EMPTY; QFREE_BV_EMPTY];
MATCH_MP_TAC EQ_IMP THEN AP_THM_TAC THEN
AP_TERM_TAC THEN REWRITE_TAC[FUN_EQ_THM; o_THM] THEN
GEN_TAC THEN SPEC_TAC(`(v:num->term) x`,`t:term`) THEN
MATCH_MP_TAC TERMVAL_TRIV THEN
REWRITE_TAC[herbrand_of_prop; Fun_DEF]]);;
Hence the Herbrand theorem .
let SATISFIES_SUBSET = prove
(`!M s t. s SUBSET t /\ M satisfies t ==> M satisfies s`,
REWRITE_TAC[satisfies; SUBSET] THEN MESON_TAC[]);;
let HERBASE_SUBSET_TERMS = prove
(`!t. t IN herbase fns ==> t IN terms fns`,
REWRITE_TAC[IN] THEN MATCH_MP_TAC herbase_INDUCT THEN
CONV_TAC(ONCE_DEPTH_CONV ETA_CONV) THEN REWRITE_TAC[terms_RULES]);;
let HERBRAND_THEOREM = prove
(`!s. (!p. p IN s ==> qfree p)
==> ((?M:(term->bool)#(num->term list->term)#(num->term list->bool).
interpretation (language s) M /\ ~(Dom M = {}) /\
M satisfies s) <=>
(?d. d psatisfies
{formsubst v p | (!x. v x IN herbase(functions s)) /\
p IN s}))`,
GEN_TAC THEN DISCH_TAC THEN EQ_TAC THEN STRIP_TAC THENL
[FIRST_ASSUM(X_CHOOSE_TAC `v:num->term` o MATCH_MP VALUATION_EXISTS) THEN
EXISTS_TAC `prop_of_model M (v:num->term)` THEN
MATCH_MP_TAC SATISFIES_PSATISFIES THEN ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL
[ASM_SIMP_TAC[IN_ELIM_THM; LEFT_IMP_EXISTS_THM; QFREE_FORMSUBST];
FIRST_ASSUM(MP_TAC o MATCH_MP SATISFIES_INSTANCES) THEN
DISCH_THEN(MP_TAC o SPEC `s:form->bool`) THEN ASM_REWRITE_TAC[] THEN
MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ]
SATISFIES_SUBSET) THEN
REWRITE_TAC[SUBSET; IN_ELIM_THM; language] THEN
MESON_TAC[HERBASE_SUBSET_TERMS; SUBSET]];
EXISTS_TAC `herbrand_of_prop (language s) d` THEN REPEAT CONJ_TAC THENL
[REWRITE_TAC[INTERPRETATION_HERBRAND_OF_PROP];
REWRITE_TAC[herbrand_of_prop; Dom_DEF; language;
EXTENSION; NOT_IN_EMPTY] THEN
REWRITE_TAC[IN] THEN MESON_TAC[herbase_RULES; ALL; LENGTH];
ASM_SIMP_TAC[PSATISFIES_HERBRAND_INSTANCES; language]]]);;
|
cc805b5f1c60240ff08f43d1b60fa7e92c66d6175e5630475f5366e1e6d14a6e | namin/logically | smt_test.clj | (ns logically.exp.smt_test
(:use [logically.exp.smt] :reload)
(:refer-clojure :exclude [==])
(:use [clojure.core.logic :exclude [is] :as l])
(:use [clojure.test]))
(deftest unsat-1
(is (= '()
(run* [q]
(smtc `(~'= ~q 1))
(smtc `(~'= ~q 2))
(smtc `(~'= ~q 3))))))
(deftest sat-1
(is (= '(1)
(run* [q]
(smtc `(~'= ~q 1))
smt-purge))))
(deftest sat-2
(is (= '(1 2)
(run 2 [q]
(smtc `(~'> ~q 0))
smt-purge))))
(deftest sat-conde-1
(is (= '(1 2)
(run* [q]
(conde
[(smtc `(~'= ~q 1))]
[(smtc `(~'= ~q 2))])
smt-purge))))
(deftest mix-constraints
(is (= '(1)
(run* [q]
(predc q number? nil)
(conde
[(smtc `(~'= ~q 1))]
[(== 'hello q)])
smt-purge))))
(defn faco [n out]
(conde
[(smtc `(~'= ~n 0))
(smtc `(~'= ~out 1))]
[(smtc `(~'> ~n 0))
(fresh [n-1 r]
(smtc `(~'= (~'- ~n 1) ~n-1))
(smtc `(~'= (~'* ~n ~r) ~out))
(faco n-1 r))]))
(deftest faco-7
(is (= '([0 1] [1 1] [2 2] [3 6] [4 24] [5 120] [6 720])
(run 7 [n out]
(faco n out)
smt-purge))))
(deftest faco-backwards-2
(is (= '(2)
(run* [q]
(faco q 2)
smt-purge))))
(deftest faco-backwards-6
(is (= '(6)
(run* [q]
(faco q 720)
smt-purge))))
(deftest rsa-small-nums
(is (= '([143 120 7 103])
(run 1 [k]
(fresh [p q n phi e d]
(smtc `(~'= ~p 11))
(smtc `(~'= ~q 13))
(smtc `(~'= ~n (~'* ~p ~q)))
(smtc `(~'= ~phi (~'* (~'- ~p 1) (~'- ~q 1))))
(smtc `(~'= ~e 7))
(smtc `(~'<= 0 ~d))
(smtc `(~'<= ~d 200)) ;; just to get a smaller answer...
(smtc `(~'= (~'mod (~'* ~e ~d) ~phi) 1))
(== k [n phi e d])
smt-purge)))))
(deftest bitvec-1
(is (= '(bv-000 bv-111 bv-110 bv-100 bv-101 bv-010 bv-011 bv-001)
(run* [q]
(smt-decl q '(_ BitVec 3))
smt-purge))))
(deftest bitvec-2
(is (= '(bv-001 bv-111 bv-101 bv-011)
(run* [q]
(smt-decl q '(_ BitVec 3))
(smtc `(~'= ~q (~'bvor ~q ~'bv-001)))
smt-purge))))
(deftest custom-datatypes-1
(is (= '([(node 21 (as nil (TreeList Int)))
(node false (as nil (TreeList Bool)))])
(run 1 [t1 t2]
(smt-any [t1 t2]
'(declare-datatypes
(T)
((Tree leaf (node (value T) (children TreeList)))
(TreeList nil (cons (car Tree) (cdr TreeList))))))
(smt-decl t1 '(Tree Int))
(smt-decl t2 '(Tree Bool))
(smtc `(~'not (~'= ~t1 (~'as ~'leaf (~'Tree ~'Int)))))
(smtc `(~'> (~'value ~t1) 20))
(smtc `(~'not (~'is-leaf ~t2)))
(smtc `(~'not (~'value ~t2)))
smt-purge))))
| null | https://raw.githubusercontent.com/namin/logically/902258221e347edf16e8ff37f918a534ff1088b4/test/logically/exp/smt_test.clj | clojure | just to get a smaller answer... | (ns logically.exp.smt_test
(:use [logically.exp.smt] :reload)
(:refer-clojure :exclude [==])
(:use [clojure.core.logic :exclude [is] :as l])
(:use [clojure.test]))
(deftest unsat-1
(is (= '()
(run* [q]
(smtc `(~'= ~q 1))
(smtc `(~'= ~q 2))
(smtc `(~'= ~q 3))))))
(deftest sat-1
(is (= '(1)
(run* [q]
(smtc `(~'= ~q 1))
smt-purge))))
(deftest sat-2
(is (= '(1 2)
(run 2 [q]
(smtc `(~'> ~q 0))
smt-purge))))
(deftest sat-conde-1
(is (= '(1 2)
(run* [q]
(conde
[(smtc `(~'= ~q 1))]
[(smtc `(~'= ~q 2))])
smt-purge))))
(deftest mix-constraints
(is (= '(1)
(run* [q]
(predc q number? nil)
(conde
[(smtc `(~'= ~q 1))]
[(== 'hello q)])
smt-purge))))
(defn faco [n out]
(conde
[(smtc `(~'= ~n 0))
(smtc `(~'= ~out 1))]
[(smtc `(~'> ~n 0))
(fresh [n-1 r]
(smtc `(~'= (~'- ~n 1) ~n-1))
(smtc `(~'= (~'* ~n ~r) ~out))
(faco n-1 r))]))
(deftest faco-7
(is (= '([0 1] [1 1] [2 2] [3 6] [4 24] [5 120] [6 720])
(run 7 [n out]
(faco n out)
smt-purge))))
(deftest faco-backwards-2
(is (= '(2)
(run* [q]
(faco q 2)
smt-purge))))
(deftest faco-backwards-6
(is (= '(6)
(run* [q]
(faco q 720)
smt-purge))))
(deftest rsa-small-nums
(is (= '([143 120 7 103])
(run 1 [k]
(fresh [p q n phi e d]
(smtc `(~'= ~p 11))
(smtc `(~'= ~q 13))
(smtc `(~'= ~n (~'* ~p ~q)))
(smtc `(~'= ~phi (~'* (~'- ~p 1) (~'- ~q 1))))
(smtc `(~'= ~e 7))
(smtc `(~'<= 0 ~d))
(smtc `(~'= (~'mod (~'* ~e ~d) ~phi) 1))
(== k [n phi e d])
smt-purge)))))
(deftest bitvec-1
(is (= '(bv-000 bv-111 bv-110 bv-100 bv-101 bv-010 bv-011 bv-001)
(run* [q]
(smt-decl q '(_ BitVec 3))
smt-purge))))
(deftest bitvec-2
(is (= '(bv-001 bv-111 bv-101 bv-011)
(run* [q]
(smt-decl q '(_ BitVec 3))
(smtc `(~'= ~q (~'bvor ~q ~'bv-001)))
smt-purge))))
(deftest custom-datatypes-1
(is (= '([(node 21 (as nil (TreeList Int)))
(node false (as nil (TreeList Bool)))])
(run 1 [t1 t2]
(smt-any [t1 t2]
'(declare-datatypes
(T)
((Tree leaf (node (value T) (children TreeList)))
(TreeList nil (cons (car Tree) (cdr TreeList))))))
(smt-decl t1 '(Tree Int))
(smt-decl t2 '(Tree Bool))
(smtc `(~'not (~'= ~t1 (~'as ~'leaf (~'Tree ~'Int)))))
(smtc `(~'> (~'value ~t1) 20))
(smtc `(~'not (~'is-leaf ~t2)))
(smtc `(~'not (~'value ~t2)))
smt-purge))))
|
3d96a3436aad48fd66b5c3e008487d38dcc76a468cc9aa09e5f6fb75686a8d12 | endobson/racket-grpc | slice.rkt | #lang racket/base
(require
"base-lib.rkt"
ffi/unsafe
ffi/unsafe/atomic
(rename-in
racket/contract
[-> c:->]))
(module* unsafe #f
(provide
_grpc-slice/arg ;; fun-syntax
_grpc-slice-pointer/arg ;; fun-syntax
_grpc-slice-pointer/output-arg ;; fun-syntax
(contract-out
[immobile-grpc-slice? predicate/c]
[malloc-immobile-grpc-slice (c:-> immobile-grpc-slice?)]
[free-immobile-grpc-slice (c:-> immobile-grpc-slice? void?)]
[immobile-grpc-slice->bytes (c:-> immobile-grpc-slice? bytes?)]
[_immobile-grpc-slice-pointer ctype?])))
(define-cstruct _grpc-slice-refcounted
([bytes _pointer]
[length _size]))
(define-cstruct _grpc-slice-inlined
([length _uint8]
[bytes (_array _uint8 (+ (ctype-sizeof _size) (ctype-sizeof _pointer) -1))]))
(define-cstruct _grpc-slice/ffi
([refcount _pointer]
[data (_union _grpc-slice-refcounted _grpc-slice-inlined)]))
(define-fun-syntax _grpc-slice/arg
(syntax-id-rules (_grpc-slice/arg)
[_grpc-slice/arg
(type: _grpc-slice/ffi
pre: (x => (begin
(unless (in-atomic-mode?)
(error '_grpc-slice/arg "Must be in atomic mode"))
(grpc-slice-from-copied-buffer x)))
post: (x => (grpc-slice-unref x)))]))
(define-fun-syntax _grpc-slice-pointer/arg
(syntax-id-rules (_grpc-slice-pointer/arg)
[_grpc-slice-painter/arg
(type: _grpc-slice/ffi-pointer
pre: (x => (begin
(unless (in-atomic-mode?)
(error '_grpc-slice-pointer/arg "Must be in atomic mode"))
(grpc-slice-from-copied-buffer x)))
post: (x => (grpc-slice-unref x)))]))
(define-fun-syntax _grpc-slice-pointer/output-arg
(syntax-id-rules (_grpc-slice-pointer/output-arg)
[_grpc-slice-painter/arg
(type: _grpc-slice/ffi-pointer
pre: (let ()
(unless (in-atomic-mode?)
(error '_grpc-slice-pointer/arg "Must be in atomic mode"))
(define p (malloc _grpc-slice/ffi))
(memset p 0 (ctype-sizeof _grpc-slice/ffi))
(ptr-ref p _grpc-slice/ffi))
post: (x =>
(begin0
(grpc-slice->bytes x)
(grpc-slice-unref x))))]))
(struct immobile-grpc-slice (pointer))
(define _immobile-grpc-slice-pointer
(make-ctype _grpc-slice/ffi-pointer
immobile-grpc-slice-pointer
(lambda (x) (error '_immobile-grpc-slice-pointer "Cannot make values"))))
(define grpc-slice-unref
(get-ffi-obj "grpc_slice_unref" lib-grpc
(_fun _grpc-slice/ffi -> _void)))
(define grpc-slice-from-copied-buffer
(get-ffi-obj "grpc_slice_from_copied_buffer" lib-grpc
(_fun (b : _bytes) (_size = (bytes-length b)) -> _grpc-slice/ffi)))
(define (grpc-slice->bytes slice)
(define-values (length start)
(if (grpc-slice/ffi-refcount slice)
(let ([data (union-ref (grpc-slice/ffi-data slice) 0)])
(values
(grpc-slice-refcounted-length data)
(grpc-slice-refcounted-bytes data)))
(let ([data (union-ref (grpc-slice/ffi-data slice) 1)])
(values
(grpc-slice-inlined-length data)
(array-ptr (grpc-slice-inlined-bytes data))))))
(define bytes (make-bytes length))
(memmove bytes start length)
bytes)
(define (malloc-immobile-grpc-slice)
(define slice (ptr-ref (malloc _grpc-slice/ffi 'raw) _grpc-slice/ffi))
(memset slice 0 (ctype-sizeof _grpc-slice/ffi))
(immobile-grpc-slice slice))
(define (free-immobile-grpc-slice slice)
(define ptr (immobile-grpc-slice-pointer slice))
(grpc-slice-unref ptr)
(free ptr))
(define (immobile-grpc-slice->bytes slice)
(grpc-slice->bytes (immobile-grpc-slice-pointer slice)))
| null | https://raw.githubusercontent.com/endobson/racket-grpc/7f3cca4b66f71490236c8db40f0011595f890fa0/ffi/slice.rkt | racket | fun-syntax
fun-syntax
fun-syntax | #lang racket/base
(require
"base-lib.rkt"
ffi/unsafe
ffi/unsafe/atomic
(rename-in
racket/contract
[-> c:->]))
(module* unsafe #f
(provide
(contract-out
[immobile-grpc-slice? predicate/c]
[malloc-immobile-grpc-slice (c:-> immobile-grpc-slice?)]
[free-immobile-grpc-slice (c:-> immobile-grpc-slice? void?)]
[immobile-grpc-slice->bytes (c:-> immobile-grpc-slice? bytes?)]
[_immobile-grpc-slice-pointer ctype?])))
(define-cstruct _grpc-slice-refcounted
([bytes _pointer]
[length _size]))
(define-cstruct _grpc-slice-inlined
([length _uint8]
[bytes (_array _uint8 (+ (ctype-sizeof _size) (ctype-sizeof _pointer) -1))]))
(define-cstruct _grpc-slice/ffi
([refcount _pointer]
[data (_union _grpc-slice-refcounted _grpc-slice-inlined)]))
(define-fun-syntax _grpc-slice/arg
(syntax-id-rules (_grpc-slice/arg)
[_grpc-slice/arg
(type: _grpc-slice/ffi
pre: (x => (begin
(unless (in-atomic-mode?)
(error '_grpc-slice/arg "Must be in atomic mode"))
(grpc-slice-from-copied-buffer x)))
post: (x => (grpc-slice-unref x)))]))
(define-fun-syntax _grpc-slice-pointer/arg
(syntax-id-rules (_grpc-slice-pointer/arg)
[_grpc-slice-painter/arg
(type: _grpc-slice/ffi-pointer
pre: (x => (begin
(unless (in-atomic-mode?)
(error '_grpc-slice-pointer/arg "Must be in atomic mode"))
(grpc-slice-from-copied-buffer x)))
post: (x => (grpc-slice-unref x)))]))
(define-fun-syntax _grpc-slice-pointer/output-arg
(syntax-id-rules (_grpc-slice-pointer/output-arg)
[_grpc-slice-painter/arg
(type: _grpc-slice/ffi-pointer
pre: (let ()
(unless (in-atomic-mode?)
(error '_grpc-slice-pointer/arg "Must be in atomic mode"))
(define p (malloc _grpc-slice/ffi))
(memset p 0 (ctype-sizeof _grpc-slice/ffi))
(ptr-ref p _grpc-slice/ffi))
post: (x =>
(begin0
(grpc-slice->bytes x)
(grpc-slice-unref x))))]))
(struct immobile-grpc-slice (pointer))
(define _immobile-grpc-slice-pointer
(make-ctype _grpc-slice/ffi-pointer
immobile-grpc-slice-pointer
(lambda (x) (error '_immobile-grpc-slice-pointer "Cannot make values"))))
(define grpc-slice-unref
(get-ffi-obj "grpc_slice_unref" lib-grpc
(_fun _grpc-slice/ffi -> _void)))
(define grpc-slice-from-copied-buffer
(get-ffi-obj "grpc_slice_from_copied_buffer" lib-grpc
(_fun (b : _bytes) (_size = (bytes-length b)) -> _grpc-slice/ffi)))
(define (grpc-slice->bytes slice)
(define-values (length start)
(if (grpc-slice/ffi-refcount slice)
(let ([data (union-ref (grpc-slice/ffi-data slice) 0)])
(values
(grpc-slice-refcounted-length data)
(grpc-slice-refcounted-bytes data)))
(let ([data (union-ref (grpc-slice/ffi-data slice) 1)])
(values
(grpc-slice-inlined-length data)
(array-ptr (grpc-slice-inlined-bytes data))))))
(define bytes (make-bytes length))
(memmove bytes start length)
bytes)
(define (malloc-immobile-grpc-slice)
(define slice (ptr-ref (malloc _grpc-slice/ffi 'raw) _grpc-slice/ffi))
(memset slice 0 (ctype-sizeof _grpc-slice/ffi))
(immobile-grpc-slice slice))
(define (free-immobile-grpc-slice slice)
(define ptr (immobile-grpc-slice-pointer slice))
(grpc-slice-unref ptr)
(free ptr))
(define (immobile-grpc-slice->bytes slice)
(grpc-slice->bytes (immobile-grpc-slice-pointer slice)))
|
3e9f7dac1142baa1e7c530d630dcd527010a4df59fb4c8eb2d8eef308d74035e | innoq/innoq-blockchain-erlang | erl_sals_chain_root.erl | -module(erl_sals_chain_root).
-export([init/2, info/3]).
init(Req, _Opts) ->
self() ! handle_request,
{cowboy_loop, Req, rumpelstielzchen}.
info(_Msg, Req, State) ->
Uuid = erl_sals_chain_uuid:get_uuid(),
BlockHeight = erl_sals_chain_keeper:get_index_of_last_block(),
Doc = {[{nodeId, Uuid}, {currentBlockHeight, BlockHeight}]},
Json = jiffy:encode(Doc),
Req2 = cowboy_req:reply(200,
#{<<"content-type">> => <<"application/json">>},
Json,
Req),
{stop, Req2, State}.
| null | https://raw.githubusercontent.com/innoq/innoq-blockchain-erlang/52187e5f572a3d9681fe172b38dd32758fde2602/erl_sals_chain/apps/erl_sals_chain/src/erl_sals_chain_root.erl | erlang | -module(erl_sals_chain_root).
-export([init/2, info/3]).
init(Req, _Opts) ->
self() ! handle_request,
{cowboy_loop, Req, rumpelstielzchen}.
info(_Msg, Req, State) ->
Uuid = erl_sals_chain_uuid:get_uuid(),
BlockHeight = erl_sals_chain_keeper:get_index_of_last_block(),
Doc = {[{nodeId, Uuid}, {currentBlockHeight, BlockHeight}]},
Json = jiffy:encode(Doc),
Req2 = cowboy_req:reply(200,
#{<<"content-type">> => <<"application/json">>},
Json,
Req),
{stop, Req2, State}.
|
|
317e992494340062752e75862ff5e44f1494c3562fdaac03571c2e8fbb1a08cd | electric-sql/vaxine | antidotec_set.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2014 SyncFree Consortium . All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(antidotec_set).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-include_lib("antidote_pb_codec/include/antidote_pb.hrl").
-behaviour(antidotec_datatype).
-export([
new/0,
new/1,
value/1,
dirty_value/1,
to_ops/2,
is_type/1,
type/0
]).
-export([
add/2,
remove/2,
contains/2
]).
-record(antidote_set, {
set :: sets:set(),
adds :: sets:set(),
rems :: sets:set()
}).
-export_type([antidote_set/0]).
-opaque antidote_set() :: #antidote_set{}.
-spec new() -> antidote_set().
new() ->
#antidote_set{set = sets:new(), adds = sets:new(), rems = sets:new()}.
-spec new(list() | sets:set()) -> antidote_set().
new(List) when is_list(List) ->
Set = sets:from_list(List),
#antidote_set{set = Set, adds = sets:new(), rems = sets:new()};
new(Set) ->
#antidote_set{set = Set, adds = sets:new(), rems = sets:new()}.
-spec value(antidote_set()) -> [term()].
value(#antidote_set{set = Set}) -> sets:to_list(Set).
-spec dirty_value(antidote_set()) -> [term()].
dirty_value(#antidote_set{set = Set, adds = Adds, rems = Rems}) ->
sets:to_list(sets:subtract(sets:union(Set, Adds), Rems)).
%% @doc Adds an element to the local set container.
-spec add(term(), antidote_set()) -> antidote_set().
add(Elem, #antidote_set{adds = Adds} = Fset) ->
Fset#antidote_set{adds = sets:add_element(Elem, Adds)}.
-spec remove(term(), antidote_set()) -> antidote_set().
remove(Elem, #antidote_set{rems = Rems} = Fset) ->
Fset#antidote_set{rems = sets:add_element(Elem, Rems)}.
-spec contains(term(), antidote_set()) -> boolean().
contains(Elem, #antidote_set{set = Set}) ->
sets:is_element(Elem, Set).
%% @doc Determines whether the passed term is a set container.
-spec is_type(term()) -> boolean().
is_type(T) ->
is_record(T, antidote_set).
%% @doc Returns the symbolic name of this container.
-spec type() -> set.
type() -> set.
to_ops(BoundObject, #antidote_set{adds = Adds, rems = Rems}) ->
R =
case sets:size(Rems) > 0 of
true -> [{BoundObject, remove_all, sets:to_list(Rems)}];
false -> []
end,
case sets:size(Adds) > 0 of
true -> [{BoundObject, add_all, sets:to_list(Adds)} | R];
false -> R
end.
%% ===================================================================
EUnit tests
%% ===================================================================
-ifdef(TEST).
add_op_test() ->
New = antidotec_set:new([]),
Set1 = antidotec_set:dirty_value(New),
?assertEqual([], Set1),
OneElement = antidotec_set:add(<<"value1">>, New),
Set2 = antidotec_set:dirty_value(OneElement),
?assertEqual([<<"value1">>], Set2).
add_op_existing_set_test() ->
New = antidotec_set:new([<<"elem1">>, <<"elem2">>, <<"elem3">>]),
ThreeElemSet = antidotec_set:dirty_value(New),
?assertEqual([<<"elem1">>, <<"elem2">>, <<"elem3">>], lists:sort(ThreeElemSet)),
AddElem = antidotec_set:add(<<"elem4">>, New),
S1 = antidotec_set:remove(<<"elem4">>, AddElem),
S2 = antidotec_set:remove(<<"elem2">>, S1),
TwoElemSet = antidotec_set:dirty_value(S2),
?assertEqual([<<"elem1">>, <<"elem3">>], lists:sort(TwoElemSet)).
-endif.
| null | https://raw.githubusercontent.com/electric-sql/vaxine/872a83ea8d4935a52c7b850bb17ab099ee9c346b/apps/antidotec_pb/src/antidotec_set.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
@doc Adds an element to the local set container.
@doc Determines whether the passed term is a set container.
@doc Returns the symbolic name of this container.
===================================================================
=================================================================== | Copyright ( c ) 2014 SyncFree Consortium . All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(antidotec_set).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-include_lib("antidote_pb_codec/include/antidote_pb.hrl").
-behaviour(antidotec_datatype).
-export([
new/0,
new/1,
value/1,
dirty_value/1,
to_ops/2,
is_type/1,
type/0
]).
-export([
add/2,
remove/2,
contains/2
]).
-record(antidote_set, {
set :: sets:set(),
adds :: sets:set(),
rems :: sets:set()
}).
-export_type([antidote_set/0]).
-opaque antidote_set() :: #antidote_set{}.
-spec new() -> antidote_set().
new() ->
#antidote_set{set = sets:new(), adds = sets:new(), rems = sets:new()}.
-spec new(list() | sets:set()) -> antidote_set().
new(List) when is_list(List) ->
Set = sets:from_list(List),
#antidote_set{set = Set, adds = sets:new(), rems = sets:new()};
new(Set) ->
#antidote_set{set = Set, adds = sets:new(), rems = sets:new()}.
-spec value(antidote_set()) -> [term()].
value(#antidote_set{set = Set}) -> sets:to_list(Set).
-spec dirty_value(antidote_set()) -> [term()].
dirty_value(#antidote_set{set = Set, adds = Adds, rems = Rems}) ->
sets:to_list(sets:subtract(sets:union(Set, Adds), Rems)).
-spec add(term(), antidote_set()) -> antidote_set().
add(Elem, #antidote_set{adds = Adds} = Fset) ->
Fset#antidote_set{adds = sets:add_element(Elem, Adds)}.
-spec remove(term(), antidote_set()) -> antidote_set().
remove(Elem, #antidote_set{rems = Rems} = Fset) ->
Fset#antidote_set{rems = sets:add_element(Elem, Rems)}.
-spec contains(term(), antidote_set()) -> boolean().
contains(Elem, #antidote_set{set = Set}) ->
sets:is_element(Elem, Set).
-spec is_type(term()) -> boolean().
is_type(T) ->
is_record(T, antidote_set).
-spec type() -> set.
type() -> set.
to_ops(BoundObject, #antidote_set{adds = Adds, rems = Rems}) ->
R =
case sets:size(Rems) > 0 of
true -> [{BoundObject, remove_all, sets:to_list(Rems)}];
false -> []
end,
case sets:size(Adds) > 0 of
true -> [{BoundObject, add_all, sets:to_list(Adds)} | R];
false -> R
end.
EUnit tests
-ifdef(TEST).
add_op_test() ->
New = antidotec_set:new([]),
Set1 = antidotec_set:dirty_value(New),
?assertEqual([], Set1),
OneElement = antidotec_set:add(<<"value1">>, New),
Set2 = antidotec_set:dirty_value(OneElement),
?assertEqual([<<"value1">>], Set2).
add_op_existing_set_test() ->
New = antidotec_set:new([<<"elem1">>, <<"elem2">>, <<"elem3">>]),
ThreeElemSet = antidotec_set:dirty_value(New),
?assertEqual([<<"elem1">>, <<"elem2">>, <<"elem3">>], lists:sort(ThreeElemSet)),
AddElem = antidotec_set:add(<<"elem4">>, New),
S1 = antidotec_set:remove(<<"elem4">>, AddElem),
S2 = antidotec_set:remove(<<"elem2">>, S1),
TwoElemSet = antidotec_set:dirty_value(S2),
?assertEqual([<<"elem1">>, <<"elem3">>], lists:sort(TwoElemSet)).
-endif.
|
7e140599a439811625023b003121f86310f3dee756759256499eb09c77042d3d | janestreet/base | test_globalize_lib.mli | (*_ Intentionally blank *)
| null | https://raw.githubusercontent.com/janestreet/base/1462b7d5458e96569275a1c673df968ecbf3342f/test/test_globalize_lib.mli | ocaml | _ Intentionally blank | |
f96da046ca9f5ed9dfd7a07480037c7780af2c15fa8e150d7ffba2551797ee7f | typelead/intellij-eta | JpsCompositeElement.hs | module FFI.Org.JetBrains.JPS.Model.JpsCompositeElement where
import P
import FFI.Org.JetBrains.JPS.Model.JpsElement
import FFI.Org.JetBrains.JPS.Model.JpsElementContainer
Start org.jetbrains.jps.model .
data JpsCompositeElement = JpsCompositeElement @org.jetbrains.jps.model.JpsCompositeElement
deriving Class
type instance Inherits JpsCompositeElement = '[JpsElement]
foreign import java unsafe getContainer :: Java JpsCompositeElement JpsElementContainer
End org.jetbrains.jps.model .
| null | https://raw.githubusercontent.com/typelead/intellij-eta/ee66d621aa0bfdf56d7d287279a9a54e89802cf9/plugin/src/main/eta/FFI/Org/JetBrains/JPS/Model/JpsCompositeElement.hs | haskell | module FFI.Org.JetBrains.JPS.Model.JpsCompositeElement where
import P
import FFI.Org.JetBrains.JPS.Model.JpsElement
import FFI.Org.JetBrains.JPS.Model.JpsElementContainer
Start org.jetbrains.jps.model .
data JpsCompositeElement = JpsCompositeElement @org.jetbrains.jps.model.JpsCompositeElement
deriving Class
type instance Inherits JpsCompositeElement = '[JpsElement]
foreign import java unsafe getContainer :: Java JpsCompositeElement JpsElementContainer
End org.jetbrains.jps.model .
|
|
61f05f8914ffe20e9ea1710b1159cb685cc968f9936558618ff68df74ea3fc08 | rd--/hsc3 | wrap.help.hs | wrap ; ln 2021 - 04 - 15 /
let s = sinOsc ar (sinOsc ar (1 / 40) 0 * 100 + 20000) 0
in wrap s (xLine ar (-1.0) (-0.01) 20 DoNothing) 1 * 0.1
---- ; drawings
UI.ui_baudline 4096 50 "linear" 2
| null | https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/wrap.help.hs | haskell | -- ; drawings | wrap ; ln 2021 - 04 - 15 /
let s = sinOsc ar (sinOsc ar (1 / 40) 0 * 100 + 20000) 0
in wrap s (xLine ar (-1.0) (-0.01) 20 DoNothing) 1 * 0.1
UI.ui_baudline 4096 50 "linear" 2
|
a47c6a8c007a4bee20f7c506a6091476f5d56ba077ed1b382bca33ba133a0037 | bobzhang/ocaml-book | basic_ulex.ml |
open Ulexing
open Batteries
let regexp op_ar = ['+' '-' '*' '/']
let regexp op_bool = ['!' '&' '|']
let regexp rel = ['=' '<' '>']
(** get string output, not int array *)
let lexeme = Ulexing.utf8_lexeme
let rec basic = lexer
| [' '] -> basic lexbuf
| op_ar | op_bool ->
let ar = lexeme lexbuf in
`Lsymbol ar
| "<=" | ">="| "<>" | rel ->
`Lsymbol (lexeme lexbuf)
|("REM" | "LET" | "PRINT"
| "INPUT" | "IF"| "THEN") ->
`Lsymbol (lexeme lexbuf)
| '-'?['0'-'9']+ ->
`Lint (int_of_string (lexeme lexbuf))
| ['A'-'z']+ ->
`Lident (lexeme lexbuf)
| '"' [^ '"'] '"' ->
`Lstring (let s = lexeme lexbuf in
String.sub s 1 (String.length s - 2))
| eof -> raise End_of_file
| _ ->
(print_endline (lexeme lexbuf ^ "unrecognized");
basic lexbuf)
let token_of_string str =
str
|> Stream.of_string
|> from_utf8_stream
|> basic
let tokens_of_string str =
let output = ref [] in
let lexbuf = str |> Stream.of_string |> from_utf8_stream in
(try
while true do
let token = basic lexbuf in
output:= token :: !output;
print_endline (dump token)
done
with End_of_file -> ());
List.rev (!output)
let _ = tokens_of_string
"a + b >= 3 > 3 < xx"
*
assert_failure , assert_equal , @ ? , assert_raises , skip_if , todo , cmp_float
bracket
assert_failure, assert_equal, @?, assert_raises, skip_if, todo, cmp_float
bracket
*)
let test_result = OUnit.(
run_test_tt ("test-suite" >:::
["test2" >:: (fun _ -> ());
"test1" >:: (fun _ -> "true" @? true)
]
))
;;
(**Remark
*)
| null | https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/code/basic_ulex.ml | ocaml | * get string output, not int array
*Remark
|
open Ulexing
open Batteries
let regexp op_ar = ['+' '-' '*' '/']
let regexp op_bool = ['!' '&' '|']
let regexp rel = ['=' '<' '>']
let lexeme = Ulexing.utf8_lexeme
let rec basic = lexer
| [' '] -> basic lexbuf
| op_ar | op_bool ->
let ar = lexeme lexbuf in
`Lsymbol ar
| "<=" | ">="| "<>" | rel ->
`Lsymbol (lexeme lexbuf)
|("REM" | "LET" | "PRINT"
| "INPUT" | "IF"| "THEN") ->
`Lsymbol (lexeme lexbuf)
| '-'?['0'-'9']+ ->
`Lint (int_of_string (lexeme lexbuf))
| ['A'-'z']+ ->
`Lident (lexeme lexbuf)
| '"' [^ '"'] '"' ->
`Lstring (let s = lexeme lexbuf in
String.sub s 1 (String.length s - 2))
| eof -> raise End_of_file
| _ ->
(print_endline (lexeme lexbuf ^ "unrecognized");
basic lexbuf)
let token_of_string str =
str
|> Stream.of_string
|> from_utf8_stream
|> basic
let tokens_of_string str =
let output = ref [] in
let lexbuf = str |> Stream.of_string |> from_utf8_stream in
(try
while true do
let token = basic lexbuf in
output:= token :: !output;
print_endline (dump token)
done
with End_of_file -> ());
List.rev (!output)
let _ = tokens_of_string
"a + b >= 3 > 3 < xx"
*
assert_failure , assert_equal , @ ? , assert_raises , skip_if , todo , cmp_float
bracket
assert_failure, assert_equal, @?, assert_raises, skip_if, todo, cmp_float
bracket
*)
let test_result = OUnit.(
run_test_tt ("test-suite" >:::
["test2" >:: (fun _ -> ());
"test1" >:: (fun _ -> "true" @? true)
]
))
;;
|
f1733428ca7cb0776dfa115613ed6e5fd1231b944200d561264e80e9d92166b5 | AccelerateHS/accelerate | Main.hs | -- |
-- Module : Main
Copyright : [ 2017 .. 2020 ] The Accelerate Team
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
module Main where
import Build_doctests ( flags, pkgs, module_sources )
import Data.Foldable ( traverse_ )
import Test.DocTest
main :: IO ()
main = do
traverse_ putStrLn args
doctest args
where
args = flags ++ pkgs ++ module_sources
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate/63e53be22aef32cd0b3b6f108e637716a92b72dc/test/doctest/Main.hs | haskell | |
Module : Main
License : BSD3
Stability : experimental
| Copyright : [ 2017 .. 2020 ] The Accelerate Team
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Main where
import Build_doctests ( flags, pkgs, module_sources )
import Data.Foldable ( traverse_ )
import Test.DocTest
main :: IO ()
main = do
traverse_ putStrLn args
doctest args
where
args = flags ++ pkgs ++ module_sources
|
410fb4984b0897686d8d1007fd6c60b07d666094a0c5151641db42fea77cfa04 | JoeDralliam/Ocsfml | myocamlbuild.ml | open Ocamlbuild_plugin
open OcamlbuildCpp
open Pathname
let link_to_static_sfml_libraries = false ;;
let compiler = List.hd (Compiler.available ()) ;;
let add_sfml_flags static =
let open FindSfml in
let modules = SfmlConfiguration.([System ; Window ; Graphics ; Audio ; Network]) in
let sfml = Sfml.find ~static compiler modules in
let libs_of_components lib =
List.map (fun cp -> Sfml.LibraryMap.find cp lib)
in
if static then flag ["c++"; "compile"] (A "-DSFML_STATIC") ;
let add_flags lib =
let open SfmlConfiguration in
let includedir = sfml.Sfml.includedir in
Library.register ~libraries:(libs_of_components lib [System])
~includedir "libsfml_system" compiler ;
Library.register ~libraries:(libs_of_components lib [System ; Window])
~includedir "libsfml_window" compiler ;
Library.register ~libraries:(libs_of_components lib [System ; Window ; Graphics])
~includedir "libsfml_graphics" compiler ;
Library.register ~libraries:(libs_of_components lib [System ; Audio])
~includedir "libsfml_audio" compiler ;
Library.register ~libraries:(libs_of_components lib [System ; Network])
~includedir "libsfml_network" compiler ;
in
let stub_dir s =
Printf.sprintf "../Ocsfml%s/ocsfml_%s_stub" (String.capitalize s) s
in
let add_path modname =
A (Compiler.BuildFlags.add_include_path (stub_dir modname) compiler)
in
flag [ "compile" ; "c++" ; "include_sfml_system" ]
(S [ add_path "system" ]) ;
flag [ "compile" ; "c++" ; "include_sfml_window" ]
(S [ add_path "system" ; add_path "window" ]) ;
flag [ "compile" ; "c++" ; "include_sfml_graphics" ]
(S [ add_path "system" ; add_path "window" ; add_path "graphics" ]) ;
flag [ "compile" ; "c++" ; "include_sfml_audio" ]
(S [ add_path "system" ; add_path "audio" ]) ;
flag [ "compile" ; "c++" ; "include_sfml_network" ]
(S [ add_path "system" ; add_path "network" ]) ;
List.iter (fun s ->
let d = Printf.sprintf "Ocsfml%s" (String.capitalize s) in
mark_tag_used ("use_libocsfml"^s) ;
dep ["link"; "ocaml"; "native"; "use_libocsfml"^s]
[d^"/libocsfml"^s^"."^(!Options.ext_lib)] ;
dep ["link"; "ocaml"; "byte"; "use_libocsfml"^s]
[d^"/dllocsfml"^s^"."^(!Options.ext_dll)] ;
ocaml_lib (d ^ "/ocsfml" ^ s);
) ["system" ; "window" ; "graphics" ; "audio" ; "network"] ;
add_flags sfml.Sfml.library ;
if fst compiler = Compiler.Clang
then (
flag ["ocamlmklib"] (S [A"-lc++"]) ;
)
else if Compiler.frontend compiler = Compiler.GccCompatible
then (
flag ["compile" ; "c++" ] (S [A "-fvisibility=hidden"]) ;
flag ["ocamlmklib" ] (S [A "-lstdc++"]) ;
)
let add_other_flags () =
let open FindBoost.Boost in
let boost = find compiler [] in
flag [ "c++" ; "compile"]
(A (Compiler.BuildFlags.add_include_path boost.FindBoost.Boost.includedir compiler)) ;
let ocaml_dir = input_line (Unix.open_process_in "ocamlc -where") in
flag [ "c++" ; "compile" ]
(A (Compiler.BuildFlags.add_include_path ocaml_dir compiler)) ;
let camlpp_dir = "../camlpp" in
flag [ "c++" ; "compile" ]
(A (Compiler.BuildFlags.add_include_path camlpp_dir compiler)) ;
flag [ "c++" ; "compile" ; "gcc"] (A "-std=c++0x") ;
flag [ "c++" ; "compile" ; "mingw"] (A "-std=c++0x") ;
flag [ "c++" ; "compile" ; "clang"] (A "-std=c++0x") ;
flag [ "c++" ; "compile" ; "clang"] (A "-stdlib=libc++") ;
flag [ "c++" ; "compile" ; "msvc"] (A "/D_VARIADIC_MAX=10")
let _ = dispatch (function
| Before_rules ->
Rule.add_cpp_rules compiler ;
Rule.add_cpp_common_tags () ;
add_sfml_flags link_to_static_sfml_libraries ;
add_other_flags ()
| After_rules ->
flag ["ocaml"; "doc" ; "colorize_code"] & A "-colorize-code" ;
flag ["ocaml"; "doc" ; "custom_intro"]
& S [ A "-intro" ; A "../Documentation/intro.camldoc" ]
| _ -> ()
)
| null | https://raw.githubusercontent.com/JoeDralliam/Ocsfml/e1bf50665aa34dea4e4d249bf73ab0036b3731fb/myocamlbuild.ml | ocaml | open Ocamlbuild_plugin
open OcamlbuildCpp
open Pathname
let link_to_static_sfml_libraries = false ;;
let compiler = List.hd (Compiler.available ()) ;;
let add_sfml_flags static =
let open FindSfml in
let modules = SfmlConfiguration.([System ; Window ; Graphics ; Audio ; Network]) in
let sfml = Sfml.find ~static compiler modules in
let libs_of_components lib =
List.map (fun cp -> Sfml.LibraryMap.find cp lib)
in
if static then flag ["c++"; "compile"] (A "-DSFML_STATIC") ;
let add_flags lib =
let open SfmlConfiguration in
let includedir = sfml.Sfml.includedir in
Library.register ~libraries:(libs_of_components lib [System])
~includedir "libsfml_system" compiler ;
Library.register ~libraries:(libs_of_components lib [System ; Window])
~includedir "libsfml_window" compiler ;
Library.register ~libraries:(libs_of_components lib [System ; Window ; Graphics])
~includedir "libsfml_graphics" compiler ;
Library.register ~libraries:(libs_of_components lib [System ; Audio])
~includedir "libsfml_audio" compiler ;
Library.register ~libraries:(libs_of_components lib [System ; Network])
~includedir "libsfml_network" compiler ;
in
let stub_dir s =
Printf.sprintf "../Ocsfml%s/ocsfml_%s_stub" (String.capitalize s) s
in
let add_path modname =
A (Compiler.BuildFlags.add_include_path (stub_dir modname) compiler)
in
flag [ "compile" ; "c++" ; "include_sfml_system" ]
(S [ add_path "system" ]) ;
flag [ "compile" ; "c++" ; "include_sfml_window" ]
(S [ add_path "system" ; add_path "window" ]) ;
flag [ "compile" ; "c++" ; "include_sfml_graphics" ]
(S [ add_path "system" ; add_path "window" ; add_path "graphics" ]) ;
flag [ "compile" ; "c++" ; "include_sfml_audio" ]
(S [ add_path "system" ; add_path "audio" ]) ;
flag [ "compile" ; "c++" ; "include_sfml_network" ]
(S [ add_path "system" ; add_path "network" ]) ;
List.iter (fun s ->
let d = Printf.sprintf "Ocsfml%s" (String.capitalize s) in
mark_tag_used ("use_libocsfml"^s) ;
dep ["link"; "ocaml"; "native"; "use_libocsfml"^s]
[d^"/libocsfml"^s^"."^(!Options.ext_lib)] ;
dep ["link"; "ocaml"; "byte"; "use_libocsfml"^s]
[d^"/dllocsfml"^s^"."^(!Options.ext_dll)] ;
ocaml_lib (d ^ "/ocsfml" ^ s);
) ["system" ; "window" ; "graphics" ; "audio" ; "network"] ;
add_flags sfml.Sfml.library ;
if fst compiler = Compiler.Clang
then (
flag ["ocamlmklib"] (S [A"-lc++"]) ;
)
else if Compiler.frontend compiler = Compiler.GccCompatible
then (
flag ["compile" ; "c++" ] (S [A "-fvisibility=hidden"]) ;
flag ["ocamlmklib" ] (S [A "-lstdc++"]) ;
)
let add_other_flags () =
let open FindBoost.Boost in
let boost = find compiler [] in
flag [ "c++" ; "compile"]
(A (Compiler.BuildFlags.add_include_path boost.FindBoost.Boost.includedir compiler)) ;
let ocaml_dir = input_line (Unix.open_process_in "ocamlc -where") in
flag [ "c++" ; "compile" ]
(A (Compiler.BuildFlags.add_include_path ocaml_dir compiler)) ;
let camlpp_dir = "../camlpp" in
flag [ "c++" ; "compile" ]
(A (Compiler.BuildFlags.add_include_path camlpp_dir compiler)) ;
flag [ "c++" ; "compile" ; "gcc"] (A "-std=c++0x") ;
flag [ "c++" ; "compile" ; "mingw"] (A "-std=c++0x") ;
flag [ "c++" ; "compile" ; "clang"] (A "-std=c++0x") ;
flag [ "c++" ; "compile" ; "clang"] (A "-stdlib=libc++") ;
flag [ "c++" ; "compile" ; "msvc"] (A "/D_VARIADIC_MAX=10")
let _ = dispatch (function
| Before_rules ->
Rule.add_cpp_rules compiler ;
Rule.add_cpp_common_tags () ;
add_sfml_flags link_to_static_sfml_libraries ;
add_other_flags ()
| After_rules ->
flag ["ocaml"; "doc" ; "colorize_code"] & A "-colorize-code" ;
flag ["ocaml"; "doc" ; "custom_intro"]
& S [ A "-intro" ; A "../Documentation/intro.camldoc" ]
| _ -> ()
)
|
|
9abba96bcddb970451c9a56ee5233bb760aa5e4181ba08ccc7ba7a354dec6683 | mwsundberg/2020-brickhack | proper_ribbons.cljs | (ns brickhack.proper-ribbons
(:require [brickhack.common :as c]
[quil.core :as q]
[quil.middleware :as middleware]))
(def body (.-body js/document))
(def w (.-clientWidth body))
(def h (.-clientHeight body))
; This-sketch custom code
(def palette (rand-nth c/palettes))
(defn trail
[id]
(c/particle-trail id (q/random w) (q/random h) (rand-nth (:colors palette))))
changes how zoomed in on curves the thing is ( smaller = = smoother , generally < 1 )
(def step-scalar 1.75) ; changes how much each point jumps
(defn noise-field-radian
"Get a position dependent radian"
[x y]
(* 4 Math/PI (c/noise-field x y noise-zoom)))
(defn polygon-to-baseboard
[point1 point2 h]
(apply q/fill (:color point1))
(q/begin-shape)
(q/vertex (:x point1) h)
(q/vertex (:x point1) (:y point1))
(q/vertex (:x point2) (:y point2))
(q/vertex (:x point2) h)
(q/end-shape :close))
; Start of the sketch codes
(defn sketch-setup []
Set color mode to HSB ( HSV ) instead of default RGB
(q/color-mode :hsb 360 100 100 1.0)
(q/no-stroke)
(apply q/background (:background palette))
Create 2000 particles at the start
; (render-field w h)
(q/no-stroke)
(sort-by (fn [trail]
(:y (first (:points trail))))
(map trail (range 0 20))))
(defn sketch-update [trails]
(->> trails
(map (fn [trail]
(let [points (:points trail)
velocity (c/point-sub (first points) (second points))
theta (noise-field-radian (:x (first points)) (:y (first points)))
new-velocity {:x (c/average (:x velocity) (Math/cos theta))
:y (c/average (:y velocity) (Math/sin theta))}]
(assoc trail :points
(cons (c/point-add (first points) (c/point-scale step-scalar new-velocity))
points)))))))
(defn sketch-draw [trails]
(apply q/background (:background palette))
; Reduce each trail to a list of point pairs (ready for cons-ing)
(as-> trails val
; Replace each trail with a list of pairs
(map
(fn [trail]
(partition 2 1 (:points trail)))
val)
; Merge all of the trails' points
(apply concat val)
; Sort them on the y axis
(sort-by
(fn
[point-pair]
(:y (first point-pair)))
val)
; Hopefully this works
(doseq [point-pair val]
(polygon-to-baseboard (first point-pair) (second point-pair) h))))
(defn create [canvas]
(q/sketch
:host canvas
:size [w h]
:draw #'sketch-draw
:setup #'sketch-setup
:update #'sketch-update
:middleware [middleware/fun-mode]
:settings (fn []
(q/random-seed 432)
(q/noise-seed 432))))
(defonce sketch (create "sketch"))
| null | https://raw.githubusercontent.com/mwsundberg/2020-brickhack/522855b897aa57c346d79d7a594cf99e7d381b76/src/brickhack/proper_ribbons.cljs | clojure | This-sketch custom code
changes how much each point jumps
Start of the sketch codes
(render-field w h)
Reduce each trail to a list of point pairs (ready for cons-ing)
Replace each trail with a list of pairs
Merge all of the trails' points
Sort them on the y axis
Hopefully this works | (ns brickhack.proper-ribbons
(:require [brickhack.common :as c]
[quil.core :as q]
[quil.middleware :as middleware]))
(def body (.-body js/document))
(def w (.-clientWidth body))
(def h (.-clientHeight body))
(def palette (rand-nth c/palettes))
(defn trail
[id]
(c/particle-trail id (q/random w) (q/random h) (rand-nth (:colors palette))))
changes how zoomed in on curves the thing is ( smaller = = smoother , generally < 1 )
(defn noise-field-radian
"Get a position dependent radian"
[x y]
(* 4 Math/PI (c/noise-field x y noise-zoom)))
(defn polygon-to-baseboard
[point1 point2 h]
(apply q/fill (:color point1))
(q/begin-shape)
(q/vertex (:x point1) h)
(q/vertex (:x point1) (:y point1))
(q/vertex (:x point2) (:y point2))
(q/vertex (:x point2) h)
(q/end-shape :close))
(defn sketch-setup []
Set color mode to HSB ( HSV ) instead of default RGB
(q/color-mode :hsb 360 100 100 1.0)
(q/no-stroke)
(apply q/background (:background palette))
Create 2000 particles at the start
(q/no-stroke)
(sort-by (fn [trail]
(:y (first (:points trail))))
(map trail (range 0 20))))
(defn sketch-update [trails]
(->> trails
(map (fn [trail]
(let [points (:points trail)
velocity (c/point-sub (first points) (second points))
theta (noise-field-radian (:x (first points)) (:y (first points)))
new-velocity {:x (c/average (:x velocity) (Math/cos theta))
:y (c/average (:y velocity) (Math/sin theta))}]
(assoc trail :points
(cons (c/point-add (first points) (c/point-scale step-scalar new-velocity))
points)))))))
(defn sketch-draw [trails]
(apply q/background (:background palette))
(as-> trails val
(map
(fn [trail]
(partition 2 1 (:points trail)))
val)
(apply concat val)
(sort-by
(fn
[point-pair]
(:y (first point-pair)))
val)
(doseq [point-pair val]
(polygon-to-baseboard (first point-pair) (second point-pair) h))))
(defn create [canvas]
(q/sketch
:host canvas
:size [w h]
:draw #'sketch-draw
:setup #'sketch-setup
:update #'sketch-update
:middleware [middleware/fun-mode]
:settings (fn []
(q/random-seed 432)
(q/noise-seed 432))))
(defonce sketch (create "sketch"))
|
358f785dbe26afe11b11b000954eb220c9b2086210ad3ecfc4763487c676095f | gafiatulin/codewars | Backronym.hs | -- makeBackronym
-- /
module Codewars.Exercise.Backronym where
import Codewars.Exercise.Backronym.Dictionary (dict)
import Data.Char (toUpper)
makeBackronym :: String -> String
makeBackronym = unwords . map (dict . toUpper)
| null | https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/7%20kyu/Backronym.hs | haskell | makeBackronym
/ |
module Codewars.Exercise.Backronym where
import Codewars.Exercise.Backronym.Dictionary (dict)
import Data.Char (toUpper)
makeBackronym :: String -> String
makeBackronym = unwords . map (dict . toUpper)
|
03c6d9ebe85b1da4989130de1b51a8d43f2db8902045e4e8f3b7e40bd3ac3fa4 | metabase/metabase | metric.clj | (ns metabase.api.metric
"/api/metric endpoints."
(:require
[clojure.data :as data]
[compojure.core :refer [DELETE GET POST PUT]]
[metabase.api.common :as api]
[metabase.api.query-description :as api.qd]
[metabase.events :as events]
[metabase.mbql.normalize :as mbql.normalize]
[metabase.models.interface :as mi]
[metabase.models.metric :as metric :refer [Metric]]
[metabase.models.revision :as revision]
[metabase.models.table :refer [Table]]
[metabase.related :as related]
[metabase.util :as u]
[metabase.util.i18n :refer [trs]]
[metabase.util.log :as log]
[metabase.util.schema :as su]
[schema.core :as s]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]]))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema POST "/"
"Create a new `Metric`."
[:as {{:keys [name description table_id definition], :as body} :body}]
{name su/NonBlankString
table_id su/IntGreaterThanZero
definition su/Map
description (s/maybe s/Str)}
;; TODO - why can't set the other properties like `show_in_getting_started` when you create a Metric?
(api/create-check Metric body)
(let [metric (api/check-500
(db/insert! Metric
:table_id table_id
:creator_id api/*current-user-id*
:name name
:description description
:definition definition))]
(-> (events/publish-event! :metric-create metric)
(hydrate :creator))))
(s/defn ^:private hydrated-metric [id :- su/IntGreaterThanZero]
(-> (api/read-check (db/select-one Metric :id id))
(hydrate :creator)))
(defn- add-query-descriptions
[metrics] {:pre [(coll? metrics)]}
(when (some? metrics)
(for [metric metrics]
(let [table (db/select-one Table :id (:table_id metric))]
(assoc metric
:query_description
(api.qd/generate-query-description table (:definition metric)))))))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema GET "/:id"
"Fetch `Metric` with ID."
[id]
(first (add-query-descriptions [(hydrated-metric id)])))
(defn- add-db-ids
"Add `:database_id` fields to `metrics` by looking them up from their `:table_id`."
[metrics]
(when (seq metrics)
(let [table-id->db-id (db/select-id->field :db_id Table, :id [:in (set (map :table_id metrics))])]
(for [metric metrics]
(assoc metric :database_id (table-id->db-id (:table_id metric)))))))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema GET "/"
"Fetch *all* `Metrics`."
[]
(as-> (db/select Metric, :archived false, {:order-by [:%lower.name]}) metrics
(hydrate metrics :creator)
(add-db-ids metrics)
(filter mi/can-read? metrics)
(add-query-descriptions metrics)))
(defn- write-check-and-update-metric!
"Check whether current user has write permissions, then update Metric with values in `body`. Publishes appropriate
event and returns updated/hydrated Metric."
[id {:keys [revision_message] :as body}]
(let [existing (api/write-check Metric id)
clean-body (u/select-keys-when body
:present #{:description :caveats :how_is_this_calculated :points_of_interest}
:non-nil #{:archived :definition :name :show_in_getting_started})
new-def (->> clean-body :definition (mbql.normalize/normalize-fragment []))
new-body (merge
(dissoc clean-body :revision_message)
(when new-def {:definition new-def}))
changes (when-not (= new-body existing)
new-body)
archive? (:archived changes)]
(when changes
(db/update! Metric id changes))
(u/prog1 (hydrated-metric id)
(events/publish-event! (if archive? :metric-delete :metric-update)
(assoc <> :actor_id api/*current-user-id*, :revision_message revision_message)))))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema PUT "/:id"
"Update a `Metric` with ID."
[id :as {{:keys [name definition revision_message archived caveats description how_is_this_calculated
points_of_interest show_in_getting_started]
:as body} :body}]
{name (s/maybe su/NonBlankString)
definition (s/maybe su/Map)
revision_message su/NonBlankString
archived (s/maybe s/Bool)
caveats (s/maybe s/Str)
description (s/maybe s/Str)
how_is_this_calculated (s/maybe s/Str)
points_of_interest (s/maybe s/Str)
show_in_getting_started (s/maybe s/Bool)}
(write-check-and-update-metric! id body))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema PUT "/:id/important_fields"
"Update the important `Fields` for a `Metric` with ID.
(This is used for the Getting Started guide)."
[id :as {{:keys [important_field_ids]} :body}]
{important_field_ids [su/IntGreaterThanZero]}
(api/check-superuser)
(api/write-check Metric id)
(api/check (<= (count important_field_ids) 3)
[400 "A Metric can have a maximum of 3 important fields."])
(let [[fields-to-remove fields-to-add] (data/diff (set (db/select-field :field_id 'MetricImportantField :metric_id id))
(set important_field_ids))]
;; delete old fields as needed
(when (seq fields-to-remove)
(db/simple-delete! 'MetricImportantField {:metric_id id, :field_id [:in fields-to-remove]}))
;; add new fields as needed
(db/insert-many! 'MetricImportantField (for [field-id fields-to-add]
{:metric_id id, :field_id field-id}))
{:success true}))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema DELETE "/:id"
"Archive a Metric. (DEPRECATED -- Just pass updated value of `:archived` to the `PUT` endpoint instead.)"
[id revision_message]
{revision_message su/NonBlankString}
(log/warn
(trs "DELETE /api/metric/:id is deprecated. Instead, change its `archived` value via PUT /api/metric/:id."))
(write-check-and-update-metric! id {:archived true, :revision_message revision_message})
api/generic-204-no-content)
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema GET "/:id/revisions"
"Fetch `Revisions` for `Metric` with ID."
[id]
(api/read-check Metric id)
(revision/revisions+details Metric id))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema POST "/:id/revert"
"Revert a `Metric` to a prior `Revision`."
[id :as {{:keys [revision_id]} :body}]
{revision_id su/IntGreaterThanZero}
(api/write-check Metric id)
(revision/revert!
:entity Metric
:id id
:user-id api/*current-user-id*
:revision-id revision_id))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema GET "/:id/related"
"Return related entities."
[id]
(-> (db/select-one Metric :id id) api/read-check related/related))
(api/define-routes)
| null | https://raw.githubusercontent.com/metabase/metabase/dad3d414e5bec482c15d826dcc97772412c98652/src/metabase/api/metric.clj | clojure | TODO - why can't set the other properties like `show_in_getting_started` when you create a Metric?
delete old fields as needed
add new fields as needed | (ns metabase.api.metric
"/api/metric endpoints."
(:require
[clojure.data :as data]
[compojure.core :refer [DELETE GET POST PUT]]
[metabase.api.common :as api]
[metabase.api.query-description :as api.qd]
[metabase.events :as events]
[metabase.mbql.normalize :as mbql.normalize]
[metabase.models.interface :as mi]
[metabase.models.metric :as metric :refer [Metric]]
[metabase.models.revision :as revision]
[metabase.models.table :refer [Table]]
[metabase.related :as related]
[metabase.util :as u]
[metabase.util.i18n :refer [trs]]
[metabase.util.log :as log]
[metabase.util.schema :as su]
[schema.core :as s]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]]))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema POST "/"
"Create a new `Metric`."
[:as {{:keys [name description table_id definition], :as body} :body}]
{name su/NonBlankString
table_id su/IntGreaterThanZero
definition su/Map
description (s/maybe s/Str)}
(api/create-check Metric body)
(let [metric (api/check-500
(db/insert! Metric
:table_id table_id
:creator_id api/*current-user-id*
:name name
:description description
:definition definition))]
(-> (events/publish-event! :metric-create metric)
(hydrate :creator))))
(s/defn ^:private hydrated-metric [id :- su/IntGreaterThanZero]
(-> (api/read-check (db/select-one Metric :id id))
(hydrate :creator)))
(defn- add-query-descriptions
[metrics] {:pre [(coll? metrics)]}
(when (some? metrics)
(for [metric metrics]
(let [table (db/select-one Table :id (:table_id metric))]
(assoc metric
:query_description
(api.qd/generate-query-description table (:definition metric)))))))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema GET "/:id"
"Fetch `Metric` with ID."
[id]
(first (add-query-descriptions [(hydrated-metric id)])))
(defn- add-db-ids
"Add `:database_id` fields to `metrics` by looking them up from their `:table_id`."
[metrics]
(when (seq metrics)
(let [table-id->db-id (db/select-id->field :db_id Table, :id [:in (set (map :table_id metrics))])]
(for [metric metrics]
(assoc metric :database_id (table-id->db-id (:table_id metric)))))))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema GET "/"
"Fetch *all* `Metrics`."
[]
(as-> (db/select Metric, :archived false, {:order-by [:%lower.name]}) metrics
(hydrate metrics :creator)
(add-db-ids metrics)
(filter mi/can-read? metrics)
(add-query-descriptions metrics)))
(defn- write-check-and-update-metric!
"Check whether current user has write permissions, then update Metric with values in `body`. Publishes appropriate
event and returns updated/hydrated Metric."
[id {:keys [revision_message] :as body}]
(let [existing (api/write-check Metric id)
clean-body (u/select-keys-when body
:present #{:description :caveats :how_is_this_calculated :points_of_interest}
:non-nil #{:archived :definition :name :show_in_getting_started})
new-def (->> clean-body :definition (mbql.normalize/normalize-fragment []))
new-body (merge
(dissoc clean-body :revision_message)
(when new-def {:definition new-def}))
changes (when-not (= new-body existing)
new-body)
archive? (:archived changes)]
(when changes
(db/update! Metric id changes))
(u/prog1 (hydrated-metric id)
(events/publish-event! (if archive? :metric-delete :metric-update)
(assoc <> :actor_id api/*current-user-id*, :revision_message revision_message)))))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema PUT "/:id"
"Update a `Metric` with ID."
[id :as {{:keys [name definition revision_message archived caveats description how_is_this_calculated
points_of_interest show_in_getting_started]
:as body} :body}]
{name (s/maybe su/NonBlankString)
definition (s/maybe su/Map)
revision_message su/NonBlankString
archived (s/maybe s/Bool)
caveats (s/maybe s/Str)
description (s/maybe s/Str)
how_is_this_calculated (s/maybe s/Str)
points_of_interest (s/maybe s/Str)
show_in_getting_started (s/maybe s/Bool)}
(write-check-and-update-metric! id body))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema PUT "/:id/important_fields"
"Update the important `Fields` for a `Metric` with ID.
(This is used for the Getting Started guide)."
[id :as {{:keys [important_field_ids]} :body}]
{important_field_ids [su/IntGreaterThanZero]}
(api/check-superuser)
(api/write-check Metric id)
(api/check (<= (count important_field_ids) 3)
[400 "A Metric can have a maximum of 3 important fields."])
(let [[fields-to-remove fields-to-add] (data/diff (set (db/select-field :field_id 'MetricImportantField :metric_id id))
(set important_field_ids))]
(when (seq fields-to-remove)
(db/simple-delete! 'MetricImportantField {:metric_id id, :field_id [:in fields-to-remove]}))
(db/insert-many! 'MetricImportantField (for [field-id fields-to-add]
{:metric_id id, :field_id field-id}))
{:success true}))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema DELETE "/:id"
"Archive a Metric. (DEPRECATED -- Just pass updated value of `:archived` to the `PUT` endpoint instead.)"
[id revision_message]
{revision_message su/NonBlankString}
(log/warn
(trs "DELETE /api/metric/:id is deprecated. Instead, change its `archived` value via PUT /api/metric/:id."))
(write-check-and-update-metric! id {:archived true, :revision_message revision_message})
api/generic-204-no-content)
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema GET "/:id/revisions"
"Fetch `Revisions` for `Metric` with ID."
[id]
(api/read-check Metric id)
(revision/revisions+details Metric id))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema POST "/:id/revert"
"Revert a `Metric` to a prior `Revision`."
[id :as {{:keys [revision_id]} :body}]
{revision_id su/IntGreaterThanZero}
(api/write-check Metric id)
(revision/revert!
:entity Metric
:id id
:user-id api/*current-user-id*
:revision-id revision_id))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema GET "/:id/related"
"Return related entities."
[id]
(-> (db/select-one Metric :id id) api/read-check related/related))
(api/define-routes)
|
a6b8d1767d49b2f72ebd6e8879f7ec8a55afa4ee9e5d285913273f18c566078b | mtolly/onyxite-customs | GuitarHero1.hs | # LANGUAGE LambdaCase #
# LANGUAGE OverloadedRecordDot #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
# LANGUAGE TupleSections #
module Onyx.Build.GuitarHero1 where
import Control.Monad.Extra
import Control.Monad.Random (evalRand, mkStdGen)
import Control.Monad.Trans.Resource
import Data.Bifunctor (bimap, first)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import Data.Conduit.Audio
import Data.Default.Class (def)
import qualified Data.EventList.Relative.TimeBody as RTB
import Data.Foldable (toList)
import Data.Hashable (Hashable, hash)
import qualified Data.HashMap.Strict as HM
import qualified Data.Map as Map
import Data.Maybe (fromMaybe, isJust,
isNothing)
import qualified Data.Text as T
import Development.Shake hiding (phony, (%>))
import Development.Shake.FilePath
import Onyx.Audio
import Onyx.Audio.VGS (writeVGSMultiRate)
import Onyx.Build.Common
import Onyx.Build.GuitarHero2.Logic (GH2AudioSection (..),
adjustSongText)
import Onyx.Build.RB3CH (BasicTiming (..),
basicTiming, makeMoods)
import Onyx.Codec.Common (valueId)
import Onyx.Guitar
import qualified Onyx.Harmonix.DTA as D
import qualified Onyx.Harmonix.DTA.Serialize as D
import qualified Onyx.Harmonix.DTA.Serialize.GH1 as D
import qualified Onyx.Harmonix.DTA.Serialize.Magma as Magma
import Onyx.Harmonix.DTA.Serialize.RockBand (AnimTempo (..))
import Onyx.Harmonix.GH1.File
import Onyx.Harmonix.GH2.PartGuitar (HandMap (..),
PartDifficulty (..))
import Onyx.MIDI.Common
import qualified Onyx.MIDI.Track.Drums as RB
import qualified Onyx.MIDI.Track.File as F
import qualified Onyx.MIDI.Track.FiveFret as RB
import qualified Onyx.MIDI.Track.Vocal as RB
import Onyx.Mode
import Onyx.Overdrive (removeNotelessOD)
import Onyx.Project
import Onyx.Reductions (completeFiveResult)
import Onyx.StackTrace
import qualified Sound.MIDI.Util as U
gh1Pad
:: (SendMessage m)
=> F.Song (GH1File U.Beats)
-> StackTraceT m (F.Song (GH1File U.Beats), Int)
gh1Pad rb3@(F.Song tmap _ trks) = let
firstEvent rtb = case RTB.viewL rtb of
Just ((dt, _), _) -> dt
Nothing -> 999
firstNoteBeats = foldr min 999 $ map (firstEvent . partGems) $ Map.elems $ gemsDifficulties $ gh1T1Gems trks
firstNoteSeconds = U.applyTempoMap tmap firstNoteBeats
no idea but just going with similar value to what Magma enforces for RB
padSeconds = max 0 $ ceiling $ 2.6 - (realToFrac firstNoteSeconds :: Rational)
in case padSeconds of
0 -> do
return (rb3, 0)
_ -> do
warn $ "Padding song by " ++ show padSeconds ++ "s due to early notes."
return (F.padAnyFile padSeconds rb3, padSeconds)
data GH1Audio = GH1Audio
{ gh1AudioSections :: [GH2AudioSection]
, gh1LeadChannels :: [Int]
, gh1BackChannels :: [Int]
, gh1LeadTrack :: F.FlexPartName
, gh1AnimBass :: Maybe F.FlexPartName
, gh1AnimDrums :: Maybe F.FlexPartName
, gh1AnimVocal :: Maybe F.FlexPartName
, gh1AnimKeys :: Maybe F.FlexPartName
}
computeGH1Audio
:: (Monad m)
=> SongYaml f
-> TargetGH1
-> (F.FlexPartName -> Bool) -- True if part has own audio
-> StackTraceT m GH1Audio
computeGH1Audio song target hasAudio = do
let canGetFiveFret = \case
Nothing -> False
Just part -> isJust $ anyFiveFret part
gh1LeadTrack <- if canGetFiveFret $ getPart target.guitar song
then return target.guitar
else fatal "computeGH1Audio: no lead guitar part selected"
let leadAudio = hasAudio gh1LeadTrack
gh1AudioSections = GH2Band : if leadAudio
then [GH2PartStereo gh1LeadTrack]
-- A single guitar track apparently doesn't work;
-- guitar also takes over channel 0 (left backing track) somehow?
So use two channels like all disc songs
else [GH2Silent, GH2Silent]
gh1LeadChannels = [2, 3] -- always stereo as per above
gh1BackChannels = [0, 1] -- should always be this for our output
gh1AnimBass = target.bass <$ (getPart target.bass song >>= (.grybo))
gh1AnimDrums = target.drums <$ (getPart target.drums song >>= (.drums))
gh1AnimVocal = target.vocal <$ (getPart target.vocal song >>= (.vocal))
gh1AnimKeys = target.keys <$ (getPart target.keys song >>= (.grybo))
return GH1Audio{..}
midiRB3toGH1
:: (SendMessage m)
=> SongYaml f
-> GH1Audio
-> F.Song (F.OnyxFile U.Beats)
-> StackTraceT m U.Seconds
-> StackTraceT m (F.Song (GH1File U.Beats), Int)
midiRB3toGH1 song audio inputMid@(F.Song tmap mmap onyx) getAudioLen = do
timing <- basicTiming inputMid getAudioLen
let makePlayBools origMoods gems = let
moods = if RTB.null origMoods
then makeMoods tmap timing gems
else origMoods
in flip fmap moods $ \case
Mood_idle_realtime -> False
Mood_idle -> False
Mood_idle_intense -> False
Mood_play -> True
Mood_mellow -> True
Mood_intense -> True
Mood_play_solo -> True
makeDiffs fpart result = do
let _ = result :: FiveResult
gap :: U.Beats
gap = fromIntegral result.settings.sustainGap / 480
editNotes
= fromClosed'
. noOpenNotes result.settings.detectMutedOpens
. noTaps
. noExtendedSustains' standardBlipThreshold gap
makeDiff diff notes = do
let notes' = editNotes notes
od <- removeNotelessOD
mmap
[(fpart, [(show diff, void notes')])]
((fpart,) <$> RB.fiveOverdrive result.other)
return PartDifficulty
{ partStarPower = snd <$> od
, partPlayer1 = RB.fivePlayer1 result.other
, partPlayer2 = RB.fivePlayer2 result.other
, partGems = RB.fiveGems $ emit5' notes'
, partForceHOPO = RTB.empty
, partForceStrum = RTB.empty
, partForceTap = RTB.empty
}
fmap Map.fromList
$ mapM (\(diff, notes) -> (diff,) <$> makeDiff diff notes)
$ Map.toList result.notes
getFive fpart = do
builder <- getPart fpart song >>= anyFiveFret
return $ builder FiveTypeGuitar ModeInput
{ tempo = tmap
, events = F.onyxEvents onyx
, part = F.getFlexPart fpart onyx
}
getLeadData fpart = case getFive fpart of
Nothing -> fatal "No guitar-compatible mode set up for lead guitar part"
Just result -> return $ completeFiveResult False mmap result
fiveResultMoods :: FiveResult -> RTB.T U.Beats Bool
fiveResultMoods result
= makePlayBools (RB.fiveMood result.other)
$ maybe mempty (splitEdges . fmap (\((fret, sht), len) -> (fret, sht, len)))
$ Map.lookup Expert result.notes
guitarResult <- getLeadData $ gh1LeadTrack audio
leadDiffs <- makeDiffs (gh1LeadTrack audio) guitarResult
gh1Pad $ F.Song tmap mmap GH1File
{ gh1T1Gems = GemsTrack
{ gemsDifficulties = leadDiffs
, gemsMouthOpen = case gh1AnimVocal audio of
Nothing -> RTB.empty
Just part -> fmap snd $ RB.vocalNotes $ F.onyxPartVocals $ F.getFlexPart part onyx
}
, gh1Anim = AnimTrack
{ animFretPosition = first FretPosition <$> RB.fiveFretPosition guitarResult.other
, animHandMap = flip fmap (RB.fiveHandMap guitarResult.other) $ \case
RB.HandMap_Default -> HandMap_Default
RB.HandMap_NoChords -> HandMap_NoChords
RB.HandMap_AllChords -> HandMap_AllChords
RB.HandMap_Solo -> HandMap_Solo
RB.HandMap_DropD -> HandMap_DropD2
RB.HandMap_DropD2 -> HandMap_DropD2
RB.HandMap_AllBend -> HandMap_Solo
RB.HandMap_Chord_C -> HandMap_Default
RB.HandMap_Chord_D -> HandMap_Default
RB.HandMap_Chord_A -> HandMap_Default
}
, gh1Triggers = mempty -- don't know what these are yet
, gh1Events = EventsTrack
{ eventsList = foldr RTB.merge RTB.empty
[ fmap (\b -> if b then Event_gtr_on else Event_gtr_off)
$ fiveResultMoods guitarResult
, case gh1AnimVocal audio of
Nothing -> RTB.empty
Just part -> let
trk = F.onyxPartVocals $ F.getFlexPart part onyx
in fmap (\b -> if b then Event_sing_on else Event_sing_off)
$ makePlayBools (RB.vocalMood trk)
$ fmap (\case (p, True) -> NoteOn () p; (p, False) -> NoteOff p)
$ RB.vocalNotes trk
, fmap (\b -> if b then Event_bass_on else Event_bass_off)
$ maybe RTB.empty fiveResultMoods
$ gh1AnimBass audio >>= getFive
, fmap (\b -> if b then Event_keys_on else Event_keys_off)
$ maybe RTB.empty fiveResultMoods
$ gh1AnimKeys audio >>= getFive
, case gh1AnimDrums audio of
Nothing -> RTB.empty
Just part -> let
trk = F.onyxPartDrums $ F.getFlexPart part onyx
anims = RB.drumAnimation $ RB.fillDrumAnimation (0.25 :: U.Seconds) tmap trk
in fmap (\b -> if b then Event_drum_on else Event_drum_off)
$ makePlayBools (RB.drumMood trk) $ Blip () () <$ anims
, RTB.singleton (timingEnd timing) Event_end
]
}
}
bandMembers :: SongYaml f -> GH1Audio -> Maybe [Either D.BandMember T.Text]
bandMembers song audio = let
vocal = case gh1AnimVocal audio of
Nothing -> Nothing
Just fpart -> Just $ fromMaybe Magma.Male $ getPart fpart song >>= (.vocal) >>= (.gender)
we 'll just assume there 's always a bassist , do n't know if required ( all songs on disc have one )
keys = isJust $ gh1AnimKeys audio
drums = True -- gh2 crashes if missing, haven't tested gh1 but likely the same
in case (vocal, bass, keys, drums) of
(Just Magma.Male, True, False, True) -> Nothing -- the default configuration
_ -> Just $ map Left $ concat
[ toList $ (\case Magma.Male -> D.SINGER_MALE_METAL; Magma.Female -> D.SINGER_FEMALE_METAL) <$> vocal
, [D.BASS_METAL | bass ]
, [D.KEYBOARD_METAL | keys && isNothing vocal] -- singer overrides keyboard, can't have both
, [D.DRUMMER_METAL | drums]
]
makeGH1DTA :: SongYaml f -> T.Text -> (Int, Int) -> GH1Audio -> T.Text -> D.SongPackage
makeGH1DTA song key preview audio title = D.SongPackage
{ D.name = adjustSongText title
, D.artist = adjustSongText $ getArtist song.metadata
, D.song = D.Song
{ D.songName = "songs/" <> key <> "/" <> key
, D.tracks = 1
, D.slip_tracks = [map fromIntegral $ gh1LeadChannels audio]
note , we do n't actually use
, D.pans = gh1AudioSections audio >>= \case
GH2PartStereo _ -> [-1, 1]
GH2PartMono _ -> [0]
GH2Band -> [-1, 1]
GH2Silent -> [0]
, D.vols = gh1AudioSections audio >>= \case
-- gh1 uses gain ratios, not decibels like gh2 and later!
GH2PartStereo _ -> [1, 1]
compensate for half volume later
GH2Band -> [1, 1]
GH2Silent -> [0] -- doesn't matter
, D.cores = gh1AudioSections audio >>= \case
GH2PartStereo _ -> [1, 1]
GH2PartMono _ -> [1]
GH2Band -> [-1, -1]
GH2Silent -> [-1]
, D.solo = ["riffs", "standard"]
}
, D.band = bandMembers song audio
, D.bank = "sfx/song_default"
, D.bpm = 120 -- does this do anything?
, D.animTempo = KTempoMedium
, D.preview = bimap fromIntegral fromIntegral preview
, D.midiFile = "songs/" <> key <> "/" <> key <> ".mid"
, D.quickplay = evalRand D.randomQuickplay $ mkStdGen $ hash key
}
hashGH1 :: (Hashable f) => SongYaml f -> TargetGH1 -> Int
hashGH1 songYaml gh1 = let
hashed =
( gh1
, songYaml.metadata.title
, songYaml.metadata.artist
)
in 1000000000 + (hash hashed `mod` 1000000000)
gh1Rules :: BuildInfo -> FilePath -> TargetGH1 -> QueueLog Rules ()
gh1Rules buildInfo dir gh1 = do
let songYaml = biSongYaml buildInfo
rel = biRelative buildInfo
(planName, plan) <- case getPlan gh1.common.plan songYaml of
Nothing -> fail $ "Couldn't locate a plan for this target: " ++ show gh1
Just pair -> return pair
let planDir = rel $ "gen/plan" </> T.unpack planName
defaultID = hashGH1 songYaml gh1
key = fromMaybe (makeShortName defaultID songYaml) gh1.key
pkg = T.unpack key
let loadPartAudioCheck = case plan of
StandardPlan x -> return $ \part -> HM.member part x.parts.getParts
MoggPlan x -> do
silentChans <- shk $ read <$> readFile' (planDir </> "silent-channels.txt")
return $ \part -> case HM.lookup part x.parts.getParts of
Nothing -> False
Just chans -> any (`notElem` (silentChans :: [Int])) $ concat $ toList chans
(dir </> "gh1/notes.mid", dir </> "gh1/pad.txt") %> \(out, pad) -> do
input <- F.shakeMIDI $ planDir </> "processed.mid"
hasAudio <- loadPartAudioCheck
audio <- computeGH1Audio songYaml gh1 hasAudio
(mid, padSeconds) <- midiRB3toGH1 songYaml audio
(applyTargetMIDI gh1.common input)
(getAudioLength buildInfo planName plan)
F.saveMIDI out mid
stackIO $ writeFile pad $ show padSeconds
let loadGH1Midi = F.shakeMIDI $ dir </> "gh1/notes.mid" :: Staction (F.Song (GH1File U.Beats))
correctAudioLength mid = do
endTime <- case RTB.filter (== Event_end) $ eventsList $ gh1Events $ F.s_tracks mid of
RNil -> fatal "panic! couldn't find [end] event in GH1 output midi"
Wait t _ _ -> return $ U.applyTempoMap (F.s_tempos mid) t
return $ endTime + 5
previously we went 0.5s past [ end ] , but that still had issues ,
particularly in GH2 practice mode when playing the last section
-- for vgs, separate sources so silence can be encoded at low sample rate
gh1SourcesVGS = do
hasAudio <- loadPartAudioCheck
audio <- computeGH1Audio songYaml gh1 hasAudio
mid <- loadGH1Midi
srcs <- forM (gh1AudioSections audio) $ \case
GH2PartStereo part -> getPartSource buildInfo [(-1, 0), (1, 0)] planName plan part 1
-- This halves the volume, so we set vols in .dta to compensate
GH2PartMono part -> applyVolsMono [0] <$> getPartSource buildInfo [(-1, 0), (1, 0)] planName plan part 1
GH2Band -> sourceBacking buildInfo def mid 0 planName plan
[ (gh1LeadTrack audio, 1)
]
GH2Silent -> return $ silent (Seconds 0) 11025 1
pad <- shk $ read <$> readFile' (dir </> "gh1/pad.txt")
audioLen <- correctAudioLength mid
let applyOffset = case compare gh1.offset 0 of
EQ -> id
GT -> dropStart $ Seconds gh1.offset
LT -> padStart $ Seconds $ negate gh1.offset
toEachSource
= setAudioLength audioLen
. applyOffset
. padAudio pad
. applyTargetAudio gh1.common mid
return $ fmap toEachSource srcs
dir </> "gh1/audio.vgs" %> \out -> do
srcs <- gh1SourcesVGS
stackIO $ runResourceT $ writeVGSMultiRate out $ map (mapSamples integralSample) srcs
(dir </> "gh1/songs.dta", dir </> "gh1/songs-inner.dta") %> \(out, outInner) -> do
input <- F.shakeMIDI $ planDir </> "processed.mid"
hasAudio <- loadPartAudioCheck
audio <- computeGH1Audio songYaml gh1 hasAudio
pad <- shk $ read <$> readFile' (dir </> "gh1/pad.txt")
let padSeconds = fromIntegral (pad :: Int) :: U.Seconds
inner = D.serialize (valueId D.stackChunks) $ makeGH1DTA
songYaml
key
(previewBounds songYaml (input :: F.Song (F.OnyxFile U.Beats)) padSeconds False)
audio
(targetTitle songYaml $ GH1 gh1)
stackIO $ D.writeFileDTA_latin1 out $ D.DTA 0 $ D.Tree 0
[ D.Parens $ D.Tree 0 $ D.Sym key : D.treeChunks (D.topTree inner) ]
stackIO $ D.writeFileDTA_latin1 outInner inner
dir </> "gh1/symbol" %> \out -> do
stackIO $ B.writeFile out $ B8.pack pkg
phony (dir </> "gh1") $ shk $ need $
[ dir </> "gh1/notes.mid"
, dir </> "gh1/audio.vgs"
, dir </> "gh1/songs.dta"
, dir </> "gh1/songs-inner.dta"
, dir </> "gh1/symbol"
]
| null | https://raw.githubusercontent.com/mtolly/onyxite-customs/0c8acd6248fe92ea0d994b18b551973816adf85b/haskell/packages/onyx-lib/src/Onyx/Build/GuitarHero1.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
True if part has own audio
A single guitar track apparently doesn't work;
guitar also takes over channel 0 (left backing track) somehow?
always stereo as per above
should always be this for our output
don't know what these are yet
gh2 crashes if missing, haven't tested gh1 but likely the same
the default configuration
singer overrides keyboard, can't have both
gh1 uses gain ratios, not decibels like gh2 and later!
doesn't matter
does this do anything?
for vgs, separate sources so silence can be encoded at low sample rate
This halves the volume, so we set vols in .dta to compensate | # LANGUAGE LambdaCase #
# LANGUAGE OverloadedRecordDot #
# LANGUAGE TupleSections #
module Onyx.Build.GuitarHero1 where
import Control.Monad.Extra
import Control.Monad.Random (evalRand, mkStdGen)
import Control.Monad.Trans.Resource
import Data.Bifunctor (bimap, first)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import Data.Conduit.Audio
import Data.Default.Class (def)
import qualified Data.EventList.Relative.TimeBody as RTB
import Data.Foldable (toList)
import Data.Hashable (Hashable, hash)
import qualified Data.HashMap.Strict as HM
import qualified Data.Map as Map
import Data.Maybe (fromMaybe, isJust,
isNothing)
import qualified Data.Text as T
import Development.Shake hiding (phony, (%>))
import Development.Shake.FilePath
import Onyx.Audio
import Onyx.Audio.VGS (writeVGSMultiRate)
import Onyx.Build.Common
import Onyx.Build.GuitarHero2.Logic (GH2AudioSection (..),
adjustSongText)
import Onyx.Build.RB3CH (BasicTiming (..),
basicTiming, makeMoods)
import Onyx.Codec.Common (valueId)
import Onyx.Guitar
import qualified Onyx.Harmonix.DTA as D
import qualified Onyx.Harmonix.DTA.Serialize as D
import qualified Onyx.Harmonix.DTA.Serialize.GH1 as D
import qualified Onyx.Harmonix.DTA.Serialize.Magma as Magma
import Onyx.Harmonix.DTA.Serialize.RockBand (AnimTempo (..))
import Onyx.Harmonix.GH1.File
import Onyx.Harmonix.GH2.PartGuitar (HandMap (..),
PartDifficulty (..))
import Onyx.MIDI.Common
import qualified Onyx.MIDI.Track.Drums as RB
import qualified Onyx.MIDI.Track.File as F
import qualified Onyx.MIDI.Track.FiveFret as RB
import qualified Onyx.MIDI.Track.Vocal as RB
import Onyx.Mode
import Onyx.Overdrive (removeNotelessOD)
import Onyx.Project
import Onyx.Reductions (completeFiveResult)
import Onyx.StackTrace
import qualified Sound.MIDI.Util as U
gh1Pad
:: (SendMessage m)
=> F.Song (GH1File U.Beats)
-> StackTraceT m (F.Song (GH1File U.Beats), Int)
gh1Pad rb3@(F.Song tmap _ trks) = let
firstEvent rtb = case RTB.viewL rtb of
Just ((dt, _), _) -> dt
Nothing -> 999
firstNoteBeats = foldr min 999 $ map (firstEvent . partGems) $ Map.elems $ gemsDifficulties $ gh1T1Gems trks
firstNoteSeconds = U.applyTempoMap tmap firstNoteBeats
no idea but just going with similar value to what Magma enforces for RB
padSeconds = max 0 $ ceiling $ 2.6 - (realToFrac firstNoteSeconds :: Rational)
in case padSeconds of
0 -> do
return (rb3, 0)
_ -> do
warn $ "Padding song by " ++ show padSeconds ++ "s due to early notes."
return (F.padAnyFile padSeconds rb3, padSeconds)
data GH1Audio = GH1Audio
{ gh1AudioSections :: [GH2AudioSection]
, gh1LeadChannels :: [Int]
, gh1BackChannels :: [Int]
, gh1LeadTrack :: F.FlexPartName
, gh1AnimBass :: Maybe F.FlexPartName
, gh1AnimDrums :: Maybe F.FlexPartName
, gh1AnimVocal :: Maybe F.FlexPartName
, gh1AnimKeys :: Maybe F.FlexPartName
}
computeGH1Audio
:: (Monad m)
=> SongYaml f
-> TargetGH1
-> StackTraceT m GH1Audio
computeGH1Audio song target hasAudio = do
let canGetFiveFret = \case
Nothing -> False
Just part -> isJust $ anyFiveFret part
gh1LeadTrack <- if canGetFiveFret $ getPart target.guitar song
then return target.guitar
else fatal "computeGH1Audio: no lead guitar part selected"
let leadAudio = hasAudio gh1LeadTrack
gh1AudioSections = GH2Band : if leadAudio
then [GH2PartStereo gh1LeadTrack]
So use two channels like all disc songs
else [GH2Silent, GH2Silent]
gh1AnimBass = target.bass <$ (getPart target.bass song >>= (.grybo))
gh1AnimDrums = target.drums <$ (getPart target.drums song >>= (.drums))
gh1AnimVocal = target.vocal <$ (getPart target.vocal song >>= (.vocal))
gh1AnimKeys = target.keys <$ (getPart target.keys song >>= (.grybo))
return GH1Audio{..}
midiRB3toGH1
:: (SendMessage m)
=> SongYaml f
-> GH1Audio
-> F.Song (F.OnyxFile U.Beats)
-> StackTraceT m U.Seconds
-> StackTraceT m (F.Song (GH1File U.Beats), Int)
midiRB3toGH1 song audio inputMid@(F.Song tmap mmap onyx) getAudioLen = do
timing <- basicTiming inputMid getAudioLen
let makePlayBools origMoods gems = let
moods = if RTB.null origMoods
then makeMoods tmap timing gems
else origMoods
in flip fmap moods $ \case
Mood_idle_realtime -> False
Mood_idle -> False
Mood_idle_intense -> False
Mood_play -> True
Mood_mellow -> True
Mood_intense -> True
Mood_play_solo -> True
makeDiffs fpart result = do
let _ = result :: FiveResult
gap :: U.Beats
gap = fromIntegral result.settings.sustainGap / 480
editNotes
= fromClosed'
. noOpenNotes result.settings.detectMutedOpens
. noTaps
. noExtendedSustains' standardBlipThreshold gap
makeDiff diff notes = do
let notes' = editNotes notes
od <- removeNotelessOD
mmap
[(fpart, [(show diff, void notes')])]
((fpart,) <$> RB.fiveOverdrive result.other)
return PartDifficulty
{ partStarPower = snd <$> od
, partPlayer1 = RB.fivePlayer1 result.other
, partPlayer2 = RB.fivePlayer2 result.other
, partGems = RB.fiveGems $ emit5' notes'
, partForceHOPO = RTB.empty
, partForceStrum = RTB.empty
, partForceTap = RTB.empty
}
fmap Map.fromList
$ mapM (\(diff, notes) -> (diff,) <$> makeDiff diff notes)
$ Map.toList result.notes
getFive fpart = do
builder <- getPart fpart song >>= anyFiveFret
return $ builder FiveTypeGuitar ModeInput
{ tempo = tmap
, events = F.onyxEvents onyx
, part = F.getFlexPart fpart onyx
}
getLeadData fpart = case getFive fpart of
Nothing -> fatal "No guitar-compatible mode set up for lead guitar part"
Just result -> return $ completeFiveResult False mmap result
fiveResultMoods :: FiveResult -> RTB.T U.Beats Bool
fiveResultMoods result
= makePlayBools (RB.fiveMood result.other)
$ maybe mempty (splitEdges . fmap (\((fret, sht), len) -> (fret, sht, len)))
$ Map.lookup Expert result.notes
guitarResult <- getLeadData $ gh1LeadTrack audio
leadDiffs <- makeDiffs (gh1LeadTrack audio) guitarResult
gh1Pad $ F.Song tmap mmap GH1File
{ gh1T1Gems = GemsTrack
{ gemsDifficulties = leadDiffs
, gemsMouthOpen = case gh1AnimVocal audio of
Nothing -> RTB.empty
Just part -> fmap snd $ RB.vocalNotes $ F.onyxPartVocals $ F.getFlexPart part onyx
}
, gh1Anim = AnimTrack
{ animFretPosition = first FretPosition <$> RB.fiveFretPosition guitarResult.other
, animHandMap = flip fmap (RB.fiveHandMap guitarResult.other) $ \case
RB.HandMap_Default -> HandMap_Default
RB.HandMap_NoChords -> HandMap_NoChords
RB.HandMap_AllChords -> HandMap_AllChords
RB.HandMap_Solo -> HandMap_Solo
RB.HandMap_DropD -> HandMap_DropD2
RB.HandMap_DropD2 -> HandMap_DropD2
RB.HandMap_AllBend -> HandMap_Solo
RB.HandMap_Chord_C -> HandMap_Default
RB.HandMap_Chord_D -> HandMap_Default
RB.HandMap_Chord_A -> HandMap_Default
}
, gh1Events = EventsTrack
{ eventsList = foldr RTB.merge RTB.empty
[ fmap (\b -> if b then Event_gtr_on else Event_gtr_off)
$ fiveResultMoods guitarResult
, case gh1AnimVocal audio of
Nothing -> RTB.empty
Just part -> let
trk = F.onyxPartVocals $ F.getFlexPart part onyx
in fmap (\b -> if b then Event_sing_on else Event_sing_off)
$ makePlayBools (RB.vocalMood trk)
$ fmap (\case (p, True) -> NoteOn () p; (p, False) -> NoteOff p)
$ RB.vocalNotes trk
, fmap (\b -> if b then Event_bass_on else Event_bass_off)
$ maybe RTB.empty fiveResultMoods
$ gh1AnimBass audio >>= getFive
, fmap (\b -> if b then Event_keys_on else Event_keys_off)
$ maybe RTB.empty fiveResultMoods
$ gh1AnimKeys audio >>= getFive
, case gh1AnimDrums audio of
Nothing -> RTB.empty
Just part -> let
trk = F.onyxPartDrums $ F.getFlexPart part onyx
anims = RB.drumAnimation $ RB.fillDrumAnimation (0.25 :: U.Seconds) tmap trk
in fmap (\b -> if b then Event_drum_on else Event_drum_off)
$ makePlayBools (RB.drumMood trk) $ Blip () () <$ anims
, RTB.singleton (timingEnd timing) Event_end
]
}
}
bandMembers :: SongYaml f -> GH1Audio -> Maybe [Either D.BandMember T.Text]
bandMembers song audio = let
vocal = case gh1AnimVocal audio of
Nothing -> Nothing
Just fpart -> Just $ fromMaybe Magma.Male $ getPart fpart song >>= (.vocal) >>= (.gender)
we 'll just assume there 's always a bassist , do n't know if required ( all songs on disc have one )
keys = isJust $ gh1AnimKeys audio
in case (vocal, bass, keys, drums) of
_ -> Just $ map Left $ concat
[ toList $ (\case Magma.Male -> D.SINGER_MALE_METAL; Magma.Female -> D.SINGER_FEMALE_METAL) <$> vocal
, [D.BASS_METAL | bass ]
, [D.DRUMMER_METAL | drums]
]
makeGH1DTA :: SongYaml f -> T.Text -> (Int, Int) -> GH1Audio -> T.Text -> D.SongPackage
makeGH1DTA song key preview audio title = D.SongPackage
{ D.name = adjustSongText title
, D.artist = adjustSongText $ getArtist song.metadata
, D.song = D.Song
{ D.songName = "songs/" <> key <> "/" <> key
, D.tracks = 1
, D.slip_tracks = [map fromIntegral $ gh1LeadChannels audio]
note , we do n't actually use
, D.pans = gh1AudioSections audio >>= \case
GH2PartStereo _ -> [-1, 1]
GH2PartMono _ -> [0]
GH2Band -> [-1, 1]
GH2Silent -> [0]
, D.vols = gh1AudioSections audio >>= \case
GH2PartStereo _ -> [1, 1]
compensate for half volume later
GH2Band -> [1, 1]
, D.cores = gh1AudioSections audio >>= \case
GH2PartStereo _ -> [1, 1]
GH2PartMono _ -> [1]
GH2Band -> [-1, -1]
GH2Silent -> [-1]
, D.solo = ["riffs", "standard"]
}
, D.band = bandMembers song audio
, D.bank = "sfx/song_default"
, D.animTempo = KTempoMedium
, D.preview = bimap fromIntegral fromIntegral preview
, D.midiFile = "songs/" <> key <> "/" <> key <> ".mid"
, D.quickplay = evalRand D.randomQuickplay $ mkStdGen $ hash key
}
hashGH1 :: (Hashable f) => SongYaml f -> TargetGH1 -> Int
hashGH1 songYaml gh1 = let
hashed =
( gh1
, songYaml.metadata.title
, songYaml.metadata.artist
)
in 1000000000 + (hash hashed `mod` 1000000000)
gh1Rules :: BuildInfo -> FilePath -> TargetGH1 -> QueueLog Rules ()
gh1Rules buildInfo dir gh1 = do
let songYaml = biSongYaml buildInfo
rel = biRelative buildInfo
(planName, plan) <- case getPlan gh1.common.plan songYaml of
Nothing -> fail $ "Couldn't locate a plan for this target: " ++ show gh1
Just pair -> return pair
let planDir = rel $ "gen/plan" </> T.unpack planName
defaultID = hashGH1 songYaml gh1
key = fromMaybe (makeShortName defaultID songYaml) gh1.key
pkg = T.unpack key
let loadPartAudioCheck = case plan of
StandardPlan x -> return $ \part -> HM.member part x.parts.getParts
MoggPlan x -> do
silentChans <- shk $ read <$> readFile' (planDir </> "silent-channels.txt")
return $ \part -> case HM.lookup part x.parts.getParts of
Nothing -> False
Just chans -> any (`notElem` (silentChans :: [Int])) $ concat $ toList chans
(dir </> "gh1/notes.mid", dir </> "gh1/pad.txt") %> \(out, pad) -> do
input <- F.shakeMIDI $ planDir </> "processed.mid"
hasAudio <- loadPartAudioCheck
audio <- computeGH1Audio songYaml gh1 hasAudio
(mid, padSeconds) <- midiRB3toGH1 songYaml audio
(applyTargetMIDI gh1.common input)
(getAudioLength buildInfo planName plan)
F.saveMIDI out mid
stackIO $ writeFile pad $ show padSeconds
let loadGH1Midi = F.shakeMIDI $ dir </> "gh1/notes.mid" :: Staction (F.Song (GH1File U.Beats))
correctAudioLength mid = do
endTime <- case RTB.filter (== Event_end) $ eventsList $ gh1Events $ F.s_tracks mid of
RNil -> fatal "panic! couldn't find [end] event in GH1 output midi"
Wait t _ _ -> return $ U.applyTempoMap (F.s_tempos mid) t
return $ endTime + 5
previously we went 0.5s past [ end ] , but that still had issues ,
particularly in GH2 practice mode when playing the last section
gh1SourcesVGS = do
hasAudio <- loadPartAudioCheck
audio <- computeGH1Audio songYaml gh1 hasAudio
mid <- loadGH1Midi
srcs <- forM (gh1AudioSections audio) $ \case
GH2PartStereo part -> getPartSource buildInfo [(-1, 0), (1, 0)] planName plan part 1
GH2PartMono part -> applyVolsMono [0] <$> getPartSource buildInfo [(-1, 0), (1, 0)] planName plan part 1
GH2Band -> sourceBacking buildInfo def mid 0 planName plan
[ (gh1LeadTrack audio, 1)
]
GH2Silent -> return $ silent (Seconds 0) 11025 1
pad <- shk $ read <$> readFile' (dir </> "gh1/pad.txt")
audioLen <- correctAudioLength mid
let applyOffset = case compare gh1.offset 0 of
EQ -> id
GT -> dropStart $ Seconds gh1.offset
LT -> padStart $ Seconds $ negate gh1.offset
toEachSource
= setAudioLength audioLen
. applyOffset
. padAudio pad
. applyTargetAudio gh1.common mid
return $ fmap toEachSource srcs
dir </> "gh1/audio.vgs" %> \out -> do
srcs <- gh1SourcesVGS
stackIO $ runResourceT $ writeVGSMultiRate out $ map (mapSamples integralSample) srcs
(dir </> "gh1/songs.dta", dir </> "gh1/songs-inner.dta") %> \(out, outInner) -> do
input <- F.shakeMIDI $ planDir </> "processed.mid"
hasAudio <- loadPartAudioCheck
audio <- computeGH1Audio songYaml gh1 hasAudio
pad <- shk $ read <$> readFile' (dir </> "gh1/pad.txt")
let padSeconds = fromIntegral (pad :: Int) :: U.Seconds
inner = D.serialize (valueId D.stackChunks) $ makeGH1DTA
songYaml
key
(previewBounds songYaml (input :: F.Song (F.OnyxFile U.Beats)) padSeconds False)
audio
(targetTitle songYaml $ GH1 gh1)
stackIO $ D.writeFileDTA_latin1 out $ D.DTA 0 $ D.Tree 0
[ D.Parens $ D.Tree 0 $ D.Sym key : D.treeChunks (D.topTree inner) ]
stackIO $ D.writeFileDTA_latin1 outInner inner
dir </> "gh1/symbol" %> \out -> do
stackIO $ B.writeFile out $ B8.pack pkg
phony (dir </> "gh1") $ shk $ need $
[ dir </> "gh1/notes.mid"
, dir </> "gh1/audio.vgs"
, dir </> "gh1/songs.dta"
, dir </> "gh1/songs-inner.dta"
, dir </> "gh1/symbol"
]
|
d79bdeafadcf9994d3c099490ccaadaf60a2f3c690e7b96998a6d4204e023680 | DSiSc/why3 | abstraction.mli | (********************************************************************)
(* *)
The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University
(* *)
(* This software is distributed under the terms of the GNU Lesser *)
General Public License version 2.1 , with the special exception
(* on linking described in file LICENSE. *)
(* *)
(********************************************************************)
val abstraction : (Term.lsymbol -> bool) -> Task.task Trans.trans
* [ abstract keep t ] applies variable abstraction of the task [ t ] ,
that is replaces subterms or subformulas headed by a logic symbol
f that do not satisfies [ keep f ] into a fresh variable .
Notice that the numeric constants are always kept
Example ( approximate syntax ):
[ abstraction ( fun f - > List.mem f [ " + " ; " - " ] ) " goal x*x+y*y = 1 " ]
returns [ " logic abs1 : int ; logic abs2 : int ; goal 1 " ]
that is replaces subterms or subformulas headed by a logic symbol
f that do not satisfies [keep f] into a fresh variable.
Notice that the numeric constants are always kept
Example (approximate syntax):
[abstraction (fun f -> List.mem f ["+";"-"]) "goal x*x+y*y = 1"]
returns ["logic abs1 : int; logic abs2 : int; goal abs1+abs2 = 1"]
*)
| null | https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/src/transform/abstraction.mli | ocaml | ******************************************************************
This software is distributed under the terms of the GNU Lesser
on linking described in file LICENSE.
****************************************************************** | The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University
General Public License version 2.1 , with the special exception
val abstraction : (Term.lsymbol -> bool) -> Task.task Trans.trans
* [ abstract keep t ] applies variable abstraction of the task [ t ] ,
that is replaces subterms or subformulas headed by a logic symbol
f that do not satisfies [ keep f ] into a fresh variable .
Notice that the numeric constants are always kept
Example ( approximate syntax ):
[ abstraction ( fun f - > List.mem f [ " + " ; " - " ] ) " goal x*x+y*y = 1 " ]
returns [ " logic abs1 : int ; logic abs2 : int ; goal 1 " ]
that is replaces subterms or subformulas headed by a logic symbol
f that do not satisfies [keep f] into a fresh variable.
Notice that the numeric constants are always kept
Example (approximate syntax):
[abstraction (fun f -> List.mem f ["+";"-"]) "goal x*x+y*y = 1"]
returns ["logic abs1 : int; logic abs2 : int; goal abs1+abs2 = 1"]
*)
|
e8fa50751108af54a61b1ce7e5adcd526d8967d0e603b0d4eb84a744e7677441 | guildhall/guile-sly | font.scm |
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
;;; </>.
(use-modules (sly game)
(sly fps)
(sly signal)
(sly window)
(sly math vector)
(sly render camera)
(sly render color)
(sly render font)
(sly render model)
(sly render scene)
(sly input mouse))
(load "common.scm")
(define font (load-default-font 18))
(define-signal message-label
(model-move (vector2 320 240)
(label font "The quick brown fox jumped over the lazy dog."
#:anchor 'center)))
(define-signal fps-label
(signal-let ((fps fps))
(let ((text (format #f "FPS: ~d" fps)))
(model-move (vector2 0 480) (label font text)))))
(define-signal mouse-label
(signal-let ((pos (signal-throttle 5 mouse-position)))
(let ((text (format #f "Mouse: (~d, ~d)" (vx pos) (vy pos))))
(model-move (vector2 0 460) (label font text)))))
(define-signal model
(signal-map model-group message-label fps-label mouse-label))
(define camera (orthographic-camera 640 480))
(define-signal scene
(signal-map (lambda (model) (make-scene camera model)) model))
(with-window (make-window #:title "Fonts")
(run-game-loop scene))
;;; Local Variables:
;;; compile-command: "../pre-inst-env guile font.scm"
;;; End:
| null | https://raw.githubusercontent.com/guildhall/guile-sly/92f5f21da76986c5b606b36afc4bb984cc63da5b/examples/font.scm | scheme |
This program is free software: you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
along with this program. If not, see
</>.
Local Variables:
compile-command: "../pre-inst-env guile font.scm"
End: |
Copyright ( C ) 2013 , 2014 >
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation , either version 3 of the
You should have received a copy of the GNU General Public License
(use-modules (sly game)
(sly fps)
(sly signal)
(sly window)
(sly math vector)
(sly render camera)
(sly render color)
(sly render font)
(sly render model)
(sly render scene)
(sly input mouse))
(load "common.scm")
(define font (load-default-font 18))
(define-signal message-label
(model-move (vector2 320 240)
(label font "The quick brown fox jumped over the lazy dog."
#:anchor 'center)))
(define-signal fps-label
(signal-let ((fps fps))
(let ((text (format #f "FPS: ~d" fps)))
(model-move (vector2 0 480) (label font text)))))
(define-signal mouse-label
(signal-let ((pos (signal-throttle 5 mouse-position)))
(let ((text (format #f "Mouse: (~d, ~d)" (vx pos) (vy pos))))
(model-move (vector2 0 460) (label font text)))))
(define-signal model
(signal-map model-group message-label fps-label mouse-label))
(define camera (orthographic-camera 640 480))
(define-signal scene
(signal-map (lambda (model) (make-scene camera model)) model))
(with-window (make-window #:title "Fonts")
(run-game-loop scene))
|
08eff7d41dcb0e5c774fe7d3e0191388db80284dcb63cccac750bdb96411a5f0 | vii/dysfunkycom | bezier.lisp | ;;;;; Converted from the "Bezier" Processing example at:
;;;;; ""
;;;;; (C)2006 Luke J Crook
(in-package #:sdl-examples)
(defun bezier ()
(let ((width 200) (height 200))
(sdl:with-init ()
(sdl:window width height :title-caption "Bezier, from Processing.org")
(setf (sdl:frame-rate) 5)
(sdl:clear-display (sdl:color :r 0 :g 0 :b 0))
(sdl:with-color (a-col (sdl:color :r 255 :g 255 :b 255))
(loop for i from 0 to 100 by 10
do (sdl:draw-bezier (list (sdl:point :x (- 90 (/ i 2.0)) :y (+ 20 i))
(sdl:point :x 210 :y 10)
(sdl:point :x 220 :y 150)
(sdl:point :x (- 120 (/ i 8.0)) :y (+ 150 (/ i 4.0)))))))
(sdl:update-display)
(sdl:with-events ()
(:quit-event () t)
(:video-expose-event () (sdl:update-display))))))
| null | https://raw.githubusercontent.com/vii/dysfunkycom/a493fa72662b79e7c4e70361ad0ea3c7235b6166/addons/lispbuilder-sdl/examples/bezier.lisp | lisp | Converted from the "Bezier" Processing example at:
""
(C)2006 Luke J Crook |
(in-package #:sdl-examples)
(defun bezier ()
(let ((width 200) (height 200))
(sdl:with-init ()
(sdl:window width height :title-caption "Bezier, from Processing.org")
(setf (sdl:frame-rate) 5)
(sdl:clear-display (sdl:color :r 0 :g 0 :b 0))
(sdl:with-color (a-col (sdl:color :r 255 :g 255 :b 255))
(loop for i from 0 to 100 by 10
do (sdl:draw-bezier (list (sdl:point :x (- 90 (/ i 2.0)) :y (+ 20 i))
(sdl:point :x 210 :y 10)
(sdl:point :x 220 :y 150)
(sdl:point :x (- 120 (/ i 8.0)) :y (+ 150 (/ i 4.0)))))))
(sdl:update-display)
(sdl:with-events ()
(:quit-event () t)
(:video-expose-event () (sdl:update-display))))))
|
12177c7b1d6bf9a84415ed7edf4751b7c3e9b6751165dd1f3921d5540a51e63d | PacktPublishing/Haskell-High-Performance-Programming | ioref-supply.hs | -- file: ioref-supply.hs
import Data.IORef
type Supply = IORef Int
createSupply :: IO Supply
createSupply = newIORef 0
newUID :: Supply -> IO Int
newUID supply = atomicModifyIORef' supply $ \uid -> (uid + 1, uid)
| null | https://raw.githubusercontent.com/PacktPublishing/Haskell-High-Performance-Programming/2b1bfdb8102129be41e8d79c7e9caf12100c5556/Chapter07/ioref-supply.hs | haskell | file: ioref-supply.hs |
import Data.IORef
type Supply = IORef Int
createSupply :: IO Supply
createSupply = newIORef 0
newUID :: Supply -> IO Int
newUID supply = atomicModifyIORef' supply $ \uid -> (uid + 1, uid)
|
4da320f90f4df39f4cf77df5c9b77d956739ae1585e4a896ac54cea212ed95d4 | techascent/tech.resource | gc_resource_test.clj | (ns tech.v3.gc-resource-test
(:require [tech.v3.resource :as resource]
[clojure.test :refer [deftest is testing]]))
(deftest gc-resources
(testing "System.gc cleans up the things"
(let [counter (atom 0)]
(let [create-fn (fn []
(swap! counter inc)
(resource/track (Object.) {:dispose-fn #(swap! counter dec)
:track-type :gc}))]
(->> (repeatedly 100 #(create-fn))
dorun)
(is (= 100 @counter))
(System/gc)
(Thread/sleep 100)
(is (= 0 @counter)))
(System/gc)
(is (= 0 @counter))))
(testing "resource context and system.gc work together"
(let [counter (atom 0)]
(resource/stack-resource-context
(let [create-fn (fn []
(swap! counter inc)
(resource/track (Object.) {:dispose-fn #(swap! counter dec)
:track-type [:gc :stack]}))
objects (vec (repeatedly 100 #(create-fn)))]
(is (= 100 @counter))
(System/gc)
(Thread/sleep 100)
(is (= 100 @counter))
;;The compiler is careful to null out things that are no longer in use.
objects))
(is (= 0 @counter))
(System/gc)
(Thread/sleep 100)
(is (= 0 @counter))))
(testing "gc-only resources get cleaned up"
(let [counter (atom 0)]
(let [create-fn (fn []
(swap! counter inc)
(resource/track (Object.) {:dispose-fn #(swap! counter dec)
:track-type :gc}))
_objects (vec (repeatedly 10 #(create-fn)))]
(is (= 10 @counter))
nil)
(System/gc)
(Thread/sleep 100)
(is (= 0 @counter)))))
| null | https://raw.githubusercontent.com/techascent/tech.resource/d27e56d14f60504a343fc221d520797231fd11ba/test/tech/v3/gc_resource_test.clj | clojure | The compiler is careful to null out things that are no longer in use. | (ns tech.v3.gc-resource-test
(:require [tech.v3.resource :as resource]
[clojure.test :refer [deftest is testing]]))
(deftest gc-resources
(testing "System.gc cleans up the things"
(let [counter (atom 0)]
(let [create-fn (fn []
(swap! counter inc)
(resource/track (Object.) {:dispose-fn #(swap! counter dec)
:track-type :gc}))]
(->> (repeatedly 100 #(create-fn))
dorun)
(is (= 100 @counter))
(System/gc)
(Thread/sleep 100)
(is (= 0 @counter)))
(System/gc)
(is (= 0 @counter))))
(testing "resource context and system.gc work together"
(let [counter (atom 0)]
(resource/stack-resource-context
(let [create-fn (fn []
(swap! counter inc)
(resource/track (Object.) {:dispose-fn #(swap! counter dec)
:track-type [:gc :stack]}))
objects (vec (repeatedly 100 #(create-fn)))]
(is (= 100 @counter))
(System/gc)
(Thread/sleep 100)
(is (= 100 @counter))
objects))
(is (= 0 @counter))
(System/gc)
(Thread/sleep 100)
(is (= 0 @counter))))
(testing "gc-only resources get cleaned up"
(let [counter (atom 0)]
(let [create-fn (fn []
(swap! counter inc)
(resource/track (Object.) {:dispose-fn #(swap! counter dec)
:track-type :gc}))
_objects (vec (repeatedly 10 #(create-fn)))]
(is (= 10 @counter))
nil)
(System/gc)
(Thread/sleep 100)
(is (= 0 @counter)))))
|
7a3d471d7a9d656b8d8978c76072ed37857b1f4d32664f10e54e6513cc63e70e | binaryage/chromex | instance_id.clj | (ns chromex.app.instance-id
"Use chrome.instanceID to access the Instance ID service.
* available since Chrome 46
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro get-id
"Retrieves an identifier for the app instance. The instance ID will be returned by the callback. The same ID will be
returned as long as the application identity has not been revoked or expired.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [instance-id] where:
|instance-id| - An Instance ID assigned to the app instance.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getID."
([] (gen-call :function ::get-id &form)))
(defmacro get-creation-time
"Retrieves the time when the InstanceID has been generated. The creation time will be returned by the callback.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [creation-time] where:
|creation-time| - The time when the Instance ID has been generated, represented in milliseconds since the epoch.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getCreationTime."
([] (gen-call :function ::get-creation-time &form)))
(defmacro get-token
"Return a token that allows the authorized entity to access the service defined by scope.
|get-token-params| - Parameters for getToken.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [token] where:
|token| - A token assigned by the requested service.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getToken."
([get-token-params] (gen-call :function ::get-token &form get-token-params)))
(defmacro delete-token
"Revokes a granted token.
|delete-token-params| - Parameters for deleteToken.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-deleteToken."
([delete-token-params] (gen-call :function ::delete-token &form delete-token-params)))
(defmacro delete-id
"Resets the app instance identifier and revokes all tokens associated with it.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-deleteID."
([] (gen-call :function ::delete-id &form)))
; -- events -----------------------------------------------------------------------------------------------------------------
;
; docs: /#tapping-events
(defmacro tap-on-token-refresh-events
"Fired when all the granted tokens need to be refreshed.
Events will be put on the |channel| with signature [::on-token-refresh []].
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onTokenRefresh."
([channel & args] (apply gen-call :event ::on-token-refresh &form channel args)))
; -- convenience ------------------------------------------------------------------------------------------------------------
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.app.instance-id namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
; ---------------------------------------------------------------------------------------------------------------------------
; -- API TABLE --------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------------
(def api-table
{:namespace "chrome.instanceID",
:since "46",
:functions
[{:id ::get-id,
:name "getID",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "instance-id", :type "string"}]}}]}
{:id ::get-creation-time,
:name "getCreationTime",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "creation-time", :type "double"}]}}]}
{:id ::get-token,
:name "getToken",
:callback? true,
:params
[{:name "get-token-params", :type "object"}
{:name "callback", :type :callback, :callback {:params [{:name "token", :type "string"}]}}]}
{:id ::delete-token,
:name "deleteToken",
:callback? true,
:params [{:name "delete-token-params", :type "object"} {:name "callback", :type :callback}]}
{:id ::delete-id, :name "deleteID", :callback? true, :params [{:name "callback", :type :callback}]}],
:events [{:id ::on-token-refresh, :name "onTokenRefresh"}]})
; -- helpers ----------------------------------------------------------------------------------------------------------------
; code generation for native API wrapper
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
; code generation for API call-site
(def gen-call (partial gen-call-helper api-table)) | null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/apps/chromex/app/instance_id.clj | clojure | -- events -----------------------------------------------------------------------------------------------------------------
docs: /#tapping-events
-- convenience ------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- API TABLE --------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- helpers ----------------------------------------------------------------------------------------------------------------
code generation for native API wrapper
code generation for API call-site | (ns chromex.app.instance-id
"Use chrome.instanceID to access the Instance ID service.
* available since Chrome 46
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro get-id
"Retrieves an identifier for the app instance. The instance ID will be returned by the callback. The same ID will be
returned as long as the application identity has not been revoked or expired.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [instance-id] where:
|instance-id| - An Instance ID assigned to the app instance.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getID."
([] (gen-call :function ::get-id &form)))
(defmacro get-creation-time
"Retrieves the time when the InstanceID has been generated. The creation time will be returned by the callback.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [creation-time] where:
|creation-time| - The time when the Instance ID has been generated, represented in milliseconds since the epoch.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getCreationTime."
([] (gen-call :function ::get-creation-time &form)))
(defmacro get-token
"Return a token that allows the authorized entity to access the service defined by scope.
|get-token-params| - Parameters for getToken.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [token] where:
|token| - A token assigned by the requested service.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getToken."
([get-token-params] (gen-call :function ::get-token &form get-token-params)))
(defmacro delete-token
"Revokes a granted token.
|delete-token-params| - Parameters for deleteToken.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-deleteToken."
([delete-token-params] (gen-call :function ::delete-token &form delete-token-params)))
(defmacro delete-id
"Resets the app instance identifier and revokes all tokens associated with it.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-deleteID."
([] (gen-call :function ::delete-id &form)))
(defmacro tap-on-token-refresh-events
"Fired when all the granted tokens need to be refreshed.
Events will be put on the |channel| with signature [::on-token-refresh []].
Note: |args| will be passed as additional parameters into Chrome event's .addListener call.
#event-onTokenRefresh."
([channel & args] (apply gen-call :event ::on-token-refresh &form channel args)))
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.app.instance-id namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
(def api-table
{:namespace "chrome.instanceID",
:since "46",
:functions
[{:id ::get-id,
:name "getID",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "instance-id", :type "string"}]}}]}
{:id ::get-creation-time,
:name "getCreationTime",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "creation-time", :type "double"}]}}]}
{:id ::get-token,
:name "getToken",
:callback? true,
:params
[{:name "get-token-params", :type "object"}
{:name "callback", :type :callback, :callback {:params [{:name "token", :type "string"}]}}]}
{:id ::delete-token,
:name "deleteToken",
:callback? true,
:params [{:name "delete-token-params", :type "object"} {:name "callback", :type :callback}]}
{:id ::delete-id, :name "deleteID", :callback? true, :params [{:name "callback", :type :callback}]}],
:events [{:id ::on-token-refresh, :name "onTokenRefresh"}]})
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
(def gen-call (partial gen-call-helper api-table)) |
6de9301bd38a45faaa2597412e97776e9036498224bfc84fa234602deeea4268 | mewhhaha/apecs-unity-tutorial-haskell | Resource.hs | module Game.Resource where
import Apecs qualified
import Data.Map.Strict qualified as Map
import Optics.Core (Lens', set, view)
import Relude hiding (init)
import SDL qualified
import SDL.Font qualified as SDLFont
import SDL.Image qualified as SDLImage
import SDL.Mixer qualified as SDLMixer
import System.FilePath ((</>))
import World (System')
import World.Component (CResources, fonts, sounds, sprites)
lazyLoad :: Ord a => Lens' CResources (Map a b) -> System' b -> a -> System' b
lazyLoad optic initializeResource key = do
resources <- Apecs.get Apecs.global
let store = view optic resources
case Map.lookup key store of
Nothing -> do
v <- initializeResource
let updatedStore = Map.insert key v store
Apecs.set Apecs.global (set optic updatedStore resources)
pure v
Just v -> pure v
resourceFont :: FilePath -> Int -> System' SDLFont.Font
resourceFont filepath fontSize =
lazyLoad fonts initializeResource (filepath, fontSize)
where
initializeResource = SDLFont.load ("resources" </> filepath) fontSize
resourceSprite :: SDL.Renderer -> FilePath -> System' SDL.Texture
resourceSprite renderer filepath = do
lazyLoad sprites initializeResource filepath
where
initializeResource = SDLImage.loadTexture renderer ("resources" </> filepath)
resourceSound :: FilePath -> System' SDLMixer.Chunk
resourceSound filepath = do
lazyLoad sounds initializeResource filepath
where
initializeResource = SDLMixer.load ("resources" </> filepath)
| null | https://raw.githubusercontent.com/mewhhaha/apecs-unity-tutorial-haskell/d995e5311210b4c186ededbd38c64f6861f5eae1/src/Game/Resource.hs | haskell | module Game.Resource where
import Apecs qualified
import Data.Map.Strict qualified as Map
import Optics.Core (Lens', set, view)
import Relude hiding (init)
import SDL qualified
import SDL.Font qualified as SDLFont
import SDL.Image qualified as SDLImage
import SDL.Mixer qualified as SDLMixer
import System.FilePath ((</>))
import World (System')
import World.Component (CResources, fonts, sounds, sprites)
lazyLoad :: Ord a => Lens' CResources (Map a b) -> System' b -> a -> System' b
lazyLoad optic initializeResource key = do
resources <- Apecs.get Apecs.global
let store = view optic resources
case Map.lookup key store of
Nothing -> do
v <- initializeResource
let updatedStore = Map.insert key v store
Apecs.set Apecs.global (set optic updatedStore resources)
pure v
Just v -> pure v
resourceFont :: FilePath -> Int -> System' SDLFont.Font
resourceFont filepath fontSize =
lazyLoad fonts initializeResource (filepath, fontSize)
where
initializeResource = SDLFont.load ("resources" </> filepath) fontSize
resourceSprite :: SDL.Renderer -> FilePath -> System' SDL.Texture
resourceSprite renderer filepath = do
lazyLoad sprites initializeResource filepath
where
initializeResource = SDLImage.loadTexture renderer ("resources" </> filepath)
resourceSound :: FilePath -> System' SDLMixer.Chunk
resourceSound filepath = do
lazyLoad sounds initializeResource filepath
where
initializeResource = SDLMixer.load ("resources" </> filepath)
|
|
f66c6055c0a6a47fdb732eb50d68fbb16146f0499f206c52c5add2c1afca4441 | degree9/meta | promise.clj | (ns meta.promise)
(defmacro defpromise [name args & body]
`(def ~name (meta.promise/promise (fn ~args ~@body))))
(defmacro with-callback [cb & body]
`(meta.promise/promise
(fn [resolve# reject#]
(let [~cb (fn [err# result#] (if err# (reject# err#) (resolve# result#)))]
~@body))))
| null | https://raw.githubusercontent.com/degree9/meta/16dee6b01dd6402250b4b7a30185c0c0466985b3/src/meta/promise.clj | clojure | (ns meta.promise)
(defmacro defpromise [name args & body]
`(def ~name (meta.promise/promise (fn ~args ~@body))))
(defmacro with-callback [cb & body]
`(meta.promise/promise
(fn [resolve# reject#]
(let [~cb (fn [err# result#] (if err# (reject# err#) (resolve# result#)))]
~@body))))
|
|
dca6146d6ba3734e8c070d4b3c4eb30e013a6d7265510b1c9cf798f2774dcdde | mmontone/cl-rest-server | error-handling.lisp | (in-package :rest-server.error)
;; Error handling configuration
(defvar *catch-errors* t)
(defvar *server-catch-errors*)
(defvar *error-handler* 'log-api-error)
(defvar *default-error-handler* 'default-error-handler)
;; Conditions
(define-condition http-error (simple-error)
((status-code :initarg :status-code
:initform (error "Provide the status code")
:accessor status-code)
(info :initarg :info
:initform nil
:accessor http-error-info
:documentation "A plist of extra error info to be serialized back"))
(:report (lambda (c s)
(format s "HTTP error ~A: ~A ~A"
(status-code c)
(apply #'format nil (simple-condition-format-control c)
(simple-condition-format-arguments c))
(http-error-info c)))))
(defun http-error (status-code datum &rest args)
(error 'http-error
:status-code status-code
:format-control datum
:format-arguments args))
(defgeneric log-error-p (error)
(:documentation "Returns true for conditions that should be logged."))
(defmethod log-error-p ((error error))
"Errors are logged"
t)
(defmethod log-error-p (error)
"The default is not to log conditions"
nil)
(defmethod log-error-p ((error http-error))
"HTTP errors are not logged"
nil)
(defmethod log-error-p ((error schemata:validation-error))
"Validation errors are not logged"
nil)
(defun default-error-handler (error)
(when (log-error-p error)
(log-api-error error))
(setup-reply-from-error error))
(defmethod log-api-error ((error error))
(log5:log-for (rs::rest-server log5:error+) "ERROR: ~A" error)
(log5:log-for (rs::rest-server log5:error+)
(trivial-backtrace:print-backtrace error :output nil))
(format *debug-io* "ERROR: ~a~%" error)
(trivial-backtrace:print-backtrace error))
(defmethod log-api-error ((error http-error))
;; We don't want to log HTTP "error" signals like
;; an application error
)
(defmacro with-error-handler ((&optional (error-handler '*default-error-handler*))
&body body)
`(call-with-error-handler ,error-handler
(lambda () (progn ,@body))))
(define-condition http-not-found-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-not-found+
:format-control "Resource not found"))
(define-condition http-internal-server-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-internal-server-error+
:format-control "Internal server error"))
(define-condition http-bad-request (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-bad-request+
:format-control "Bad request"))
(define-condition http-authorization-required-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-authorization-required+
:format-control "Authorization required"))
(define-condition http-forbidden-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-forbidden+
:format-control "Forbidden"))
(define-condition http-service-unavailable-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-service-unavailable+
:format-control "Service unavailable"))
(define-condition http-unsupported-media-type-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-unsupported-media-type+
:format-control "Unsupported media type"))
(define-condition http-not-acceptable-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-not-acceptable+
:format-control "Not acceptable"))
(define-condition http-method-not-allowed-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-method-not-allowed+
:format-control "Method not allowed"))
(defparameter *http-status-codes-conditions*
'((404 . http-not-found-error)
(400 . http-bad-request)
(401 . http-authorization-required-error)
(403 . http-forbidden-error)
(500 . http-internal-server-error)
(415 . http-unsupported-media-type-error)))
(defun serialize-error (error)
(let ((serializer (rs::accept-serializer)))
(set-reply-content-type (generic-serializer::serializer-content-type serializer))
(with-output-to-string (s)
(generic-serializer:with-serializer-output s
(generic-serializer:with-serializer serializer
(generic-serializer:serialize error))))))
(defmethod generic-serializer:serialize ((error error) &optional
(serializer generic-serializer::*serializer*)
(stream generic-serializer::*serializer-output*) &rest args)
(declare (ignore args))
(generic-serializer:with-object ("error" :serializer serializer
:stream stream)
(generic-serializer:set-attribute
"detail"
(let ((debug-mode (if (boundp 'rs:*server-debug-mode*)
rs:*server-debug-mode*
rs:*debug-mode*)))
(if (not debug-mode)
"Internal server error"
;; else, debug mode
(with-output-to-string (s)
(princ error s)
(terpri s)
(trivial-backtrace:print-backtrace-to-stream s))))
:serializer serializer
:stream stream)))
(defmethod generic-serializer:serialize ((error http-error) &optional
(serializer generic-serializer::*serializer*)
(stream generic-serializer::*serializer-output*) &rest args)
(declare (ignore args))
(generic-serializer:with-object ("error" :serializer serializer
:stream stream)
(generic-serializer:set-attribute
"detail"
(apply #'format
nil
(simple-condition-format-control error)
(simple-condition-format-arguments error))
:serializer serializer
:stream stream)
(alexandria:doplist (key val (http-error-info error))
(generic-serializer:set-attribute
(princ-to-string key)
val))))
;; http-return-code decides the HTTP status code to return for
;; the signaled condition. Implement this method for new conditions.
;; Example:
(defmethod http-return-code ((error schemata:validation-error))
hunchentoot:+http-bad-request+)
(defmethod generic-serializer:serialize ((error schemata:validation-error)
&optional
(serializer generic-serializer::*serializer*)
(stream generic-serializer::*serializer-output*) &rest args)
(declare (ignore args))
(generic-serializer:with-object ("error" :serializer serializer
:stream stream)
(generic-serializer:set-attribute
"message"
(apply #'format
nil
(simple-condition-format-control error)
(simple-condition-format-arguments error))
:serializer serializer
:stream stream)))
(defmethod http-return-code ((condition error))
hunchentoot:+http-internal-server-error+)
(defmethod http-return-code ((condition http-error))
(status-code condition))
(defmethod setup-reply-from-error ((error error))
(setf (hunchentoot:return-code*)
(http-return-code error))
(serialize-error error))
(defmethod setup-reply-from-error ((error http-error))
(setf (hunchentoot:return-code*)
(http-return-code error))
(serialize-error error))
(defvar *retry-after-seconds* 5)
(defmethod setup-reply-from-error ((error http-service-unavailable-error))
"We add a retry-after header for the user to try again. The retry-after header value is in seconds"
(call-next-method)
(setf (hunchentoot:header-out "Retry-After") *retry-after-seconds*))
(defun call-with-error-handler (error-handler function)
(let ((catch-errors (if (boundp '*server-catch-errors*)
*server-catch-errors*
*catch-errors*))
(error-handler (or (and (symbolp error-handler)
(symbol-function error-handler))
error-handler)))
(if catch-errors
(handler-case
(funcall function)
(error (e)
(funcall error-handler e)))
(funcall function))))
;; Plugging
(defclass error-handling-resource-operation-implementation-decoration
(rs::resource-operation-implementation-decoration)
((error-handler :initarg :error-handler
:accessor error-handler
:initform *default-error-handler*))
(:metaclass closer-mop:funcallable-standard-class))
(defmethod rs::process-resource-operation-implementation-option
((option (eql :error-handling))
resource-operation-implementation
&key (enabled t)
#+(or abcl ecl) &allow-other-keys)
(if enabled
(make-instance 'error-handling-resource-operation-implementation-decoration
:decorates resource-operation-implementation)
resource-operation-implementation))
(defmethod execute :around ((decoration error-handling-resource-operation-implementation-decoration)
&rest args)
(declare (ignore args))
(with-error-handler ((error-handler decoration))
(call-next-method)))
(cl-annot:defannotation error-handling (args resource-operation-implementation)
(:arity 2)
`(rs::configure-resource-operation-implementation
(rs::name (rs::resource-operation ,resource-operation-implementation))
(list :error-handling ,@args)))
| null | https://raw.githubusercontent.com/mmontone/cl-rest-server/cd3a08681a1c3215866fedcd36a6bc98d223d52d/src/error-handling.lisp | lisp | Error handling configuration
Conditions
We don't want to log HTTP "error" signals like
an application error
else, debug mode
http-return-code decides the HTTP status code to return for
the signaled condition. Implement this method for new conditions.
Example:
Plugging | (in-package :rest-server.error)
(defvar *catch-errors* t)
(defvar *server-catch-errors*)
(defvar *error-handler* 'log-api-error)
(defvar *default-error-handler* 'default-error-handler)
(define-condition http-error (simple-error)
((status-code :initarg :status-code
:initform (error "Provide the status code")
:accessor status-code)
(info :initarg :info
:initform nil
:accessor http-error-info
:documentation "A plist of extra error info to be serialized back"))
(:report (lambda (c s)
(format s "HTTP error ~A: ~A ~A"
(status-code c)
(apply #'format nil (simple-condition-format-control c)
(simple-condition-format-arguments c))
(http-error-info c)))))
(defun http-error (status-code datum &rest args)
(error 'http-error
:status-code status-code
:format-control datum
:format-arguments args))
(defgeneric log-error-p (error)
(:documentation "Returns true for conditions that should be logged."))
(defmethod log-error-p ((error error))
"Errors are logged"
t)
(defmethod log-error-p (error)
"The default is not to log conditions"
nil)
(defmethod log-error-p ((error http-error))
"HTTP errors are not logged"
nil)
(defmethod log-error-p ((error schemata:validation-error))
"Validation errors are not logged"
nil)
(defun default-error-handler (error)
(when (log-error-p error)
(log-api-error error))
(setup-reply-from-error error))
(defmethod log-api-error ((error error))
(log5:log-for (rs::rest-server log5:error+) "ERROR: ~A" error)
(log5:log-for (rs::rest-server log5:error+)
(trivial-backtrace:print-backtrace error :output nil))
(format *debug-io* "ERROR: ~a~%" error)
(trivial-backtrace:print-backtrace error))
(defmethod log-api-error ((error http-error))
)
(defmacro with-error-handler ((&optional (error-handler '*default-error-handler*))
&body body)
`(call-with-error-handler ,error-handler
(lambda () (progn ,@body))))
(define-condition http-not-found-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-not-found+
:format-control "Resource not found"))
(define-condition http-internal-server-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-internal-server-error+
:format-control "Internal server error"))
(define-condition http-bad-request (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-bad-request+
:format-control "Bad request"))
(define-condition http-authorization-required-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-authorization-required+
:format-control "Authorization required"))
(define-condition http-forbidden-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-forbidden+
:format-control "Forbidden"))
(define-condition http-service-unavailable-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-service-unavailable+
:format-control "Service unavailable"))
(define-condition http-unsupported-media-type-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-unsupported-media-type+
:format-control "Unsupported media type"))
(define-condition http-not-acceptable-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-not-acceptable+
:format-control "Not acceptable"))
(define-condition http-method-not-allowed-error (http-error)
()
(:default-initargs
:status-code hunchentoot:+http-method-not-allowed+
:format-control "Method not allowed"))
(defparameter *http-status-codes-conditions*
'((404 . http-not-found-error)
(400 . http-bad-request)
(401 . http-authorization-required-error)
(403 . http-forbidden-error)
(500 . http-internal-server-error)
(415 . http-unsupported-media-type-error)))
(defun serialize-error (error)
(let ((serializer (rs::accept-serializer)))
(set-reply-content-type (generic-serializer::serializer-content-type serializer))
(with-output-to-string (s)
(generic-serializer:with-serializer-output s
(generic-serializer:with-serializer serializer
(generic-serializer:serialize error))))))
(defmethod generic-serializer:serialize ((error error) &optional
(serializer generic-serializer::*serializer*)
(stream generic-serializer::*serializer-output*) &rest args)
(declare (ignore args))
(generic-serializer:with-object ("error" :serializer serializer
:stream stream)
(generic-serializer:set-attribute
"detail"
(let ((debug-mode (if (boundp 'rs:*server-debug-mode*)
rs:*server-debug-mode*
rs:*debug-mode*)))
(if (not debug-mode)
"Internal server error"
(with-output-to-string (s)
(princ error s)
(terpri s)
(trivial-backtrace:print-backtrace-to-stream s))))
:serializer serializer
:stream stream)))
(defmethod generic-serializer:serialize ((error http-error) &optional
(serializer generic-serializer::*serializer*)
(stream generic-serializer::*serializer-output*) &rest args)
(declare (ignore args))
(generic-serializer:with-object ("error" :serializer serializer
:stream stream)
(generic-serializer:set-attribute
"detail"
(apply #'format
nil
(simple-condition-format-control error)
(simple-condition-format-arguments error))
:serializer serializer
:stream stream)
(alexandria:doplist (key val (http-error-info error))
(generic-serializer:set-attribute
(princ-to-string key)
val))))
(defmethod http-return-code ((error schemata:validation-error))
hunchentoot:+http-bad-request+)
(defmethod generic-serializer:serialize ((error schemata:validation-error)
&optional
(serializer generic-serializer::*serializer*)
(stream generic-serializer::*serializer-output*) &rest args)
(declare (ignore args))
(generic-serializer:with-object ("error" :serializer serializer
:stream stream)
(generic-serializer:set-attribute
"message"
(apply #'format
nil
(simple-condition-format-control error)
(simple-condition-format-arguments error))
:serializer serializer
:stream stream)))
(defmethod http-return-code ((condition error))
hunchentoot:+http-internal-server-error+)
(defmethod http-return-code ((condition http-error))
(status-code condition))
(defmethod setup-reply-from-error ((error error))
(setf (hunchentoot:return-code*)
(http-return-code error))
(serialize-error error))
(defmethod setup-reply-from-error ((error http-error))
(setf (hunchentoot:return-code*)
(http-return-code error))
(serialize-error error))
(defvar *retry-after-seconds* 5)
(defmethod setup-reply-from-error ((error http-service-unavailable-error))
"We add a retry-after header for the user to try again. The retry-after header value is in seconds"
(call-next-method)
(setf (hunchentoot:header-out "Retry-After") *retry-after-seconds*))
(defun call-with-error-handler (error-handler function)
(let ((catch-errors (if (boundp '*server-catch-errors*)
*server-catch-errors*
*catch-errors*))
(error-handler (or (and (symbolp error-handler)
(symbol-function error-handler))
error-handler)))
(if catch-errors
(handler-case
(funcall function)
(error (e)
(funcall error-handler e)))
(funcall function))))
(defclass error-handling-resource-operation-implementation-decoration
(rs::resource-operation-implementation-decoration)
((error-handler :initarg :error-handler
:accessor error-handler
:initform *default-error-handler*))
(:metaclass closer-mop:funcallable-standard-class))
(defmethod rs::process-resource-operation-implementation-option
((option (eql :error-handling))
resource-operation-implementation
&key (enabled t)
#+(or abcl ecl) &allow-other-keys)
(if enabled
(make-instance 'error-handling-resource-operation-implementation-decoration
:decorates resource-operation-implementation)
resource-operation-implementation))
(defmethod execute :around ((decoration error-handling-resource-operation-implementation-decoration)
&rest args)
(declare (ignore args))
(with-error-handler ((error-handler decoration))
(call-next-method)))
(cl-annot:defannotation error-handling (args resource-operation-implementation)
(:arity 2)
`(rs::configure-resource-operation-implementation
(rs::name (rs::resource-operation ,resource-operation-implementation))
(list :error-handling ,@args)))
|
24ea6ee823a46713e3e448a56a814369b77d1eb1e5f2b828f05235bc06a71f60 | shayne-fletcher/zen | bdate_test.ml | let _ =
let t = Bdate.local_day ()
and u = Bdate.mk_date (2015, 01, 01) in
let yr, mon, day= Bdate.year_month_day u in
Printf.printf "%s\n" (Bdate.string_of_date t);
Printf.printf "%s\n" (Bdate.string_of_date u);
Printf.printf "%d\n" (compare u t);
Printf.printf "%d\n" (compare t u);
Printf.printf "%d\n" (compare t t);
Printf.printf "%d\n" (compare u u);
Printf.printf "%d/%d/%d\n" yr mon day
| null | https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/bdate/bdate_test.ml | ocaml | let _ =
let t = Bdate.local_day ()
and u = Bdate.mk_date (2015, 01, 01) in
let yr, mon, day= Bdate.year_month_day u in
Printf.printf "%s\n" (Bdate.string_of_date t);
Printf.printf "%s\n" (Bdate.string_of_date u);
Printf.printf "%d\n" (compare u t);
Printf.printf "%d\n" (compare t u);
Printf.printf "%d\n" (compare t t);
Printf.printf "%d\n" (compare u u);
Printf.printf "%d/%d/%d\n" yr mon day
|
|
341cae67835055cd4dd6a990034c577f05961c8629e8120051120c63fdf19845 | lambdacube3d/lambdacube-edsl | CubeMap.hs | {-# OPTIONS -cpp #-}
# LANGUAGE OverloadedStrings , , TypeOperators , DataKinds , FlexibleContexts #
import Control.Applicative hiding (Const)
import Control.Monad
import qualified Data.ByteString.Char8 as SB
import qualified Data.Trie as T
import Data.Vect hiding (reflect')
import Data.Vect.Float.Instances ()
import FRP.Elerea.Param
import qualified Graphics.UI.GLFW as GLFW
import Text.Printf
import LambdaCube.GL
import LambdaCube.GL.Mesh
import Common.Utils
import Common.GraphicsUtils
#ifdef CAPTURE
import Graphics.Rendering.OpenGL.Raw.Core32
import Codec.Image.DevIL
import Text.Printf
import Foreign
withFrameBuffer :: Int -> Int -> Int -> Int -> (Ptr Word8 -> IO ()) -> IO ()
withFrameBuffer x y w h fn = allocaBytes (w*h*4) $ \p -> do
glReadPixels (fromIntegral x) (fromIntegral y) (fromIntegral w) (fromIntegral h) gl_RGBA gl_UNSIGNED_BYTE $ castPtr p
fn p
#endif
main :: IO ()
main = do
#ifdef CAPTURE
ilInit
#endif
let pipeline :: Exp Obj (Image 1 V4F)
pipeline = PrjFrameBuffer "outFB" tix0 sceneRender
(win,windowSize) <- initWindow "LambdaCube 3D Cube Map Demo" 1280 720
let keyIsPressed k = fmap (==GLFW.KeyState'Pressed) $ GLFW.getKey win k
(duration, renderer) <- measureDuration $ compileRenderer (ScreenOut pipeline)
putStrLn $ "Renderer compiled - " ++ show duration
putStrLn "Renderer uniform slots:"
forM_ (T.toList (slotUniform renderer)) $ \(name, slot) -> do
putStrLn $ " " ++ SB.unpack name
forM_ (T.toList slot) $ \(inputName, inputType) -> do
putStrLn $ " " ++ SB.unpack inputName ++ " :: " ++ show inputType
putStrLn "Renderer stream slots:"
forM_ (T.toList (slotStream renderer)) $ \(name, (primitive, attributes)) -> do
putStrLn $ " " ++ SB.unpack name ++ " - " ++ show primitive
forM_ (T.toList attributes) $ \(attributeName, attributeType) -> do
putStrLn $ " " ++ SB.unpack attributeName ++ " :: " ++ show attributeType
quadMesh <- compileMesh quad
addMesh renderer "postSlot" quadMesh []
cubeMesh <- compileMesh (cube 1)
(duration, cubeObjects) <- measureDuration $ replicateM 6 $ addMesh renderer "geometrySlot" cubeMesh ["modelMatrix"]
putStrLn $ "Cube meshes added - " ++ show duration
( sphere 5 25 )
(duration, reflectorObject) <- measureDuration $ addMesh renderer "reflectSlot" reflectorMesh ["modelMatrix"]
putStrLn $ "Reflector mesh added - " ++ show duration
let objectSlots = reflectorSlot : map objectUniformSetter cubeObjects
reflectorSlot = objectUniformSetter reflectorObject
sceneSlots = uniformSetter renderer
draw command = do
render renderer
command
GLFW.swapBuffers win >> GLFW.pollEvents
sceneSignal <- start $ do
thread <- scene win keyIsPressed (setScreenSize renderer) sceneSlots objectSlots windowSize
return $ draw <$> thread
driveNetwork sceneSignal $ readInput keyIsPressed
dispose renderer
putStrLn "Renderer destroyed."
GLFW.destroyWindow win
GLFW.terminate
scene win keyIsPressed setSize sceneSlots (reflectorSlot:planeSlot:cubeSlots) windowSize = do
pause <- toggle =<< risingEdge =<< effectful (keyIsPressed (GLFW.Key'P))
time <- transfer 0 (\dt paused time -> time + if paused then 0 else dt) pause
capture <- toggle =<< risingEdge =<< effectful (keyIsPressed (GLFW.Key'C))
frameCount <- stateful (0 :: Int) (const (+1))
fpsTracking <- stateful (0, 0, Nothing) $ \dt (time, count, _) ->
let time' = time + dt
done = time > 5
in if done
then (0, 0, Just (count / time'))
else (time', count + 1, Nothing)
mousePosition <- effectful $ do
(x, y) <- GLFW.getCursorPos win
return $ Vec2 (realToFrac x) (realToFrac y)
directionControl <- effectful $ (,,,,)
<$> keyIsPressed GLFW.Key'Left
<*> keyIsPressed GLFW.Key'Up
<*> keyIsPressed GLFW.Key'Down
<*> keyIsPressed GLFW.Key'Right
<*> keyIsPressed GLFW.Key'RightShift
mousePosition' <- delay zero mousePosition
camera <- userCamera (Vec3 (-4) 0 10) (mousePosition - mousePosition') directionControl
let setViewCameraMatrix = uniformM44F "viewCameraMatrix" sceneSlots . fromMat4
setViewCameraPosition = uniformV3F "viewCameraPosition" sceneSlots . fromVec3
setCubeCameraMatrix i = uniformM44F (cubeMatrixName i) sceneSlots . fromMat4
setCubeCameraPosition = uniformV3F "cubeCameraPosition" sceneSlots . fromVec3
setLightPosition = uniformV3F "lightPosition" sceneSlots . fromVec3
setPlaneModelMatrix = uniformM44F "modelMatrix" planeSlot . fromMat4
setCubeModelMatrices = [uniformM44F "modelMatrix" cubeSlot . fromMat4 | cubeSlot <- cubeSlots]
setReflectorModelMatrix = uniformM44F "modelMatrix" reflectorSlot . fromMat4
setupRendering ((_, _, fps), frameCount, capture) (windowWidth, windowHeight) (cameraPosition, cameraDirection, cameraUp, _) time = do
let aspect = fromIntegral windowWidth / fromIntegral windowHeight
cameraView = fromProjective (lookat cameraPosition (cameraPosition &+ cameraDirection) cameraUp)
cameraProjection = perspective 0.1 50 (pi/2) aspect
lightPosition = Vec3 (15 * sin time) 2 10
reflectorPosition = Vec3 (-8) (5 * sin (time * 0.25)) 0
cubeCameraProjection = perspective 0.1 50 (pi/2) 1
cubeLookAt dir up = fromProjective (lookat reflectorPosition (reflectorPosition &+ dir) up)
cubeCameraMatrix 1 = cubeLookAt (Vec3 1 0 0) (Vec3 0 (-1) 0)
cubeCameraMatrix 2 = cubeLookAt (Vec3 (-1) 0 0) (Vec3 0 (-1) 0)
cubeCameraMatrix 3 = cubeLookAt (Vec3 0 1 0) (Vec3 0 0 1)
cubeCameraMatrix 4 = cubeLookAt (Vec3 0 (-1) 0) (Vec3 0 0 (-1))
cubeCameraMatrix 5 = cubeLookAt (Vec3 0 0 1) (Vec3 0 (-1) 0)
cubeCameraMatrix 6 = cubeLookAt (Vec3 0 0 (-1)) (Vec3 0 (-1) 0)
case fps of
Just value -> putStrLn $ "FPS: " ++ show value
Nothing -> return ()
setViewCameraMatrix (cameraView .*. cameraProjection)
setViewCameraPosition cameraPosition
setLightPosition lightPosition
setCubeCameraPosition reflectorPosition
setReflectorModelMatrix (fromProjective (translation reflectorPosition))
forM_ [1..6] $ \index -> setCubeCameraMatrix index (cubeCameraMatrix index .*. cubeCameraProjection)
setPlaneModelMatrix (fromProjective $ scaling (Vec3 12 12 1) .*. translation (Vec3 0 (-2) (-12)))
forM_ (zip setCubeModelMatrices [0..]) $ \(setCubeModelMatrix, i) -> do
let t = i * 2 * pi / 5
s = (t + 2) * 0.3
trans = scaling (Vec3 s s s) .*. rotationEuler (Vec3 0 0 s) .*. translation (Vec3 (t * 0.3) (sin t * 4) (cos t * 4))
setCubeModelMatrix (fromProjective trans)
setSize (fromIntegral windowWidth) (fromIntegral windowHeight)
return $ do
#ifdef CAPTURE
when capture $ do
glFinish
withFrameBuffer 0 0 windowWidth windowHeight $ writeImageFromPtr (printf "frame%08d.jpg" frameCount) (windowHeight, windowWidth)
#endif
return ()
effectful4 setupRendering ((,,) <$> fpsTracking <*> frameCount <*> capture) windowSize camera time
: : IO ( Maybe Float )
readInput keyIsPressed = do
Just t <- GLFW.getTime
GLFW.setTime 0
k <- keyIsPressed GLFW.Key'Escape
return $ if k then Nothing else Just (realToFrac t)
sceneRender :: Exp Obj (FrameBuffer 1 (Float, V4F))
sceneRender = Accumulate accCtx PassAll reflectFrag (Rasterize rastCtx reflectPrims) directRender
where
directRender = Accumulate accCtx PassAll frag (Rasterize rastCtx directPrims) clearBuf
cubeMapRender = Accumulate accCtx PassAll frag (Rasterize rastCtx cubePrims) clearBuf6
accCtx = AccumulationContext Nothing (DepthOp Less True :. ColorOp NoBlending (one' :: V4B) :. ZT)
rastCtx = triangleCtx { ctxCullMode = CullFront CCW }
clearBuf = FrameBuffer (DepthImage n1 1000 :. ColorImage n1 (V4 0.1 0.2 0.6 1) :. ZT)
clearBuf6 = FrameBuffer (DepthImage n6 1000 :. ColorImage n6 (V4 0.05 0.1 0.3 1) :. ZT)
worldInput = Fetch "geometrySlot" Triangles (IV3F "position", IV3F "normal")
reflectInput = Fetch "reflectSlot" Triangles (IV3F "position", IV3F "normal")
directPrims = Transform directVert worldInput
cubePrims = Reassemble geom (Transform cubeMapVert worldInput)
reflectPrims = Transform directVert reflectInput
lightPosition = Uni (IV3F "lightPosition")
viewCameraMatrix = Uni (IM44F "viewCameraMatrix")
viewCameraPosition = Uni (IV3F "viewCameraPosition")
cubeCameraMatrix i = Uni (IM44F (cubeMatrixName i))
cubeCameraPosition = Uni (IV3F "cubeCameraPosition")
modelMatrix = Uni (IM44F "modelMatrix")
transformGeometry :: Exp f V4F -> Exp f V3F -> Exp f M44F -> (Exp f V4F, Exp f V4F, Exp f V3F)
transformGeometry localPos localNormal viewMatrix = (viewPos, worldPos, worldNormal)
where
worldPos = modelMatrix @*. localPos
viewPos = viewMatrix @*. worldPos
worldNormal = normalize' (v4v3 (modelMatrix @*. n3v4 localNormal))
directVert :: Exp V (V3F, V3F) -> VertexOut () (V3F, V3F, V3F)
directVert attr = VertexOut viewPos (floatV 1) ZT (Smooth (v4v3 worldPos) :. Smooth worldNormal :. Flat viewCameraPosition :. ZT)
where
(localPos, localNormal) = untup2 attr
(viewPos, worldPos, worldNormal) = transformGeometry (v3v4 localPos) localNormal viewCameraMatrix
cubeMapVert :: Exp V (V3F, V3F) -> VertexOut () V3F
cubeMapVert attr = VertexOut (v3v4 localPos) (floatV 1) ZT (Smooth localNormal :. ZT)
where
(localPos, localNormal) = untup2 attr
geom :: GeometryShader Triangle Triangle () () 6 V3F (V3F, V3F, V3F)
geom = GeometryShader n6 TrianglesOutput 18 init prim vert
where
init attr = tup2 (primInit, intG 6)
where
primInit = tup2 (intG 0, attr)
prim primState = tup5 (layer, layer, primState', vertInit, intG 3)
where
(layer, attr) = untup2 primState
primState' = tup2 (layer @+ intG 1, attr)
vertInit = tup3 (intG 0, viewMatrix, attr)
viewMatrix = indexG (map cubeCameraMatrix [1..6]) layer
vert vertState = GeometryOut vertState' viewPos pointSize ZT (Smooth (v4v3 worldPos) :. Smooth worldNormal :. Flat cubeCameraPosition :. ZT)
where
(index, viewMatrix, attr) = untup3 vertState
vertState' = tup3 (index @+ intG 1, viewMatrix, attr)
(attr0, attr1, attr2) = untup3 attr
(localPos, pointSize, _, localNormal) = untup4 (indexG [attr0, attr1, attr2] index)
(viewPos, worldPos, worldNormal) = transformGeometry localPos localNormal viewMatrix
frag :: Exp F (V3F, V3F, V3F) -> FragmentOut (Depth Float :+: Color V4F :+: ZZ)
frag attr = FragmentOutRastDepth (luminance :. ZT)
where
lambert = max' (floatF 0) (worldNormal @. normalize' (lightPosition @- worldPos))
reflectedRay = normalize' (reflect' (worldPos @- (cameraPosition :: Exp F V3F)) worldNormal)
directLight = normalize' (lightPosition @- worldPos)
phong = max' (floatF 0) (reflectedRay @. directLight)
colour = pack' (V3 (floatF 0.7) (floatF 0.05) (floatF 0))
luminance = v3v4 (colour @* lambert @+ pow' phong (floatF 10))
(worldPos, worldNormal, cameraPosition) = untup3 attr
reflectFrag :: Exp F (V3F, V3F, V3F) -> FragmentOut (Depth Float :+: Color V4F :+: ZZ)
reflectFrag attr = FragmentOutRastDepth (luminance :. ZT)
where
reflectedRay = reflect' (worldPos @- (cameraPosition :: Exp F V3F)) worldNormal
luminance = reflectionSample reflectedRay
(worldPos, worldNormal, cameraPosition) = untup3 attr
reflectionSample dir = texture' (Sampler LinearFilter ClampToEdge reflectionMap) dir
reflectionMap = Texture (TextureCube (Float RGBA)) (V2 256 256) NoMip [PrjFrameBuffer "" tix0 cubeMapRender]
indexG :: GPU a => [Exp G a] -> Exp G Int32 -> Exp G a
indexG xs index = go xs 0
where
go [x] _ = x
go (x:xs) i = Cond (index @== intG i) x (go xs (i+1))
cubeMatrixName :: Int -> SB.ByteString
cubeMatrixName i = SB.pack (printf "cubeCameraMatrix%d" i)
| null | https://raw.githubusercontent.com/lambdacube3d/lambdacube-edsl/4347bb0ed344e71c0333136cf2e162aec5941df7/lambdacube-samples/CubeMap.hs | haskell | # OPTIONS -cpp # | # LANGUAGE OverloadedStrings , , TypeOperators , DataKinds , FlexibleContexts #
import Control.Applicative hiding (Const)
import Control.Monad
import qualified Data.ByteString.Char8 as SB
import qualified Data.Trie as T
import Data.Vect hiding (reflect')
import Data.Vect.Float.Instances ()
import FRP.Elerea.Param
import qualified Graphics.UI.GLFW as GLFW
import Text.Printf
import LambdaCube.GL
import LambdaCube.GL.Mesh
import Common.Utils
import Common.GraphicsUtils
#ifdef CAPTURE
import Graphics.Rendering.OpenGL.Raw.Core32
import Codec.Image.DevIL
import Text.Printf
import Foreign
withFrameBuffer :: Int -> Int -> Int -> Int -> (Ptr Word8 -> IO ()) -> IO ()
withFrameBuffer x y w h fn = allocaBytes (w*h*4) $ \p -> do
glReadPixels (fromIntegral x) (fromIntegral y) (fromIntegral w) (fromIntegral h) gl_RGBA gl_UNSIGNED_BYTE $ castPtr p
fn p
#endif
main :: IO ()
main = do
#ifdef CAPTURE
ilInit
#endif
let pipeline :: Exp Obj (Image 1 V4F)
pipeline = PrjFrameBuffer "outFB" tix0 sceneRender
(win,windowSize) <- initWindow "LambdaCube 3D Cube Map Demo" 1280 720
let keyIsPressed k = fmap (==GLFW.KeyState'Pressed) $ GLFW.getKey win k
(duration, renderer) <- measureDuration $ compileRenderer (ScreenOut pipeline)
putStrLn $ "Renderer compiled - " ++ show duration
putStrLn "Renderer uniform slots:"
forM_ (T.toList (slotUniform renderer)) $ \(name, slot) -> do
putStrLn $ " " ++ SB.unpack name
forM_ (T.toList slot) $ \(inputName, inputType) -> do
putStrLn $ " " ++ SB.unpack inputName ++ " :: " ++ show inputType
putStrLn "Renderer stream slots:"
forM_ (T.toList (slotStream renderer)) $ \(name, (primitive, attributes)) -> do
putStrLn $ " " ++ SB.unpack name ++ " - " ++ show primitive
forM_ (T.toList attributes) $ \(attributeName, attributeType) -> do
putStrLn $ " " ++ SB.unpack attributeName ++ " :: " ++ show attributeType
quadMesh <- compileMesh quad
addMesh renderer "postSlot" quadMesh []
cubeMesh <- compileMesh (cube 1)
(duration, cubeObjects) <- measureDuration $ replicateM 6 $ addMesh renderer "geometrySlot" cubeMesh ["modelMatrix"]
putStrLn $ "Cube meshes added - " ++ show duration
( sphere 5 25 )
(duration, reflectorObject) <- measureDuration $ addMesh renderer "reflectSlot" reflectorMesh ["modelMatrix"]
putStrLn $ "Reflector mesh added - " ++ show duration
let objectSlots = reflectorSlot : map objectUniformSetter cubeObjects
reflectorSlot = objectUniformSetter reflectorObject
sceneSlots = uniformSetter renderer
draw command = do
render renderer
command
GLFW.swapBuffers win >> GLFW.pollEvents
sceneSignal <- start $ do
thread <- scene win keyIsPressed (setScreenSize renderer) sceneSlots objectSlots windowSize
return $ draw <$> thread
driveNetwork sceneSignal $ readInput keyIsPressed
dispose renderer
putStrLn "Renderer destroyed."
GLFW.destroyWindow win
GLFW.terminate
scene win keyIsPressed setSize sceneSlots (reflectorSlot:planeSlot:cubeSlots) windowSize = do
pause <- toggle =<< risingEdge =<< effectful (keyIsPressed (GLFW.Key'P))
time <- transfer 0 (\dt paused time -> time + if paused then 0 else dt) pause
capture <- toggle =<< risingEdge =<< effectful (keyIsPressed (GLFW.Key'C))
frameCount <- stateful (0 :: Int) (const (+1))
fpsTracking <- stateful (0, 0, Nothing) $ \dt (time, count, _) ->
let time' = time + dt
done = time > 5
in if done
then (0, 0, Just (count / time'))
else (time', count + 1, Nothing)
mousePosition <- effectful $ do
(x, y) <- GLFW.getCursorPos win
return $ Vec2 (realToFrac x) (realToFrac y)
directionControl <- effectful $ (,,,,)
<$> keyIsPressed GLFW.Key'Left
<*> keyIsPressed GLFW.Key'Up
<*> keyIsPressed GLFW.Key'Down
<*> keyIsPressed GLFW.Key'Right
<*> keyIsPressed GLFW.Key'RightShift
mousePosition' <- delay zero mousePosition
camera <- userCamera (Vec3 (-4) 0 10) (mousePosition - mousePosition') directionControl
let setViewCameraMatrix = uniformM44F "viewCameraMatrix" sceneSlots . fromMat4
setViewCameraPosition = uniformV3F "viewCameraPosition" sceneSlots . fromVec3
setCubeCameraMatrix i = uniformM44F (cubeMatrixName i) sceneSlots . fromMat4
setCubeCameraPosition = uniformV3F "cubeCameraPosition" sceneSlots . fromVec3
setLightPosition = uniformV3F "lightPosition" sceneSlots . fromVec3
setPlaneModelMatrix = uniformM44F "modelMatrix" planeSlot . fromMat4
setCubeModelMatrices = [uniformM44F "modelMatrix" cubeSlot . fromMat4 | cubeSlot <- cubeSlots]
setReflectorModelMatrix = uniformM44F "modelMatrix" reflectorSlot . fromMat4
setupRendering ((_, _, fps), frameCount, capture) (windowWidth, windowHeight) (cameraPosition, cameraDirection, cameraUp, _) time = do
let aspect = fromIntegral windowWidth / fromIntegral windowHeight
cameraView = fromProjective (lookat cameraPosition (cameraPosition &+ cameraDirection) cameraUp)
cameraProjection = perspective 0.1 50 (pi/2) aspect
lightPosition = Vec3 (15 * sin time) 2 10
reflectorPosition = Vec3 (-8) (5 * sin (time * 0.25)) 0
cubeCameraProjection = perspective 0.1 50 (pi/2) 1
cubeLookAt dir up = fromProjective (lookat reflectorPosition (reflectorPosition &+ dir) up)
cubeCameraMatrix 1 = cubeLookAt (Vec3 1 0 0) (Vec3 0 (-1) 0)
cubeCameraMatrix 2 = cubeLookAt (Vec3 (-1) 0 0) (Vec3 0 (-1) 0)
cubeCameraMatrix 3 = cubeLookAt (Vec3 0 1 0) (Vec3 0 0 1)
cubeCameraMatrix 4 = cubeLookAt (Vec3 0 (-1) 0) (Vec3 0 0 (-1))
cubeCameraMatrix 5 = cubeLookAt (Vec3 0 0 1) (Vec3 0 (-1) 0)
cubeCameraMatrix 6 = cubeLookAt (Vec3 0 0 (-1)) (Vec3 0 (-1) 0)
case fps of
Just value -> putStrLn $ "FPS: " ++ show value
Nothing -> return ()
setViewCameraMatrix (cameraView .*. cameraProjection)
setViewCameraPosition cameraPosition
setLightPosition lightPosition
setCubeCameraPosition reflectorPosition
setReflectorModelMatrix (fromProjective (translation reflectorPosition))
forM_ [1..6] $ \index -> setCubeCameraMatrix index (cubeCameraMatrix index .*. cubeCameraProjection)
setPlaneModelMatrix (fromProjective $ scaling (Vec3 12 12 1) .*. translation (Vec3 0 (-2) (-12)))
forM_ (zip setCubeModelMatrices [0..]) $ \(setCubeModelMatrix, i) -> do
let t = i * 2 * pi / 5
s = (t + 2) * 0.3
trans = scaling (Vec3 s s s) .*. rotationEuler (Vec3 0 0 s) .*. translation (Vec3 (t * 0.3) (sin t * 4) (cos t * 4))
setCubeModelMatrix (fromProjective trans)
setSize (fromIntegral windowWidth) (fromIntegral windowHeight)
return $ do
#ifdef CAPTURE
when capture $ do
glFinish
withFrameBuffer 0 0 windowWidth windowHeight $ writeImageFromPtr (printf "frame%08d.jpg" frameCount) (windowHeight, windowWidth)
#endif
return ()
effectful4 setupRendering ((,,) <$> fpsTracking <*> frameCount <*> capture) windowSize camera time
: : IO ( Maybe Float )
readInput keyIsPressed = do
Just t <- GLFW.getTime
GLFW.setTime 0
k <- keyIsPressed GLFW.Key'Escape
return $ if k then Nothing else Just (realToFrac t)
sceneRender :: Exp Obj (FrameBuffer 1 (Float, V4F))
sceneRender = Accumulate accCtx PassAll reflectFrag (Rasterize rastCtx reflectPrims) directRender
where
directRender = Accumulate accCtx PassAll frag (Rasterize rastCtx directPrims) clearBuf
cubeMapRender = Accumulate accCtx PassAll frag (Rasterize rastCtx cubePrims) clearBuf6
accCtx = AccumulationContext Nothing (DepthOp Less True :. ColorOp NoBlending (one' :: V4B) :. ZT)
rastCtx = triangleCtx { ctxCullMode = CullFront CCW }
clearBuf = FrameBuffer (DepthImage n1 1000 :. ColorImage n1 (V4 0.1 0.2 0.6 1) :. ZT)
clearBuf6 = FrameBuffer (DepthImage n6 1000 :. ColorImage n6 (V4 0.05 0.1 0.3 1) :. ZT)
worldInput = Fetch "geometrySlot" Triangles (IV3F "position", IV3F "normal")
reflectInput = Fetch "reflectSlot" Triangles (IV3F "position", IV3F "normal")
directPrims = Transform directVert worldInput
cubePrims = Reassemble geom (Transform cubeMapVert worldInput)
reflectPrims = Transform directVert reflectInput
lightPosition = Uni (IV3F "lightPosition")
viewCameraMatrix = Uni (IM44F "viewCameraMatrix")
viewCameraPosition = Uni (IV3F "viewCameraPosition")
cubeCameraMatrix i = Uni (IM44F (cubeMatrixName i))
cubeCameraPosition = Uni (IV3F "cubeCameraPosition")
modelMatrix = Uni (IM44F "modelMatrix")
transformGeometry :: Exp f V4F -> Exp f V3F -> Exp f M44F -> (Exp f V4F, Exp f V4F, Exp f V3F)
transformGeometry localPos localNormal viewMatrix = (viewPos, worldPos, worldNormal)
where
worldPos = modelMatrix @*. localPos
viewPos = viewMatrix @*. worldPos
worldNormal = normalize' (v4v3 (modelMatrix @*. n3v4 localNormal))
directVert :: Exp V (V3F, V3F) -> VertexOut () (V3F, V3F, V3F)
directVert attr = VertexOut viewPos (floatV 1) ZT (Smooth (v4v3 worldPos) :. Smooth worldNormal :. Flat viewCameraPosition :. ZT)
where
(localPos, localNormal) = untup2 attr
(viewPos, worldPos, worldNormal) = transformGeometry (v3v4 localPos) localNormal viewCameraMatrix
cubeMapVert :: Exp V (V3F, V3F) -> VertexOut () V3F
cubeMapVert attr = VertexOut (v3v4 localPos) (floatV 1) ZT (Smooth localNormal :. ZT)
where
(localPos, localNormal) = untup2 attr
geom :: GeometryShader Triangle Triangle () () 6 V3F (V3F, V3F, V3F)
geom = GeometryShader n6 TrianglesOutput 18 init prim vert
where
init attr = tup2 (primInit, intG 6)
where
primInit = tup2 (intG 0, attr)
prim primState = tup5 (layer, layer, primState', vertInit, intG 3)
where
(layer, attr) = untup2 primState
primState' = tup2 (layer @+ intG 1, attr)
vertInit = tup3 (intG 0, viewMatrix, attr)
viewMatrix = indexG (map cubeCameraMatrix [1..6]) layer
vert vertState = GeometryOut vertState' viewPos pointSize ZT (Smooth (v4v3 worldPos) :. Smooth worldNormal :. Flat cubeCameraPosition :. ZT)
where
(index, viewMatrix, attr) = untup3 vertState
vertState' = tup3 (index @+ intG 1, viewMatrix, attr)
(attr0, attr1, attr2) = untup3 attr
(localPos, pointSize, _, localNormal) = untup4 (indexG [attr0, attr1, attr2] index)
(viewPos, worldPos, worldNormal) = transformGeometry localPos localNormal viewMatrix
frag :: Exp F (V3F, V3F, V3F) -> FragmentOut (Depth Float :+: Color V4F :+: ZZ)
frag attr = FragmentOutRastDepth (luminance :. ZT)
where
lambert = max' (floatF 0) (worldNormal @. normalize' (lightPosition @- worldPos))
reflectedRay = normalize' (reflect' (worldPos @- (cameraPosition :: Exp F V3F)) worldNormal)
directLight = normalize' (lightPosition @- worldPos)
phong = max' (floatF 0) (reflectedRay @. directLight)
colour = pack' (V3 (floatF 0.7) (floatF 0.05) (floatF 0))
luminance = v3v4 (colour @* lambert @+ pow' phong (floatF 10))
(worldPos, worldNormal, cameraPosition) = untup3 attr
reflectFrag :: Exp F (V3F, V3F, V3F) -> FragmentOut (Depth Float :+: Color V4F :+: ZZ)
reflectFrag attr = FragmentOutRastDepth (luminance :. ZT)
where
reflectedRay = reflect' (worldPos @- (cameraPosition :: Exp F V3F)) worldNormal
luminance = reflectionSample reflectedRay
(worldPos, worldNormal, cameraPosition) = untup3 attr
reflectionSample dir = texture' (Sampler LinearFilter ClampToEdge reflectionMap) dir
reflectionMap = Texture (TextureCube (Float RGBA)) (V2 256 256) NoMip [PrjFrameBuffer "" tix0 cubeMapRender]
indexG :: GPU a => [Exp G a] -> Exp G Int32 -> Exp G a
indexG xs index = go xs 0
where
go [x] _ = x
go (x:xs) i = Cond (index @== intG i) x (go xs (i+1))
cubeMatrixName :: Int -> SB.ByteString
cubeMatrixName i = SB.pack (printf "cubeCameraMatrix%d" i)
|
9250d4239458b229fe1d0635e016b4826262add79c07c081091eead709fe8540 | RunOrg/RunOrg | rich.mli | (* © 2014 RunOrg *)
* A rich text block is a long UTF-8 string that includes formatting tags .
Tags follow an XML - like syntax , but the parser has been kept intentionally
simple . Supported tags are : < h1 > to < h6 > , < strong > , < em > , < p > , < ,
< a href > and < blockquote > .
The intent is that a rich text block should be usable as - is for HTML rendering
( at least , for the features that are supported by HTML rendering ) .
Special escape sequences & amp ; & lt ; & gt ; & quot ; are also supported .
Any other tags will be escaped .
Tags follow an XML-like syntax, but the parser has been kept intentionally
simple. Supported tags are: <h1> to <h6>, <strong>, <em>, <p>, <img src>,
<a href> and <blockquote>.
The intent is that a rich text block should be usable as-is for HTML rendering
(at least, for the features that are supported by HTML rendering).
Special escape sequences & < > " are also supported.
Any other tags will be escaped.
*)
include Fmt.FMT
(** Attempt to parse a string as a rich text block. Return [None] if the string
does not satisfy the requirements.
Also, even if [let Some rich = Rich.of_string str], there is no guarantee
that [Rich.to_string rich = str] (and indeed, the rich text block might
rename and reformat tags and whitespace. *)
val of_string : string -> t option
(** Returns the string representation of a rich text block. *)
val to_string : t -> string
| null | https://raw.githubusercontent.com/RunOrg/RunOrg/b53ee2357f4bcb919ac48577426d632dffc25062/server/stdLib/rich.mli | ocaml | © 2014 RunOrg
* Attempt to parse a string as a rich text block. Return [None] if the string
does not satisfy the requirements.
Also, even if [let Some rich = Rich.of_string str], there is no guarantee
that [Rich.to_string rich = str] (and indeed, the rich text block might
rename and reformat tags and whitespace.
* Returns the string representation of a rich text block. |
* A rich text block is a long UTF-8 string that includes formatting tags .
Tags follow an XML - like syntax , but the parser has been kept intentionally
simple . Supported tags are : < h1 > to < h6 > , < strong > , < em > , < p > , < ,
< a href > and < blockquote > .
The intent is that a rich text block should be usable as - is for HTML rendering
( at least , for the features that are supported by HTML rendering ) .
Special escape sequences & amp ; & lt ; & gt ; & quot ; are also supported .
Any other tags will be escaped .
Tags follow an XML-like syntax, but the parser has been kept intentionally
simple. Supported tags are: <h1> to <h6>, <strong>, <em>, <p>, <img src>,
<a href> and <blockquote>.
The intent is that a rich text block should be usable as-is for HTML rendering
(at least, for the features that are supported by HTML rendering).
Special escape sequences & < > " are also supported.
Any other tags will be escaped.
*)
include Fmt.FMT
val of_string : string -> t option
val to_string : t -> string
|
4f05c53d091c7ee79523c1faac301d9f4ab9060fbb0cdb03da292816de4c5d68 | cgrand/boring | project.clj | (defproject net.cgrand/boring "0.1.0-SNAPSHOT"
:description "A library to bore tunnels."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0"]
[org.apache.sshd/sshd-core "1.7.0"]])
| null | https://raw.githubusercontent.com/cgrand/boring/bca8885f01f8c7c0ad67c8d23cdd4ccc199dec1c/project.clj | clojure | (defproject net.cgrand/boring "0.1.0-SNAPSHOT"
:description "A library to bore tunnels."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.9.0"]
[org.apache.sshd/sshd-core "1.7.0"]])
|
|
a74d14bd88ebe231b611f2d101b0fd474033f8f96551bae128c76b475d2137a7 | backtracking/bibtex2html | biboutput.mli | (**************************************************************************)
(* bibtex2html - A BibTeX to HTML translator *)
Copyright ( C ) 1997 - 2014 and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU General Public
License version 2 , as published by the Free Software Foundation .
(* *)
(* This software is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *)
(* *)
See the GNU General Public License version 2 for more details
(* (enclosed in the file GPL). *)
(**************************************************************************)
s [ output_bib html ch bib keys ] outputs to the channel [ ch ] the
fields of the bibliography [ bib ] whose key belong to [ keys ] . [ html ]
is a flag that tells whether html anchors must be added : if [ html ]
is false , the output is a regular file , if [ html ] is true ,
anchors are added on crossrefs , abbreviations , and URLs in
fields . Notice that to guarantee that the generated part of the
bibliography is coherent , that is all needed abbreviations and
cross - references are included , one as to call Bibfilter.saturate
before . Notice finally that the channel [ ch ] is NOT closed by this
function
fields of the bibliography [bib] whose key belong to [keys]. [html]
is a flag that tells whether html anchors must be added: if [html]
is false, the output is a regular bibtex file, if [html] is true,
anchors are added on crossrefs, abbreviations, and URLs in
fields. Notice that to guarantee that the generated part of the
bibliography is coherent, that is all needed abbreviations and
cross-references are included, one as to call Bibfilter.saturate
before. Notice finally that the channel [ch] is NOT closed by this
function *)
open Bibtex
exception Bad_input_for_php of string
val output_bib :
?remove:string list -> ?rename:(string * string) list ->
?php:bool -> html:bool -> ?html_file:string ->
out_channel -> biblio -> KeySet.t option -> unit
s [ add_link_field f ] declares a new field [ f ] to be displayed as a web link
( when HTML option of [ output_bib ] is set )
(when HTML option of [output_bib] is set) *)
val add_link_field : string -> unit
| null | https://raw.githubusercontent.com/backtracking/bibtex2html/7c9547da79a13c3accffc9947c846df96a6edd68/biboutput.mli | ocaml | ************************************************************************
bibtex2html - A BibTeX to HTML translator
This software is free software; you can redistribute it and/or
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
(enclosed in the file GPL).
************************************************************************ | Copyright ( C ) 1997 - 2014 and
modify it under the terms of the GNU General Public
License version 2 , as published by the Free Software Foundation .
See the GNU General Public License version 2 for more details
s [ output_bib html ch bib keys ] outputs to the channel [ ch ] the
fields of the bibliography [ bib ] whose key belong to [ keys ] . [ html ]
is a flag that tells whether html anchors must be added : if [ html ]
is false , the output is a regular file , if [ html ] is true ,
anchors are added on crossrefs , abbreviations , and URLs in
fields . Notice that to guarantee that the generated part of the
bibliography is coherent , that is all needed abbreviations and
cross - references are included , one as to call Bibfilter.saturate
before . Notice finally that the channel [ ch ] is NOT closed by this
function
fields of the bibliography [bib] whose key belong to [keys]. [html]
is a flag that tells whether html anchors must be added: if [html]
is false, the output is a regular bibtex file, if [html] is true,
anchors are added on crossrefs, abbreviations, and URLs in
fields. Notice that to guarantee that the generated part of the
bibliography is coherent, that is all needed abbreviations and
cross-references are included, one as to call Bibfilter.saturate
before. Notice finally that the channel [ch] is NOT closed by this
function *)
open Bibtex
exception Bad_input_for_php of string
val output_bib :
?remove:string list -> ?rename:(string * string) list ->
?php:bool -> html:bool -> ?html_file:string ->
out_channel -> biblio -> KeySet.t option -> unit
s [ add_link_field f ] declares a new field [ f ] to be displayed as a web link
( when HTML option of [ output_bib ] is set )
(when HTML option of [output_bib] is set) *)
val add_link_field : string -> unit
|
cb4b8d289e3e5de4ea0e9d2cc9ffdadb1d8bb214847d476a955538f71d207534 | ml4tp/tcoq | scheme.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*s Production of Scheme syntax. *)
open Pp
open CErrors
open Util
open Names
open Miniml
open Mlutil
open Table
open Common
(*s Scheme renaming issues. *)
let keywords =
List.fold_right (fun s -> Id.Set.add (Id.of_string s))
[ "define"; "let"; "lambda"; "lambdas"; "match";
"apply"; "car"; "cdr";
"error"; "delay"; "force"; "_"; "__"]
Id.Set.empty
let pp_comment s = str";; "++h 0 s++fnl ()
let pp_header_comment = function
| None -> mt ()
| Some com -> pp_comment com ++ fnl () ++ fnl ()
let preamble _ comment _ usf =
pp_header_comment comment ++
str ";; This extracted scheme code relies on some additional macros\n" ++
str ";; available at -paris-diderot.fr/~letouzey/scheme\n" ++
str "(load \"macros_extr.scm\")\n\n" ++
(if usf.mldummy then str "(define __ (lambda (_) __))\n\n" else mt ())
let pr_id id =
let s = Id.to_string id in
for i = 0 to String.length s - 1 do
if s.[i] == '\'' then s.[i] <- '~'
done;
str s
let paren = pp_par true
let pp_abst st = function
| [] -> assert false
| [id] -> paren (str "lambda " ++ paren (pr_id id) ++ spc () ++ st)
| l -> paren
(str "lambdas " ++ paren (prlist_with_sep spc pr_id l) ++ spc () ++ st)
let pp_apply st _ = function
| [] -> st
| [a] -> hov 2 (paren (st ++ spc () ++ a))
| args -> hov 2 (paren (str "@ " ++ st ++
(prlist_strict (fun x -> spc () ++ x) args)))
(*s The pretty-printer for Scheme syntax *)
let pp_global k r = str (Common.pp_global k r)
(*s Pretty-printing of expressions. *)
let rec pp_expr env args =
let apply st = pp_apply st true args in
function
| MLrel n ->
let id = get_db_name n env in apply (pr_id id)
| MLapp (f,args') ->
let stl = List.map (pp_expr env []) args' in
pp_expr env (stl @ args) f
| MLlam _ as a ->
let fl,a' = collect_lams a in
let fl,env' = push_vars (List.map id_of_mlid fl) env in
apply (pp_abst (pp_expr env' [] a') (List.rev fl))
| MLletin (id,a1,a2) ->
let i,env' = push_vars [id_of_mlid id] env in
apply
(hv 0
(hov 2
(paren
(str "let " ++
paren
(paren
(pr_id (List.hd i) ++ spc () ++ pp_expr env [] a1))
++ spc () ++ hov 0 (pp_expr env' [] a2)))))
| MLglob r ->
apply (pp_global Term r)
| MLcons (_,r,args') ->
assert (List.is_empty args);
let st =
str "`" ++
paren (pp_global Cons r ++
(if List.is_empty args' then mt () else spc ()) ++
prlist_with_sep spc (pp_cons_args env) args')
in
if is_coinductive r then paren (str "delay " ++ st) else st
| MLtuple _ -> error "Cannot handle tuples in Scheme yet."
| MLcase (_,_,pv) when not (is_regular_match pv) ->
error "Cannot handle general patterns in Scheme yet."
| MLcase (_,t,pv) when is_custom_match pv ->
let mkfun (ids,_,e) =
if not (List.is_empty ids) then named_lams (List.rev ids) e
else dummy_lams (ast_lift 1 e) 1
in
apply
(paren
(hov 2
(str (find_custom_match pv) ++ fnl () ++
prvect (fun tr -> pp_expr env [] (mkfun tr) ++ fnl ()) pv
++ pp_expr env [] t)))
| MLcase (typ,t, pv) ->
let e =
if not (is_coinductive_type typ) then pp_expr env [] t
else paren (str "force" ++ spc () ++ pp_expr env [] t)
in
apply (v 3 (paren (str "match " ++ e ++ fnl () ++ pp_pat env pv)))
| MLfix (i,ids,defs) ->
let ids',env' = push_vars (List.rev (Array.to_list ids)) env in
pp_fix env' i (Array.of_list (List.rev ids'),defs) args
| MLexn s ->
An [ MLexn ] may be applied , but I do n't really care .
paren (str "error" ++ spc () ++ qs s)
| MLdummy _ ->
str "__" (* An [MLdummy] may be applied, but I don't really care. *)
| MLmagic a ->
pp_expr env args a
| MLaxiom -> paren (str "error \"AXIOM TO BE REALIZED\"")
and pp_cons_args env = function
| MLcons (_,r,args) when is_coinductive r ->
paren (pp_global Cons r ++
(if List.is_empty args then mt () else spc ()) ++
prlist_with_sep spc (pp_cons_args env) args)
| e -> str "," ++ pp_expr env [] e
and pp_one_pat env (ids,p,t) =
let r = match p with
| Pusual r -> r
| Pcons (r,l) -> r (* cf. the check [is_regular_match] above *)
| _ -> assert false
in
let ids,env' = push_vars (List.rev_map id_of_mlid ids) env in
let args =
if List.is_empty ids then mt ()
else (str " " ++ prlist_with_sep spc pr_id (List.rev ids))
in
(pp_global Cons r ++ args), (pp_expr env' [] t)
and pp_pat env pv =
prvect_with_sep fnl
(fun x -> let s1,s2 = pp_one_pat env x in
hov 2 (str "((" ++ s1 ++ str ")" ++ spc () ++ s2 ++ str ")")) pv
(*s names of the functions ([ids]) are already pushed in [env],
and passed here just for convenience. *)
and pp_fix env j (ids,bl) args =
paren
(str "letrec " ++
(v 0 (paren
(prvect_with_sep fnl
(fun (fi,ti) ->
paren ((pr_id fi) ++ spc () ++ (pp_expr env [] ti)))
(Array.map2 (fun id b -> (id,b)) ids bl)) ++
fnl () ++
hov 2 (pp_apply (pr_id (ids.(j))) true args))))
(*s Pretty-printing of a declaration. *)
let pp_decl = function
| Dind _ -> mt ()
| Dtype _ -> mt ()
| Dfix (rv, defs,_) ->
let names = Array.map
(fun r -> if is_inline_custom r then mt () else pp_global Term r) rv
in
prvecti
(fun i r ->
let void = is_inline_custom r ||
(not (is_custom r) &&
match defs.(i) with MLexn "UNUSED" -> true | _ -> false)
in
if void then mt ()
else
hov 2
(paren (str "define " ++ names.(i) ++ spc () ++
(if is_custom r then str (find_custom r)
else pp_expr (empty_env ()) [] defs.(i)))
++ fnl ()) ++ fnl ())
rv
| Dterm (r, a, _) ->
if is_inline_custom r then mt ()
else
hov 2 (paren (str "define " ++ pp_global Term r ++ spc () ++
(if is_custom r then str (find_custom r)
else pp_expr (empty_env ()) [] a)))
++ fnl2 ()
let rec pp_structure_elem = function
| (l,SEdecl d) -> pp_decl d
| (l,SEmodule m) -> pp_module_expr m.ml_mod_expr
| (l,SEmodtype m) -> mt ()
(* for the moment we simply discard module type *)
and pp_module_expr = function
| MEstruct (mp,sel) -> prlist_strict pp_structure_elem sel
| MEfunctor _ -> mt ()
(* for the moment we simply discard unapplied functors *)
| MEident _ | MEapply _ -> assert false
(* should be expanded in extract_env *)
let pp_struct =
let pp_sel (mp,sel) =
push_visible mp [];
let p = prlist_strict pp_structure_elem sel in
pop_visible (); p
in
prlist_strict pp_sel
let scheme_descr = {
keywords = keywords;
file_suffix = ".scm";
file_naming = file_of_modfile;
preamble = preamble;
pp_struct = pp_struct;
sig_suffix = None;
sig_preamble = (fun _ _ _ _ -> mt ());
pp_sig = (fun _ -> mt ());
pp_decl = pp_decl;
}
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/plugins/extraction/scheme.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
s Production of Scheme syntax.
s Scheme renaming issues.
s The pretty-printer for Scheme syntax
s Pretty-printing of expressions.
An [MLdummy] may be applied, but I don't really care.
cf. the check [is_regular_match] above
s names of the functions ([ids]) are already pushed in [env],
and passed here just for convenience.
s Pretty-printing of a declaration.
for the moment we simply discard module type
for the moment we simply discard unapplied functors
should be expanded in extract_env | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Pp
open CErrors
open Util
open Names
open Miniml
open Mlutil
open Table
open Common
let keywords =
List.fold_right (fun s -> Id.Set.add (Id.of_string s))
[ "define"; "let"; "lambda"; "lambdas"; "match";
"apply"; "car"; "cdr";
"error"; "delay"; "force"; "_"; "__"]
Id.Set.empty
let pp_comment s = str";; "++h 0 s++fnl ()
let pp_header_comment = function
| None -> mt ()
| Some com -> pp_comment com ++ fnl () ++ fnl ()
let preamble _ comment _ usf =
pp_header_comment comment ++
str ";; This extracted scheme code relies on some additional macros\n" ++
str ";; available at -paris-diderot.fr/~letouzey/scheme\n" ++
str "(load \"macros_extr.scm\")\n\n" ++
(if usf.mldummy then str "(define __ (lambda (_) __))\n\n" else mt ())
let pr_id id =
let s = Id.to_string id in
for i = 0 to String.length s - 1 do
if s.[i] == '\'' then s.[i] <- '~'
done;
str s
let paren = pp_par true
let pp_abst st = function
| [] -> assert false
| [id] -> paren (str "lambda " ++ paren (pr_id id) ++ spc () ++ st)
| l -> paren
(str "lambdas " ++ paren (prlist_with_sep spc pr_id l) ++ spc () ++ st)
let pp_apply st _ = function
| [] -> st
| [a] -> hov 2 (paren (st ++ spc () ++ a))
| args -> hov 2 (paren (str "@ " ++ st ++
(prlist_strict (fun x -> spc () ++ x) args)))
let pp_global k r = str (Common.pp_global k r)
let rec pp_expr env args =
let apply st = pp_apply st true args in
function
| MLrel n ->
let id = get_db_name n env in apply (pr_id id)
| MLapp (f,args') ->
let stl = List.map (pp_expr env []) args' in
pp_expr env (stl @ args) f
| MLlam _ as a ->
let fl,a' = collect_lams a in
let fl,env' = push_vars (List.map id_of_mlid fl) env in
apply (pp_abst (pp_expr env' [] a') (List.rev fl))
| MLletin (id,a1,a2) ->
let i,env' = push_vars [id_of_mlid id] env in
apply
(hv 0
(hov 2
(paren
(str "let " ++
paren
(paren
(pr_id (List.hd i) ++ spc () ++ pp_expr env [] a1))
++ spc () ++ hov 0 (pp_expr env' [] a2)))))
| MLglob r ->
apply (pp_global Term r)
| MLcons (_,r,args') ->
assert (List.is_empty args);
let st =
str "`" ++
paren (pp_global Cons r ++
(if List.is_empty args' then mt () else spc ()) ++
prlist_with_sep spc (pp_cons_args env) args')
in
if is_coinductive r then paren (str "delay " ++ st) else st
| MLtuple _ -> error "Cannot handle tuples in Scheme yet."
| MLcase (_,_,pv) when not (is_regular_match pv) ->
error "Cannot handle general patterns in Scheme yet."
| MLcase (_,t,pv) when is_custom_match pv ->
let mkfun (ids,_,e) =
if not (List.is_empty ids) then named_lams (List.rev ids) e
else dummy_lams (ast_lift 1 e) 1
in
apply
(paren
(hov 2
(str (find_custom_match pv) ++ fnl () ++
prvect (fun tr -> pp_expr env [] (mkfun tr) ++ fnl ()) pv
++ pp_expr env [] t)))
| MLcase (typ,t, pv) ->
let e =
if not (is_coinductive_type typ) then pp_expr env [] t
else paren (str "force" ++ spc () ++ pp_expr env [] t)
in
apply (v 3 (paren (str "match " ++ e ++ fnl () ++ pp_pat env pv)))
| MLfix (i,ids,defs) ->
let ids',env' = push_vars (List.rev (Array.to_list ids)) env in
pp_fix env' i (Array.of_list (List.rev ids'),defs) args
| MLexn s ->
An [ MLexn ] may be applied , but I do n't really care .
paren (str "error" ++ spc () ++ qs s)
| MLdummy _ ->
| MLmagic a ->
pp_expr env args a
| MLaxiom -> paren (str "error \"AXIOM TO BE REALIZED\"")
and pp_cons_args env = function
| MLcons (_,r,args) when is_coinductive r ->
paren (pp_global Cons r ++
(if List.is_empty args then mt () else spc ()) ++
prlist_with_sep spc (pp_cons_args env) args)
| e -> str "," ++ pp_expr env [] e
and pp_one_pat env (ids,p,t) =
let r = match p with
| Pusual r -> r
| _ -> assert false
in
let ids,env' = push_vars (List.rev_map id_of_mlid ids) env in
let args =
if List.is_empty ids then mt ()
else (str " " ++ prlist_with_sep spc pr_id (List.rev ids))
in
(pp_global Cons r ++ args), (pp_expr env' [] t)
and pp_pat env pv =
prvect_with_sep fnl
(fun x -> let s1,s2 = pp_one_pat env x in
hov 2 (str "((" ++ s1 ++ str ")" ++ spc () ++ s2 ++ str ")")) pv
and pp_fix env j (ids,bl) args =
paren
(str "letrec " ++
(v 0 (paren
(prvect_with_sep fnl
(fun (fi,ti) ->
paren ((pr_id fi) ++ spc () ++ (pp_expr env [] ti)))
(Array.map2 (fun id b -> (id,b)) ids bl)) ++
fnl () ++
hov 2 (pp_apply (pr_id (ids.(j))) true args))))
let pp_decl = function
| Dind _ -> mt ()
| Dtype _ -> mt ()
| Dfix (rv, defs,_) ->
let names = Array.map
(fun r -> if is_inline_custom r then mt () else pp_global Term r) rv
in
prvecti
(fun i r ->
let void = is_inline_custom r ||
(not (is_custom r) &&
match defs.(i) with MLexn "UNUSED" -> true | _ -> false)
in
if void then mt ()
else
hov 2
(paren (str "define " ++ names.(i) ++ spc () ++
(if is_custom r then str (find_custom r)
else pp_expr (empty_env ()) [] defs.(i)))
++ fnl ()) ++ fnl ())
rv
| Dterm (r, a, _) ->
if is_inline_custom r then mt ()
else
hov 2 (paren (str "define " ++ pp_global Term r ++ spc () ++
(if is_custom r then str (find_custom r)
else pp_expr (empty_env ()) [] a)))
++ fnl2 ()
let rec pp_structure_elem = function
| (l,SEdecl d) -> pp_decl d
| (l,SEmodule m) -> pp_module_expr m.ml_mod_expr
| (l,SEmodtype m) -> mt ()
and pp_module_expr = function
| MEstruct (mp,sel) -> prlist_strict pp_structure_elem sel
| MEfunctor _ -> mt ()
| MEident _ | MEapply _ -> assert false
let pp_struct =
let pp_sel (mp,sel) =
push_visible mp [];
let p = prlist_strict pp_structure_elem sel in
pop_visible (); p
in
prlist_strict pp_sel
let scheme_descr = {
keywords = keywords;
file_suffix = ".scm";
file_naming = file_of_modfile;
preamble = preamble;
pp_struct = pp_struct;
sig_suffix = None;
sig_preamble = (fun _ _ _ _ -> mt ());
pp_sig = (fun _ -> mt ());
pp_decl = pp_decl;
}
|
96f8d2d5217387bf06aa7dd3ce4879278c019c5e805ab344355d4ec10eec25b6 | ekmett/hask | Fin.hs | # LANGUAGE DeriveFunctor , , DeriveTraversable , LambdaCase #
import Control.Applicative
import Control.Monad
import Data.Foldable hiding (elem)
import Data.List (nub)
import Data.Traversable
import Data.Void
import Prelude hiding (all, any, elem)
newtype Fin a = Fin { runFin :: [Monomial a] }
deriving (Show, Read, Functor, Foldable, Traversable)
data Monomial a
= Var a
| Set (Fin a)
deriving (Show, Read, Functor, Foldable, Traversable)
reduce :: Eq a => Fin a -> Fin a
reduce (Fin xs) = Fin $ nub (mon <$> xs) where
mon (Set xs) = Set (reduce xs)
mon x = x
null :: Fin a -> Bool
null (Fin xs) = Prelude.null xs
size :: Eq a => Fin a -> Int
size xs = length $ runFin $ reduce xs
elem :: Eq a => Fin a -> Fin a -> Bool
elem xs = any (Set xs ==) . runFin
set :: Fin a -> Fin a
set xs = Fin [Set xs]
unit :: Fin a
unit = set empty
(∧) :: Eq a => Fin a -> Fin a -> Fin a
Fin xs ∧ Fin ys = Fin $ filter (\x -> any (== x) ys) xs
(∨) :: Fin a -> Fin a -> Fin a
(∨) = (<|>)
(⊆) :: Eq a => Fin a -> Fin a -> Bool
Fin xs ⊆ Fin ys = all (\x -> any (== x) ys) xs
instance Eq a => Eq (Fin a) where
Fin xs == Fin ys = all (\x -> any (== x) ys) xs
&& all (\y -> any (== y) xs) ys
instance Applicative Fin where
pure a = Fin [Var a]
(<*>) = ap
instance Alternative Fin where
empty = Fin []
Fin xs <|> Fin ys = Fin (xs ++ ys)
instance Monad Fin where
return a = Fin [Var a]
Fin m >>= f = Fin $ m >>= \ case
Var a -> runFin (f a)
Set m -> [Set (m >>= f)]
instance MonadPlus Fin where
mzero = empty
mplus = (<|>)
instance Eq a => Eq (Monomial a) where
Var a == Var b = a == b
Set a == Set b = a == b
_ == _ = False
-- countable if made up of all initial elements
countable :: Fin a -> Maybe [a]
countable (Fin xs) = traverse (\ case Var g -> Just g; _ -> Nothing) xs
| null | https://raw.githubusercontent.com/ekmett/hask/54ea964af8e0c1673ac2699492f4c07d977cb3c8/wip/Fin.hs | haskell | countable if made up of all initial elements | # LANGUAGE DeriveFunctor , , DeriveTraversable , LambdaCase #
import Control.Applicative
import Control.Monad
import Data.Foldable hiding (elem)
import Data.List (nub)
import Data.Traversable
import Data.Void
import Prelude hiding (all, any, elem)
newtype Fin a = Fin { runFin :: [Monomial a] }
deriving (Show, Read, Functor, Foldable, Traversable)
data Monomial a
= Var a
| Set (Fin a)
deriving (Show, Read, Functor, Foldable, Traversable)
reduce :: Eq a => Fin a -> Fin a
reduce (Fin xs) = Fin $ nub (mon <$> xs) where
mon (Set xs) = Set (reduce xs)
mon x = x
null :: Fin a -> Bool
null (Fin xs) = Prelude.null xs
size :: Eq a => Fin a -> Int
size xs = length $ runFin $ reduce xs
elem :: Eq a => Fin a -> Fin a -> Bool
elem xs = any (Set xs ==) . runFin
set :: Fin a -> Fin a
set xs = Fin [Set xs]
unit :: Fin a
unit = set empty
(∧) :: Eq a => Fin a -> Fin a -> Fin a
Fin xs ∧ Fin ys = Fin $ filter (\x -> any (== x) ys) xs
(∨) :: Fin a -> Fin a -> Fin a
(∨) = (<|>)
(⊆) :: Eq a => Fin a -> Fin a -> Bool
Fin xs ⊆ Fin ys = all (\x -> any (== x) ys) xs
instance Eq a => Eq (Fin a) where
Fin xs == Fin ys = all (\x -> any (== x) ys) xs
&& all (\y -> any (== y) xs) ys
instance Applicative Fin where
pure a = Fin [Var a]
(<*>) = ap
instance Alternative Fin where
empty = Fin []
Fin xs <|> Fin ys = Fin (xs ++ ys)
instance Monad Fin where
return a = Fin [Var a]
Fin m >>= f = Fin $ m >>= \ case
Var a -> runFin (f a)
Set m -> [Set (m >>= f)]
instance MonadPlus Fin where
mzero = empty
mplus = (<|>)
instance Eq a => Eq (Monomial a) where
Var a == Var b = a == b
Set a == Set b = a == b
_ == _ = False
countable :: Fin a -> Maybe [a]
countable (Fin xs) = traverse (\ case Var g -> Just g; _ -> Nothing) xs
|
c5677d72bcb91e89e5b4e5cf9e13e49b3486906efde2ecdc12064255e91e4c69 | tonsky/advent2018 | day4.clj | (ns advent2018.day4
(:require
[clojure.string :as str]
[clojure.set :as set]
[clojure.walk :as walk]))
(def input (slurp "inputs/day4"))
(def lines (->> (str/split input #"\n") sort))
(defn parse-line
"line => [:asleep minute] | [:awake minute] | [:guard id]"
[l]
(let [[_ m t] (re-matches #"\[\d{4}-\d\d-\d\d \d\d:(\d\d)\] (.*)" l)]
(println t)
(cond
(= t "falls asleep") [:asleep (Integer/parseInt m)]
(= t "wakes up") [:awake (Integer/parseInt m)]
:else (let [id (re-find #"\d+" t)]
[:guard (Integer/parseInt id)]))))
(def ^{:doc "[[guard-id asleew awake] ...]"}
intervals
(loop [res []
lines lines
guard nil
asleep nil]
(if (empty? lines)
res
(let [[op arg] (parse-line (first lines))]
(case op
:guard (recur res (next lines) arg nil)
:asleep (recur res (next lines) guard arg)
:awake (recur (conj res [guard asleep arg]) (next lines) guard nil))))))
(defn guards-asleep-total
"_ => [guard-id how-often]"
[]
(reduce
(fn [m [guard asleep awake]]
(update m guard #(+ (or % 0) (- awake asleep))))
{}
intervals))
(defn interval->map
"[_ 5 8] => {5 1, 6 1, 7 1}"
[[_ asleep awake]]
(into {}
(for [m (range asleep awake)]
[m 1])))
(defn minute-asleep-most
"guard => [which-minute how-often]"
[guard]
(->> intervals
(filter #(= guard (first %)))
(map interval->map)
(apply merge-with +)
(sort-by second)
(reverse)
first))
;; guard minute times
(defn part1 []
(let [most-asleep (->> (guards-asleep-total)
(sort-by second)
(last)
2441
(* most-asleep
(first (minute-asleep-most most-asleep)))))
#_(part1)
(def guards (into #{} (map first intervals)))
(defn part2 []
(let [[guard which-minute _] (->> guards
(reduce
(fn [acc guard]
(conj acc (into [guard] (minute-asleep-most guard))))
[])
(sort-by #(nth % 2))
(reverse)
(first))]
(* guard which-minute)))
#_(part2) | null | https://raw.githubusercontent.com/tonsky/advent2018/6f8d15bf37a150a288e3447df7766c362f7086e9/src/advent2018/day4.clj | clojure | guard minute times | (ns advent2018.day4
(:require
[clojure.string :as str]
[clojure.set :as set]
[clojure.walk :as walk]))
(def input (slurp "inputs/day4"))
(def lines (->> (str/split input #"\n") sort))
(defn parse-line
"line => [:asleep minute] | [:awake minute] | [:guard id]"
[l]
(let [[_ m t] (re-matches #"\[\d{4}-\d\d-\d\d \d\d:(\d\d)\] (.*)" l)]
(println t)
(cond
(= t "falls asleep") [:asleep (Integer/parseInt m)]
(= t "wakes up") [:awake (Integer/parseInt m)]
:else (let [id (re-find #"\d+" t)]
[:guard (Integer/parseInt id)]))))
(def ^{:doc "[[guard-id asleew awake] ...]"}
intervals
(loop [res []
lines lines
guard nil
asleep nil]
(if (empty? lines)
res
(let [[op arg] (parse-line (first lines))]
(case op
:guard (recur res (next lines) arg nil)
:asleep (recur res (next lines) guard arg)
:awake (recur (conj res [guard asleep arg]) (next lines) guard nil))))))
(defn guards-asleep-total
"_ => [guard-id how-often]"
[]
(reduce
(fn [m [guard asleep awake]]
(update m guard #(+ (or % 0) (- awake asleep))))
{}
intervals))
(defn interval->map
"[_ 5 8] => {5 1, 6 1, 7 1}"
[[_ asleep awake]]
(into {}
(for [m (range asleep awake)]
[m 1])))
(defn minute-asleep-most
"guard => [which-minute how-often]"
[guard]
(->> intervals
(filter #(= guard (first %)))
(map interval->map)
(apply merge-with +)
(sort-by second)
(reverse)
first))
(defn part1 []
(let [most-asleep (->> (guards-asleep-total)
(sort-by second)
(last)
2441
(* most-asleep
(first (minute-asleep-most most-asleep)))))
#_(part1)
(def guards (into #{} (map first intervals)))
(defn part2 []
(let [[guard which-minute _] (->> guards
(reduce
(fn [acc guard]
(conj acc (into [guard] (minute-asleep-most guard))))
[])
(sort-by #(nth % 2))
(reverse)
(first))]
(* guard which-minute)))
#_(part2) |
706933fff459b77c88ac08d0e1e6e757b915d06df736bdd4b89735dd14dc8501 | nikodemus/SBCL | seq.pure.lisp | ;;;; tests related to sequences
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
While most of SBCL is derived from the CMU CL system , the test
;;;; files (like this one) were written from scratch after the fork
from CMU CL .
;;;;
;;;; This software is in the public domain and is provided with
;;;; absolutely no warranty. See the COPYING and CREDITS files for
;;;; more information.
(in-package :cl-user)
As reported by from his ansi - test suite for gcl , REMOVE
malfunctioned when given : START , : END and : FROM - END arguments .
;;; Make sure it doesn't happen again.
(let* ((orig '(1 2 3 2 6 1 2 4 1 3 2 7))
(x (copy-seq orig))
(y (remove 3 x :from-end t :start 1 :end 5))
(z (remove 2 x :from-end t :start 1 :end 5)))
(assert (equalp orig x))
(assert (equalp y '(1 2 2 6 1 2 4 1 3 2 7)))
(assert (equalp z '(1 3 6 1 2 4 1 3 2 7))))
Similarly , NSUBSTITUTE and friends were getting things wrong with
: START , : END and : FROM - END :
(assert
(loop for i from 0 to 9 always
(loop for j from i to 10 always
(loop for c from 0 to (- j i) always
(let* ((orig '(a a a a a a a a a a))
(x (copy-seq orig))
(y (nsubstitute 'x 'a x :start i :end j :count c)))
(equal y (nconc (make-list i :initial-element 'a)
(make-list c :initial-element 'x)
(make-list (- 10 (+ i c))
:initial-element 'a))))))))
(assert
(loop for i from 0 to 9 always
(loop for j from i to 10 always
(loop for c from 0 to (- j i) always
(let* ((orig '(a a a a a a a a a a))
(x (copy-seq orig))
(y (nsubstitute-if 'x (lambda (x) (eq x 'a)) x
:start i :end j
:count c :from-end t)))
(equal y (nconc (make-list (- j c) :initial-element 'a)
(make-list c :initial-element 'x)
(make-list (- 10 j)
:initial-element 'a))))))))
(assert
(loop for i from 0 to 9 always
(loop for j from i to 10 always
(loop for c from 0 to (- j i) always
(let* ((orig '(a a a a a a a a a a))
(x (copy-seq orig))
(y (nsubstitute-if-not 'x (lambda (x)
(not (eq x 'a))) x
:start i :end j
:count c :from-end t)))
(equal y (nconc (make-list (- j c) :initial-element 'a)
(make-list c :initial-element 'x)
(make-list (- 10 j)
:initial-element 'a))))))))
;;; And equally similarly, REMOVE-DUPLICATES misbehaved when given
;;; :START arguments:
(let ((orig (list 0 1 2 0 1 2 0 1 2 0 1 2)))
(assert (equalp (remove-duplicates orig :start 3 :end 9) '(0 1 2 0 1 2 0 1 2)))
(assert (equalp (delete-duplicates orig :start 3 :end 9) '(0 1 2 0 1 2 0 1 2))))
;;; tests of COUNT
(assert (= 1 (count 1 '(1 2 3))))
(assert (= 2 (count 'z #(z 1 2 3 z))))
(assert (= 0 (count 'y '(z 1 2 3 z))))
;;; tests of COUNT-IF and COUNT-IF-NOT
the guts of CCI , abstracted over whether we 're testing
;; COUNT-IF or COUNT-IF-NOT
(%cci (expected count-if test sequence-as-list &rest keys)
`(let* ((list ',sequence-as-list)
(simple-vector (coerce list 'simple-vector))
(length (length list))
(vector (make-array (* 2 length) :fill-pointer length)))
(replace vector list :end1 length)
(dolist (seq (list list simple-vector vector))
(assert (= ,expected (,count-if ,test seq ,@keys))))))
;; "Check COUNT-IF"
(cci (expected test sequence-as-list &rest keys)
`(progn
(format t "~&SEQUENCE-AS-LIST=~S~%" ',sequence-as-list)
(%cci ,expected
count-if
,test
,sequence-as-list
,@keys)
(%cci ,expected
count-if-not
(complement ,test)
,sequence-as-list
,@keys))))
(cci 1 #'consp (1 (12) 1))
(cci 3 #'consp (1 (2) 3 (4) (5) 6))
(cci 3 #'consp (1 (2) 3 (4) (5) 6) :from-end t)
(cci 2 #'consp (1 (2) 3 (4) (5) 6) :start 2)
(cci 0 #'consp (1 (2) 3 (4) (5) 6) :start 2 :end 3)
(cci 1 #'consp (1 (2) 3 (4) (5) 6) :start 1 :end 3)
(cci 1 #'consp (1 (2) 3 (4) (5) 6) :start 1 :end 2)
(cci 0 #'consp (1 (2) 3 (4) (5) 6) :start 2 :end 2)
(cci 2 #'zerop (0 10 0 11 12))
(cci 1 #'zerop (0 10 0 11 12) :start 1)
(cci 2 #'minusp (0 10 0 11 12) :key #'1-)
(cci 1 #'minusp (0 10 0 11 12) :key #'1- :end 2))
(multiple-value-bind (v e)
(ignore-errors (count-if #'zerop '(0 a 0 b c) :start 1))
(declare (ignore v))
(assert (eql (type-error-datum e) 'a)))
(multiple-value-bind (v e)
(ignore-errors (count-if #'zerop #(0 a 0 b c) :start 1 :from-end 11))
(declare (ignore v))
(assert (eql (type-error-datum e) 'c)))
: COUNT may be negative and BIGNUM
(assert (equal (remove 1 '(1 2 3 1) :count 1) '(2 3 1)))
(assert (equal (remove 1 '(1 2 3 1) :count (* 2 most-positive-fixnum)) '(2 3)))
(assert (equal (remove 1 '(1 2 3 1) :count (* -2 most-positive-fixnum)) '(1 2 3 1)))
bug reported by on sbcl - devel 2003 - 01 - 04 :
;;; embedded calls of SORT do not work
(assert (equal (sort (list 0 0 0) (lambda (x y) (sort (list 0 0 0) #'<) nil))
'(0 0 0)))
(assert (equal (sort (list 0 0 0 0 0)
(lambda (x y)
(declare (ignore x y))
(block compare
(sort (make-list 11 :initial-element 1)
(let ((counter 7))
(lambda (x y)
(declare (ignore x y))
(when (= (decf counter) 0)
(return-from compare nil))
t))))))
'(0 0 0 0 0)))
;;; miscellaneous sanity checks on stuff which could've been broken by
changes in MERGE - LIST * in sbcl-0.7.11 . *
(assert (equal (merge 'list () () '<) ()))
(assert (equal (merge 'list () (list 1) #'< :key 'identity) '(1)))
(assert (equal (merge 'list (list 2) () '>) '(2)))
(assert (equal (merge 'list (list 1 2 4) (list 2 3 7) '<) '(1 2 2 3 4 7)))
(assert (equal (merge 'list (list 1 2 4) (list -2 3 7) #'<) '(-2 1 2 3 4 7)))
(assert (equal (merge 'list (list 1 2 4) (vector -2 3 7) '< :key 'abs)
'(1 2 -2 3 4 7)))
(assert (equal (merge 'list (list 1 -2 4) (list -2 3 7) '< :key #'abs)
'(1 -2 -2 3 4 7)))
(assert (equal (stable-sort (list 1 10 2 12 13 3) '<) '(1 2 3 10 12 13)))
(assert (equal (stable-sort (list 1 10 2 12 13 3) #'< :key '-)
'(13 12 10 3 2 1)))
(assert (equal (stable-sort (list 1 10 2 12 13 3) '> :key #'-)
'(1 2 3 10 12 13)))
(assert (equal (stable-sort (list 1 2 3 -3 -2 -1) '< :key 'abs)
'(1 -1 2 -2 3 -3)))
CSR broke FILL by not returning the sequence argument in a transform .
(let* ((s1 (copy-seq "abcde"))
(s2 (fill s1 #\z)))
(assert s2)
(assert (string= s2 "zzzzz")))
POSITION on displaced arrays with non - zero offset has been broken
;;; for quite a while...
(let ((fn (compile nil '(lambda (x) (position x)))))
(let* ((x #(1 2 3))
(y (make-array 2 :displaced-to x :displaced-index-offset 1)))
(assert (= (position 2 y) 0))))
;;; (SIMPLE-STRING) is a legal type specifier for creation functions
(let ((a (make-sequence '(simple-string) 5))
(b (concatenate '(simple-string) "a" "bdec"))
(c (map '(simple-string) 'identity "abcde"))
(d (merge '(simple-string) (copy-seq "acd") (copy-seq "be") 'char>))
(e (coerce '(#\a #\b #\c #\e #\d) '(simple-string))))
(assert (= (length a) 5))
(assert (string= b "abdec"))
(assert (string= c "abcde"))
(assert (string= d "beacd"))
(assert (string= e "abced")))
;;; COPY-SEQ "should be prepared to signal an error if sequence is not
;;; a proper sequence".
(locally (declare (optimize safety))
(multiple-value-bind (seq err) (ignore-errors (copy-seq '(1 2 3 . 4)))
(assert (not seq))
(assert (typep err 'type-error))))
UBX - BASH - COPY transform had an inconsistent return type
(let ((sb-c::*check-consistency* t))
(handler-bind ((warning #'error))
(compile nil
'(lambda (l)
(declare (type fixnum l))
(let* ((bsize 128)
(b1 (make-array bsize :element-type '(unsigned-byte 8)))
(b2 (make-array l :element-type '(unsigned-byte 8))))
(replace b1 b2 :start2 0 :end2 l))))))
(with-test (:name :bug-452008)
;; FIND & POSITION on lists should check bounds and (in safe code) detect
;; circular and dotted lists.
(macrolet ((test (type lambda)
`(let ((got (handler-case
(funcall (compile nil ',lambda))
(,type () :error)
(:no-error (res)
(list :no-error res)))))
(let ((*print-circle* t))
(format t "test: ~S~%" ',lambda))
(unless (eq :error got)
(error "wanted an error, got ~S for~% ~S"
(second got) ',lambda)))))
(test sb-kernel:bounding-indices-bad-error
(lambda ()
(find :foo '(1 2 3 :foo) :start 1 :end 5 :from-end t)))
(test sb-kernel:bounding-indices-bad-error
(lambda ()
(position :foo '(1 2 3 :foo) :start 1 :end 5 :from-end t)))
(test sb-kernel:bounding-indices-bad-error
(lambda ()
(find :foo '(1 2 3 :foo) :start 3 :end 0 :from-end t)))
(test sb-kernel:bounding-indices-bad-error
(lambda ()
(position :foo '(1 2 3 :foo) :start 3 :end 0 :from-end t)))
(test type-error
(lambda ()
(let ((list (list 1 2 3 :foo)))
(find :bar (nconc list list)))))
(test type-error
(lambda ()
(let ((list (list 1 2 3 :foo)))
(position :bar (nconc list list)))))))
(with-test (:name :bug-554385)
;; FIND-IF shouldn't look through the entire list.
(assert (= 2 (find-if #'evenp '(1 2 1 1 1 1 1 1 1 1 1 1 :foo))))
;; Even though the end bounds are incorrect, the
;; element is found before that's an issue.
(assert (eq :foo (find :foo '(1 2 3 :foo) :start 1 :end 5)))
(assert (= 3 (position :foo '(1 2 3 :foo) :start 1 :end 5))))
(with-test (:name (:search :empty-seq))
(assert (eql 0
(funcall (compile nil
`(lambda (x)
(declare (optimize (speed 3)) (simple-vector x))
(search x #())))
#())))
(assert (eql 0
(funcall (compile nil
`(lambda (x)
(declare (optimize (speed 3)) (simple-vector x))
(search x #(t t t))))
#())))
(assert (eql 0
(funcall (compile nil
`(lambda (x)
(declare (optimize (speed 3)) (simple-vector x))
(search x #(t t t) :end1 0)))
#(t t t))))
(assert (eql 0
(funcall (compile nil
`(lambda (x)
(declare (optimize (speed 3)) (simple-vector x))
(search x #(t t t) :key nil)))
#())))
(assert (eql 0
(funcall (compile nil
`(lambda (x k)
(declare (optimize (speed 3)) (simple-vector x))
(search x #(t t t) :key k)))
#() nil)))
(assert (eq :ok
(handler-case
(funcall (compile nil
`(lambda (x)
(declare (optimize (speed 3)) (simple-vector x))
(search x #(t t t) :start2 1 :end2 0 :end1 0)))
#(t t t))
(sb-kernel:bounding-indices-bad-error ()
:ok))))
(assert (eql 1
(funcall (lambda ()
(declare (optimize speed))
(search #() #(1 1) :start2 1 :end2 1)))))
(assert (eql 2
(funcall (lambda ()
(declare (optimize speed))
(search #(1) #(1 1) :start1 1 :start2 2)))))
(assert (eql 2
(funcall (lambda ()
(declare (optimize speed))
(search #() #(1 1) :from-end t))))))
(with-test (:name :sort-smoke-test)
(flet ((iota (n type &aux (i 0))
(map-into (make-sequence type n)
(lambda ()
(incf i))))
(shuffle (n type)
(let ((vector (let ((i 0))
(map-into (make-array n)
(lambda ()
(incf i))))))
(dotimes (i n (coerce vector type))
(let ((j (+ i (random (- n i)))))
(rotatef (aref vector i) (aref vector j))))))
(sortedp (x)
(let* ((nonce (list nil))
(prev nonce))
(every (lambda (x)
(prog1 (or (eql prev nonce)
(< prev x))
(setf prev x)))
x))))
(dolist (type '(simple-vector list))
(dolist (size '(7 8 9 13 1023 1024 1025 1536))
(loop for repeat below 5 do
(assert (sortedp
(sort (funcall (case repeat
(0 #'iota)
(1 (lambda (n type)
(reverse (iota n type))))
(t #'shuffle))
size type)
#'<))))))))
(with-test (:name :stable-sort-smoke-test)
(flet ((iota (n type &aux (i 0))
(map-into (make-sequence type n)
(lambda ()
(cons 0 (incf i)))))
(shuffle (n type)
(let ((max (truncate (expt n 1/4)))
(i 0))
(map-into (make-sequence type n)
(lambda ()
(cons (random max) (incf i))))))
(sortedp (x)
(let* ((nonce (list nil))
(prev nonce))
(every (lambda (x)
(prog1 (or (eql prev nonce)
(< (car prev) (car x))
(and (= (car prev) (car x))
(< (cdr prev) (cdr x))))
(setf prev x)))
x))))
(dolist (type '(simple-vector list))
(dolist (size '(0 1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16 17
1023 1024 1025 1536))
(loop for repeat below 5 do
(assert
(sortedp
(stable-sort (funcall (case repeat
(0 #'iota)
(t #'shuffle))
size type)
#'< :key #'car))))))))
| null | https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/tests/seq.pure.lisp | lisp | tests related to sequences
more information.
files (like this one) were written from scratch after the fork
This software is in the public domain and is provided with
absolutely no warranty. See the COPYING and CREDITS files for
more information.
Make sure it doesn't happen again.
And equally similarly, REMOVE-DUPLICATES misbehaved when given
:START arguments:
tests of COUNT
tests of COUNT-IF and COUNT-IF-NOT
COUNT-IF or COUNT-IF-NOT
"Check COUNT-IF"
embedded calls of SORT do not work
miscellaneous sanity checks on stuff which could've been broken by
for quite a while...
(SIMPLE-STRING) is a legal type specifier for creation functions
COPY-SEQ "should be prepared to signal an error if sequence is not
a proper sequence".
FIND & POSITION on lists should check bounds and (in safe code) detect
circular and dotted lists.
FIND-IF shouldn't look through the entire list.
Even though the end bounds are incorrect, the
element is found before that's an issue. |
This software is part of the SBCL system . See the README file for
While most of SBCL is derived from the CMU CL system , the test
from CMU CL .
(in-package :cl-user)
As reported by from his ansi - test suite for gcl , REMOVE
malfunctioned when given : START , : END and : FROM - END arguments .
(let* ((orig '(1 2 3 2 6 1 2 4 1 3 2 7))
(x (copy-seq orig))
(y (remove 3 x :from-end t :start 1 :end 5))
(z (remove 2 x :from-end t :start 1 :end 5)))
(assert (equalp orig x))
(assert (equalp y '(1 2 2 6 1 2 4 1 3 2 7)))
(assert (equalp z '(1 3 6 1 2 4 1 3 2 7))))
Similarly , NSUBSTITUTE and friends were getting things wrong with
: START , : END and : FROM - END :
(assert
(loop for i from 0 to 9 always
(loop for j from i to 10 always
(loop for c from 0 to (- j i) always
(let* ((orig '(a a a a a a a a a a))
(x (copy-seq orig))
(y (nsubstitute 'x 'a x :start i :end j :count c)))
(equal y (nconc (make-list i :initial-element 'a)
(make-list c :initial-element 'x)
(make-list (- 10 (+ i c))
:initial-element 'a))))))))
(assert
(loop for i from 0 to 9 always
(loop for j from i to 10 always
(loop for c from 0 to (- j i) always
(let* ((orig '(a a a a a a a a a a))
(x (copy-seq orig))
(y (nsubstitute-if 'x (lambda (x) (eq x 'a)) x
:start i :end j
:count c :from-end t)))
(equal y (nconc (make-list (- j c) :initial-element 'a)
(make-list c :initial-element 'x)
(make-list (- 10 j)
:initial-element 'a))))))))
(assert
(loop for i from 0 to 9 always
(loop for j from i to 10 always
(loop for c from 0 to (- j i) always
(let* ((orig '(a a a a a a a a a a))
(x (copy-seq orig))
(y (nsubstitute-if-not 'x (lambda (x)
(not (eq x 'a))) x
:start i :end j
:count c :from-end t)))
(equal y (nconc (make-list (- j c) :initial-element 'a)
(make-list c :initial-element 'x)
(make-list (- 10 j)
:initial-element 'a))))))))
(let ((orig (list 0 1 2 0 1 2 0 1 2 0 1 2)))
(assert (equalp (remove-duplicates orig :start 3 :end 9) '(0 1 2 0 1 2 0 1 2)))
(assert (equalp (delete-duplicates orig :start 3 :end 9) '(0 1 2 0 1 2 0 1 2))))
(assert (= 1 (count 1 '(1 2 3))))
(assert (= 2 (count 'z #(z 1 2 3 z))))
(assert (= 0 (count 'y '(z 1 2 3 z))))
the guts of CCI , abstracted over whether we 're testing
(%cci (expected count-if test sequence-as-list &rest keys)
`(let* ((list ',sequence-as-list)
(simple-vector (coerce list 'simple-vector))
(length (length list))
(vector (make-array (* 2 length) :fill-pointer length)))
(replace vector list :end1 length)
(dolist (seq (list list simple-vector vector))
(assert (= ,expected (,count-if ,test seq ,@keys))))))
(cci (expected test sequence-as-list &rest keys)
`(progn
(format t "~&SEQUENCE-AS-LIST=~S~%" ',sequence-as-list)
(%cci ,expected
count-if
,test
,sequence-as-list
,@keys)
(%cci ,expected
count-if-not
(complement ,test)
,sequence-as-list
,@keys))))
(cci 1 #'consp (1 (12) 1))
(cci 3 #'consp (1 (2) 3 (4) (5) 6))
(cci 3 #'consp (1 (2) 3 (4) (5) 6) :from-end t)
(cci 2 #'consp (1 (2) 3 (4) (5) 6) :start 2)
(cci 0 #'consp (1 (2) 3 (4) (5) 6) :start 2 :end 3)
(cci 1 #'consp (1 (2) 3 (4) (5) 6) :start 1 :end 3)
(cci 1 #'consp (1 (2) 3 (4) (5) 6) :start 1 :end 2)
(cci 0 #'consp (1 (2) 3 (4) (5) 6) :start 2 :end 2)
(cci 2 #'zerop (0 10 0 11 12))
(cci 1 #'zerop (0 10 0 11 12) :start 1)
(cci 2 #'minusp (0 10 0 11 12) :key #'1-)
(cci 1 #'minusp (0 10 0 11 12) :key #'1- :end 2))
(multiple-value-bind (v e)
(ignore-errors (count-if #'zerop '(0 a 0 b c) :start 1))
(declare (ignore v))
(assert (eql (type-error-datum e) 'a)))
(multiple-value-bind (v e)
(ignore-errors (count-if #'zerop #(0 a 0 b c) :start 1 :from-end 11))
(declare (ignore v))
(assert (eql (type-error-datum e) 'c)))
: COUNT may be negative and BIGNUM
(assert (equal (remove 1 '(1 2 3 1) :count 1) '(2 3 1)))
(assert (equal (remove 1 '(1 2 3 1) :count (* 2 most-positive-fixnum)) '(2 3)))
(assert (equal (remove 1 '(1 2 3 1) :count (* -2 most-positive-fixnum)) '(1 2 3 1)))
bug reported by on sbcl - devel 2003 - 01 - 04 :
(assert (equal (sort (list 0 0 0) (lambda (x y) (sort (list 0 0 0) #'<) nil))
'(0 0 0)))
(assert (equal (sort (list 0 0 0 0 0)
(lambda (x y)
(declare (ignore x y))
(block compare
(sort (make-list 11 :initial-element 1)
(let ((counter 7))
(lambda (x y)
(declare (ignore x y))
(when (= (decf counter) 0)
(return-from compare nil))
t))))))
'(0 0 0 0 0)))
changes in MERGE - LIST * in sbcl-0.7.11 . *
(assert (equal (merge 'list () () '<) ()))
(assert (equal (merge 'list () (list 1) #'< :key 'identity) '(1)))
(assert (equal (merge 'list (list 2) () '>) '(2)))
(assert (equal (merge 'list (list 1 2 4) (list 2 3 7) '<) '(1 2 2 3 4 7)))
(assert (equal (merge 'list (list 1 2 4) (list -2 3 7) #'<) '(-2 1 2 3 4 7)))
(assert (equal (merge 'list (list 1 2 4) (vector -2 3 7) '< :key 'abs)
'(1 2 -2 3 4 7)))
(assert (equal (merge 'list (list 1 -2 4) (list -2 3 7) '< :key #'abs)
'(1 -2 -2 3 4 7)))
(assert (equal (stable-sort (list 1 10 2 12 13 3) '<) '(1 2 3 10 12 13)))
(assert (equal (stable-sort (list 1 10 2 12 13 3) #'< :key '-)
'(13 12 10 3 2 1)))
(assert (equal (stable-sort (list 1 10 2 12 13 3) '> :key #'-)
'(1 2 3 10 12 13)))
(assert (equal (stable-sort (list 1 2 3 -3 -2 -1) '< :key 'abs)
'(1 -1 2 -2 3 -3)))
CSR broke FILL by not returning the sequence argument in a transform .
(let* ((s1 (copy-seq "abcde"))
(s2 (fill s1 #\z)))
(assert s2)
(assert (string= s2 "zzzzz")))
POSITION on displaced arrays with non - zero offset has been broken
(let ((fn (compile nil '(lambda (x) (position x)))))
(let* ((x #(1 2 3))
(y (make-array 2 :displaced-to x :displaced-index-offset 1)))
(assert (= (position 2 y) 0))))
(let ((a (make-sequence '(simple-string) 5))
(b (concatenate '(simple-string) "a" "bdec"))
(c (map '(simple-string) 'identity "abcde"))
(d (merge '(simple-string) (copy-seq "acd") (copy-seq "be") 'char>))
(e (coerce '(#\a #\b #\c #\e #\d) '(simple-string))))
(assert (= (length a) 5))
(assert (string= b "abdec"))
(assert (string= c "abcde"))
(assert (string= d "beacd"))
(assert (string= e "abced")))
(locally (declare (optimize safety))
(multiple-value-bind (seq err) (ignore-errors (copy-seq '(1 2 3 . 4)))
(assert (not seq))
(assert (typep err 'type-error))))
UBX - BASH - COPY transform had an inconsistent return type
(let ((sb-c::*check-consistency* t))
(handler-bind ((warning #'error))
(compile nil
'(lambda (l)
(declare (type fixnum l))
(let* ((bsize 128)
(b1 (make-array bsize :element-type '(unsigned-byte 8)))
(b2 (make-array l :element-type '(unsigned-byte 8))))
(replace b1 b2 :start2 0 :end2 l))))))
(with-test (:name :bug-452008)
(macrolet ((test (type lambda)
`(let ((got (handler-case
(funcall (compile nil ',lambda))
(,type () :error)
(:no-error (res)
(list :no-error res)))))
(let ((*print-circle* t))
(format t "test: ~S~%" ',lambda))
(unless (eq :error got)
(error "wanted an error, got ~S for~% ~S"
(second got) ',lambda)))))
(test sb-kernel:bounding-indices-bad-error
(lambda ()
(find :foo '(1 2 3 :foo) :start 1 :end 5 :from-end t)))
(test sb-kernel:bounding-indices-bad-error
(lambda ()
(position :foo '(1 2 3 :foo) :start 1 :end 5 :from-end t)))
(test sb-kernel:bounding-indices-bad-error
(lambda ()
(find :foo '(1 2 3 :foo) :start 3 :end 0 :from-end t)))
(test sb-kernel:bounding-indices-bad-error
(lambda ()
(position :foo '(1 2 3 :foo) :start 3 :end 0 :from-end t)))
(test type-error
(lambda ()
(let ((list (list 1 2 3 :foo)))
(find :bar (nconc list list)))))
(test type-error
(lambda ()
(let ((list (list 1 2 3 :foo)))
(position :bar (nconc list list)))))))
(with-test (:name :bug-554385)
(assert (= 2 (find-if #'evenp '(1 2 1 1 1 1 1 1 1 1 1 1 :foo))))
(assert (eq :foo (find :foo '(1 2 3 :foo) :start 1 :end 5)))
(assert (= 3 (position :foo '(1 2 3 :foo) :start 1 :end 5))))
(with-test (:name (:search :empty-seq))
(assert (eql 0
(funcall (compile nil
`(lambda (x)
(declare (optimize (speed 3)) (simple-vector x))
(search x #())))
#())))
(assert (eql 0
(funcall (compile nil
`(lambda (x)
(declare (optimize (speed 3)) (simple-vector x))
(search x #(t t t))))
#())))
(assert (eql 0
(funcall (compile nil
`(lambda (x)
(declare (optimize (speed 3)) (simple-vector x))
(search x #(t t t) :end1 0)))
#(t t t))))
(assert (eql 0
(funcall (compile nil
`(lambda (x)
(declare (optimize (speed 3)) (simple-vector x))
(search x #(t t t) :key nil)))
#())))
(assert (eql 0
(funcall (compile nil
`(lambda (x k)
(declare (optimize (speed 3)) (simple-vector x))
(search x #(t t t) :key k)))
#() nil)))
(assert (eq :ok
(handler-case
(funcall (compile nil
`(lambda (x)
(declare (optimize (speed 3)) (simple-vector x))
(search x #(t t t) :start2 1 :end2 0 :end1 0)))
#(t t t))
(sb-kernel:bounding-indices-bad-error ()
:ok))))
(assert (eql 1
(funcall (lambda ()
(declare (optimize speed))
(search #() #(1 1) :start2 1 :end2 1)))))
(assert (eql 2
(funcall (lambda ()
(declare (optimize speed))
(search #(1) #(1 1) :start1 1 :start2 2)))))
(assert (eql 2
(funcall (lambda ()
(declare (optimize speed))
(search #() #(1 1) :from-end t))))))
(with-test (:name :sort-smoke-test)
(flet ((iota (n type &aux (i 0))
(map-into (make-sequence type n)
(lambda ()
(incf i))))
(shuffle (n type)
(let ((vector (let ((i 0))
(map-into (make-array n)
(lambda ()
(incf i))))))
(dotimes (i n (coerce vector type))
(let ((j (+ i (random (- n i)))))
(rotatef (aref vector i) (aref vector j))))))
(sortedp (x)
(let* ((nonce (list nil))
(prev nonce))
(every (lambda (x)
(prog1 (or (eql prev nonce)
(< prev x))
(setf prev x)))
x))))
(dolist (type '(simple-vector list))
(dolist (size '(7 8 9 13 1023 1024 1025 1536))
(loop for repeat below 5 do
(assert (sortedp
(sort (funcall (case repeat
(0 #'iota)
(1 (lambda (n type)
(reverse (iota n type))))
(t #'shuffle))
size type)
#'<))))))))
(with-test (:name :stable-sort-smoke-test)
(flet ((iota (n type &aux (i 0))
(map-into (make-sequence type n)
(lambda ()
(cons 0 (incf i)))))
(shuffle (n type)
(let ((max (truncate (expt n 1/4)))
(i 0))
(map-into (make-sequence type n)
(lambda ()
(cons (random max) (incf i))))))
(sortedp (x)
(let* ((nonce (list nil))
(prev nonce))
(every (lambda (x)
(prog1 (or (eql prev nonce)
(< (car prev) (car x))
(and (= (car prev) (car x))
(< (cdr prev) (cdr x))))
(setf prev x)))
x))))
(dolist (type '(simple-vector list))
(dolist (size '(0 1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16 17
1023 1024 1025 1536))
(loop for repeat below 5 do
(assert
(sortedp
(stable-sort (funcall (case repeat
(0 #'iota)
(t #'shuffle))
size type)
#'< :key #'car))))))))
|
85a591b9abf8dfb6d6b5cae8dc1bc002b69544cc3fda7fc42802ed51838330b6 | coq-tactician/coq-tactician | find_tactic_syntax.ml | open Ltac_plugin
open Monad_util
open Map_all_the_things
open Tacexpr
open Names
module TacticFinderDef = struct
module M = WriterMonad
(struct type w = bool let id = false let comb = Bool.(||) end)
include MapDefTemplate (M)
end
module TacticFinderMapper = MakeMapper(TacticFinderDef)
open TacticFinderDef
let contains_ml_tactic ml t =
let seen = ref KNset.empty in
let rec contains_ml_tactic_ltac k =
if KNset.mem k !seen then
return ()
else
let tac = Tacenv.interp_ltac k in
seen := KNset.add k !seen;
map (fun _ -> ()) @@ TacticFinderMapper.glob_tactic_expr_map mapper tac
and contains_ml_tactic_alias k =
if KNset.mem k !seen then
return ()
else
let tac = Tacenv.interp_alias k in
seen := KNset.add k !seen;
map (fun _ -> ()) @@ TacticFinderMapper.glob_tactic_expr_map mapper tac.alias_body
and mapper = { TacticFinderDef.default_mapper with
glob_tactic_arg = (fun a c -> (match a with
| TacCall CAst.{ v=(ArgArg (_, k), _args); _} ->
let* _ = contains_ml_tactic_ltac k in
c a
| _ -> c a))
; glob_tactic = (fun t c -> (match t with
| TacML CAst.{ v=(e, _args); _} ->
let* () = if ml = e then M.tell true else return () in
c t
| TacAlias CAst.{ v=(k, _args); _} ->
let* () = contains_ml_tactic_alias k in
c t
| _ -> c t)) } in
fst @@ M.run @@ TacticFinderMapper.glob_tactic_expr_map mapper t
| null | https://raw.githubusercontent.com/coq-tactician/coq-tactician/989067831f1ab76d0676e8ddcdd3c963a2335de7/src/find_tactic_syntax.ml | ocaml | open Ltac_plugin
open Monad_util
open Map_all_the_things
open Tacexpr
open Names
module TacticFinderDef = struct
module M = WriterMonad
(struct type w = bool let id = false let comb = Bool.(||) end)
include MapDefTemplate (M)
end
module TacticFinderMapper = MakeMapper(TacticFinderDef)
open TacticFinderDef
let contains_ml_tactic ml t =
let seen = ref KNset.empty in
let rec contains_ml_tactic_ltac k =
if KNset.mem k !seen then
return ()
else
let tac = Tacenv.interp_ltac k in
seen := KNset.add k !seen;
map (fun _ -> ()) @@ TacticFinderMapper.glob_tactic_expr_map mapper tac
and contains_ml_tactic_alias k =
if KNset.mem k !seen then
return ()
else
let tac = Tacenv.interp_alias k in
seen := KNset.add k !seen;
map (fun _ -> ()) @@ TacticFinderMapper.glob_tactic_expr_map mapper tac.alias_body
and mapper = { TacticFinderDef.default_mapper with
glob_tactic_arg = (fun a c -> (match a with
| TacCall CAst.{ v=(ArgArg (_, k), _args); _} ->
let* _ = contains_ml_tactic_ltac k in
c a
| _ -> c a))
; glob_tactic = (fun t c -> (match t with
| TacML CAst.{ v=(e, _args); _} ->
let* () = if ml = e then M.tell true else return () in
c t
| TacAlias CAst.{ v=(k, _args); _} ->
let* () = contains_ml_tactic_alias k in
c t
| _ -> c t)) } in
fst @@ M.run @@ TacticFinderMapper.glob_tactic_expr_map mapper t
|
|
7961300e7b8600c6521444527cf288497eb698e4dfb1251df03101f71fe33ef0 | JacquesCarette/Drasil | AST.hs | module GOOL.Drasil.AST (Terminator(..), ScopeTag(..), QualifiedName, qualName,
FileType(..), isSource, Binding(..), onBinding, BindData(bind, bindDoc), bd,
FileData(filePath, fileMod), fileD, updateFileMod, FuncData(fType, funcDoc),
fd, ModData(name, modDoc), md, updateMod, MethodData(mthdDoc), mthd,
updateMthd, OpData(opPrec, opDoc), od, ParamData(paramVar, paramDoc), pd,
paramName, updateParam, ProgData(progName, progMods), progD, emptyProg,
StateVarData(getStVarScp, stVar, destructSts), svd,
TypeData(cType, typeString, typeDoc), td, ValData(valPrec, valType, val),
vd, updateValDoc, VarData(varBind, varName, varType, varDoc), vard
) where
import GOOL.Drasil.CodeType (CodeType)
import Prelude hiding ((<>))
import Text.PrettyPrint.HughesPJ (Doc, isEmpty)
-- For how statement endings are printed
data Terminator = Semi | Empty
-- Used for state variables and methods
-- Eq is needed for organizing methods and state variables into public and
-- private groups for C++ class rendering
data ScopeTag = Pub | Priv deriving Eq
-- Used in method exception map and call map.
Qualification first , name second
and needed for map lookups
data QualifiedName = QN String String deriving (Eq, Ord)
qualName :: String -> String -> QualifiedName
qualName = QN
In C++ Source and Header files are separate , other languages have a single
-- (Combined) file
deriving Eq
isSource :: FileType -> Bool
isSource Header = False
isSource _ = True
Static means bound at compile - time , Dynamic at run - time , used in BindData
and VarData
data Binding = Static | Dynamic
onBinding :: Binding -> a -> a -> a
onBinding Static s _ = s
onBinding Dynamic _ d = d
Used as the underlying data type for Permanence in the C++ renderer
data BindData = BD {bind :: Binding, bindDoc :: Doc}
bd :: Binding -> Doc -> BindData
bd = BD
-- Used as the underlying data type for Files in all renderers
data FileData = FileD {filePath :: FilePath, fileMod :: ModData}
fileD :: FilePath -> ModData -> FileData
fileD = FileD
Replace a FileData 's ModData with a new ModData
updateFileMod :: ModData -> FileData -> FileData
updateFileMod m f = fileD (filePath f) m
-- Used as the underlying data type for Functions in all renderers
data FuncData = FD {fType :: TypeData, funcDoc :: Doc}
fd :: TypeData -> Doc -> FuncData
fd = FD
-- Used as the underlying data type for Modules in all renderers
data ModData = MD {name :: String, modDoc :: Doc}
md :: String -> Doc -> ModData
md = MD
updateMod :: (Doc -> Doc) -> ModData -> ModData
updateMod f m = md (name m) (f $ modDoc m)
Used as the underlying data type for Methods in all renderers except C++
newtype MethodData = MthD {mthdDoc :: Doc}
mthd :: Doc -> MethodData
mthd = MthD
updateMthd :: MethodData -> (Doc -> Doc) -> MethodData
updateMthd m f = mthd ((f . mthdDoc) m)
Used as the underlying data type for UnaryOp and BinaryOp in all renderers
data OpData = OD {opPrec :: Int, opDoc :: Doc}
od :: Int -> Doc -> OpData
od = OD
-- Used as the underlying data type for Parameters in all renderers
data ParamData = PD {paramVar :: VarData, paramDoc :: Doc}
pd :: VarData -> Doc -> ParamData
pd = PD
paramName :: ParamData -> String
paramName = varName . paramVar
updateParam :: (Doc -> Doc) -> ParamData -> ParamData
updateParam f v = pd (paramVar v) ((f . paramDoc) v)
-- Used as the underlying data type for Programs in all renderers
data ProgData = ProgD {progName :: String, progMods :: [FileData]}
progD :: String -> [FileData] -> ProgData
progD n fs = ProgD n (filter (not . isEmpty . modDoc . fileMod) fs)
emptyProg :: ProgData
emptyProg = progD "" []
Used as the underlying data type for StateVars in the C++ renderer
data StateVarData = SVD {getStVarScp :: ScopeTag, stVar :: Doc,
destructSts :: (Doc, Terminator)}
svd :: ScopeTag -> Doc -> (Doc, Terminator) -> StateVarData
svd = SVD
-- Used as the underlying data type for Types in all renderers
data TypeData = TD {cType :: CodeType, typeString :: String, typeDoc :: Doc}
td :: CodeType -> String -> Doc -> TypeData
td = TD
-- Used as the underlying data type for Values in all renderers
data ValData = VD {valPrec :: Maybe Int, valType :: TypeData, val :: Doc}
vd :: Maybe Int -> TypeData -> Doc -> ValData
vd = VD
updateValDoc :: (Doc -> Doc) -> ValData -> ValData
updateValDoc f v = vd (valPrec v) (valType v) ((f . val) v)
-- Used as the underlying data type for Variables in all renderers
data VarData = VarD {varBind :: Binding, varName :: String,
varType :: TypeData, varDoc :: Doc}
vard :: Binding -> String -> TypeData -> Doc -> VarData
vard = VarD | null | https://raw.githubusercontent.com/JacquesCarette/Drasil/92dddf7a545ba5029f99ad5c5eddcd8dad56a2d8/code/drasil-gool/lib/GOOL/Drasil/AST.hs | haskell | For how statement endings are printed
Used for state variables and methods
Eq is needed for organizing methods and state variables into public and
private groups for C++ class rendering
Used in method exception map and call map.
(Combined) file
Used as the underlying data type for Files in all renderers
Used as the underlying data type for Functions in all renderers
Used as the underlying data type for Modules in all renderers
Used as the underlying data type for Parameters in all renderers
Used as the underlying data type for Programs in all renderers
Used as the underlying data type for Types in all renderers
Used as the underlying data type for Values in all renderers
Used as the underlying data type for Variables in all renderers | module GOOL.Drasil.AST (Terminator(..), ScopeTag(..), QualifiedName, qualName,
FileType(..), isSource, Binding(..), onBinding, BindData(bind, bindDoc), bd,
FileData(filePath, fileMod), fileD, updateFileMod, FuncData(fType, funcDoc),
fd, ModData(name, modDoc), md, updateMod, MethodData(mthdDoc), mthd,
updateMthd, OpData(opPrec, opDoc), od, ParamData(paramVar, paramDoc), pd,
paramName, updateParam, ProgData(progName, progMods), progD, emptyProg,
StateVarData(getStVarScp, stVar, destructSts), svd,
TypeData(cType, typeString, typeDoc), td, ValData(valPrec, valType, val),
vd, updateValDoc, VarData(varBind, varName, varType, varDoc), vard
) where
import GOOL.Drasil.CodeType (CodeType)
import Prelude hiding ((<>))
import Text.PrettyPrint.HughesPJ (Doc, isEmpty)
data Terminator = Semi | Empty
data ScopeTag = Pub | Priv deriving Eq
Qualification first , name second
and needed for map lookups
data QualifiedName = QN String String deriving (Eq, Ord)
qualName :: String -> String -> QualifiedName
qualName = QN
In C++ Source and Header files are separate , other languages have a single
deriving Eq
isSource :: FileType -> Bool
isSource Header = False
isSource _ = True
Static means bound at compile - time , Dynamic at run - time , used in BindData
and VarData
data Binding = Static | Dynamic
onBinding :: Binding -> a -> a -> a
onBinding Static s _ = s
onBinding Dynamic _ d = d
Used as the underlying data type for Permanence in the C++ renderer
data BindData = BD {bind :: Binding, bindDoc :: Doc}
bd :: Binding -> Doc -> BindData
bd = BD
data FileData = FileD {filePath :: FilePath, fileMod :: ModData}
fileD :: FilePath -> ModData -> FileData
fileD = FileD
Replace a FileData 's ModData with a new ModData
updateFileMod :: ModData -> FileData -> FileData
updateFileMod m f = fileD (filePath f) m
data FuncData = FD {fType :: TypeData, funcDoc :: Doc}
fd :: TypeData -> Doc -> FuncData
fd = FD
data ModData = MD {name :: String, modDoc :: Doc}
md :: String -> Doc -> ModData
md = MD
updateMod :: (Doc -> Doc) -> ModData -> ModData
updateMod f m = md (name m) (f $ modDoc m)
Used as the underlying data type for Methods in all renderers except C++
newtype MethodData = MthD {mthdDoc :: Doc}
mthd :: Doc -> MethodData
mthd = MthD
updateMthd :: MethodData -> (Doc -> Doc) -> MethodData
updateMthd m f = mthd ((f . mthdDoc) m)
Used as the underlying data type for UnaryOp and BinaryOp in all renderers
data OpData = OD {opPrec :: Int, opDoc :: Doc}
od :: Int -> Doc -> OpData
od = OD
data ParamData = PD {paramVar :: VarData, paramDoc :: Doc}
pd :: VarData -> Doc -> ParamData
pd = PD
paramName :: ParamData -> String
paramName = varName . paramVar
updateParam :: (Doc -> Doc) -> ParamData -> ParamData
updateParam f v = pd (paramVar v) ((f . paramDoc) v)
data ProgData = ProgD {progName :: String, progMods :: [FileData]}
progD :: String -> [FileData] -> ProgData
progD n fs = ProgD n (filter (not . isEmpty . modDoc . fileMod) fs)
emptyProg :: ProgData
emptyProg = progD "" []
Used as the underlying data type for StateVars in the C++ renderer
data StateVarData = SVD {getStVarScp :: ScopeTag, stVar :: Doc,
destructSts :: (Doc, Terminator)}
svd :: ScopeTag -> Doc -> (Doc, Terminator) -> StateVarData
svd = SVD
data TypeData = TD {cType :: CodeType, typeString :: String, typeDoc :: Doc}
td :: CodeType -> String -> Doc -> TypeData
td = TD
data ValData = VD {valPrec :: Maybe Int, valType :: TypeData, val :: Doc}
vd :: Maybe Int -> TypeData -> Doc -> ValData
vd = VD
updateValDoc :: (Doc -> Doc) -> ValData -> ValData
updateValDoc f v = vd (valPrec v) (valType v) ((f . val) v)
data VarData = VarD {varBind :: Binding, varName :: String,
varType :: TypeData, varDoc :: Doc}
vard :: Binding -> String -> TypeData -> Doc -> VarData
vard = VarD |
a3ad9c866465809fd904f8108fc41db9802133065161035987248c10c6f46f90 | PacktWorkshops/The-Clojure-Workshop | project.clj | (defproject hello-clojurescript.core "0.1.0-SNAPSHOT"
:description "Sample project showing a Figwheel and Rum application"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:min-lein-version "2.7.1"
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/clojurescript "1.10.520"]
[rum "0.11.2"]]
:source-paths ["src"]
:aliases {"fig" ["trampoline" "run" "-m" "figwheel.main"]
"fig:build" ["trampoline" "run" "-m" "figwheel.main" "-b" "dev" "-r"]
"fig:min" ["run" "-m" "figwheel.main" "-O" "advanced" "-bo" "dev"]
"fig:test" ["run" "-m" "figwheel.main" "-co" "test.cljs.edn" "-m" "hello-clojurescript.test-runner"]}
:profiles {:dev {:dependencies [[com.bhauman/figwheel-main "0.2.3"]
[com.bhauman/rebel-readline-cljs "0.1.4"]]
}})
| null | https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter09/Exercise9.08/hello-clojurescript.core/project.clj | clojure | (defproject hello-clojurescript.core "0.1.0-SNAPSHOT"
:description "Sample project showing a Figwheel and Rum application"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:min-lein-version "2.7.1"
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/clojurescript "1.10.520"]
[rum "0.11.2"]]
:source-paths ["src"]
:aliases {"fig" ["trampoline" "run" "-m" "figwheel.main"]
"fig:build" ["trampoline" "run" "-m" "figwheel.main" "-b" "dev" "-r"]
"fig:min" ["run" "-m" "figwheel.main" "-O" "advanced" "-bo" "dev"]
"fig:test" ["run" "-m" "figwheel.main" "-co" "test.cljs.edn" "-m" "hello-clojurescript.test-runner"]}
:profiles {:dev {:dependencies [[com.bhauman/figwheel-main "0.2.3"]
[com.bhauman/rebel-readline-cljs "0.1.4"]]
}})
|
|
ca2d1b2d5059b40a1518acb967abb0bea5ce23f2afa17ecb40dd75385d60a6aa | ygmpkk/house | PointParameter.hs | -- #hide
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.PointParameter
Copyright : ( c ) 2003
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- This is a purely internal module for setting point parameters.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.PointParameter (
PointParameter(..), pointParameterf, pointParameterfv, pointParameteri
) where
import Foreign.Ptr ( Ptr )
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum, GLfloat, GLint )
import Graphics.Rendering.OpenGL.GL.Extensions (
FunPtr, unsafePerformIO, Invoker, getProcAddress )
--------------------------------------------------------------------------------
#include "HsOpenGLExt.h"
--------------------------------------------------------------------------------
data PointParameter =
PointSizeMin
| PointSizeMax
| PointFadeThresholdSize
| PointDistanceAttenuation
| PointSpriteRMode
marshalPointParameter :: PointParameter -> GLenum
marshalPointParameter x = case x of
PointSizeMin -> 0x8126
PointSizeMax -> 0x8127
PointFadeThresholdSize -> 0x8128
PointDistanceAttenuation -> 0x8129
PointSpriteRMode -> 0x8863
--------------------------------------------------------------------------------
pointParameterf :: PointParameter -> GLfloat -> IO ()
pointParameterf = glPointParameterfARB . marshalPointParameter
EXTENSION_ENTRY("GL_ARB_point_parameters or OpenGL 1.4",glPointParameterfARB,GLenum -> GLfloat -> IO ())
pointParameterfv :: PointParameter -> Ptr GLfloat -> IO ()
pointParameterfv = glPointParameterfvARB . marshalPointParameter
EXTENSION_ENTRY("GL_ARB_point_parameters or OpenGL 1.4",glPointParameterfvARB,GLenum -> Ptr GLfloat -> IO ())
pointParameteri :: PointParameter -> GLint -> IO ()
pointParameteri = glPointParameteriNV . marshalPointParameter
EXTENSION_ENTRY("GL_NV_point_sprite",glPointParameteriNV,GLenum -> GLint -> IO ())
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/OpenGL/Graphics/Rendering/OpenGL/GL/PointParameter.hs | haskell | #hide
------------------------------------------------------------------------------
|
Module : Graphics.Rendering.OpenGL.GL.PointParameter
License : BSD-style (see the file libraries/OpenGL/LICENSE)
Maintainer :
Stability : provisional
Portability : portable
This is a purely internal module for setting point parameters.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | Copyright : ( c ) 2003
module Graphics.Rendering.OpenGL.GL.PointParameter (
PointParameter(..), pointParameterf, pointParameterfv, pointParameteri
) where
import Foreign.Ptr ( Ptr )
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum, GLfloat, GLint )
import Graphics.Rendering.OpenGL.GL.Extensions (
FunPtr, unsafePerformIO, Invoker, getProcAddress )
#include "HsOpenGLExt.h"
data PointParameter =
PointSizeMin
| PointSizeMax
| PointFadeThresholdSize
| PointDistanceAttenuation
| PointSpriteRMode
marshalPointParameter :: PointParameter -> GLenum
marshalPointParameter x = case x of
PointSizeMin -> 0x8126
PointSizeMax -> 0x8127
PointFadeThresholdSize -> 0x8128
PointDistanceAttenuation -> 0x8129
PointSpriteRMode -> 0x8863
pointParameterf :: PointParameter -> GLfloat -> IO ()
pointParameterf = glPointParameterfARB . marshalPointParameter
EXTENSION_ENTRY("GL_ARB_point_parameters or OpenGL 1.4",glPointParameterfARB,GLenum -> GLfloat -> IO ())
pointParameterfv :: PointParameter -> Ptr GLfloat -> IO ()
pointParameterfv = glPointParameterfvARB . marshalPointParameter
EXTENSION_ENTRY("GL_ARB_point_parameters or OpenGL 1.4",glPointParameterfvARB,GLenum -> Ptr GLfloat -> IO ())
pointParameteri :: PointParameter -> GLint -> IO ()
pointParameteri = glPointParameteriNV . marshalPointParameter
EXTENSION_ENTRY("GL_NV_point_sprite",glPointParameteriNV,GLenum -> GLint -> IO ())
|
cb373e66b4ecda77b79342f5e68c368378ccc14cf4b67cd975bf59eb29595664 | phadej/staged | Main.hs | # LANGUAGE TemplateHaskell #
# OPTIONS_GHC -ddump - splices #
module Main (main) where
import Examples
import Staged.Commons
main :: IO ()
main = do
-- simple example
print $$(ex01 [|| True ||])
-- letrec and letrecH
print $$(fromCode $ fibnr 8)
print $ $$(fromCode $ isEvenCodeH TagE) (10 :: Int)
| null | https://raw.githubusercontent.com/phadej/staged/b51c8c508af71ddb2aca4a75030da9b2c4f9e3dd/staged-commons/example/Main.hs | haskell | simple example
letrec and letrecH | # LANGUAGE TemplateHaskell #
# OPTIONS_GHC -ddump - splices #
module Main (main) where
import Examples
import Staged.Commons
main :: IO ()
main = do
print $$(ex01 [|| True ||])
print $$(fromCode $ fibnr 8)
print $ $$(fromCode $ isEvenCodeH TagE) (10 :: Int)
|
ffe1ba600ee36c31164dc49c13634024576e64b52e1e4913a620d2d8bb477f57 | haskell-tools/haskell-tools | InRhsGuard.hs | {-# LANGUAGE BangPatterns #-}
module InRhsGuard where
f x
| [!y] <- x = 5 {-* BangPatterns *-}
| null | https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/test/ExtensionOrganizerTest/BangPatternsTest/InRhsGuard.hs | haskell | # LANGUAGE BangPatterns #
* BangPatterns * |
module InRhsGuard where
f x
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.