_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
|
---|---|---|---|---|---|---|---|---|
bac704031384e1633fdd32f790107ffb837d4dcd6227c477560e5effc20b0926 | ucsd-progsys/liquidhaskell | Bounds.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE TupleSections #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
# OPTIONS_GHC -Wno - incomplete - uni - patterns #
module Language.Haskell.Liquid.Types.Bounds (
Bound(..),
RBound, RRBound,
RBEnv, RRBEnv,
makeBound,
) where
import Prelude hiding (error)
import Text.PrettyPrint.HughesPJ
import GHC.Generics
import Data.List (partition)
import Data.Maybe
import Data.Hashable
import Data.Bifunctor
import Data.Data
import qualified Data.Binary as B
import qualified Data.HashMap.Strict as M
import qualified Language.Fixpoint.Types as F
( , mapSnd )
import Language.Haskell.Liquid.Types.Types
import Language.Haskell.Liquid.Types.RefType
data Bound t e = Bound
{ bname :: LocSymbol -- ^ The name of the bound
, tyvars :: [t] -- ^ Type variables that appear in the bounds
, bparams :: [(LocSymbol, t)] -- ^ These are abstract refinements, for now
, bargs :: [(LocSymbol, t)] -- ^ These are value variables
, bbody :: e -- ^ The body of the bound
} deriving (Data, Typeable, Generic)
instance (B.Binary t, B.Binary e) => B.Binary (Bound t e)
type RBound = RRBound RSort
type RRBound tv = Bound tv F.Expr
type RBEnv = M.HashMap LocSymbol RBound
type RRBEnv tv = M.HashMap LocSymbol (RRBound tv)
instance Hashable (Bound t e) where
hashWithSalt i = hashWithSalt i . bname
instance Eq (Bound t e) where
b1 == b2 = bname b1 == bname b2
instance (PPrint e, PPrint t) => (Show (Bound t e)) where
show = showpp
instance (PPrint e, PPrint t) => (PPrint (Bound t e)) where
pprintTidy k (Bound s vs ps ys e) = "bound" <+> pprintTidy k s <+>
"forall" <+> pprintTidy k vs <+> "." <+>
pprintTidy k (fst <$> ps) <+> "=" <+>
ppBsyms k (fst <$> ys) <+> pprintTidy k e
where
ppBsyms _ [] = ""
ppBsyms k' xs = "\\" <+> pprintTidy k' xs <+> "->"
instance Bifunctor Bound where
first f (Bound s vs ps xs e) = Bound s (f <$> vs) (Misc.mapSnd f <$> ps) (Misc.mapSnd f <$> xs) e
second f (Bound s vs ps xs e) = Bound s vs ps xs (f e)
makeBound :: (PPrint r, UReftable r, SubsTy RTyVar (RType RTyCon RTyVar ()) r)
=> RRBound RSort -> [RRType r] -> [F.Symbol] -> RRType r -> RRType r
makeBound (Bound _ vs ps xs expr) ts qs
= RRTy cts mempty OCons
where
cts = (\(x, t) -> (x, foldr subsTyVarMeet t su)) <$> cts'
cts' = makeBoundType penv rs xs
penv = zip (val . fst <$> ps) qs
rs = bkImp [] expr
bkImp acc (F.PImp p q) = bkImp (p:acc) q
bkImp acc p = p:acc
su = [(α, toRSort t, t) | (RVar α _, t) <- zip vs ts ]
makeBoundType :: (PPrint r, UReftable r)
=> [(F.Symbol, F.Symbol)]
-> [F.Expr]
-> [(LocSymbol, RSort)]
-> [(F.Symbol, RRType r)]
makeBoundType penv (q:qs) xts = go xts
where
-- NV TODO: Turn this into a proper error
go [] = panic Nothing "Bound with empty symbols"
go [(x, t)] = [(F.dummySymbol, tp t x), (F.dummySymbol, tq t x)]
go ((x, t):xtss) = (val x, mkt t x) : go xtss
mkt t x = ofRSort t `strengthen` ofUReft (MkUReft (F.Reft (val x, mempty))
(Pr $ M.lookupDefault [] (val x) ps))
tp t x = ofRSort t `strengthen` ofUReft (MkUReft (F.Reft (val x, F.pAnd rs))
(Pr $ M.lookupDefault [] (val x) ps))
tq t x = ofRSort t `strengthen` makeRef penv x q
(ps, rs) = partitionPs penv qs
-- NV TODO: Turn this into a proper error
makeBoundType _ _ _ = panic Nothing "Bound with empty predicates"
partitionPs :: [(F.Symbol, F.Symbol)] -> [F.Expr] -> (M.HashMap F.Symbol [UsedPVar], [F.Expr])
partitionPs penv qs = Misc.mapFst makeAR $ partition (isPApp penv) qs
where
makeAR ps = M.fromListWith (++) $ map (toUsedPVars penv) ps
isPApp :: [(F.Symbol, a)] -> F.Expr -> Bool
isPApp penv (F.EApp (F.EVar p) _) = isJust $ lookup p penv
isPApp penv (F.EApp e _) = isPApp penv e
isPApp _ _ = False
toUsedPVars :: [(F.Symbol, F.Symbol)] -> F.Expr -> (F.Symbol, [PVar ()])
toUsedPVars penv q@(F.EApp _ expr) = (sym, [toUsedPVar penv q])
where
NV : TODO make this a better error
sym = case {- unProp -} expr of {F.EVar x -> x; e -> todo Nothing ("Bound fails in " ++ show e) }
toUsedPVars _ _ = impossible Nothing "This cannot happen"
toUsedPVar :: [(F.Symbol, F.Symbol)] -> F.Expr -> PVar ()
toUsedPVar penv ee@(F.EApp _ _)
= PV q (PVProp ()) e (((), F.dummySymbol,) <$> es')
where
F.EVar e = {- unProp $ -} last es
es' = init es
Just q = lookup p penv
(F.EVar p, es) = F.splitEApp ee
toUsedPVar _ _ = impossible Nothing "This cannot happen"
-- `makeRef` is used to make the refinement of the last implication,
-- thus it can contain both concrete and abstract refinements
makeRef :: (UReftable r) => [(F.Symbol, F.Symbol)] -> LocSymbol -> F.Expr -> r
makeRef penv v (F.PAnd rs) = ofUReft (MkUReft (F.Reft (val v, F.pAnd rrs)) r)
where
r = Pr (toUsedPVar penv <$> pps)
(pps, rrs) = partition (isPApp penv) rs
makeRef penv v rr
| isPApp penv rr = ofUReft (MkUReft (F.Reft(val v, mempty)) r)
where
r = Pr [toUsedPVar penv rr]
makeRef _ v p = F.ofReft (F.Reft (val v, p))
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/2ead75f10a7dc664186828a6299e99f26042e754/src/Language/Haskell/Liquid/Types/Bounds.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE DeriveDataTypeable #
^ The name of the bound
^ Type variables that appear in the bounds
^ These are abstract refinements, for now
^ These are value variables
^ The body of the bound
NV TODO: Turn this into a proper error
NV TODO: Turn this into a proper error
unProp
unProp $
`makeRef` is used to make the refinement of the last implication,
thus it can contain both concrete and abstract refinements | # LANGUAGE FlexibleContexts #
# LANGUAGE TupleSections #
# LANGUAGE DeriveGeneric #
# OPTIONS_GHC -Wno - incomplete - uni - patterns #
module Language.Haskell.Liquid.Types.Bounds (
Bound(..),
RBound, RRBound,
RBEnv, RRBEnv,
makeBound,
) where
import Prelude hiding (error)
import Text.PrettyPrint.HughesPJ
import GHC.Generics
import Data.List (partition)
import Data.Maybe
import Data.Hashable
import Data.Bifunctor
import Data.Data
import qualified Data.Binary as B
import qualified Data.HashMap.Strict as M
import qualified Language.Fixpoint.Types as F
( , mapSnd )
import Language.Haskell.Liquid.Types.Types
import Language.Haskell.Liquid.Types.RefType
data Bound t e = Bound
} deriving (Data, Typeable, Generic)
instance (B.Binary t, B.Binary e) => B.Binary (Bound t e)
type RBound = RRBound RSort
type RRBound tv = Bound tv F.Expr
type RBEnv = M.HashMap LocSymbol RBound
type RRBEnv tv = M.HashMap LocSymbol (RRBound tv)
instance Hashable (Bound t e) where
hashWithSalt i = hashWithSalt i . bname
instance Eq (Bound t e) where
b1 == b2 = bname b1 == bname b2
instance (PPrint e, PPrint t) => (Show (Bound t e)) where
show = showpp
instance (PPrint e, PPrint t) => (PPrint (Bound t e)) where
pprintTidy k (Bound s vs ps ys e) = "bound" <+> pprintTidy k s <+>
"forall" <+> pprintTidy k vs <+> "." <+>
pprintTidy k (fst <$> ps) <+> "=" <+>
ppBsyms k (fst <$> ys) <+> pprintTidy k e
where
ppBsyms _ [] = ""
ppBsyms k' xs = "\\" <+> pprintTidy k' xs <+> "->"
instance Bifunctor Bound where
first f (Bound s vs ps xs e) = Bound s (f <$> vs) (Misc.mapSnd f <$> ps) (Misc.mapSnd f <$> xs) e
second f (Bound s vs ps xs e) = Bound s vs ps xs (f e)
makeBound :: (PPrint r, UReftable r, SubsTy RTyVar (RType RTyCon RTyVar ()) r)
=> RRBound RSort -> [RRType r] -> [F.Symbol] -> RRType r -> RRType r
makeBound (Bound _ vs ps xs expr) ts qs
= RRTy cts mempty OCons
where
cts = (\(x, t) -> (x, foldr subsTyVarMeet t su)) <$> cts'
cts' = makeBoundType penv rs xs
penv = zip (val . fst <$> ps) qs
rs = bkImp [] expr
bkImp acc (F.PImp p q) = bkImp (p:acc) q
bkImp acc p = p:acc
su = [(α, toRSort t, t) | (RVar α _, t) <- zip vs ts ]
makeBoundType :: (PPrint r, UReftable r)
=> [(F.Symbol, F.Symbol)]
-> [F.Expr]
-> [(LocSymbol, RSort)]
-> [(F.Symbol, RRType r)]
makeBoundType penv (q:qs) xts = go xts
where
go [] = panic Nothing "Bound with empty symbols"
go [(x, t)] = [(F.dummySymbol, tp t x), (F.dummySymbol, tq t x)]
go ((x, t):xtss) = (val x, mkt t x) : go xtss
mkt t x = ofRSort t `strengthen` ofUReft (MkUReft (F.Reft (val x, mempty))
(Pr $ M.lookupDefault [] (val x) ps))
tp t x = ofRSort t `strengthen` ofUReft (MkUReft (F.Reft (val x, F.pAnd rs))
(Pr $ M.lookupDefault [] (val x) ps))
tq t x = ofRSort t `strengthen` makeRef penv x q
(ps, rs) = partitionPs penv qs
makeBoundType _ _ _ = panic Nothing "Bound with empty predicates"
partitionPs :: [(F.Symbol, F.Symbol)] -> [F.Expr] -> (M.HashMap F.Symbol [UsedPVar], [F.Expr])
partitionPs penv qs = Misc.mapFst makeAR $ partition (isPApp penv) qs
where
makeAR ps = M.fromListWith (++) $ map (toUsedPVars penv) ps
isPApp :: [(F.Symbol, a)] -> F.Expr -> Bool
isPApp penv (F.EApp (F.EVar p) _) = isJust $ lookup p penv
isPApp penv (F.EApp e _) = isPApp penv e
isPApp _ _ = False
toUsedPVars :: [(F.Symbol, F.Symbol)] -> F.Expr -> (F.Symbol, [PVar ()])
toUsedPVars penv q@(F.EApp _ expr) = (sym, [toUsedPVar penv q])
where
NV : TODO make this a better error
toUsedPVars _ _ = impossible Nothing "This cannot happen"
toUsedPVar :: [(F.Symbol, F.Symbol)] -> F.Expr -> PVar ()
toUsedPVar penv ee@(F.EApp _ _)
= PV q (PVProp ()) e (((), F.dummySymbol,) <$> es')
where
es' = init es
Just q = lookup p penv
(F.EVar p, es) = F.splitEApp ee
toUsedPVar _ _ = impossible Nothing "This cannot happen"
makeRef :: (UReftable r) => [(F.Symbol, F.Symbol)] -> LocSymbol -> F.Expr -> r
makeRef penv v (F.PAnd rs) = ofUReft (MkUReft (F.Reft (val v, F.pAnd rrs)) r)
where
r = Pr (toUsedPVar penv <$> pps)
(pps, rrs) = partition (isPApp penv) rs
makeRef penv v rr
| isPApp penv rr = ofUReft (MkUReft (F.Reft(val v, mempty)) r)
where
r = Pr [toUsedPVar penv rr]
makeRef _ v p = F.ofReft (F.Reft (val v, p))
|
522ed153d1cde47e135e14a719736a4057e4db1320c5f29585a08cf4850f42f9 | serokell/ariadne | TxMeta.hs | -- | Transaction metadata conform the wallet specification
module Ariadne.Wallet.Cardano.Kernel.DB.TxMeta
( -- * Transaction metadata
module Types
-- * Handy re-export to not leak our current choice of storage backend.
, openMetaDB
) where
import qualified Ariadne.Wallet.Cardano.Kernel.DB.Sqlite as ConcreteStorage
import Ariadne.Wallet.Cardano.Kernel.DB.TxMeta.Types as Types
-- Concrete instantiation of 'MetaDBHandle'
openMetaDB :: FilePath -> IO MetaDBHandle
openMetaDB fp = do
conn <- ConcreteStorage.newConnection fp
return MetaDBHandle {
closeMetaDB = ConcreteStorage.closeMetaDB conn
, migrateMetaDB = ConcreteStorage.unsafeMigrateMetaDB conn
, getTxMeta = ConcreteStorage.getTxMeta conn
, putTxMeta = ConcreteStorage.putTxMeta conn
, getTxMetas = ConcreteStorage.getTxMetas conn
}
| null | https://raw.githubusercontent.com/serokell/ariadne/5f49ee53b6bbaf332cb6f110c75f7b971acdd452/ariadne/cardano/src/Ariadne/Wallet/Cardano/Kernel/DB/TxMeta.hs | haskell | | Transaction metadata conform the wallet specification
* Transaction metadata
* Handy re-export to not leak our current choice of storage backend.
Concrete instantiation of 'MetaDBHandle' | module Ariadne.Wallet.Cardano.Kernel.DB.TxMeta
module Types
, openMetaDB
) where
import qualified Ariadne.Wallet.Cardano.Kernel.DB.Sqlite as ConcreteStorage
import Ariadne.Wallet.Cardano.Kernel.DB.TxMeta.Types as Types
openMetaDB :: FilePath -> IO MetaDBHandle
openMetaDB fp = do
conn <- ConcreteStorage.newConnection fp
return MetaDBHandle {
closeMetaDB = ConcreteStorage.closeMetaDB conn
, migrateMetaDB = ConcreteStorage.unsafeMigrateMetaDB conn
, getTxMeta = ConcreteStorage.getTxMeta conn
, putTxMeta = ConcreteStorage.putTxMeta conn
, getTxMetas = ConcreteStorage.getTxMetas conn
}
|
8c015c1714dd34369db91c2fde01ef9414220e9ff9ca4c3cf242c32756e621fb | danabr/visualize.erl | process_communication_analysis_transform.erl | %% Implements a parse transform for analysing communication between
%% processes. It transforms the following functions:
%% x The ! (bang) operator
%% x spawn
%% x spawn_link
%% x register
%% * gen_server:call
%% * gen_server:cast
%% * gen_server:reply
%% * gen_server:start
* gen_server : start_link
-module(process_communication_analysis_transform).
-export([parse_transform/2]).
-record(state, {module, func}).
%%%
%%% Exported functions
%%%
-spec(parse_transform(Forms, Options) -> Forms2 when
Forms :: [erl_parse:abstract_form()],
Forms2 :: [erl_parse:abstract_form()],
Options :: [Option],
Option :: type_checker | compile:option()).
parse_transform(Forms, _Options) ->
io:format("Performing parse transform!~n"),
forms(Forms, #state{}).
forms({op, _, '!', Lhs, Rhs}, State) ->
NewLhs = forms(Lhs, State),
NewRhs = forms(Rhs, State),
analysis_for(send, [NewLhs, NewRhs], State);
%% Calls
% spawn
forms({call, _, {atom, _, spawn}, Args}, State) ->
analysis_for_generic(spawn, Args, State);
forms({call, _, {remote,_,{atom,_,erlang}, {atom,_,spawn}}, Args},S)->
analysis_for_generic(spawn, Args, S);
% spawn_link
forms({call, _, {atom, _, spawn_link}, Args}, State) ->
analysis_for_generic(spawn_link, Args, State);
forms({call, _, {remote,_,{atom,_,erlang},{atom,_,spawn_link}}, Args},S)->
analysis_for_generic(spawn_link, Args, S);
% register
forms({call, _, {atom, _, register}, Args}, State) ->
analysis_for(register, Args, State);
forms({call, _, {remote,_,{atom,_,erlang},{atom,_,register}}, Args},S)->
analysis_for(register, Args, S);
% Catch all
forms(List, State) when is_list(List) ->
[forms(F, State) || F <- List];
forms(Tuple, State) when is_tuple(Tuple) ->
List = tuple_to_list(Tuple),
Transformed = forms(List, State),
list_to_tuple(Transformed);
forms(Any, _State) ->
% io:format("Catchall:~n~p~n", [Any]),
Any.
forms([{attribute , _ Line , module , Mod}=F|T ] , State ) - >
[ F|forms(T , State#state{module = Mod } ) ] ;
forms([{function , , Name , Arity , Clauses}|T ] , State ) - >
NameStr = atom_to_list(Name ) + + " / " + + integer_to_list(Arity ) ,
State2 = State#state{func = NameStr } ,
% NewF = {function, Line, Name, Arity, forms(Clauses, State2)},
[ NewF|forms(T , State ) ] ;
forms([{'fun ' , Line , { clauses , Clauses}}|T ] , State ) - >
NewClauses = forms(Clauses , State ) ,
NewF = { ' fun ' , Line , { clauses , NewClauses } } ,
[ NewF|forms(T , State ) ] ;
forms([{clause , Line , Vars , Guards , Exprs}|T ] , State ) - >
NewF = { clause , Line , Vars , Guards , forms(Exprs , State ) } ,
[ NewF|forms(T , State ) ] ;
forms([{match , Line , Lhs , Rhs}|T ] , State ) - >
NewLhs = hd(forms([Lhs ] , State ) ) ,
NewRhs = hd(forms([Rhs ] , State ) ) ,
NewF = { match , Line , NewLhs , } ,
[ NewF|forms(T , State ) ] ;
% % Noise
% forms([{attribute, _Line, _, _}=F|T], State) ->
[ F|forms(T , State ) ] ;
forms([{var , _ Line , _ Name}=F|T ] , State ) - >
[ F|forms(T , State ) ] ;
% forms([{eof, _Line}], _State) -> [];
% % Catch all
forms([F|T ] , State ) - >
io : format("Ignoring ( ~p):~n ~ p ~ n " , [ State , F ] ) ,
[ F|forms(T , State ) ] .
%%% Helpers
analysis_for(FunName, Args, State) ->
{call, 0,
{remote, 0, {atom, 0, process_analyser}, {atom, 0, FunName}},
forms(Args, State)}.
analysis_for_generic(FunName, Args, State) ->
{call, 0,
{remote, 0, {atom, 0, process_analyser}, {atom, 0, FunName}},
[to_cons(forms(Args, State))]}.
to_cons([]) -> {nil, 0};
to_cons([H|T]) -> {cons, 0, H, to_cons(T)}.
| null | https://raw.githubusercontent.com/danabr/visualize.erl/abf1d35a2dcbb274792e517c0e670c40688c162a/src/process_analyser/process_communication_analysis_transform.erl | erlang | Implements a parse transform for analysing communication between
processes. It transforms the following functions:
x The ! (bang) operator
x spawn
x spawn_link
x register
* gen_server:call
* gen_server:cast
* gen_server:reply
* gen_server:start
Exported functions
Calls
spawn
spawn_link
register
Catch all
io:format("Catchall:~n~p~n", [Any]),
NewF = {function, Line, Name, Arity, forms(Clauses, State2)},
% Noise
forms([{attribute, _Line, _, _}=F|T], State) ->
forms([{eof, _Line}], _State) -> [];
% Catch all
Helpers | * gen_server : start_link
-module(process_communication_analysis_transform).
-export([parse_transform/2]).
-record(state, {module, func}).
-spec(parse_transform(Forms, Options) -> Forms2 when
Forms :: [erl_parse:abstract_form()],
Forms2 :: [erl_parse:abstract_form()],
Options :: [Option],
Option :: type_checker | compile:option()).
parse_transform(Forms, _Options) ->
io:format("Performing parse transform!~n"),
forms(Forms, #state{}).
forms({op, _, '!', Lhs, Rhs}, State) ->
NewLhs = forms(Lhs, State),
NewRhs = forms(Rhs, State),
analysis_for(send, [NewLhs, NewRhs], State);
forms({call, _, {atom, _, spawn}, Args}, State) ->
analysis_for_generic(spawn, Args, State);
forms({call, _, {remote,_,{atom,_,erlang}, {atom,_,spawn}}, Args},S)->
analysis_for_generic(spawn, Args, S);
forms({call, _, {atom, _, spawn_link}, Args}, State) ->
analysis_for_generic(spawn_link, Args, State);
forms({call, _, {remote,_,{atom,_,erlang},{atom,_,spawn_link}}, Args},S)->
analysis_for_generic(spawn_link, Args, S);
forms({call, _, {atom, _, register}, Args}, State) ->
analysis_for(register, Args, State);
forms({call, _, {remote,_,{atom,_,erlang},{atom,_,register}}, Args},S)->
analysis_for(register, Args, S);
forms(List, State) when is_list(List) ->
[forms(F, State) || F <- List];
forms(Tuple, State) when is_tuple(Tuple) ->
List = tuple_to_list(Tuple),
Transformed = forms(List, State),
list_to_tuple(Transformed);
forms(Any, _State) ->
Any.
forms([{attribute , _ Line , module , Mod}=F|T ] , State ) - >
[ F|forms(T , State#state{module = Mod } ) ] ;
forms([{function , , Name , Arity , Clauses}|T ] , State ) - >
NameStr = atom_to_list(Name ) + + " / " + + integer_to_list(Arity ) ,
State2 = State#state{func = NameStr } ,
[ NewF|forms(T , State ) ] ;
forms([{'fun ' , Line , { clauses , Clauses}}|T ] , State ) - >
NewClauses = forms(Clauses , State ) ,
NewF = { ' fun ' , Line , { clauses , NewClauses } } ,
[ NewF|forms(T , State ) ] ;
forms([{clause , Line , Vars , Guards , Exprs}|T ] , State ) - >
NewF = { clause , Line , Vars , Guards , forms(Exprs , State ) } ,
[ NewF|forms(T , State ) ] ;
forms([{match , Line , Lhs , Rhs}|T ] , State ) - >
NewLhs = hd(forms([Lhs ] , State ) ) ,
NewRhs = hd(forms([Rhs ] , State ) ) ,
NewF = { match , Line , NewLhs , } ,
[ NewF|forms(T , State ) ] ;
[ F|forms(T , State ) ] ;
forms([{var , _ Line , _ Name}=F|T ] , State ) - >
[ F|forms(T , State ) ] ;
forms([F|T ] , State ) - >
io : format("Ignoring ( ~p):~n ~ p ~ n " , [ State , F ] ) ,
[ F|forms(T , State ) ] .
analysis_for(FunName, Args, State) ->
{call, 0,
{remote, 0, {atom, 0, process_analyser}, {atom, 0, FunName}},
forms(Args, State)}.
analysis_for_generic(FunName, Args, State) ->
{call, 0,
{remote, 0, {atom, 0, process_analyser}, {atom, 0, FunName}},
[to_cons(forms(Args, State))]}.
to_cons([]) -> {nil, 0};
to_cons([H|T]) -> {cons, 0, H, to_cons(T)}.
|
8a396e3f0e76dd2ede3a93a0b8cbf81e1838a7e528cf924cc4aec69244b3c96d | oxidizing/letters | test.ml | open Letters
let ( let* ) = Lwt.bind
let get_ethereal_account_details () =
let open Yojson.Basic.Util in
(* see the README.md how to generate the account file and the path
* below is relative to the location of the executable under _build
*)
let json = Yojson.Basic.from_file "../../../ethereal_account.json" in
let username = json |> member "username" |> to_string in
let password = json |> member "password" |> to_string in
let hostname = json |> member "hostname" |> to_string in
let port = json |> member "port" |> to_int in
let with_starttls = json |> member "secure" |> to_bool |> not in
Config.create ~username ~password ~hostname ~with_starttls ()
|> Config.set_port (Some port)
|> Lwt.return
;;
let get_mailtrap_account_details () =
let open Yojson.Basic.Util in
(* see the README.md how to generate the account file and the path
* below is relative to the location of the executable under _build
*)
let json = Yojson.Basic.from_file "../../../mailtrap_account.json" in
let username = json |> member "username" |> to_string in
let password = json |> member "password" |> to_string in
let hostname = json |> member "hostname" |> to_string in
let port = json |> member "port" |> to_int in
let with_starttls = json |> member "secure" |> to_bool |> not in
Config.create ~username ~password ~hostname ~with_starttls ()
|> Config.set_port (Some port)
|> Lwt.return
;;
let test_send_plain_text_email config _ () =
let sender = "" in
let recipients =
[ To ""
; To ""
; Cc ""
; Bcc ""
]
in
let subject = "Plain text test email" in
let body =
Plain
{|
Hi there,
have you already seen the very cool new web framework written in ocaml:
Regards,
The team
|}
in
let mail = create_email ~from:sender ~recipients ~subject ~body () in
match mail with
| Ok message -> send ~config ~sender ~recipients ~message
| Error reason -> Lwt.fail_with reason
;;
let test_send_html_email config _ () =
let sender = "" in
let recipients =
[ To ""
; To ""
; Cc ""
; Bcc ""
]
in
let reply_to = "" in
let subject = "HTML only test email" in
let body =
Html
{|
<h>Hi there,</h>
<p>
have you already seen the very cool new web framework written in ocaml:
<a href="">Sihl</a>
</p>
<p>
Regards,<br>
The team
</p>
|}
in
let mail = create_email ~reply_to ~from:sender ~recipients ~subject ~body () in
match mail with
| Ok message -> send ~config ~sender ~recipients ~message
| Error reason -> Lwt.fail_with reason
;;
let test_send_mixed_body_email config _ () =
let sender = "" in
let recipients =
[ To ""
; To ""
; Cc ""
; Bcc ""
]
in
let subject = "Mixed body email with plain text and HTML" in
let text =
{|
Hi there,
have you already seen the very cool new web framework written in ocaml:
Regards,
The team
|}
in
let html =
{|
<h>Hi there,</h>
<p>
have you already seen the very cool new web framework written in ocaml:
<a href="">Sihl</a>
</p>
<p>
Regards,<br>
The team
</p>
|}
in
let mail =
create_email ~from:sender ~recipients ~subject ~body:(Mixed (text, html, None)) ()
in
match mail with
| Ok message -> send ~config ~sender ~recipients ~message
| Error reason -> Lwt.fail_with reason
;;
let test_send_mixed_body_email_with_dot_starting_a_line config _ () =
let sender = "" in
let recipients =
[ To ""
; To ""
; Cc ""
; Bcc ""
]
in
let subject = "Mixed body email with dot starting a line in raw source" in
let text =
{|
This email is carefully crafted so that the dot in the URL is expected to hit
the beginning of a new line in the encoded body, this tests that the case is
correctly handled and the dot does not vanish::
|}
in
let html =
{|
<div>
This email is carefully crafted so that the dot in the URL is expected to hit
the beginning of a new line in the encoded body, this tests that the case is
correctly handled and the dot does not vanish that would render this URL
broken::: <a href="">Sihl</a>
</div>
|}
in
let mail =
create_email ~from:sender ~recipients ~subject ~body:(Mixed (text, html, None)) ()
in
match mail with
| Ok message -> send ~config ~sender ~recipients ~message
| Error reason -> Lwt.fail_with reason
;;
(* Run it *)
let () =
Lwt_main.run
(let* ethereal_conf_with_ca_detect = get_ethereal_account_details () in
let* mailtrap_conf_with_ca_detect = get_mailtrap_account_details () in
let ethereal_conf_with_ca_cert_bundle =
Config.set_ca_cert
"/etc/ssl/certs/ca-certificates.crt"
ethereal_conf_with_ca_detect
in
let ethereal_conf_with_single_ca_cert =
(* Use PEM file containing correct chain *)
Config.set_ca_cert "../../../ethereal-email-chain.pem" ethereal_conf_with_ca_detect
in
let ethereal_conf_with_ca_path =
Config.set_ca_path "/etc/ssl/certs/" ethereal_conf_with_ca_detect
in
Alcotest_lwt.run
"SMTP client"
[ ( "use ethereal.email, auto-detect CA certs"
, [ Alcotest_lwt.test_case
"Send plain text email, auto-detect CA certs"
`Slow
(test_send_plain_text_email ethereal_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send plain text email, use CA cert bundle"
`Slow
(test_send_plain_text_email ethereal_conf_with_ca_cert_bundle)
; Alcotest_lwt.test_case
"Send plain text email, use specific CA cert file"
`Slow
(test_send_plain_text_email ethereal_conf_with_single_ca_cert)
; Alcotest_lwt.test_case
"Send plain text email, load CA certificates from a folder"
`Slow
(test_send_plain_text_email ethereal_conf_with_ca_path)
] )
; ( "use ethereal.email, test different email message types"
, [ Alcotest_lwt.test_case
"Send plain text email"
`Slow
(test_send_plain_text_email ethereal_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send HTML only email"
`Slow
(test_send_html_email ethereal_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send mixed content email with plain text and HTML"
`Slow
(test_send_mixed_body_email ethereal_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send email with content including line starting with dot (SMTP \
Transparency)"
`Slow
(test_send_mixed_body_email_with_dot_starting_a_line
ethereal_conf_with_ca_detect)
] )
; ( "use mailtrap, test different email message types"
, [ Alcotest_lwt.test_case
"Send plain text email"
`Slow
(test_send_plain_text_email mailtrap_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send HTML only email"
`Slow
(test_send_html_email mailtrap_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send mixed content email with plain text and HTML"
`Slow
(test_send_mixed_body_email mailtrap_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send email with content including line starting with dot (SMTP \
Transparency)"
`Slow
(test_send_mixed_body_email_with_dot_starting_a_line
mailtrap_conf_with_ca_detect)
] )
])
;;
| null | https://raw.githubusercontent.com/oxidizing/letters/35f7594d15e3e670a5b99c8f6f75248bad9f7f85/service-test/test.ml | ocaml | see the README.md how to generate the account file and the path
* below is relative to the location of the executable under _build
see the README.md how to generate the account file and the path
* below is relative to the location of the executable under _build
Run it
Use PEM file containing correct chain | open Letters
let ( let* ) = Lwt.bind
let get_ethereal_account_details () =
let open Yojson.Basic.Util in
let json = Yojson.Basic.from_file "../../../ethereal_account.json" in
let username = json |> member "username" |> to_string in
let password = json |> member "password" |> to_string in
let hostname = json |> member "hostname" |> to_string in
let port = json |> member "port" |> to_int in
let with_starttls = json |> member "secure" |> to_bool |> not in
Config.create ~username ~password ~hostname ~with_starttls ()
|> Config.set_port (Some port)
|> Lwt.return
;;
let get_mailtrap_account_details () =
let open Yojson.Basic.Util in
let json = Yojson.Basic.from_file "../../../mailtrap_account.json" in
let username = json |> member "username" |> to_string in
let password = json |> member "password" |> to_string in
let hostname = json |> member "hostname" |> to_string in
let port = json |> member "port" |> to_int in
let with_starttls = json |> member "secure" |> to_bool |> not in
Config.create ~username ~password ~hostname ~with_starttls ()
|> Config.set_port (Some port)
|> Lwt.return
;;
let test_send_plain_text_email config _ () =
let sender = "" in
let recipients =
[ To ""
; To ""
; Cc ""
; Bcc ""
]
in
let subject = "Plain text test email" in
let body =
Plain
{|
Hi there,
have you already seen the very cool new web framework written in ocaml:
Regards,
The team
|}
in
let mail = create_email ~from:sender ~recipients ~subject ~body () in
match mail with
| Ok message -> send ~config ~sender ~recipients ~message
| Error reason -> Lwt.fail_with reason
;;
let test_send_html_email config _ () =
let sender = "" in
let recipients =
[ To ""
; To ""
; Cc ""
; Bcc ""
]
in
let reply_to = "" in
let subject = "HTML only test email" in
let body =
Html
{|
<h>Hi there,</h>
<p>
have you already seen the very cool new web framework written in ocaml:
<a href="">Sihl</a>
</p>
<p>
Regards,<br>
The team
</p>
|}
in
let mail = create_email ~reply_to ~from:sender ~recipients ~subject ~body () in
match mail with
| Ok message -> send ~config ~sender ~recipients ~message
| Error reason -> Lwt.fail_with reason
;;
let test_send_mixed_body_email config _ () =
let sender = "" in
let recipients =
[ To ""
; To ""
; Cc ""
; Bcc ""
]
in
let subject = "Mixed body email with plain text and HTML" in
let text =
{|
Hi there,
have you already seen the very cool new web framework written in ocaml:
Regards,
The team
|}
in
let html =
{|
<h>Hi there,</h>
<p>
have you already seen the very cool new web framework written in ocaml:
<a href="">Sihl</a>
</p>
<p>
Regards,<br>
The team
</p>
|}
in
let mail =
create_email ~from:sender ~recipients ~subject ~body:(Mixed (text, html, None)) ()
in
match mail with
| Ok message -> send ~config ~sender ~recipients ~message
| Error reason -> Lwt.fail_with reason
;;
let test_send_mixed_body_email_with_dot_starting_a_line config _ () =
let sender = "" in
let recipients =
[ To ""
; To ""
; Cc ""
; Bcc ""
]
in
let subject = "Mixed body email with dot starting a line in raw source" in
let text =
{|
This email is carefully crafted so that the dot in the URL is expected to hit
the beginning of a new line in the encoded body, this tests that the case is
correctly handled and the dot does not vanish::
|}
in
let html =
{|
<div>
This email is carefully crafted so that the dot in the URL is expected to hit
the beginning of a new line in the encoded body, this tests that the case is
correctly handled and the dot does not vanish that would render this URL
broken::: <a href="">Sihl</a>
</div>
|}
in
let mail =
create_email ~from:sender ~recipients ~subject ~body:(Mixed (text, html, None)) ()
in
match mail with
| Ok message -> send ~config ~sender ~recipients ~message
| Error reason -> Lwt.fail_with reason
;;
let () =
Lwt_main.run
(let* ethereal_conf_with_ca_detect = get_ethereal_account_details () in
let* mailtrap_conf_with_ca_detect = get_mailtrap_account_details () in
let ethereal_conf_with_ca_cert_bundle =
Config.set_ca_cert
"/etc/ssl/certs/ca-certificates.crt"
ethereal_conf_with_ca_detect
in
let ethereal_conf_with_single_ca_cert =
Config.set_ca_cert "../../../ethereal-email-chain.pem" ethereal_conf_with_ca_detect
in
let ethereal_conf_with_ca_path =
Config.set_ca_path "/etc/ssl/certs/" ethereal_conf_with_ca_detect
in
Alcotest_lwt.run
"SMTP client"
[ ( "use ethereal.email, auto-detect CA certs"
, [ Alcotest_lwt.test_case
"Send plain text email, auto-detect CA certs"
`Slow
(test_send_plain_text_email ethereal_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send plain text email, use CA cert bundle"
`Slow
(test_send_plain_text_email ethereal_conf_with_ca_cert_bundle)
; Alcotest_lwt.test_case
"Send plain text email, use specific CA cert file"
`Slow
(test_send_plain_text_email ethereal_conf_with_single_ca_cert)
; Alcotest_lwt.test_case
"Send plain text email, load CA certificates from a folder"
`Slow
(test_send_plain_text_email ethereal_conf_with_ca_path)
] )
; ( "use ethereal.email, test different email message types"
, [ Alcotest_lwt.test_case
"Send plain text email"
`Slow
(test_send_plain_text_email ethereal_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send HTML only email"
`Slow
(test_send_html_email ethereal_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send mixed content email with plain text and HTML"
`Slow
(test_send_mixed_body_email ethereal_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send email with content including line starting with dot (SMTP \
Transparency)"
`Slow
(test_send_mixed_body_email_with_dot_starting_a_line
ethereal_conf_with_ca_detect)
] )
; ( "use mailtrap, test different email message types"
, [ Alcotest_lwt.test_case
"Send plain text email"
`Slow
(test_send_plain_text_email mailtrap_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send HTML only email"
`Slow
(test_send_html_email mailtrap_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send mixed content email with plain text and HTML"
`Slow
(test_send_mixed_body_email mailtrap_conf_with_ca_detect)
; Alcotest_lwt.test_case
"Send email with content including line starting with dot (SMTP \
Transparency)"
`Slow
(test_send_mixed_body_email_with_dot_starting_a_line
mailtrap_conf_with_ca_detect)
] )
])
;;
|
9e93f369f548008b0ae1a100d167622e19807869df985faac7de875f9564b00a | typedclojure/typedclojure | ctyp97_tvar_scoping.clj | (ns clojure.core.typed.test.ctyp97-tvar-scoping
(:import (clojure.lang ASeq LazySeq))
(:require [clojure.core.typed :as t :refer [ann]]))
(ann reduce_ (t/All [a b]
(t/IFn
[[a b -> b] b (t/Seqable a) -> b]
[[a (t/Seqable (t/U a b)) -> (t/Seqable (t/U a b))]
(t/Seqable (t/U a b)) (t/Seqable a) -> (t/Seqable (t/U a b))])))
(defn reduce_
[f zero coll]
(if-let [s (seq coll)]
(f (first s)
(reduce_ f zero (rest s)))
zero))
(ann append_ (t/All [a b] [(t/Seqable a) (t/Seqable b) -> (t/U (t/Seqable (t/U a b))
(ASeq (t/U a b)))]))
(defn append_
[coll1 coll2]
(reduce_ (t/inst cons (t/U a b)) coll2 coll1))
; -------- main
; if you comment out this function, you will get :ok
(ann map-1 (t/All [a b] [[a -> b] (t/Seqable a)
-> (LazySeq b)]))
(defn map-1 [f coll]
(lazy-seq
(if-let [s (seq coll)]
(cons (f (first s))
(map-1 f (rest s))))))
(ann map-2 (t/All [a b] [[a -> b] (t/Seqable a) -> (LazySeq b)]))
(defn map-2
[f coll]
(lazy-seq
(reduce_ (t/fn [x :- a ; ERROR!! -- Cannot resolve type: a
y :- (t/Seqable b)]
(append_ [(f x)] y))
[]
coll)))
| null | https://raw.githubusercontent.com/typedclojure/typedclojure/f0f736bdeb2cbdb86a1194aa8217cf5e9cb675c7/typed/clj.checker/test/clojure/core/typed/test/ctyp97_tvar_scoping.clj | clojure | -------- main
if you comment out this function, you will get :ok
ERROR!! -- Cannot resolve type: a | (ns clojure.core.typed.test.ctyp97-tvar-scoping
(:import (clojure.lang ASeq LazySeq))
(:require [clojure.core.typed :as t :refer [ann]]))
(ann reduce_ (t/All [a b]
(t/IFn
[[a b -> b] b (t/Seqable a) -> b]
[[a (t/Seqable (t/U a b)) -> (t/Seqable (t/U a b))]
(t/Seqable (t/U a b)) (t/Seqable a) -> (t/Seqable (t/U a b))])))
(defn reduce_
[f zero coll]
(if-let [s (seq coll)]
(f (first s)
(reduce_ f zero (rest s)))
zero))
(ann append_ (t/All [a b] [(t/Seqable a) (t/Seqable b) -> (t/U (t/Seqable (t/U a b))
(ASeq (t/U a b)))]))
(defn append_
[coll1 coll2]
(reduce_ (t/inst cons (t/U a b)) coll2 coll1))
(ann map-1 (t/All [a b] [[a -> b] (t/Seqable a)
-> (LazySeq b)]))
(defn map-1 [f coll]
(lazy-seq
(if-let [s (seq coll)]
(cons (f (first s))
(map-1 f (rest s))))))
(ann map-2 (t/All [a b] [[a -> b] (t/Seqable a) -> (LazySeq b)]))
(defn map-2
[f coll]
(lazy-seq
y :- (t/Seqable b)]
(append_ [(f x)] y))
[]
coll)))
|
06429c92244ad21a0a9bf88415ee611ed0167ff1e835c3e040bb701223d9c4e6 | grin-compiler/ghc-wpc-sample-programs | Pretty.hs | module Agda.Compiler.JS.Pretty where
import Prelude hiding ( null )
import Data.Char ( isAsciiLower, isAsciiUpper, isDigit )
import Data.List ( intercalate )
import Data.Set ( Set, toList, singleton, insert, member )
import Data.Map ( Map, toAscList, empty, null )
import Agda.Syntax.Common ( Nat )
import Agda.Utils.Hash
import Agda.Compiler.JS.Syntax hiding (exports)
Pretty - print a lambda - calculus expression as ECMAScript .
Since ECMAScript is C - like rather than - like , it 's easier to
-- do the pretty-printing directly than use the Pretty library, which
assumes - like indentation .
br :: Int -> String
br i = "\n" ++ take (2*i) (repeat ' ')
unescape :: Char -> String
unescape '"' = "\\\""
unescape '\\' = "\\\\"
unescape '\n' = "\\n"
unescape '\r' = "\\r"
unescape '\x2028' = "\\u2028"
unescape '\x2029' = "\\u2029"
unescape c = [c]
unescapes :: String -> String
unescapes s = concat (map unescape s)
pretty n i e pretty - prints e , under n levels of de Bruijn binding ,
-- with i levels of indentation.
class Pretty a where
pretty :: Nat -> Int -> a -> String
instance (Pretty a, Pretty b) => Pretty (a,b) where
pretty n i (x,y) = pretty n i x ++ ": " ++ pretty n (i+1) y
-- Pretty-print collections
class Pretties a where
pretties :: Nat -> Int -> a -> [String]
instance Pretty a => Pretties [a] where
pretties n i = map (pretty n i)
instance (Pretty a, Pretty b) => Pretties (Map a b) where
pretties n i o = pretties n i (toAscList o)
-- Pretty print identifiers
instance Pretty LocalId where
pretty n i (LocalId x) = "x" ++ show (n - x - 1)
instance Pretty GlobalId where
pretty n i (GlobalId m) = variableName $ intercalate "_" m
instance Pretty MemberId where
pretty n i (MemberId s) = "\"" ++ unescapes s ++ "\""
-- Pretty print expressions
instance Pretty Exp where
pretty n i (Self) = "exports"
pretty n i (Local x) = pretty n i x
pretty n i (Global m) = pretty n i m
pretty n i (Undefined) = "undefined"
pretty n i (String s) = "\"" ++ unescapes s ++ "\""
pretty n i (Char c) = "\"" ++ unescape c ++ "\""
pretty n i (Integer x) = "agdaRTS.primIntegerFromString(\"" ++ show x ++ "\")"
pretty n i (Double x) = show x
pretty n i (Lambda x e) =
"function (" ++
intercalate ", " (pretties (n+x) i (map LocalId [x-1, x-2 .. 0])) ++
") " ++ block (n+x) i e
pretty n i (Object o) | null o = "{}"
pretty n i (Object o) | otherwise =
"{" ++ br (i+1) ++ intercalate ("," ++ br (i+1)) (pretties n i o) ++ br i ++ "}"
pretty n i (Apply f es) = pretty n i f ++ "(" ++ intercalate ", " (pretties n i es) ++ ")"
pretty n i (Lookup e l) = pretty n i e ++ "[" ++ pretty n i l ++ "]"
pretty n i (If e f g) =
"(" ++ pretty n i e ++ "? " ++ pretty n i f ++ ": " ++ pretty n i g ++ ")"
pretty n i (PreOp op e) = "(" ++ op ++ " " ++ pretty n i e ++ ")"
pretty n i (BinOp e op f) = "(" ++ pretty n i e ++ " " ++ op ++ " " ++ pretty n i f ++ ")"
pretty n i (Const c) = c
pretty n i (PlainJS js) = "(" ++ js ++ ")"
block :: Nat -> Int -> Exp -> String
block n i (If e f g) = "{" ++ br (i+1) ++ block' n (i+1) (If e f g) ++ br i ++ "}"
block n i e = "{" ++ br (i+1) ++ "return " ++ pretty n (i+1) e ++ ";" ++ br i ++ "}"
block' :: Nat -> Int -> Exp -> String
block' n i (If e f g) = "if (" ++ pretty n i e ++ ") " ++ block n i f ++ " else " ++ block' n i g
block' n i e = block n i e
modname :: GlobalId -> String
modname (GlobalId ms) = "\"" ++ intercalate "." ms ++ "\""
exports :: Nat -> Int -> Set [MemberId] -> [Export] -> String
exports n i lss [] = ""
exports n i lss (Export ls e : es) | member (init ls) lss =
"exports[" ++ intercalate "][" (pretties n i ls) ++ "] = " ++ pretty n (i+1) e ++ ";" ++ br i ++
exports n i (insert ls lss) es
exports n i lss (Export ls e : es) | otherwise =
exports n i lss (Export (init ls) (Object empty) : Export ls e : es)
instance Pretty Module where
pretty n i (Module m es ex) =
imports ++ br i
++ exports n i (singleton []) es ++ br i
++ maybe "" (pretty n i) ex
where
js = toList (globals es)
imports = unlines $
["var agdaRTS = require(\"agda-rts\");"] ++
["var " ++ pretty n (i+1) e ++ " = require(" ++ modname e ++ ");"
| e <- js]
variableName :: String -> String
variableName s = if isValidJSIdent s then "z_" ++ s else "h_" ++ show (hashString s)
-- | Check if a string is a valid JS identifier. The check ignores keywords
-- as we prepend z_ to our identifiers. The check
-- is conservative and may not admit all valid JS identifiers.
isValidJSIdent :: String -> Bool
isValidJSIdent [] = False
isValidJSIdent (c:cs) = validFirst c && all validOther cs
where
validFirst :: Char -> Bool
validFirst c = isAsciiUpper c || isAsciiLower c || c == '_' || c == '$'
validOther :: Char -> Bool
validOther c = validFirst c || isDigit c
| null | https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/Agda-2.6.1/src/full/Agda/Compiler/JS/Pretty.hs | haskell | do the pretty-printing directly than use the Pretty library, which
with i levels of indentation.
Pretty-print collections
Pretty print identifiers
Pretty print expressions
| Check if a string is a valid JS identifier. The check ignores keywords
as we prepend z_ to our identifiers. The check
is conservative and may not admit all valid JS identifiers. | module Agda.Compiler.JS.Pretty where
import Prelude hiding ( null )
import Data.Char ( isAsciiLower, isAsciiUpper, isDigit )
import Data.List ( intercalate )
import Data.Set ( Set, toList, singleton, insert, member )
import Data.Map ( Map, toAscList, empty, null )
import Agda.Syntax.Common ( Nat )
import Agda.Utils.Hash
import Agda.Compiler.JS.Syntax hiding (exports)
Pretty - print a lambda - calculus expression as ECMAScript .
Since ECMAScript is C - like rather than - like , it 's easier to
assumes - like indentation .
br :: Int -> String
br i = "\n" ++ take (2*i) (repeat ' ')
unescape :: Char -> String
unescape '"' = "\\\""
unescape '\\' = "\\\\"
unescape '\n' = "\\n"
unescape '\r' = "\\r"
unescape '\x2028' = "\\u2028"
unescape '\x2029' = "\\u2029"
unescape c = [c]
unescapes :: String -> String
unescapes s = concat (map unescape s)
pretty n i e pretty - prints e , under n levels of de Bruijn binding ,
class Pretty a where
pretty :: Nat -> Int -> a -> String
instance (Pretty a, Pretty b) => Pretty (a,b) where
pretty n i (x,y) = pretty n i x ++ ": " ++ pretty n (i+1) y
class Pretties a where
pretties :: Nat -> Int -> a -> [String]
instance Pretty a => Pretties [a] where
pretties n i = map (pretty n i)
instance (Pretty a, Pretty b) => Pretties (Map a b) where
pretties n i o = pretties n i (toAscList o)
instance Pretty LocalId where
pretty n i (LocalId x) = "x" ++ show (n - x - 1)
instance Pretty GlobalId where
pretty n i (GlobalId m) = variableName $ intercalate "_" m
instance Pretty MemberId where
pretty n i (MemberId s) = "\"" ++ unescapes s ++ "\""
instance Pretty Exp where
pretty n i (Self) = "exports"
pretty n i (Local x) = pretty n i x
pretty n i (Global m) = pretty n i m
pretty n i (Undefined) = "undefined"
pretty n i (String s) = "\"" ++ unescapes s ++ "\""
pretty n i (Char c) = "\"" ++ unescape c ++ "\""
pretty n i (Integer x) = "agdaRTS.primIntegerFromString(\"" ++ show x ++ "\")"
pretty n i (Double x) = show x
pretty n i (Lambda x e) =
"function (" ++
intercalate ", " (pretties (n+x) i (map LocalId [x-1, x-2 .. 0])) ++
") " ++ block (n+x) i e
pretty n i (Object o) | null o = "{}"
pretty n i (Object o) | otherwise =
"{" ++ br (i+1) ++ intercalate ("," ++ br (i+1)) (pretties n i o) ++ br i ++ "}"
pretty n i (Apply f es) = pretty n i f ++ "(" ++ intercalate ", " (pretties n i es) ++ ")"
pretty n i (Lookup e l) = pretty n i e ++ "[" ++ pretty n i l ++ "]"
pretty n i (If e f g) =
"(" ++ pretty n i e ++ "? " ++ pretty n i f ++ ": " ++ pretty n i g ++ ")"
pretty n i (PreOp op e) = "(" ++ op ++ " " ++ pretty n i e ++ ")"
pretty n i (BinOp e op f) = "(" ++ pretty n i e ++ " " ++ op ++ " " ++ pretty n i f ++ ")"
pretty n i (Const c) = c
pretty n i (PlainJS js) = "(" ++ js ++ ")"
block :: Nat -> Int -> Exp -> String
block n i (If e f g) = "{" ++ br (i+1) ++ block' n (i+1) (If e f g) ++ br i ++ "}"
block n i e = "{" ++ br (i+1) ++ "return " ++ pretty n (i+1) e ++ ";" ++ br i ++ "}"
block' :: Nat -> Int -> Exp -> String
block' n i (If e f g) = "if (" ++ pretty n i e ++ ") " ++ block n i f ++ " else " ++ block' n i g
block' n i e = block n i e
modname :: GlobalId -> String
modname (GlobalId ms) = "\"" ++ intercalate "." ms ++ "\""
exports :: Nat -> Int -> Set [MemberId] -> [Export] -> String
exports n i lss [] = ""
exports n i lss (Export ls e : es) | member (init ls) lss =
"exports[" ++ intercalate "][" (pretties n i ls) ++ "] = " ++ pretty n (i+1) e ++ ";" ++ br i ++
exports n i (insert ls lss) es
exports n i lss (Export ls e : es) | otherwise =
exports n i lss (Export (init ls) (Object empty) : Export ls e : es)
instance Pretty Module where
pretty n i (Module m es ex) =
imports ++ br i
++ exports n i (singleton []) es ++ br i
++ maybe "" (pretty n i) ex
where
js = toList (globals es)
imports = unlines $
["var agdaRTS = require(\"agda-rts\");"] ++
["var " ++ pretty n (i+1) e ++ " = require(" ++ modname e ++ ");"
| e <- js]
variableName :: String -> String
variableName s = if isValidJSIdent s then "z_" ++ s else "h_" ++ show (hashString s)
isValidJSIdent :: String -> Bool
isValidJSIdent [] = False
isValidJSIdent (c:cs) = validFirst c && all validOther cs
where
validFirst :: Char -> Bool
validFirst c = isAsciiUpper c || isAsciiLower c || c == '_' || c == '$'
validOther :: Char -> Bool
validOther c = validFirst c || isDigit c
|
42ba3fe5e46761080427d100161c24dead43950db87000eb2f9d35ebc857ba95 | zellige/hastile | Tile.hs | {-# LANGUAGE DeriveFunctor #-}
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Hastile.Types.Tile where
import qualified Data.Aeson as Aeson
import qualified Data.Functor.Contravariant as Contravariant
import qualified Data.Geometry.Types.Geography as GeometryTypesGeography
import qualified Data.Maybe as Maybe
import Data.Monoid ((<>))
import qualified Data.Scientific as Scientific
import qualified Data.Text as Text
import qualified Data.Vector as Vector
import qualified Hasql.Encoders as HasqlEncoders
import qualified Hastile.Types.Config as Config
import qualified Hastile.Types.Layer as Layer
SW and NE points given as W , S , E , N
data BBox a = BBox
{ _bboxLlx :: a
, _bboxLly :: a
, _bboxUrx :: a
, _bboxUry :: a
} deriving (Show, Eq, Functor)
newtype Metres = Metres Double deriving (Show, Eq, Num, Floating, Fractional, Ord)
metreValue :: HasqlEncoders.Value Metres
metreValue =
Contravariant.contramap metreTodouble HasqlEncoders.float8
where
metreTodouble (Metres double) = double
bboxEncoder :: HasqlEncoders.Params (BBox Metres)
bboxEncoder =
Contravariant.contramap _bboxLlx (HasqlEncoders.param metreValue)
<> Contravariant.contramap _bboxLly (HasqlEncoders.param metreValue)
<> Contravariant.contramap _bboxUrx (HasqlEncoders.param metreValue)
<> Contravariant.contramap _bboxUry (HasqlEncoders.param metreValue)
data TileScheme = TileSchemeXyz | TileSchemeTms
deriving Show
instance Aeson.ToJSON TileScheme where
toJSON TileSchemeXyz = Aeson.String "xyz"
toJSON TileSchemeTms = Aeson.String "tms"
data TileCenter = TileCenter
{ _tileCenterLongitude :: Double
, _tileCenterLatitude :: Double
, _tileCenterZoom :: Int
}
instance Aeson.ToJSON TileCenter where
toJSON TileCenter{..} = Aeson.Array $ Vector.fromList [doubleToNumber _tileCenterLongitude, doubleToNumber _tileCenterLatitude, intToNumber _tileCenterZoom]
where
doubleToNumber = Aeson.Number . Scientific.fromFloatDigits
intToNumber i = Aeson.Number (fromInteger $ toInteger i :: Scientific.Scientific)
data Tile = Tile
{ _tileStyleVersion :: Text.Text
, _tileName :: Maybe Text.Text
, _tileDescription :: Maybe Text.Text
, _tileVersion :: Maybe Text.Text
, _tileAttribution :: Maybe Text.Text
, _tileTemplate :: Maybe Text.Text
, _tileLegend :: Maybe Text.Text
, _tileScheme :: Maybe TileScheme
, _tileTiles :: [Text.Text]
, _tileGrids :: Maybe [Text.Text]
, _tileData :: Maybe [Text.Text]
, _tileMinZoom :: Maybe GeometryTypesGeography.ZoomLevel
, _tileMaxZoom :: Maybe GeometryTypesGeography.ZoomLevel
, _tileBoundingBox :: Maybe GeometryTypesGeography.BoundingBox
, _tileCenter :: Maybe TileCenter
}
instance Aeson.ToJSON Tile where
toJSON tile = Aeson.object $
[ "tilejson" Aeson..= _tileStyleVersion tile
, "tiles" Aeson..= _tileTiles tile
] ++
Maybe.catMaybes
[ ("name" Aeson..=) <$> _tileName tile
, ("description" Aeson..=) <$> _tileDescription tile
, ("version" Aeson..=) <$> _tileVersion tile
, ("attribution" Aeson..=) <$> _tileAttribution tile
, ("template" Aeson..=) <$> _tileTemplate tile
, ("legend" Aeson..=) <$> _tileLegend tile
, ("scheme" Aeson..=) <$> _tileScheme tile
, ("grids" Aeson..=) <$> _tileGrids tile
, ("data" Aeson..=) <$> _tileData tile
, ("minzoom" Aeson..=) <$> _tileMinZoom tile
, ("maxzoom" Aeson..=) <$> _tileMaxZoom tile
, ("bounds" Aeson..=) <$> _tileBoundingBox tile
, ("center" Aeson..=) <$> _tileCenter tile
]
fromConfig :: Config.Config -> Layer.Layer -> Tile
fromConfig Config.Config{..} {..} =
Tile
{ _tileStyleVersion = "2.2.0"
, _tileName = Just _layerName
, _tileDescription = Nothing
, _tileVersion = Just "1.0.0"
, _tileAttribution = Nothing
, _tileTemplate = Nothing
, _tileLegend = Nothing
, _tileScheme = Just TileSchemeXyz
, _tileTiles = [tileUrl]
, _tileGrids = Nothing
, _tileData = Nothing
, _tileMinZoom = Just $ Layer.layerMinZoom layer
, _tileMaxZoom = Just $ Layer.layerMaxZoom layer
, _tileBoundingBox = Layer._layerBounds _layerSettings
, _tileCenter = Nothing
}
where
tileUrl = _configProtocolHost <> ":" <> Text.pack (show _configPort) <> "/" <> _layerName <> "/{z}/{x}/{y}.mvt"
| null | https://raw.githubusercontent.com/zellige/hastile/4dabe66bd997e91128ab4136b6f40da51c204a2b/src/Hastile/Types/Tile.hs | haskell | # LANGUAGE DeriveFunctor #
# LANGUAGE OverloadedStrings # | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RecordWildCards #
module Hastile.Types.Tile where
import qualified Data.Aeson as Aeson
import qualified Data.Functor.Contravariant as Contravariant
import qualified Data.Geometry.Types.Geography as GeometryTypesGeography
import qualified Data.Maybe as Maybe
import Data.Monoid ((<>))
import qualified Data.Scientific as Scientific
import qualified Data.Text as Text
import qualified Data.Vector as Vector
import qualified Hasql.Encoders as HasqlEncoders
import qualified Hastile.Types.Config as Config
import qualified Hastile.Types.Layer as Layer
SW and NE points given as W , S , E , N
data BBox a = BBox
{ _bboxLlx :: a
, _bboxLly :: a
, _bboxUrx :: a
, _bboxUry :: a
} deriving (Show, Eq, Functor)
newtype Metres = Metres Double deriving (Show, Eq, Num, Floating, Fractional, Ord)
metreValue :: HasqlEncoders.Value Metres
metreValue =
Contravariant.contramap metreTodouble HasqlEncoders.float8
where
metreTodouble (Metres double) = double
bboxEncoder :: HasqlEncoders.Params (BBox Metres)
bboxEncoder =
Contravariant.contramap _bboxLlx (HasqlEncoders.param metreValue)
<> Contravariant.contramap _bboxLly (HasqlEncoders.param metreValue)
<> Contravariant.contramap _bboxUrx (HasqlEncoders.param metreValue)
<> Contravariant.contramap _bboxUry (HasqlEncoders.param metreValue)
data TileScheme = TileSchemeXyz | TileSchemeTms
deriving Show
instance Aeson.ToJSON TileScheme where
toJSON TileSchemeXyz = Aeson.String "xyz"
toJSON TileSchemeTms = Aeson.String "tms"
data TileCenter = TileCenter
{ _tileCenterLongitude :: Double
, _tileCenterLatitude :: Double
, _tileCenterZoom :: Int
}
instance Aeson.ToJSON TileCenter where
toJSON TileCenter{..} = Aeson.Array $ Vector.fromList [doubleToNumber _tileCenterLongitude, doubleToNumber _tileCenterLatitude, intToNumber _tileCenterZoom]
where
doubleToNumber = Aeson.Number . Scientific.fromFloatDigits
intToNumber i = Aeson.Number (fromInteger $ toInteger i :: Scientific.Scientific)
data Tile = Tile
{ _tileStyleVersion :: Text.Text
, _tileName :: Maybe Text.Text
, _tileDescription :: Maybe Text.Text
, _tileVersion :: Maybe Text.Text
, _tileAttribution :: Maybe Text.Text
, _tileTemplate :: Maybe Text.Text
, _tileLegend :: Maybe Text.Text
, _tileScheme :: Maybe TileScheme
, _tileTiles :: [Text.Text]
, _tileGrids :: Maybe [Text.Text]
, _tileData :: Maybe [Text.Text]
, _tileMinZoom :: Maybe GeometryTypesGeography.ZoomLevel
, _tileMaxZoom :: Maybe GeometryTypesGeography.ZoomLevel
, _tileBoundingBox :: Maybe GeometryTypesGeography.BoundingBox
, _tileCenter :: Maybe TileCenter
}
instance Aeson.ToJSON Tile where
toJSON tile = Aeson.object $
[ "tilejson" Aeson..= _tileStyleVersion tile
, "tiles" Aeson..= _tileTiles tile
] ++
Maybe.catMaybes
[ ("name" Aeson..=) <$> _tileName tile
, ("description" Aeson..=) <$> _tileDescription tile
, ("version" Aeson..=) <$> _tileVersion tile
, ("attribution" Aeson..=) <$> _tileAttribution tile
, ("template" Aeson..=) <$> _tileTemplate tile
, ("legend" Aeson..=) <$> _tileLegend tile
, ("scheme" Aeson..=) <$> _tileScheme tile
, ("grids" Aeson..=) <$> _tileGrids tile
, ("data" Aeson..=) <$> _tileData tile
, ("minzoom" Aeson..=) <$> _tileMinZoom tile
, ("maxzoom" Aeson..=) <$> _tileMaxZoom tile
, ("bounds" Aeson..=) <$> _tileBoundingBox tile
, ("center" Aeson..=) <$> _tileCenter tile
]
fromConfig :: Config.Config -> Layer.Layer -> Tile
fromConfig Config.Config{..} {..} =
Tile
{ _tileStyleVersion = "2.2.0"
, _tileName = Just _layerName
, _tileDescription = Nothing
, _tileVersion = Just "1.0.0"
, _tileAttribution = Nothing
, _tileTemplate = Nothing
, _tileLegend = Nothing
, _tileScheme = Just TileSchemeXyz
, _tileTiles = [tileUrl]
, _tileGrids = Nothing
, _tileData = Nothing
, _tileMinZoom = Just $ Layer.layerMinZoom layer
, _tileMaxZoom = Just $ Layer.layerMaxZoom layer
, _tileBoundingBox = Layer._layerBounds _layerSettings
, _tileCenter = Nothing
}
where
tileUrl = _configProtocolHost <> ":" <> Text.pack (show _configPort) <> "/" <> _layerName <> "/{z}/{x}/{y}.mvt"
|
7a3dd8455797ebb71a01911b47a6ed8c0cd8ca61494e760700290f5f6f5519c4 | cblp/stack-offline | Simple.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
module Development.Shake.Simple
(Rule, need, rule, simpleRule, simpleStoredValue, storedValue, want) where
import Data.Functor (($>))
import Development.Shake (Action, Rules, ShakeOptions, ShakeValue, action)
import Development.Shake.Classes (Binary, Hashable, NFData)
import Development.Shake.Rule (Rule, apply, rule, storedValue)
newtype SimpleKey a = SimpleKey a
deriving (Binary, Eq, Hashable, NFData, Show)
fromSimpleKey :: SimpleKey a -> a
fromSimpleKey (SimpleKey a) = a
instance ShakeValue key => Rule (SimpleKey key) () where
storedValue = simpleStoredValue
need :: Rule (SimpleKey key) () => [key] -> Action ()
need keys = (apply $ fmap SimpleKey keys :: Action [()]) $> ()
want :: Rule (SimpleKey key) () => [key] -> Rules ()
want = action . need
simpleStoredValue :: Rule key value => ShakeOptions -> key -> IO (Maybe value)
simpleStoredValue _ _ = pure Nothing
simpleRule :: Rule (SimpleKey key) value => (key -> Action value) -> Rules ()
simpleRule r = rule $ Just . r . fromSimpleKey
| null | https://raw.githubusercontent.com/cblp/stack-offline/94215104d0cd295e39815db307513a5cc959e02f/test/Development/Shake/Simple.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
module Development.Shake.Simple
(Rule, need, rule, simpleRule, simpleStoredValue, storedValue, want) where
import Data.Functor (($>))
import Development.Shake (Action, Rules, ShakeOptions, ShakeValue, action)
import Development.Shake.Classes (Binary, Hashable, NFData)
import Development.Shake.Rule (Rule, apply, rule, storedValue)
newtype SimpleKey a = SimpleKey a
deriving (Binary, Eq, Hashable, NFData, Show)
fromSimpleKey :: SimpleKey a -> a
fromSimpleKey (SimpleKey a) = a
instance ShakeValue key => Rule (SimpleKey key) () where
storedValue = simpleStoredValue
need :: Rule (SimpleKey key) () => [key] -> Action ()
need keys = (apply $ fmap SimpleKey keys :: Action [()]) $> ()
want :: Rule (SimpleKey key) () => [key] -> Rules ()
want = action . need
simpleStoredValue :: Rule key value => ShakeOptions -> key -> IO (Maybe value)
simpleStoredValue _ _ = pure Nothing
simpleRule :: Rule (SimpleKey key) value => (key -> Action value) -> Rules ()
simpleRule r = rule $ Just . r . fromSimpleKey
|
|
ffc7f379df363ab3b36fe6ff96111cde302331493f5c716d87069eba1a80d14f | fogfish/typhoon | typhoon_sup.erl | %%
%% Copyright 2015 Zalando SE
%%
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(typhoon_sup).
-behaviour(supervisor).
-author('').
-export([
start_link/0, init/1
]).
-define(CHILD(Type, I), {I, {I, start_link, []}, permanent, 5000, Type, dynamic}).
-define(CHILD(Type, I, Args), {I, {I, start_link, Args}, permanent, 5000, Type, dynamic}).
-define(CHILD(Type, ID, I, Args), {ID, {I, start_link, Args}, permanent, 5000, Type, dynamic}).
%%-----------------------------------------------------------------------------
%%
%% supervisor
%%
%%-----------------------------------------------------------------------------
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
{ok,
{
{one_for_one, 4, 1800},
[
?CHILD(worker, typhoon_peer)
]
}
}.
| null | https://raw.githubusercontent.com/fogfish/typhoon/db0d76050a9c41c45582e9928206270450600d00/apps/typhoon/src/typhoon_sup.erl | erlang |
Copyright 2015 Zalando SE
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.
-----------------------------------------------------------------------------
supervisor
----------------------------------------------------------------------------- | Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(typhoon_sup).
-behaviour(supervisor).
-author('').
-export([
start_link/0, init/1
]).
-define(CHILD(Type, I), {I, {I, start_link, []}, permanent, 5000, Type, dynamic}).
-define(CHILD(Type, I, Args), {I, {I, start_link, Args}, permanent, 5000, Type, dynamic}).
-define(CHILD(Type, ID, I, Args), {ID, {I, start_link, Args}, permanent, 5000, Type, dynamic}).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
{ok,
{
{one_for_one, 4, 1800},
[
?CHILD(worker, typhoon_peer)
]
}
}.
|
862496a55bfbf9ec2667bd48a0671778a37dd0ed0665f7c33c1d53fdf7b6479a | madgen/exalog | Error.hs | # LANGUAGE RecordWildCards #
module Language.Exalog.Error
( Error(..)
, Severity(..)
) where
import Protolude hiding ((<>))
import Text.PrettyPrint
import Language.Exalog.Pretty.Helper (Pretty(..), ($+?$))
import Language.Exalog.SrcLoc (SrcSpan, prettySpan)
data Severity =
-- |Error that should never be thrown
Impossible
-- |Standard user error
| User
-- |Warning
| Warning
deriving (Eq)
data Error = Error
{ _severity :: Severity
, _mSource :: Maybe Text
, _span :: SrcSpan
, _message :: Text
}
instance Pretty Severity where
pretty Impossible = "Impossible happened! Please submit a bug report"
pretty User = "Error"
pretty Warning = "Warning"
instance Pretty Error where
pretty Error{..} =
brackets (pretty _severity) <> colon
$+$ nest 2 prettyError
where
prettyError = pretty _span
$+$ pretty _message
$+$ maybe mempty
(("" $+?$) . (`prettySpan` _span))
_mSource
| null | https://raw.githubusercontent.com/madgen/exalog/7d169b066c5c08f2b8e44f5e078df264731ac177/src/Language/Exalog/Error.hs | haskell | |Error that should never be thrown
|Standard user error
|Warning | # LANGUAGE RecordWildCards #
module Language.Exalog.Error
( Error(..)
, Severity(..)
) where
import Protolude hiding ((<>))
import Text.PrettyPrint
import Language.Exalog.Pretty.Helper (Pretty(..), ($+?$))
import Language.Exalog.SrcLoc (SrcSpan, prettySpan)
data Severity =
Impossible
| User
| Warning
deriving (Eq)
data Error = Error
{ _severity :: Severity
, _mSource :: Maybe Text
, _span :: SrcSpan
, _message :: Text
}
instance Pretty Severity where
pretty Impossible = "Impossible happened! Please submit a bug report"
pretty User = "Error"
pretty Warning = "Warning"
instance Pretty Error where
pretty Error{..} =
brackets (pretty _severity) <> colon
$+$ nest 2 prettyError
where
prettyError = pretty _span
$+$ pretty _message
$+$ maybe mempty
(("" $+?$) . (`prettySpan` _span))
_mSource
|
344f750ed145406cdfa423e6173f02a9efbea6341979394c519cf444772843f7 | taksatou/cl-gearman | backup-server.lisp | Run two gearman servers using
docker run --rm -p 4730:4730 artefactual / gearmand:1.1.19.1 - alpine
docker run --rm -p 4731:4730 artefactual / gearmand:1.1.19.1 - alpine
1 ) Test with two servers active
2 ) Shutdown the first server and check that still got the answer to the client side
(ql:quickload :cl-gearman)
(defparameter *servers* '("localhost:4730" "localhost:4731"))
;; worker side
(cl-gearman:with-multiple-servers-worker (wx *servers*)
(defvar lisp-info (lambda (arg job)
(declare (ignorable arg job))
(format nil "~A ~A ~%"
(lisp-implementation-type)
(lisp-implementation-version))))
(defvar reverse! (lambda (arg job)
(declare (ignorable arg job))
(format nil "~a~%" (reverse arg))))
(cl-gearman:add-ability wx "task1" lisp-info)
(cl-gearman:add-ability wx "task2" reverse!)
(loop
do (handler-case (cl-gearman:work wx)
(error (c)
(format t "Worker lost because of error ~a , please restart this connection ~%" c)))))
;; client side
(handler-bind ((error #'(lambda (c) (invoke-restart 'cl-gearman::skip-connection))))
(cl-gearman:with-multiple-servers-client (client *servers*)
(format t "~A"
(cl-gearman:submit-job client "task1"
:arg ""))
(format t "~A"
(cl-gearman:submit-job client "task2"
:arg "Hello Lisp World!"))))
| null | https://raw.githubusercontent.com/taksatou/cl-gearman/94658c51cd58f4720de8973d8aed5ee9d9d6ba13/examples/backup-server.lisp | lisp | worker side
client side | Run two gearman servers using
docker run --rm -p 4730:4730 artefactual / gearmand:1.1.19.1 - alpine
docker run --rm -p 4731:4730 artefactual / gearmand:1.1.19.1 - alpine
1 ) Test with two servers active
2 ) Shutdown the first server and check that still got the answer to the client side
(ql:quickload :cl-gearman)
(defparameter *servers* '("localhost:4730" "localhost:4731"))
(cl-gearman:with-multiple-servers-worker (wx *servers*)
(defvar lisp-info (lambda (arg job)
(declare (ignorable arg job))
(format nil "~A ~A ~%"
(lisp-implementation-type)
(lisp-implementation-version))))
(defvar reverse! (lambda (arg job)
(declare (ignorable arg job))
(format nil "~a~%" (reverse arg))))
(cl-gearman:add-ability wx "task1" lisp-info)
(cl-gearman:add-ability wx "task2" reverse!)
(loop
do (handler-case (cl-gearman:work wx)
(error (c)
(format t "Worker lost because of error ~a , please restart this connection ~%" c)))))
(handler-bind ((error #'(lambda (c) (invoke-restart 'cl-gearman::skip-connection))))
(cl-gearman:with-multiple-servers-client (client *servers*)
(format t "~A"
(cl-gearman:submit-job client "task1"
:arg ""))
(format t "~A"
(cl-gearman:submit-job client "task2"
:arg "Hello Lisp World!"))))
|
23475c002950dcca197c4199cc69c4a94de38f3c6b6e5bed270909a811c4c927 | byorgey/thesis | SpeciesDiagrams.hs | # LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE NoMonomorphismRestriction #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
module SpeciesDiagrams where
import Control.Arrow (first, second)
import Control.Lens (_head, _last)
import Data.Colour.Palette.BrewerSet
import Data.List (intersperse, permutations)
import Data.List.Split
import qualified Data.Map as M
import Data.Maybe (fromJust, fromMaybe)
import Data.Tree
import Diagrams.Backend.Cairo.CmdLine
import Diagrams.Core.Points
import Diagrams.Prelude
import Diagrams.TwoD.Layout.Tree
import Graphics.SVGFonts.ReadFont
import qualified Math.Combinatorics.Multiset as MS
colors :: [Colour Double]
colors = brewerSet Set1 9
labR, arrowGap :: Double
labR = 0.3
arrowGap = 0.2
aLabels :: [Diagram B R2]
aLabels = map (sized (Dims (4*labR) (4*labR)))
[ circle 1
, triangle 1
, square 1
, pentagon 1
, rect 1 1.618
, rect 1.618 1
, circle 1 # scaleX 1.618
, circle 1 # scaleY 1.618
]
type EdgeLabel = P2 -> P2 -> Diagram B R2
sLabels :: [EdgeLabel]
sLabels =
[ connStyle mempty
, connStyle $ (mempty # lw veryThick)
, connStyle $ (mempty # dashingG [0.1,0.1] 0)
, connStyle $ (mempty # dashingG [0.05,0.15] 0)
, connStyle $ (mempty # dashingG [0.05,0.05,0.1,0.05] 0)
, \p q -> let v = 0.03 *^ normalized (perp (q .-. p))
in ((p .+^ v) ~~ (q .+^ v)) <> ((p .-^ v) ~~ (q .-^ v))
]
where
connStyle sty p q = (p ~~ q) # applyStyle sty
perp = rotateBy (1/4)
labSty :: Int -> Maybe EdgeLabel
labSty i = Just (sLabels !! i)
leafData :: Int -> Diagram B R2
leafData i = (aLabels !! i) # sized (Dims labR labR) # fc black <> square (labR*1.5) # fc white
text' :: Double -> String -> Diagram B R2
text' d s = (stroke $ textSVG' (TextOpts s lin INSIDE_H KERN False d d)) # fc black # lw none
labT :: Int -> Diagram B R2
labT n = text' 1.5 (show n) # scale labR <> lab n
lab :: Int -> Diagram B R2
lab n = lab' (colors !! n)
lab' :: (TrailLike b, Transformable b, HasStyle b, V b ~ R2) => Colour Double -> b
lab' c = circle labR
# fc white
# lc c
# lwG (labR / 5)
cyc :: [Int] -> Double -> Diagram B R2
cyc labs r = cyc' (map lab labs) r
cyc' :: (Monoid' a, TrailLike a, Transformable a, HasStyle a, HasOrigin a, V a ~ R2) => [a] -> Double -> a
cyc' labs r
= mconcat
. zipWith (\l (p,a) -> l # moveTo p <> a) labs
$ zipWith rotateBy
[1/4, 1/4 + 1/(fromIntegral n) .. ]
(map mkLink labs)
where
n = length labs
mkLink _ = ( origin # translateX r
,
( arc startAngle endAngle
# scale r
<>
eqTriangle 0.1
# translateX r
# rotate endAngle
# fc black
)
)
startAngle = (labR + arrowGap)/r @@ rad
endAngle = (tau/fromIntegral n @@ rad) ^-^ startAngle
newtype Cyc a = Cyc {getCyc :: [a]}
deriving Functor
data Pointed a = Plain a | Pointed a
class Drawable d where
draw :: d -> Diagram B R2
instance Drawable (Diagram B R2) where
draw = id
instance Drawable a => Drawable (Cyc a) where
draw (Cyc ls) = cyc' (map draw ls # sized (Width (labR*2))) 1
instance Drawable a => Drawable [a] where
draw ls = centerX . hcat' (with & sep .~ 0.1)
$ intersperse (mkArrow 0.5 mempty) (map draw ls)
instance Drawable a => Drawable (Pointed a) where
draw (Plain a) = draw a
draw (Pointed a) = point (draw a)
point :: Diagram B R2 -> Diagram B R2
point d = d <> drawSpN Hole # sizedAs (d # scale 5)
down :: Cyc (Diagram B R2) -> Cyc (Cyc (Pointed (Diagram B R2)))
down (Cyc ls) = Cyc (map Cyc (pointings ls))
pointings :: [a] -> [[Pointed a]]
pointings [] = []
pointings (x:xs) = (Pointed x : map Plain xs) : map (Plain x :) (pointings xs)
elimArrow :: Diagram B R2
elimArrow = hrule 2
||| eqTriangle 0.2 # rotateBy (-1/4) # fc black
mkArrow :: Double -> Diagram B R2 -> Diagram B R2
mkArrow len l =
( l
===
(arrow len # translateX (-len/2) <> rect len 0.5 # lw none)
)
# alignB
data SpN = Lab (Either Int String)
| Leaf (Maybe (Diagram B R2))
| Hole
| Point
| Sp (Diagram B R2) Angle
| Bag
type SpT = Tree (Maybe EdgeLabel, SpN)
drawSpT' :: T2 -> SymmLayoutOpts (Maybe EdgeLabel, SpN) -> SpT -> Diagram B R2
drawSpT' tr slopts
= transform tr
. renderTree' (drawSpN' (inv tr) . snd) drawSpE
. symmLayout' slopts
drawSpT :: SpT -> Diagram B R2
drawSpT = drawSpT' (rotation (1/4 @@ turn))
(with & slHSep .~ 0.5 & slVSep .~ 2 & slWidth .~ slw)
where
slw (_, Leaf (Just d)) = (-width d/2, width d/2)
slw (_, sp@(Sp _ _)) = let w = width (drawSpN' (rotation (1/4 @@ turn)) sp)
in (-w/2, w/2)
slw _ = (0,0)
drawSpN' :: Transformation R2 -> SpN -> Diagram B R2
drawSpN' _ (Lab (Left n)) = lab n # scale 0.5
drawSpN' tr (Lab (Right t)) = (drawSpN' tr (Leaf Nothing) ||| strutX (labR/2) ||| text' 0.3 t) # transform tr
drawSpN' _ (Leaf Nothing) = circle (labR/2) # fc black
drawSpN' _ (Leaf (Just d)) = d
drawSpN' _ Hole = circle (labR/2) # lwG (labR / 10) # fc white
drawSpN' tr Point = drawSpN' tr (Leaf Nothing) <> drawSpN' tr Hole # scale 1.7
drawSpN' tr (Sp s f) = ( arc ((3/4 @@ turn) ^-^ f^/2) ((3/4 @@ turn) ^+^ f^/2) # scale 0.3
|||
strutX 0.1
|||
s # transform tr
)
drawSpN' _ Bag =
( text' 1 "{" # scale 0.5 ||| strutX (labR/4)
||| circle (labR/2) # fc black
||| strutX (labR/4) ||| text' 1 "}" # scale 0.5
) # centerX
drawSpN :: SpN -> Diagram B R2
drawSpN = drawSpN' mempty
drawSpE :: (t, P2) -> ((Maybe EdgeLabel, SpN), P2) -> Diagram B R2
drawSpE (_,p) ((_,Hole),q) = (p ~~ q) # dashingG [0.05,0.05] 0
drawSpE (_,p) ((Just f,_), q) = f p q
drawSpE (_,p) (_,q) = p ~~ q
nd :: Diagram B R2 -> Forest (Maybe EdgeLabel, SpN) -> SpT
nd x = Node (Nothing, Sp x (1/3 @@ turn))
nd' :: EdgeLabel -> Diagram B R2 -> Forest (Maybe EdgeLabel, SpN) -> SpT
nd' l x = Node (Just l, Sp x (1/3 @@ turn))
lf :: a -> Tree (Maybe EdgeLabel, a)
lf x = Node (Nothing, x) []
lf' :: EdgeLabel -> a -> Tree (Maybe EdgeLabel, a)
lf' l x = Node (Just l, x) []
struct :: Int -> String -> Diagram B R2
struct n x = drawSpT (struct' n x)
# centerXY
struct' :: Int -> String -> SpT
struct' n x = struct'' n (text' 1 x <> rect 2 1 # lw none)
struct'' :: Int -> Diagram B R2 -> SpT
struct'' n d = nd d (replicate n (lf (Leaf Nothing)))
linOrd :: [Int] -> Diagram B R2
linOrd ls =
connect' (with & arrowHead .~ noHead) "head" "last"
. hcat' (with & sep .~ 0.5)
$ map labT ls & _head %~ named "head" & _last %~ named "last"
unord :: (Monoid' b, Semigroup b, TrailLike b, Alignable b, Transformable b, HasStyle b, Juxtaposable b, HasOrigin b, Enveloped b, V b ~ R2) => [b] -> b
unord [] = circle 1 # lc gray
unord ds = elts # centerXY
<> roundedRect w (mh + s*2) ((mh + s*2) / 5)
where
elts = hcat' (with & sep .~ s) ds
mw = maximum' 0 . map width $ ds
s = mw * 0.5
mh = maximum' 0 . map height $ ds
w = ((fromIntegral (length ds + 1) * s) +) . sum . map width $ ds
maximum' d [] = d
maximum' _ xs = maximum xs
enRect' :: (Semigroup a, TrailLike a, Alignable a, Enveloped a, HasOrigin a, V a ~ R2) => Double -> a -> a
enRect' o d = roundedRect (w+o) (h+o) o <> d # centerXY
where (w,h) = size2D d
enRect :: (Semigroup a, TrailLike a, Alignable a, Enveloped a, HasOrigin a, V a ~ R2) => a -> a
enRect = enRect' 0.5
txt x = text x # fontSizeO 10 <> square 1 # lw none
------------------------------------------------------------
-- Some specific constructions
mlocColor = blend 0.5 white lightblue
eltColor = blend 0.5 white lightgreen
mloc m = text (show m) <> circle 0.8 # fc mlocColor
elt x = text (show x) <> square 1.6 # fc eltColor
arm typ m n r = ( typ m # rotateBy (-r)
||| hrule 1.5
||| typ n # rotateBy (-r)
)
# translateX 3
# rotateBy r
arms typ elts = zipWith (\[e1,e2] r -> arm typ e1 e2 r) (chunksOf 2 elts) [1/8 + 0.001, 1/8+0.001 +1/4 .. 1]
octo' typ elts = (mconcat (arms typ elts) <> circle 3)
octo = octo' mloc
sampleT7 = Node 3 [Node 4 (map lf [2,1,6]), Node 5 [], Node 0 [lf 7]]
where
lf x = Node x []
tree :: Diagram B R2
tree = renderTree
mloc
(~~)
(symmLayout' (with & slHSep .~ 4 & slVSep .~ 4) sampleT7)
drawBinTree' :: SymmLayoutOpts (Diagram B R2) -> BTree (Diagram B R2) -> Diagram B R2
drawBinTree' opts
= maybe mempty (renderTree id (~~))
. symmLayoutBin' opts
drawBinTree :: BTree (Diagram B R2) -> Diagram B R2
drawBinTree = drawBinTree' with
drawBinTreeWide :: BTree (Diagram B R2) -> Diagram B R2
drawBinTreeWide = drawBinTree' (with & slHSep .~ 1.5)
select :: [a] -> [(a,[a])]
select [] = []
select (a:as) = (a,as) : (map . second) (a:) (select as)
subsets :: [a] -> [([a],[a])]
subsets [] = [([],[])]
subsets (a:as) = (map . first) (a:) s ++ (map . second) (a:) s
where s = subsets as
type Edge = (Int,Int)
type Graph = (M.Map Int P2, [Edge])
drawGraph drawLoc (locs, edges) = drawLocs <> drawEdges
where
drawLocs = mconcat . map (\(n,p) -> drawLoc n # moveTo p) . M.assocs $ locs
drawEdges = mconcat . map drawEdge $ edges
drawEdge (i1,i2) = lkup i1 ~~ lkup i2
lkup i = fromMaybe origin $ M.lookup i locs
gr :: Diagram B R2
gr = drawGraph mloc
( M.fromList
[ (0, 3 ^& (-1))
, (1, 8 ^& 0)
, (2, origin)
, (3, 8 ^& 2)
, (4, 4 ^& 2)
, (5, 3 ^& (-3))
] # scale 1.5
, [(2,0), (2,4), (0,4), (4,3), (3,1), (0,1), (0,5)]
)
--------------------------------------------------
sampleBTree5, sampleBTree7 :: BTree Int
sampleBTree5 = (BNode (0 :: Int) (BNode 1 Empty Empty) (BNode 2 (BNode 3 Empty Empty) (BNode 4 Empty Empty)))
sampleBTree7 = (BNode (0 :: Int) (BNode 1 (BNode 2 Empty (BNode 3 Empty Empty)) Empty) (BNode 4 (BNode 5 Empty Empty) (BNode 6 Empty Empty)))
wideTree
:: (Monoid m, Semigroup m, TrailLike (QDiagram b R2 m))
=> (a -> QDiagram b R2 m) -> BTree a -> QDiagram b R2 m
wideTree n
= maybe mempty (renderTree n (~~))
. symmLayoutBin' (with & slVSep .~ 4 & slHSep .~ 6)
mkLeaf
:: ( Semigroup m, IsName n )
=> QDiagram b R2 m -> n -> QDiagram b R2 m
mkLeaf shp n = shp # fc white # named n
numbered :: Show a => a -> Diagram B R2
numbered n = mkLeaf (text (show n) # fc black <> circle 1) ()
lettered :: Int -> Diagram B R2
lettered n = mkLeaf (text [['a' ..] !! n] # fc black <> circle 1) ()
drawList nd n = drawList' nd [0::Int .. (n - 1)]
drawList' nd ns = lst # centerX `atop` hrule (width lst - w)
where
elts = map nd ns
w = maximum . map width $ elts
lst = hcat' (with & sep .~ w/2) elts
enumTrees :: [a] -> [BTree a]
enumTrees [] = [ Empty ]
enumTrees xxs = [ BNode x l r
| (x,xs) <- select xxs
, (ys, zs) <- subsets xs
, l <- enumTrees ys
, r <- enumTrees zs
]
tag :: Int -> Diagram B R2 -> Diagram B R2
tag i d = d # centerXY <> roundedRect w h r # applyStyle (tagStyles !! i)
where
w = width d + 1
h = height d + 1
r = 0.5
tagStyles :: [Style R2]
tagStyles = cycle
[ mempty
, mempty # lw veryThick # lc green
, mempty # lw veryThick # lc green # dashingG [0.1,0.1] 0
]
--------------------------------------------------
enclose :: Double -> Double -> Diagram B R2 -> Diagram B R2
enclose g r d = d # centerXY <> roundedRect (width d + g) (height d + g) r
objs :: IsName n => [n] -> Diagram B R2
objs = enclose 1 1 . vcat' (with & sep .~ 1.5) . (map (\n -> dot # named n))
where
dot = circle 0.1 # fc black
--------------------------------------------------
-- Partial bijections
data PBij a b where
PBij :: [a] -> (a -> b) -> PBij a b
applyPBij :: PBij a b -> (a -> b)
applyPBij (PBij _ f) = f
pbComp :: PBij b c -> PBij a b -> PBij a c
pbComp (PBij _ f) (PBij as g) = PBij as (f . g)
fromRel :: Eq a => [(a,b)] -> PBij a b
fromRel rs = PBij (map fst rs) (fromJust . flip lookup rs)
drawPBij :: (IsName a, IsName b) => PBij a b -> Diagram B R2 -> Diagram B R2
drawPBij (PBij as f) = applyAll [ conn a (f a) | a <- as ]
where
conn x y = connect' pBijAOpts x y
pBijAOpts = with & arrowTail .~ spike' & gaps .~ Local 0.3 & lengths .~ Local 0.3
mkSet = mkSet' (const dot)
where
dot = circle 0.2 # fc black
mkSet' dn names
= enclose 0.5 1
. vcat' (with & sep .~ 0.5)
. zipWith named names
. map dn
$ names
pb1 :: PBij Int Char
pb1 = fromRel
[ (0, 'd')
, (1, 'a')
, (2, 'b')
, (3, 'e')
]
pb2 :: PBij Int Int
pb2 = fromRel [ (100, 3), (101, 2) ]
------------------------------------------------------------------------
parts :: [a] -> [[[a]]]
parts = map (map MS.toList . MS.toList) . MS.partitions . MS.fromDistinctList
cycles [] = []
cycles (x:xs) = map (x:) (permutations xs)
perms :: [a] -> [[[a]]]
perms = concatMap (mapM cycles) . parts
drawPerm = hcat' (with & sep .~ 0.2) . map ((\l -> cyc' l 0.8) . map labT)
smallHoleNode = circle labR # fc white # dashingL [0.05,0.05] 0
holeNode = (circle 0.8 # fc white # dashingL [0.1,0.1] 0)
fun x y = hcat' (with & sep .~ 1)
[ x # centerY
, arrow 3
, y # centerY
]
| null | https://raw.githubusercontent.com/byorgey/thesis/b60af0501cdb2d1154d9303694884f461c0e499a/SpeciesDiagrams.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeSynonymInstances #
----------------------------------------------------------
Some specific constructions
------------------------------------------------
------------------------------------------------
------------------------------------------------
Partial bijections
---------------------------------------------------------------------- | # LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE NoMonomorphismRestriction #
module SpeciesDiagrams where
import Control.Arrow (first, second)
import Control.Lens (_head, _last)
import Data.Colour.Palette.BrewerSet
import Data.List (intersperse, permutations)
import Data.List.Split
import qualified Data.Map as M
import Data.Maybe (fromJust, fromMaybe)
import Data.Tree
import Diagrams.Backend.Cairo.CmdLine
import Diagrams.Core.Points
import Diagrams.Prelude
import Diagrams.TwoD.Layout.Tree
import Graphics.SVGFonts.ReadFont
import qualified Math.Combinatorics.Multiset as MS
colors :: [Colour Double]
colors = brewerSet Set1 9
labR, arrowGap :: Double
labR = 0.3
arrowGap = 0.2
aLabels :: [Diagram B R2]
aLabels = map (sized (Dims (4*labR) (4*labR)))
[ circle 1
, triangle 1
, square 1
, pentagon 1
, rect 1 1.618
, rect 1.618 1
, circle 1 # scaleX 1.618
, circle 1 # scaleY 1.618
]
type EdgeLabel = P2 -> P2 -> Diagram B R2
sLabels :: [EdgeLabel]
sLabels =
[ connStyle mempty
, connStyle $ (mempty # lw veryThick)
, connStyle $ (mempty # dashingG [0.1,0.1] 0)
, connStyle $ (mempty # dashingG [0.05,0.15] 0)
, connStyle $ (mempty # dashingG [0.05,0.05,0.1,0.05] 0)
, \p q -> let v = 0.03 *^ normalized (perp (q .-. p))
in ((p .+^ v) ~~ (q .+^ v)) <> ((p .-^ v) ~~ (q .-^ v))
]
where
connStyle sty p q = (p ~~ q) # applyStyle sty
perp = rotateBy (1/4)
labSty :: Int -> Maybe EdgeLabel
labSty i = Just (sLabels !! i)
leafData :: Int -> Diagram B R2
leafData i = (aLabels !! i) # sized (Dims labR labR) # fc black <> square (labR*1.5) # fc white
text' :: Double -> String -> Diagram B R2
text' d s = (stroke $ textSVG' (TextOpts s lin INSIDE_H KERN False d d)) # fc black # lw none
labT :: Int -> Diagram B R2
labT n = text' 1.5 (show n) # scale labR <> lab n
lab :: Int -> Diagram B R2
lab n = lab' (colors !! n)
lab' :: (TrailLike b, Transformable b, HasStyle b, V b ~ R2) => Colour Double -> b
lab' c = circle labR
# fc white
# lc c
# lwG (labR / 5)
cyc :: [Int] -> Double -> Diagram B R2
cyc labs r = cyc' (map lab labs) r
cyc' :: (Monoid' a, TrailLike a, Transformable a, HasStyle a, HasOrigin a, V a ~ R2) => [a] -> Double -> a
cyc' labs r
= mconcat
. zipWith (\l (p,a) -> l # moveTo p <> a) labs
$ zipWith rotateBy
[1/4, 1/4 + 1/(fromIntegral n) .. ]
(map mkLink labs)
where
n = length labs
mkLink _ = ( origin # translateX r
,
( arc startAngle endAngle
# scale r
<>
eqTriangle 0.1
# translateX r
# rotate endAngle
# fc black
)
)
startAngle = (labR + arrowGap)/r @@ rad
endAngle = (tau/fromIntegral n @@ rad) ^-^ startAngle
newtype Cyc a = Cyc {getCyc :: [a]}
deriving Functor
data Pointed a = Plain a | Pointed a
class Drawable d where
draw :: d -> Diagram B R2
instance Drawable (Diagram B R2) where
draw = id
instance Drawable a => Drawable (Cyc a) where
draw (Cyc ls) = cyc' (map draw ls # sized (Width (labR*2))) 1
instance Drawable a => Drawable [a] where
draw ls = centerX . hcat' (with & sep .~ 0.1)
$ intersperse (mkArrow 0.5 mempty) (map draw ls)
instance Drawable a => Drawable (Pointed a) where
draw (Plain a) = draw a
draw (Pointed a) = point (draw a)
point :: Diagram B R2 -> Diagram B R2
point d = d <> drawSpN Hole # sizedAs (d # scale 5)
down :: Cyc (Diagram B R2) -> Cyc (Cyc (Pointed (Diagram B R2)))
down (Cyc ls) = Cyc (map Cyc (pointings ls))
pointings :: [a] -> [[Pointed a]]
pointings [] = []
pointings (x:xs) = (Pointed x : map Plain xs) : map (Plain x :) (pointings xs)
elimArrow :: Diagram B R2
elimArrow = hrule 2
||| eqTriangle 0.2 # rotateBy (-1/4) # fc black
mkArrow :: Double -> Diagram B R2 -> Diagram B R2
mkArrow len l =
( l
===
(arrow len # translateX (-len/2) <> rect len 0.5 # lw none)
)
# alignB
data SpN = Lab (Either Int String)
| Leaf (Maybe (Diagram B R2))
| Hole
| Point
| Sp (Diagram B R2) Angle
| Bag
type SpT = Tree (Maybe EdgeLabel, SpN)
drawSpT' :: T2 -> SymmLayoutOpts (Maybe EdgeLabel, SpN) -> SpT -> Diagram B R2
drawSpT' tr slopts
= transform tr
. renderTree' (drawSpN' (inv tr) . snd) drawSpE
. symmLayout' slopts
drawSpT :: SpT -> Diagram B R2
drawSpT = drawSpT' (rotation (1/4 @@ turn))
(with & slHSep .~ 0.5 & slVSep .~ 2 & slWidth .~ slw)
where
slw (_, Leaf (Just d)) = (-width d/2, width d/2)
slw (_, sp@(Sp _ _)) = let w = width (drawSpN' (rotation (1/4 @@ turn)) sp)
in (-w/2, w/2)
slw _ = (0,0)
drawSpN' :: Transformation R2 -> SpN -> Diagram B R2
drawSpN' _ (Lab (Left n)) = lab n # scale 0.5
drawSpN' tr (Lab (Right t)) = (drawSpN' tr (Leaf Nothing) ||| strutX (labR/2) ||| text' 0.3 t) # transform tr
drawSpN' _ (Leaf Nothing) = circle (labR/2) # fc black
drawSpN' _ (Leaf (Just d)) = d
drawSpN' _ Hole = circle (labR/2) # lwG (labR / 10) # fc white
drawSpN' tr Point = drawSpN' tr (Leaf Nothing) <> drawSpN' tr Hole # scale 1.7
drawSpN' tr (Sp s f) = ( arc ((3/4 @@ turn) ^-^ f^/2) ((3/4 @@ turn) ^+^ f^/2) # scale 0.3
|||
strutX 0.1
|||
s # transform tr
)
drawSpN' _ Bag =
( text' 1 "{" # scale 0.5 ||| strutX (labR/4)
||| circle (labR/2) # fc black
||| strutX (labR/4) ||| text' 1 "}" # scale 0.5
) # centerX
drawSpN :: SpN -> Diagram B R2
drawSpN = drawSpN' mempty
drawSpE :: (t, P2) -> ((Maybe EdgeLabel, SpN), P2) -> Diagram B R2
drawSpE (_,p) ((_,Hole),q) = (p ~~ q) # dashingG [0.05,0.05] 0
drawSpE (_,p) ((Just f,_), q) = f p q
drawSpE (_,p) (_,q) = p ~~ q
nd :: Diagram B R2 -> Forest (Maybe EdgeLabel, SpN) -> SpT
nd x = Node (Nothing, Sp x (1/3 @@ turn))
nd' :: EdgeLabel -> Diagram B R2 -> Forest (Maybe EdgeLabel, SpN) -> SpT
nd' l x = Node (Just l, Sp x (1/3 @@ turn))
lf :: a -> Tree (Maybe EdgeLabel, a)
lf x = Node (Nothing, x) []
lf' :: EdgeLabel -> a -> Tree (Maybe EdgeLabel, a)
lf' l x = Node (Just l, x) []
struct :: Int -> String -> Diagram B R2
struct n x = drawSpT (struct' n x)
# centerXY
struct' :: Int -> String -> SpT
struct' n x = struct'' n (text' 1 x <> rect 2 1 # lw none)
struct'' :: Int -> Diagram B R2 -> SpT
struct'' n d = nd d (replicate n (lf (Leaf Nothing)))
linOrd :: [Int] -> Diagram B R2
linOrd ls =
connect' (with & arrowHead .~ noHead) "head" "last"
. hcat' (with & sep .~ 0.5)
$ map labT ls & _head %~ named "head" & _last %~ named "last"
unord :: (Monoid' b, Semigroup b, TrailLike b, Alignable b, Transformable b, HasStyle b, Juxtaposable b, HasOrigin b, Enveloped b, V b ~ R2) => [b] -> b
unord [] = circle 1 # lc gray
unord ds = elts # centerXY
<> roundedRect w (mh + s*2) ((mh + s*2) / 5)
where
elts = hcat' (with & sep .~ s) ds
mw = maximum' 0 . map width $ ds
s = mw * 0.5
mh = maximum' 0 . map height $ ds
w = ((fromIntegral (length ds + 1) * s) +) . sum . map width $ ds
maximum' d [] = d
maximum' _ xs = maximum xs
enRect' :: (Semigroup a, TrailLike a, Alignable a, Enveloped a, HasOrigin a, V a ~ R2) => Double -> a -> a
enRect' o d = roundedRect (w+o) (h+o) o <> d # centerXY
where (w,h) = size2D d
enRect :: (Semigroup a, TrailLike a, Alignable a, Enveloped a, HasOrigin a, V a ~ R2) => a -> a
enRect = enRect' 0.5
txt x = text x # fontSizeO 10 <> square 1 # lw none
mlocColor = blend 0.5 white lightblue
eltColor = blend 0.5 white lightgreen
mloc m = text (show m) <> circle 0.8 # fc mlocColor
elt x = text (show x) <> square 1.6 # fc eltColor
arm typ m n r = ( typ m # rotateBy (-r)
||| hrule 1.5
||| typ n # rotateBy (-r)
)
# translateX 3
# rotateBy r
arms typ elts = zipWith (\[e1,e2] r -> arm typ e1 e2 r) (chunksOf 2 elts) [1/8 + 0.001, 1/8+0.001 +1/4 .. 1]
octo' typ elts = (mconcat (arms typ elts) <> circle 3)
octo = octo' mloc
sampleT7 = Node 3 [Node 4 (map lf [2,1,6]), Node 5 [], Node 0 [lf 7]]
where
lf x = Node x []
tree :: Diagram B R2
tree = renderTree
mloc
(~~)
(symmLayout' (with & slHSep .~ 4 & slVSep .~ 4) sampleT7)
drawBinTree' :: SymmLayoutOpts (Diagram B R2) -> BTree (Diagram B R2) -> Diagram B R2
drawBinTree' opts
= maybe mempty (renderTree id (~~))
. symmLayoutBin' opts
drawBinTree :: BTree (Diagram B R2) -> Diagram B R2
drawBinTree = drawBinTree' with
drawBinTreeWide :: BTree (Diagram B R2) -> Diagram B R2
drawBinTreeWide = drawBinTree' (with & slHSep .~ 1.5)
select :: [a] -> [(a,[a])]
select [] = []
select (a:as) = (a,as) : (map . second) (a:) (select as)
subsets :: [a] -> [([a],[a])]
subsets [] = [([],[])]
subsets (a:as) = (map . first) (a:) s ++ (map . second) (a:) s
where s = subsets as
type Edge = (Int,Int)
type Graph = (M.Map Int P2, [Edge])
drawGraph drawLoc (locs, edges) = drawLocs <> drawEdges
where
drawLocs = mconcat . map (\(n,p) -> drawLoc n # moveTo p) . M.assocs $ locs
drawEdges = mconcat . map drawEdge $ edges
drawEdge (i1,i2) = lkup i1 ~~ lkup i2
lkup i = fromMaybe origin $ M.lookup i locs
gr :: Diagram B R2
gr = drawGraph mloc
( M.fromList
[ (0, 3 ^& (-1))
, (1, 8 ^& 0)
, (2, origin)
, (3, 8 ^& 2)
, (4, 4 ^& 2)
, (5, 3 ^& (-3))
] # scale 1.5
, [(2,0), (2,4), (0,4), (4,3), (3,1), (0,1), (0,5)]
)
sampleBTree5, sampleBTree7 :: BTree Int
sampleBTree5 = (BNode (0 :: Int) (BNode 1 Empty Empty) (BNode 2 (BNode 3 Empty Empty) (BNode 4 Empty Empty)))
sampleBTree7 = (BNode (0 :: Int) (BNode 1 (BNode 2 Empty (BNode 3 Empty Empty)) Empty) (BNode 4 (BNode 5 Empty Empty) (BNode 6 Empty Empty)))
wideTree
:: (Monoid m, Semigroup m, TrailLike (QDiagram b R2 m))
=> (a -> QDiagram b R2 m) -> BTree a -> QDiagram b R2 m
wideTree n
= maybe mempty (renderTree n (~~))
. symmLayoutBin' (with & slVSep .~ 4 & slHSep .~ 6)
mkLeaf
:: ( Semigroup m, IsName n )
=> QDiagram b R2 m -> n -> QDiagram b R2 m
mkLeaf shp n = shp # fc white # named n
numbered :: Show a => a -> Diagram B R2
numbered n = mkLeaf (text (show n) # fc black <> circle 1) ()
lettered :: Int -> Diagram B R2
lettered n = mkLeaf (text [['a' ..] !! n] # fc black <> circle 1) ()
drawList nd n = drawList' nd [0::Int .. (n - 1)]
drawList' nd ns = lst # centerX `atop` hrule (width lst - w)
where
elts = map nd ns
w = maximum . map width $ elts
lst = hcat' (with & sep .~ w/2) elts
enumTrees :: [a] -> [BTree a]
enumTrees [] = [ Empty ]
enumTrees xxs = [ BNode x l r
| (x,xs) <- select xxs
, (ys, zs) <- subsets xs
, l <- enumTrees ys
, r <- enumTrees zs
]
tag :: Int -> Diagram B R2 -> Diagram B R2
tag i d = d # centerXY <> roundedRect w h r # applyStyle (tagStyles !! i)
where
w = width d + 1
h = height d + 1
r = 0.5
tagStyles :: [Style R2]
tagStyles = cycle
[ mempty
, mempty # lw veryThick # lc green
, mempty # lw veryThick # lc green # dashingG [0.1,0.1] 0
]
enclose :: Double -> Double -> Diagram B R2 -> Diagram B R2
enclose g r d = d # centerXY <> roundedRect (width d + g) (height d + g) r
objs :: IsName n => [n] -> Diagram B R2
objs = enclose 1 1 . vcat' (with & sep .~ 1.5) . (map (\n -> dot # named n))
where
dot = circle 0.1 # fc black
data PBij a b where
PBij :: [a] -> (a -> b) -> PBij a b
applyPBij :: PBij a b -> (a -> b)
applyPBij (PBij _ f) = f
pbComp :: PBij b c -> PBij a b -> PBij a c
pbComp (PBij _ f) (PBij as g) = PBij as (f . g)
fromRel :: Eq a => [(a,b)] -> PBij a b
fromRel rs = PBij (map fst rs) (fromJust . flip lookup rs)
drawPBij :: (IsName a, IsName b) => PBij a b -> Diagram B R2 -> Diagram B R2
drawPBij (PBij as f) = applyAll [ conn a (f a) | a <- as ]
where
conn x y = connect' pBijAOpts x y
pBijAOpts = with & arrowTail .~ spike' & gaps .~ Local 0.3 & lengths .~ Local 0.3
mkSet = mkSet' (const dot)
where
dot = circle 0.2 # fc black
mkSet' dn names
= enclose 0.5 1
. vcat' (with & sep .~ 0.5)
. zipWith named names
. map dn
$ names
pb1 :: PBij Int Char
pb1 = fromRel
[ (0, 'd')
, (1, 'a')
, (2, 'b')
, (3, 'e')
]
pb2 :: PBij Int Int
pb2 = fromRel [ (100, 3), (101, 2) ]
parts :: [a] -> [[[a]]]
parts = map (map MS.toList . MS.toList) . MS.partitions . MS.fromDistinctList
cycles [] = []
cycles (x:xs) = map (x:) (permutations xs)
perms :: [a] -> [[[a]]]
perms = concatMap (mapM cycles) . parts
drawPerm = hcat' (with & sep .~ 0.2) . map ((\l -> cyc' l 0.8) . map labT)
smallHoleNode = circle labR # fc white # dashingL [0.05,0.05] 0
holeNode = (circle 0.8 # fc white # dashingL [0.1,0.1] 0)
fun x y = hcat' (with & sep .~ 1)
[ x # centerY
, arrow 3
, y # centerY
]
|
0963eb2d3befccd87079f4e9f22b4a8957de2528b3a05ebcee4b2da7d81c18bd | tonyg/kali-scheme | write.scm |
(define (test)
(let* ((b (allocate-memory 16))
(res (read-block (current-input-port)
b
16
(lambda (okay? eof? got)
(if (or (not okay?)
eof?)
-1
(write-block (current-output-port)
b
got
(lambda (okay? sent)
(if okay? sent -1))))))))
(deallocate-memory b)
res))
| null | https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/ps-compiler/prescheme/test/write.scm | scheme |
(define (test)
(let* ((b (allocate-memory 16))
(res (read-block (current-input-port)
b
16
(lambda (okay? eof? got)
(if (or (not okay?)
eof?)
-1
(write-block (current-output-port)
b
got
(lambda (okay? sent)
(if okay? sent -1))))))))
(deallocate-memory b)
res))
|
|
9018ca4c09b62fa09f65ee05c1d14b3d496b8eccfa8a229107eaa712d6ab4885 | seth/pooler | pooler_tests.erl | -module(pooler_tests).
-include_lib("eunit/include/eunit.hrl").
-include("../src/pooler.hrl").
-compile([export_all]).
% The `user' processes represent users of the pooler library. A user
% process will take a pid, report details on the pid it has, release
% and take a new pid, stop cleanly, and crash.
start_user() ->
spawn(fun() -> user_loop(start) end).
user_id(Pid) ->
Pid ! {get_tc_id, self()},
receive
{Type, Id} ->
{Type, Id}
end.
user_new_tc(Pid) ->
Pid ! new_tc.
user_stop(Pid) ->
Pid ! stop.
user_crash(Pid) ->
Pid ! crash.
user_loop(Atom) when Atom =:= error_no_members orelse Atom =:= start ->
user_loop(pooler:take_member(test_pool_1));
user_loop(MyTC) ->
receive
{get_tc_id, From} ->
From ! pooled_gs:get_id(MyTC),
user_loop(MyTC);
{ping_tc, From} ->
From ! pooled_gs:ping(MyTC),
user_loop(MyTC);
{ping_count, From} ->
From ! pooled_gs:ping_count(MyTC),
user_loop(MyTC);
new_tc ->
pooler:return_member(test_pool_1, MyTC, ok),
MyNewTC = pooler:take_member(test_pool_1),
user_loop(MyNewTC);
stop ->
pooler:return_member(test_pool_1, MyTC, ok),
stopped;
crash ->
erlang:error({user_loop, kaboom})
end.
% The `tc' processes represent the pids tracked by pooler for testing.
% They have a type and an ID and can report their type and ID and
% stop.
tc_loop({Type, Id}) ->
receive
{get_id, From} ->
From ! {ok, Type, Id},
tc_loop({Type, Id});
stop -> stopped;
crash ->
erlang:error({tc_loop, kaboom})
end.
get_tc_id(Pid) ->
Pid ! {get_id, self()},
receive
{ok, Type, Id} ->
{Type, Id}
after 200 ->
timeout
end.
stop_tc(Pid) ->
Pid ! stop.
tc_starter(Type) ->
Ref = make_ref(),
spawn_link(fun() -> tc_loop({Type, Ref}) end).
assert_tc_valid(Pid) ->
?assertMatch({_Type, _Ref}, get_tc_id(Pid)),
ok.
% tc_sanity_test() ->
% Pid1 = tc_starter("1"),
{ " 1 " , Id1 } = ) ,
Pid2 = tc_starter("1 " ) ,
{ " 1 " , Id2 } = get_tc_id(Pid2 ) ,
? = Id2 ) ,
% stop_tc(Pid1),
% stop_tc(Pid2).
% user_sanity_test() ->
% Pid1 = tc_starter("1"),
% User = spawn(fun() -> user_loop(Pid1) end),
? assertMatch({"1 " , _ Ref } , ) ) ,
% user_crash(User),
% stop_tc(Pid1).
pooler_basics_via_config_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
% setup
fun() ->
Pools = [[{name, test_pool_1},
{max_count, 3},
{init_count, 2},
{cull_interval, {0, min}},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}]],
application:set_env(pooler, pools, Pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler)
end,
fun(_X) ->
application:stop(pooler)
end,
basic_tests()}}.
pooler_basics_dynamic_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
% setup
fun() ->
Pool = [{name, test_pool_1},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}],
application:unset_env(pooler, pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
pooler:new_pool(Pool)
end,
fun(_X) ->
application:stop(pooler)
end,
basic_tests()}}.
pooler_basics_integration_to_other_supervisor_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
% setup
fun() ->
Pool = [{name, test_pool_1},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}],
application:unset_env(pooler, pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
supervisor:start_link(fake_external_supervisor, Pool)
end,
fun({ok, SupPid}) ->
exit(SupPid, normal),
application:stop(pooler)
end,
basic_tests()}}.
basic_tests() ->
[
{"there are init_count members at start",
fun() ->
Stats = [ P || {P, {_, free, _}} <- pooler:pool_stats(test_pool_1) ],
?assertEqual(2, length(Stats))
end},
{"take and return one",
fun() ->
P = pooler:take_member(test_pool_1),
?assertMatch({"type-0", _Id}, pooled_gs:get_id(P)),
ok = pooler:return_member(test_pool_1, P, ok)
end},
{"take and return one, named pool",
fun() ->
P = pooler:take_member(test_pool_1),
?assertMatch({"type-0", _Id}, pooled_gs:get_id(P)),
ok, pooler:return_member(test_pool_1, P)
end},
{"attempt to take form unknown pool",
fun() ->
%% since pools are now servers, an unknown pool will timeout
?assertExit({noproc, _}, pooler:take_member(bad_pool_name))
end},
{"members creation is triggered after pool exhaustion until max",
fun() ->
init count is 2
Pids0 = [pooler:take_member(test_pool_1), pooler:take_member(test_pool_1)],
%% since new member creation is async, can only assert
that we will get a pid , but may not be first try .
Pids = get_n_pids(1, Pids0),
pool is at now , requests should give error
?assertEqual(error_no_members, pooler:take_member(test_pool_1)),
?assertEqual(error_no_members, pooler:take_member(test_pool_1)),
PRefs = [ R || {_T, R} <- [ pooled_gs:get_id(P) || P <- Pids ] ],
% no duplicates
?assertEqual(length(PRefs), length(lists:usort(PRefs)))
end
},
{"pids are reused most recent return first",
fun() ->
P1 = pooler:take_member(test_pool_1),
P2 = pooler:take_member(test_pool_1),
?assertNot(P1 == P2),
ok = pooler:return_member(test_pool_1, P1, ok),
ok = pooler:return_member(test_pool_1, P2, ok),
pids are reused most recent first
?assertEqual(P2, pooler:take_member(test_pool_1)),
?assertEqual(P1, pooler:take_member(test_pool_1))
end},
{"if an in-use pid crashes it is replaced",
fun() ->
Pids0 = get_n_pids(3, []),
Ids0 = [ pooled_gs:get_id(P) || P <- Pids0 ],
% crash them all
[ pooled_gs:crash(P) || P <- Pids0 ],
Pids1 = get_n_pids(3, []),
Ids1 = [ pooled_gs:get_id(P) || P <- Pids1 ],
[ ?assertNot(lists:member(I, Ids0)) || I <- Ids1 ]
end
},
{"if a free pid crashes it is replaced",
fun() ->
FreePids = [ P || {P, {_, free, _}} <- pooler:pool_stats(test_pool_1) ],
[ exit(P, kill) || P <- FreePids ],
Pids1 = get_n_pids(3, []),
?assertEqual(3, length(Pids1))
end},
{"if a pid is returned with bad status it is replaced",
fun() ->
Pids0 = get_n_pids(3, []),
Ids0 = [ pooled_gs:get_id(P) || P <- Pids0 ],
% return them all marking as bad
[ pooler:return_member(test_pool_1, P, fail) || P <- Pids0 ],
Pids1 = get_n_pids(3, []),
Ids1 = [ pooled_gs:get_id(P) || P <- Pids1 ],
[ ?assertNot(lists:member(I, Ids0)) || I <- Ids1 ]
end
},
{"if a consumer crashes, pid is replaced",
fun() ->
Consumer = start_user(),
StartId = user_id(Consumer),
user_crash(Consumer),
NewPid = hd(get_n_pids(1, [])),
NewId = pooled_gs:get_id(NewPid),
?assertNot(NewId == StartId)
end
},
{"it is ok to return an unknown pid",
fun() ->
Bogus1 = spawn(fun() -> ok end),
Bogus2 = spawn(fun() -> ok end),
?assertEqual(ok, pooler:return_member(test_pool_1, Bogus1, ok)),
?assertEqual(ok, pooler:return_member(test_pool_1, Bogus2, fail))
end
},
{"it is ok to return a pid more than once",
fun() ->
M = pooler:take_member(test_pool_1),
[ pooler:return_member(test_pool_1, M)
|| _I <- lists:seq(1, 37) ],
M1 = pooler:take_member(test_pool_1),
M2 = pooler:take_member(test_pool_1),
?assert(M1 =/= M2),
Pool1 = gen_server:call(test_pool_1, dump_pool),
?assertEqual(2, Pool1#pool.in_use_count),
?assertEqual(0, Pool1#pool.free_count),
pooler:return_member(test_pool_1, M1),
pooler:return_member(test_pool_1, M2),
Pool2 = gen_server:call(test_pool_1, dump_pool),
?assertEqual(0, Pool2#pool.in_use_count),
?assertEqual(2, Pool2#pool.free_count),
ok
end},
{"calling return_member on error_no_members is ignored",
fun() ->
?assertEqual(ok, pooler:return_member(test_pool_1, error_no_members)),
?assertEqual(ok, pooler:return_member(test_pool_1, error_no_members, ok)),
?assertEqual(ok, pooler:return_member(test_pool_1, error_no_members, fail))
end
},
{"dynamic pool creation",
fun() ->
PoolSpec = [{name, dyn_pool_1},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"dyn-0"}]}}],
{ok, SupPid1} = pooler:new_pool(PoolSpec),
?assert(is_pid(SupPid1)),
M = pooler:take_member(dyn_pool_1),
?assertMatch({"dyn-0", _Id}, pooled_gs:get_id(M)),
?assertEqual(ok, pooler:rm_pool(dyn_pool_1)),
?assertExit({noproc, _}, pooler:take_member(dyn_pool_1)),
%% verify pool of same name can be created after removal
{ok, SupPid2} = pooler:new_pool(PoolSpec),
?assert(is_pid(SupPid2)),
%% remove non-existing pool
?assertEqual(ok, pooler:rm_pool(dyn_pool_X)),
?assertEqual(ok, pooler:rm_pool(dyn_pool_1))
end},
{"metrics have been called (no timeout/queue)",
fun() ->
%% exercise the API to ensure we have certain keys reported as metrics
fake_metrics:reset_metrics(),
Pids = [ pooler:take_member(test_pool_1) || _I <- lists:seq(1, 10) ],
[ pooler:return_member(test_pool_1, P) || P <- Pids ],
catch pooler:take_member(bad_pool_name),
%% kill and unused member
exit(hd(Pids), kill),
%% kill a used member
KillMe = pooler:take_member(test_pool_1),
exit(KillMe, kill),
%% FIXME: We need to wait for pooler to process the
%% exit message. This is ugly, will fix later.
timer:sleep(200), % :(
ExpectKeys = lists:sort([<<"pooler.test_pool_1.error_no_members_count">>,
<<"pooler.test_pool_1.events">>,
<<"pooler.test_pool_1.free_count">>,
<<"pooler.test_pool_1.in_use_count">>,
<<"pooler.test_pool_1.killed_free_count">>,
<<"pooler.test_pool_1.killed_in_use_count">>,
<<"pooler.test_pool_1.take_rate">>]),
Metrics = fake_metrics:get_metrics(),
GotKeys = lists:usort([ Name || {Name, _, _} <- Metrics ]),
?assertEqual(ExpectKeys, GotKeys)
end},
{"metrics have been called (with timeout/queue)",
fun() ->
%% exercise the API to ensure we have certain keys reported as metrics
fake_metrics:reset_metrics(),
pass a non - zero timeout here to exercise queueing
Pids = [ pooler:take_member(test_pool_1, 1) || _I <- lists:seq(1, 10) ],
[ pooler:return_member(test_pool_1, P) || P <- Pids ],
catch pooler:take_member(bad_pool_name),
%% kill and unused member
exit(hd(Pids), kill),
%% kill a used member
KillMe = pooler:take_member(test_pool_1),
exit(KillMe, kill),
%% FIXME: We need to wait for pooler to process the
%% exit message. This is ugly, will fix later.
timer:sleep(200), % :(
ExpectKeys = lists:sort([<<"pooler.test_pool_1.error_no_members_count">>,
<<"pooler.test_pool_1.events">>,
<<"pooler.test_pool_1.free_count">>,
<<"pooler.test_pool_1.in_use_count">>,
<<"pooler.test_pool_1.killed_free_count">>,
<<"pooler.test_pool_1.killed_in_use_count">>,
<<"pooler.test_pool_1.take_rate">>,
<<"pooler.test_pool_1.queue_count">>]),
Metrics = fake_metrics:get_metrics(),
GotKeys = lists:usort([ Name || {Name, _, _} <- Metrics ]),
?assertEqual(ExpectKeys, GotKeys)
end},
{"accept bad member is handled",
fun() ->
Bad = spawn(fun() -> ok end),
FakeStarter = spawn(fun() -> starter end),
?assertEqual(ok, pooler:accept_member(test_pool_1, {FakeStarter, Bad}))
end},
{"utilization returns sane results",
fun() ->
#pool{max_count = MaxCount, queue_max = QueueMax} = Pool = sys:get_state(test_pool_1),
?assertEqual(MaxCount, ?gv(max_count, pooler:pool_utilization(test_pool_1))),
?assertEqual(0, ?gv(in_use_count, pooler:pool_utilization(test_pool_1))),
?assertEqual(2, ?gv(free_count, pooler:pool_utilization(test_pool_1))),
?assertEqual(0, ?gv(queued_count, pooler:pool_utilization(test_pool_1))),
?assertEqual(QueueMax, ?gv(queue_max, pooler:pool_utilization(test_pool_1)))
end}
].
pooler_groups_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
% setup
fun() ->
Pools = [[{name, test_pool_1},
{group, group_1},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-1-1"}]}}],
[{name, test_pool_2},
{group, group_1},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-1-2"}]}}],
%% test_pool_3 not part of the group
[{name, test_pool_3},
{group, undefined},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-3"}]}}]
],
application:set_env(pooler, pools, Pools),
error_logger : ) ,
pg2:start(),
application:start(pooler)
end,
fun(_X) ->
application:stop(pooler),
application:stop(pg2)
end,
[
{"take and return one group member (repeated)",
fun() ->
Types = [ begin
Pid = pooler:take_group_member(group_1),
{Type, _} = pooled_gs:get_id(Pid),
?assertMatch("type-1" ++ _, Type),
ok = pooler:return_group_member(group_1, Pid, ok),
Type
end
|| _I <- lists:seq(1, 50) ],
Type_1_1 = [ X || "type-1-1" = X <- Types ],
Type_1_2 = [ X || "type-1-2" = X <- Types ],
?assert(length(Type_1_1) > 0),
?assert(length(Type_1_2) > 0)
end},
{"take member from unknown group",
fun() ->
?assertEqual({error_no_group, not_a_group},
pooler:take_group_member(not_a_group))
end},
{"return member to unknown group",
fun() ->
Pid = pooler:take_group_member(group_1),
?assertEqual(ok, pooler:return_group_member(no_such_group, Pid))
end},
{"return member to wrong group",
fun() ->
Pid = pooler:take_member(test_pool_3),
?assertEqual(ok, pooler:return_group_member(group_1, Pid))
end},
{"return member with something which is not a pid",
fun() ->
?assertException(error, _, pooler:return_group_member(group_1, not_pid))
end},
{"take member from empty group",
fun() ->
%% artificially empty group member list
[ pg2:leave(group_1, M) || M <- pg2:get_members(group_1) ],
?assertEqual(error_no_members, pooler:take_group_member(group_1))
end},
{"return member to group, implied ok",
fun() ->
Pid = pooler:take_group_member(group_1),
?assertEqual(ok, pooler:return_group_member(group_1, Pid))
end},
{"return error_no_member to group",
fun() ->
?assertEqual(ok, pooler:return_group_member(group_1, error_no_members))
end},
{"exhaust pools in group",
fun() ->
Pids = get_n_pids_group(group_1, 6, []),
%% they should all be pids
[ begin
{Type, _} = pooled_gs:get_id(P),
?assertMatch("type-1" ++ _, Type),
ok
end || P <- Pids ],
%% further attempts should be error
[error_no_members,
error_no_members,
error_no_members] = [ pooler:take_group_member(group_1)
|| _I <- lists:seq(1, 3) ]
end},
{"rm_group with nonexisting group",
fun() ->
?assertEqual(ok, pooler:rm_group(i_dont_exist))
end},
{"rm_group with existing empty group",
fun() ->
?assertEqual(ok, pooler:rm_pool(test_pool_1)),
?assertEqual(ok, pooler:rm_pool(test_pool_2)),
?assertEqual(error_no_members, pooler:take_group_member(group_1)),
?assertEqual(ok, pooler:rm_group(group_1)),
?assertExit({noproc, _}, pooler:take_member(test_pool_1)),
?assertExit({noproc, _}, pooler:take_member(test_pool_2)),
?assertEqual({error_no_group, group_1},
pooler:take_group_member(group_1))
end},
{"rm_group with existing non-empty group",
fun() ->
%% Verify that group members exist
MemberPid = pooler:take_group_member(group_1),
?assert(is_pid(MemberPid)),
pooler:return_group_member(group_1, MemberPid),
Pool1Pid = pooler:take_member(test_pool_1),
?assert(is_pid(Pool1Pid)),
pooler:return_member(test_pool_1, Pool1Pid),
Pool2Pid = pooler:take_member(test_pool_2),
?assert(is_pid(Pool2Pid)),
pooler:return_member(test_pool_2, Pool2Pid),
%% Delete and verify that group and pools are destroyed
?assertEqual(ok, pooler:rm_group(group_1)),
?assertExit({noproc, _}, pooler:take_member(test_pool_1)),
?assertExit({noproc, _}, pooler:take_member(test_pool_2)),
?assertEqual({error_no_group, group_1},
pooler:take_group_member(group_1))
end}
]}}.
pooler_limit_failed_adds_test_() ->
%% verify that pooler crashes completely if too many failures are
%% encountered while trying to add pids.
{setup,
fun() ->
Pools = [[{name, test_pool_1},
{max_count, 10},
{init_count, 10},
{start_mfa,
{pooled_gs, start_link, [crash]}}]],
application:set_env(pooler, pools, Pools)
end,
fun(_) ->
application:stop(pooler)
end,
fun() ->
application:start(pooler),
?assertEqual(error_no_members, pooler:take_member(test_pool_1)),
?assertEqual(error_no_members, pooler:take_member(test_pool_1))
end}.
pooler_scheduled_cull_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link(),
Pools = [[{name, test_pool_1},
{max_count, 10},
{init_count, 2},
{start_mfa, {pooled_gs, start_link, [{"type-0"}]}},
{cull_interval, {200, ms}},
{max_age, {0, min}}]],
application:set_env(pooler, pools, Pools),
error_logger : ) ,
application:start(pooler)
end,
fun(_X) ->
fake_metrics:stop(),
application:stop(pooler)
end,
[
{foreach,
fun() ->
Pids = get_n_pids(test_pool_1, 10, []),
?assertEqual(10, length(pooler:pool_stats(test_pool_1))),
?assertEqual(10, length(Pids)),
Pids
end,
fun(Pids) ->
[ pooler:return_member(test_pool_1, P) || P <- Pids ]
end,
[
fun(Pids) ->
{"excess members are culled run 1",
fun() ->
[ pooler:return_member(test_pool_1, P) || P <- Pids ],
%% wait for longer than cull delay
timer:sleep(250),
?assertEqual(2, length(pooler:pool_stats(test_pool_1))),
?assertEqual(2, ?gv(free_count,pooler:pool_utilization(test_pool_1)))
end}
end,
fun(Pids) ->
{"excess members are culled run 2",
fun() ->
[ pooler:return_member(test_pool_1, P) || P <- Pids ],
%% wait for longer than cull delay
timer:sleep(250),
?assertEqual(2, length(pooler:pool_stats(test_pool_1))),
?assertEqual(2, ?gv(free_count,pooler:pool_utilization(test_pool_1)))
end}
end,
fun(Pids) -> in_use_members_not_culled(Pids, 1) end,
fun(Pids) -> in_use_members_not_culled(Pids, 2) end,
fun(Pids) -> in_use_members_not_culled(Pids, 3) end,
fun(Pids) -> in_use_members_not_culled(Pids, 4) end,
fun(Pids) -> in_use_members_not_culled(Pids, 5) end,
fun(Pids) -> in_use_members_not_culled(Pids, 6) end
]},
{"no cull when init_count matches max_count",
%% not sure how to verify this. But this test at least
%% exercises the code path.
fun() ->
Config = [{name, test_static_pool_1},
{max_count, 2},
{init_count, 2},
{start_mfa, {pooled_gs, start_link, [{"static-0"}]}},
{cull_interval, {200, ms}}], % ignored
pooler:new_pool(Config),
P = pooler:take_member(test_static_pool_1),
?assertMatch({"static-0", _}, pooled_gs:get_id(P)),
pooler:return_member(test_static_pool_1, P),
ok
end}
]}.
in_use_members_not_culled(Pids, N) ->
{"in-use members are not culled " ++ erlang:integer_to_list(N),
fun() ->
%% wait for longer than cull delay
timer:sleep(250),
PidCount = length(Pids),
?assertEqual(PidCount,
length(pooler:pool_stats(test_pool_1))),
?assertEqual(0, ?gv(free_count,pooler:pool_utilization(test_pool_1))),
?assertEqual(PidCount, ?gv(in_use_count,pooler:pool_utilization(test_pool_1))),
Returns = lists:sublist(Pids, N),
[ pooler:return_member(test_pool_1, P)
|| P <- Returns ],
timer:sleep(250),
?assertEqual(PidCount - N,
length(pooler:pool_stats(test_pool_1)))
end}.
random_message_test_() ->
{setup,
fun() ->
Pools = [[{name, test_pool_1},
{max_count, 2},
{init_count, 1},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}]],
application:set_env(pooler, pools, Pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
%% now send some bogus messages
%% do the call in a throw-away process to avoid timeout error
spawn(fun() -> catch gen_server:call(test_pool_1, {unexpected_garbage_msg, 5}) end),
gen_server:cast(test_pool_1, {unexpected_garbage_msg, 6}),
whereis(test_pool_1) ! {unexpected_garbage_msg, 7},
ok
end,
fun(_) ->
application:stop(pooler)
end,
[
fun() ->
Pid = spawn(fun() -> ok end),
MonMsg = {'DOWN', erlang:make_ref(), process, Pid, because},
test_pool_1 ! MonMsg
end,
fun() ->
Pid = pooler:take_member(test_pool_1),
{Type, _} = pooled_gs:get_id(Pid),
?assertEqual("type-0", Type)
end,
fun() ->
RawPool = gen_server:call(test_pool_1, dump_pool),
?assertEqual(pool, element(1, RawPool))
end
]}.
pooler_integration_long_init_test_() ->
{foreach,
% setup
fun() ->
Pool = [{name, test_pool_1},
{max_count, 10},
{init_count, 0},
{member_start_timeout, {10, ms}},
{start_mfa,
{pooled_gs, start_link, [{"type-0", fun() -> timer:sleep(15) end}]}}],
application:set_env(pooler, pools, [Pool]),
application:start(pooler)
end,
% cleanup
fun(_) ->
application:stop(pooler)
end,
%
[
fun(_) ->
% Test what happens when pool members take too long to start.
% The pooler_starter should kill off stale members, there by
% reducing the number of children of the member_sup. This
% activity occurs both during take member and accept member.
Accordingly , the count should go to zero once all starters
% check in.
fun() ->
?assertEqual(0, children_count(pooler_test_pool_1_member_sup)),
[begin
?assertEqual(error_no_members, pooler:take_member(test_pool_1)),
?assertEqual(1, starting_members(test_pool_1))
end
|| _ <- lists:seq(1,10)],
?assertEqual(10, children_count(pooler_test_pool_1_member_sup)),
timer:sleep(150),
?assertEqual(0, children_count(pooler_test_pool_1_member_sup)),
?assertEqual(0, starting_members(test_pool_1))
end
end
]
}.
sleep_for_configured_timeout() ->
SleepTime = case application:get_env(pooler, sleep_time) of
{ok, Val} ->
Val;
_ ->
0
end,
timer:sleep(SleepTime).
pooler_integration_queueing_test_() ->
{foreach,
% setup
fun() ->
Pool = [{name, test_pool_1},
{max_count, 10},
{queue_max, 10},
{init_count, 0},
{metrics, fake_metrics},
{member_start_timeout, {5, sec}},
{start_mfa,
{pooled_gs, start_link, [
{"type-0",
fun pooler_tests:sleep_for_configured_timeout/0 }
]
}
}
],
application:set_env(pooler, pools, [Pool]),
fake_metrics:start_link(),
application:start(pooler)
end,
% cleanup
fun(_) ->
fake_metrics:stop(),
application:stop(pooler)
end,
[
fun(_) ->
fun() ->
?assertEqual(0, (dump_pool(test_pool_1))#pool.free_count),
Val = pooler:take_member(test_pool_1, 10),
?assert(is_pid(Val)),
pooler:return_member(test_pool_1, Val)
end
end,
fun(_) ->
fun() ->
application:set_env(pooler, sleep_time, 1),
?assertEqual(0, (dump_pool(test_pool_1))#pool.free_count),
Val = pooler:take_member(test_pool_1, 0),
?assertEqual(error_no_members, Val),
?assertEqual(0, ?gv(free_count,pooler:pool_utilization(test_pool_1))),
timer:sleep(50),
%Next request should be available
Pid = pooler:take_member(test_pool_1, 0),
?assert(is_pid(Pid)),
pooler:return_member(test_pool_1, Pid)
end
end,
fun(_) ->
fun() ->
application:set_env(pooler, sleep_time, 10),
?assertEqual(0, (dump_pool(test_pool_1))#pool.free_count),
[
?assertEqual(pooler:take_member(test_pool_1, 0), error_no_members) ||
_ <- lists:seq(1, (dump_pool(test_pool_1))#pool.max_count)],
timer:sleep(50),
%Next request should be available
Pid = pooler:take_member(test_pool_1, 0),
?assert(is_pid(Pid)),
pooler:return_member(test_pool_1, Pid)
end
end,
fun(_) ->
fun() ->
fill to queue_max , next request should return immediately with no_members
Will return a if queue is not enforced .
application:set_env(pooler, sleep_time, 100),
[ proc_lib:spawn(fun() ->
Val = pooler:take_member(test_pool_1, 200),
?assert(is_pid(Val)),
pooler:return_member(Val)
end)
|| _ <- lists:seq(1, (dump_pool(test_pool_1))#pool.max_count)
],
?assertEqual(0, ?gv(free_count,pooler:pool_utilization(test_pool_1))),
?assert(?gv(queued_count,pooler:pool_utilization(test_pool_1)) >= 1),
?assertEqual(10, ?gv(queue_max,pooler:pool_utilization(test_pool_1))),
timer:sleep(50),
?assertEqual(10, queue:len((dump_pool(test_pool_1))#pool.queued_requestors)),
?assertEqual(10, ?gv(queue_max,pooler:pool_utilization(test_pool_1))),
?assertEqual(pooler:take_member(test_pool_1, 500), error_no_members),
ExpectKeys = lists:sort([<<"pooler.test_pool_1.error_no_members_count">>,
<<"pooler.test_pool_1.events">>,
<<"pooler.test_pool_1.take_rate">>,
<<"pooler.test_pool_1.queue_count">>,
<<"pooler.test_pool_1.queue_max_reached">>]),
Metrics = fake_metrics:get_metrics(),
GotKeys = lists:usort([ Name || {Name, _, _} <- Metrics ]),
?assertEqual(ExpectKeys, GotKeys),
timer:sleep(100),
Val = pooler:take_member(test_pool_1, 500),
?assert(is_pid(Val)),
pooler:return_member(test_pool_1, Val)
end
end
]
}.
pooler_integration_queueing_return_member_test_() ->
{foreach,
% setup
fun() ->
Pool = [{name, test_pool_1},
{max_count, 10},
{queue_max, 10},
{init_count, 10},
{metrics, fake_metrics},
{member_start_timeout, {5, sec}},
{start_mfa,
{pooled_gs, start_link, [
{"type-0",
fun pooler_tests:sleep_for_configured_timeout/0 }
]
}
}
],
application:set_env(pooler, pools, [Pool]),
fake_metrics:start_link(),
application:start(pooler)
end,
% cleanup
fun(_) ->
fake_metrics:stop(),
application:stop(pooler)
end,
[
fun(_) ->
fun() ->
application:set_env(pooler, sleep_time, 0),
Pids = [ proc_lib:spawn_link(fun() ->
Val = pooler:take_member(test_pool_1, 200),
?assert(is_pid(Val)),
receive
_ ->
pooler:return_member(test_pool_1, Val)
after
5000 ->
pooler:return_member(test_pool_1, Val)
end
end)
|| _ <- lists:seq(1, (dump_pool(test_pool_1))#pool.max_count)
],
timer:sleep(1),
Parent = self(),
proc_lib:spawn_link(fun() ->
Val = pooler:take_member(test_pool_1, 200),
Parent ! Val
end),
[Pid ! return || Pid <- Pids],
receive
Result ->
?assert(is_pid(Result)),
pooler:return_member(test_pool_1, Result)
end,
?assertEqual((dump_pool(test_pool_1))#pool.max_count, length((dump_pool(test_pool_1))#pool.free_pids)),
?assertEqual((dump_pool(test_pool_1))#pool.max_count, (dump_pool(test_pool_1))#pool.free_count)
end
end
]
}.
pooler_integration_test_() ->
{foreach,
% setup
fun() ->
Pools = [[{name, test_pool_1},
{max_count, 10},
{init_count, 10},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}]],
application:set_env(pooler, pools, Pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
Users = [ start_user() || _X <- lists:seq(1, 10) ],
Users
end,
% cleanup
fun(Users) ->
[ user_stop(U) || U <- Users ],
application:stop(pooler)
end,
%
[
fun(Users) ->
fun() ->
% each user has a different tc ID
TcIds = lists:sort([ user_id(UPid) || UPid <- Users ]),
?assertEqual(lists:usort(TcIds), TcIds)
end
end
,
fun(Users) ->
fun() ->
% users still unique after a renew cycle
[ user_new_tc(UPid) || UPid <- Users ],
TcIds = lists:sort([ user_id(UPid) || UPid <- Users ]),
?assertEqual(lists:usort(TcIds), TcIds)
end
end
,
fun(Users) ->
fun() ->
% all users crash, pids are replaced
TcIds1 = lists:sort([ user_id(UPid) || UPid <- Users ]),
[ user_crash(UPid) || UPid <- Users ],
Seq = lists:seq(1, 5),
Users2 = [ start_user() || _X <- Seq ],
TcIds2 = lists:sort([ user_id(UPid) || UPid <- Users2 ]),
Both =
sets:to_list(sets:intersection([sets:from_list(TcIds1),
sets:from_list(TcIds2)])),
?assertEqual([], Both)
end
end
]
}.
pooler_auto_grow_disabled_by_default_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
% setup
fun() ->
Pool = [{name, test_pool_1},
{max_count, 5},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}],
application:unset_env(pooler, pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
pooler:new_pool(Pool)
end,
fun(_X) ->
application:stop(pooler)
end,
[
{"take one, and it should not auto-grow",
fun() ->
?assertEqual(2, (dump_pool(test_pool_1))#pool.free_count),
P = pooler:take_member(test_pool_1),
?assertMatch({"type-0", _Id}, pooled_gs:get_id(P)),
timer:sleep(100),
?assertEqual(1, (dump_pool(test_pool_1))#pool.free_count),
ok, pooler:return_member(test_pool_1, P)
end}
]}}.
pooler_auto_grow_enabled_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
% setup
fun() ->
Pool = [{name, test_pool_1},
{max_count, 5},
{init_count, 2},
{auto_grow_threshold, 1},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}],
application:unset_env(pooler, pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
pooler:new_pool(Pool)
end,
fun(_X) ->
application:stop(pooler)
end,
[
{"take one, and it should grow by 2",
fun() ->
?assertEqual(2, (dump_pool(test_pool_1))#pool.free_count),
P = pooler:take_member(test_pool_1),
?assertMatch({"type-0", _Id}, pooled_gs:get_id(P)),
timer:sleep(100),
?assertEqual(3, (dump_pool(test_pool_1))#pool.free_count),
ok, pooler:return_member(test_pool_1, P)
end}
]}}.
pooler_custom_stop_mfa_test_() ->
{foreach,
fun() ->
Pool = [{name, test_pool_1},
{max_count, 3},
{init_count, 2},
{cull_interval, {200, ms}},
{max_age, {0, min}},
{start_mfa, {pooled_gs, start_link, [{foo_type}]}}],
application:set_env(pooler, pools, [Pool])
end,
fun(_) ->
application:unset_env(pooler, pools)
end,
[
{"default behavior kills the pool member",
fun() ->
ok = application:start(pooler),
Reason = monitor_members_trigger_culling_and_return_reason(),
ok = application:stop(pooler),
?assertEqual(killed, Reason)
end},
{"custom callback terminates the pool member normally",
fun() ->
{ok, [Pool]} = application:get_env(pooler, pools),
Stop = {stop_mfa, {pooled_gs, stop, ['$pooler_pid']}},
application:set_env(pooler, pools, [[Stop | Pool]]),
ok = application:start(pooler),
Reason = monitor_members_trigger_culling_and_return_reason(),
ok = application:stop(pooler),
?assertEqual(normal, Reason)
end}]}.
no_error_logger_reports_after_culling_test_() ->
%% damn those wraiths! This is the cure
{foreach,
fun() ->
{ok, _Pid} = error_logger_mon:start_link(),
Pool = [{name, test_pool_1},
{max_count, 3},
{init_count, 2},
{cull_interval, {200, ms}},
{max_age, {0, min}},
{start_mfa, {pooled_gs, start_link, [{type}]}}],
application:set_env(pooler, pools, [Pool])
end,
fun(_) ->
ok = error_logger_mon:stop(),
error_logger:delete_report_handler(error_logger_pooler_h),
application:unset_env(pooler, pools)
end,
[
{"Force supervisor to report by using exit/2 instead of terminate_child",
fun() ->
{ok, [Pool]} = application:get_env(pooler, pools),
Stop = {stop_mfa, {erlang, exit, ['$pooler_pid', kill]}},
application:set_env(pooler, pools, [[Stop | Pool]]),
ok = application:start(pooler),
error_logger:add_report_handler(error_logger_pooler_h),
Reason = monitor_members_trigger_culling_and_return_reason(),
%% we need to wait for the message to arrive before deleting handler
timer:sleep(250),
error_logger:delete_report_handler(error_logger_pooler_h),
ok = application:stop(pooler),
?assertEqual(killed, Reason),
?assertEqual(1, error_logger_mon:get_msg_count())
end},
{"Default MFA shouldn't generate any reports during culling",
fun() ->
ok = application:start(pooler),
error_logger:add_report_handler(error_logger_pooler_h),
Reason = monitor_members_trigger_culling_and_return_reason(),
error_logger:delete_report_handler(error_logger_pooler_h),
ok = application:stop(pooler),
?assertEqual(killed, Reason),
?assertEqual(0, error_logger_mon:get_msg_count())
end}
]}.
monitor_members_trigger_culling_and_return_reason() ->
Pids = get_n_pids(test_pool_1, 3, []),
[ erlang:monitor(process, P) || P <- Pids ],
[ pooler:return_member(test_pool_1, P) || P <- Pids ],
receive
{'DOWN', _Ref, process, _Pid, Reason} ->
Reason
after
250 -> timeout
end.
time_as_millis_test_() ->
Zeros = [ {{0, U}, 0} || U <- [min, sec, ms, mu] ],
Ones = [{{1, min}, 60000},
{{1, sec}, 1000},
{{1, ms}, 1},
{{1, mu}, 0}],
Misc = [{{3000, mu}, 3}],
Tests = Zeros ++ Ones ++ Misc,
[ ?_assertEqual(E, pooler:time_as_millis(I)) || {I, E} <- Tests ].
time_as_micros_test_() ->
Zeros = [ {{0, U}, 0} || U <- [min, sec, ms, mu] ],
Ones = [{{1, min}, 60000000},
{{1, sec}, 1000000},
{{1, ms}, 1000},
{{1, mu}, 1}],
Misc = [{{3000, mu}, 3000}],
Tests = Zeros ++ Ones ++ Misc,
[ ?_assertEqual(E, pooler:time_as_micros(I)) || {I, E} <- Tests ].
call_free_members_test_() ->
NumWorkers = 10,
PoolName = test_pool_1,
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
fun() ->
Pool = [{name, PoolName},
{max_count, NumWorkers},
{init_count, NumWorkers},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}],
application:unset_env(pooler, pools),
application:start(pooler),
pooler:new_pool(Pool)
end,
fun(_X) ->
application:stop(pooler)
end,
[
{"perform a ping across the pool when all workers are free",
fun() ->
?assertEqual(NumWorkers, (dump_pool(PoolName))#pool.free_count),
Res = pooler:call_free_members(PoolName, fun pooled_gs:ping/1),
?assertEqual(NumWorkers, count_pongs(Res))
end},
{"perform a ping across the pool when two workers are taken",
fun() ->
?assertEqual(NumWorkers, (dump_pool(PoolName))#pool.free_count),
Pids = [pooler:take_member(PoolName) || _X <- lists:seq(0, 1)],
Res = pooler:call_free_members(PoolName, fun pooled_gs:ping/1),
?assertEqual(NumWorkers -2, count_pongs(Res)),
[pooler:return_member(PoolName, P) || P <- Pids]
end},
{"perform an op where the op crashes all free members",
fun() ->
?assertEqual(NumWorkers, (dump_pool(PoolName))#pool.free_count),
Res = pooler:call_free_members(PoolName,
fun pooled_gs:error_on_call/1),
?assertEqual(NumWorkers, count_errors(Res))
end}
]}}.
count_pongs(Result) ->
lists:foldl(fun({ok, pong}, Acc) -> Acc + 1;
({error, _}, Acc) -> Acc
end,
0,
Result).
count_errors(Result) ->
lists:foldl(fun({error, _}, Acc) -> Acc + 1;
({ok, _}, Acc) -> Acc
end,
0,
Result).
% testing crash recovery means race conditions when either pids
% haven't yet crashed or pooler hasn't recovered. So this helper loops
% forver until N pids are obtained, ignoring error_no_members.
get_n_pids(N, Acc) ->
get_n_pids(test_pool_1, N, Acc).
get_n_pids(_Pool, 0, Acc) ->
Acc;
get_n_pids(Pool, N, Acc) ->
case pooler:take_member(Pool) of
error_no_members ->
get_n_pids(Pool, N, Acc);
Pid ->
get_n_pids(Pool, N - 1, [Pid|Acc])
end.
get_n_pids_group(_Group, 0, Acc) ->
Acc;
get_n_pids_group(Group, N, Acc) ->
case pooler:take_group_member(Group) of
error_no_members ->
get_n_pids_group(Group, N, Acc);
Pid ->
get_n_pids_group(Group, N - 1, [Pid|Acc])
end.
children_count(SupId) ->
length(supervisor:which_children(SupId)).
starting_members(PoolName) ->
length((dump_pool(PoolName))#pool.starting_members).
dump_pool(PoolName) ->
gen_server:call(PoolName, dump_pool).
| null | https://raw.githubusercontent.com/seth/pooler/9c28fb479f9329e2a1644565a632bc222780f1b7/test/pooler_tests.erl | erlang | The `user' processes represent users of the pooler library. A user
process will take a pid, report details on the pid it has, release
and take a new pid, stop cleanly, and crash.
The `tc' processes represent the pids tracked by pooler for testing.
They have a type and an ID and can report their type and ID and
stop.
tc_sanity_test() ->
Pid1 = tc_starter("1"),
stop_tc(Pid1),
stop_tc(Pid2).
user_sanity_test() ->
Pid1 = tc_starter("1"),
User = spawn(fun() -> user_loop(Pid1) end),
user_crash(User),
stop_tc(Pid1).
setup
setup
setup
since pools are now servers, an unknown pool will timeout
since new member creation is async, can only assert
no duplicates
crash them all
return them all marking as bad
verify pool of same name can be created after removal
remove non-existing pool
exercise the API to ensure we have certain keys reported as metrics
kill and unused member
kill a used member
FIXME: We need to wait for pooler to process the
exit message. This is ugly, will fix later.
:(
exercise the API to ensure we have certain keys reported as metrics
kill and unused member
kill a used member
FIXME: We need to wait for pooler to process the
exit message. This is ugly, will fix later.
:(
setup
test_pool_3 not part of the group
artificially empty group member list
they should all be pids
further attempts should be error
Verify that group members exist
Delete and verify that group and pools are destroyed
verify that pooler crashes completely if too many failures are
encountered while trying to add pids.
wait for longer than cull delay
wait for longer than cull delay
not sure how to verify this. But this test at least
exercises the code path.
ignored
wait for longer than cull delay
now send some bogus messages
do the call in a throw-away process to avoid timeout error
setup
cleanup
Test what happens when pool members take too long to start.
The pooler_starter should kill off stale members, there by
reducing the number of children of the member_sup. This
activity occurs both during take member and accept member.
check in.
setup
cleanup
Next request should be available
Next request should be available
setup
cleanup
setup
cleanup
each user has a different tc ID
users still unique after a renew cycle
all users crash, pids are replaced
setup
setup
damn those wraiths! This is the cure
we need to wait for the message to arrive before deleting handler
testing crash recovery means race conditions when either pids
haven't yet crashed or pooler hasn't recovered. So this helper loops
forver until N pids are obtained, ignoring error_no_members. | -module(pooler_tests).
-include_lib("eunit/include/eunit.hrl").
-include("../src/pooler.hrl").
-compile([export_all]).
start_user() ->
spawn(fun() -> user_loop(start) end).
user_id(Pid) ->
Pid ! {get_tc_id, self()},
receive
{Type, Id} ->
{Type, Id}
end.
user_new_tc(Pid) ->
Pid ! new_tc.
user_stop(Pid) ->
Pid ! stop.
user_crash(Pid) ->
Pid ! crash.
user_loop(Atom) when Atom =:= error_no_members orelse Atom =:= start ->
user_loop(pooler:take_member(test_pool_1));
user_loop(MyTC) ->
receive
{get_tc_id, From} ->
From ! pooled_gs:get_id(MyTC),
user_loop(MyTC);
{ping_tc, From} ->
From ! pooled_gs:ping(MyTC),
user_loop(MyTC);
{ping_count, From} ->
From ! pooled_gs:ping_count(MyTC),
user_loop(MyTC);
new_tc ->
pooler:return_member(test_pool_1, MyTC, ok),
MyNewTC = pooler:take_member(test_pool_1),
user_loop(MyNewTC);
stop ->
pooler:return_member(test_pool_1, MyTC, ok),
stopped;
crash ->
erlang:error({user_loop, kaboom})
end.
tc_loop({Type, Id}) ->
receive
{get_id, From} ->
From ! {ok, Type, Id},
tc_loop({Type, Id});
stop -> stopped;
crash ->
erlang:error({tc_loop, kaboom})
end.
get_tc_id(Pid) ->
Pid ! {get_id, self()},
receive
{ok, Type, Id} ->
{Type, Id}
after 200 ->
timeout
end.
stop_tc(Pid) ->
Pid ! stop.
tc_starter(Type) ->
Ref = make_ref(),
spawn_link(fun() -> tc_loop({Type, Ref}) end).
assert_tc_valid(Pid) ->
?assertMatch({_Type, _Ref}, get_tc_id(Pid)),
ok.
{ " 1 " , Id1 } = ) ,
Pid2 = tc_starter("1 " ) ,
{ " 1 " , Id2 } = get_tc_id(Pid2 ) ,
? = Id2 ) ,
? assertMatch({"1 " , _ Ref } , ) ) ,
pooler_basics_via_config_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
fun() ->
Pools = [[{name, test_pool_1},
{max_count, 3},
{init_count, 2},
{cull_interval, {0, min}},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}]],
application:set_env(pooler, pools, Pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler)
end,
fun(_X) ->
application:stop(pooler)
end,
basic_tests()}}.
pooler_basics_dynamic_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
fun() ->
Pool = [{name, test_pool_1},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}],
application:unset_env(pooler, pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
pooler:new_pool(Pool)
end,
fun(_X) ->
application:stop(pooler)
end,
basic_tests()}}.
pooler_basics_integration_to_other_supervisor_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
fun() ->
Pool = [{name, test_pool_1},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}],
application:unset_env(pooler, pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
supervisor:start_link(fake_external_supervisor, Pool)
end,
fun({ok, SupPid}) ->
exit(SupPid, normal),
application:stop(pooler)
end,
basic_tests()}}.
basic_tests() ->
[
{"there are init_count members at start",
fun() ->
Stats = [ P || {P, {_, free, _}} <- pooler:pool_stats(test_pool_1) ],
?assertEqual(2, length(Stats))
end},
{"take and return one",
fun() ->
P = pooler:take_member(test_pool_1),
?assertMatch({"type-0", _Id}, pooled_gs:get_id(P)),
ok = pooler:return_member(test_pool_1, P, ok)
end},
{"take and return one, named pool",
fun() ->
P = pooler:take_member(test_pool_1),
?assertMatch({"type-0", _Id}, pooled_gs:get_id(P)),
ok, pooler:return_member(test_pool_1, P)
end},
{"attempt to take form unknown pool",
fun() ->
?assertExit({noproc, _}, pooler:take_member(bad_pool_name))
end},
{"members creation is triggered after pool exhaustion until max",
fun() ->
init count is 2
Pids0 = [pooler:take_member(test_pool_1), pooler:take_member(test_pool_1)],
that we will get a pid , but may not be first try .
Pids = get_n_pids(1, Pids0),
pool is at now , requests should give error
?assertEqual(error_no_members, pooler:take_member(test_pool_1)),
?assertEqual(error_no_members, pooler:take_member(test_pool_1)),
PRefs = [ R || {_T, R} <- [ pooled_gs:get_id(P) || P <- Pids ] ],
?assertEqual(length(PRefs), length(lists:usort(PRefs)))
end
},
{"pids are reused most recent return first",
fun() ->
P1 = pooler:take_member(test_pool_1),
P2 = pooler:take_member(test_pool_1),
?assertNot(P1 == P2),
ok = pooler:return_member(test_pool_1, P1, ok),
ok = pooler:return_member(test_pool_1, P2, ok),
pids are reused most recent first
?assertEqual(P2, pooler:take_member(test_pool_1)),
?assertEqual(P1, pooler:take_member(test_pool_1))
end},
{"if an in-use pid crashes it is replaced",
fun() ->
Pids0 = get_n_pids(3, []),
Ids0 = [ pooled_gs:get_id(P) || P <- Pids0 ],
[ pooled_gs:crash(P) || P <- Pids0 ],
Pids1 = get_n_pids(3, []),
Ids1 = [ pooled_gs:get_id(P) || P <- Pids1 ],
[ ?assertNot(lists:member(I, Ids0)) || I <- Ids1 ]
end
},
{"if a free pid crashes it is replaced",
fun() ->
FreePids = [ P || {P, {_, free, _}} <- pooler:pool_stats(test_pool_1) ],
[ exit(P, kill) || P <- FreePids ],
Pids1 = get_n_pids(3, []),
?assertEqual(3, length(Pids1))
end},
{"if a pid is returned with bad status it is replaced",
fun() ->
Pids0 = get_n_pids(3, []),
Ids0 = [ pooled_gs:get_id(P) || P <- Pids0 ],
[ pooler:return_member(test_pool_1, P, fail) || P <- Pids0 ],
Pids1 = get_n_pids(3, []),
Ids1 = [ pooled_gs:get_id(P) || P <- Pids1 ],
[ ?assertNot(lists:member(I, Ids0)) || I <- Ids1 ]
end
},
{"if a consumer crashes, pid is replaced",
fun() ->
Consumer = start_user(),
StartId = user_id(Consumer),
user_crash(Consumer),
NewPid = hd(get_n_pids(1, [])),
NewId = pooled_gs:get_id(NewPid),
?assertNot(NewId == StartId)
end
},
{"it is ok to return an unknown pid",
fun() ->
Bogus1 = spawn(fun() -> ok end),
Bogus2 = spawn(fun() -> ok end),
?assertEqual(ok, pooler:return_member(test_pool_1, Bogus1, ok)),
?assertEqual(ok, pooler:return_member(test_pool_1, Bogus2, fail))
end
},
{"it is ok to return a pid more than once",
fun() ->
M = pooler:take_member(test_pool_1),
[ pooler:return_member(test_pool_1, M)
|| _I <- lists:seq(1, 37) ],
M1 = pooler:take_member(test_pool_1),
M2 = pooler:take_member(test_pool_1),
?assert(M1 =/= M2),
Pool1 = gen_server:call(test_pool_1, dump_pool),
?assertEqual(2, Pool1#pool.in_use_count),
?assertEqual(0, Pool1#pool.free_count),
pooler:return_member(test_pool_1, M1),
pooler:return_member(test_pool_1, M2),
Pool2 = gen_server:call(test_pool_1, dump_pool),
?assertEqual(0, Pool2#pool.in_use_count),
?assertEqual(2, Pool2#pool.free_count),
ok
end},
{"calling return_member on error_no_members is ignored",
fun() ->
?assertEqual(ok, pooler:return_member(test_pool_1, error_no_members)),
?assertEqual(ok, pooler:return_member(test_pool_1, error_no_members, ok)),
?assertEqual(ok, pooler:return_member(test_pool_1, error_no_members, fail))
end
},
{"dynamic pool creation",
fun() ->
PoolSpec = [{name, dyn_pool_1},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"dyn-0"}]}}],
{ok, SupPid1} = pooler:new_pool(PoolSpec),
?assert(is_pid(SupPid1)),
M = pooler:take_member(dyn_pool_1),
?assertMatch({"dyn-0", _Id}, pooled_gs:get_id(M)),
?assertEqual(ok, pooler:rm_pool(dyn_pool_1)),
?assertExit({noproc, _}, pooler:take_member(dyn_pool_1)),
{ok, SupPid2} = pooler:new_pool(PoolSpec),
?assert(is_pid(SupPid2)),
?assertEqual(ok, pooler:rm_pool(dyn_pool_X)),
?assertEqual(ok, pooler:rm_pool(dyn_pool_1))
end},
{"metrics have been called (no timeout/queue)",
fun() ->
fake_metrics:reset_metrics(),
Pids = [ pooler:take_member(test_pool_1) || _I <- lists:seq(1, 10) ],
[ pooler:return_member(test_pool_1, P) || P <- Pids ],
catch pooler:take_member(bad_pool_name),
exit(hd(Pids), kill),
KillMe = pooler:take_member(test_pool_1),
exit(KillMe, kill),
ExpectKeys = lists:sort([<<"pooler.test_pool_1.error_no_members_count">>,
<<"pooler.test_pool_1.events">>,
<<"pooler.test_pool_1.free_count">>,
<<"pooler.test_pool_1.in_use_count">>,
<<"pooler.test_pool_1.killed_free_count">>,
<<"pooler.test_pool_1.killed_in_use_count">>,
<<"pooler.test_pool_1.take_rate">>]),
Metrics = fake_metrics:get_metrics(),
GotKeys = lists:usort([ Name || {Name, _, _} <- Metrics ]),
?assertEqual(ExpectKeys, GotKeys)
end},
{"metrics have been called (with timeout/queue)",
fun() ->
fake_metrics:reset_metrics(),
pass a non - zero timeout here to exercise queueing
Pids = [ pooler:take_member(test_pool_1, 1) || _I <- lists:seq(1, 10) ],
[ pooler:return_member(test_pool_1, P) || P <- Pids ],
catch pooler:take_member(bad_pool_name),
exit(hd(Pids), kill),
KillMe = pooler:take_member(test_pool_1),
exit(KillMe, kill),
ExpectKeys = lists:sort([<<"pooler.test_pool_1.error_no_members_count">>,
<<"pooler.test_pool_1.events">>,
<<"pooler.test_pool_1.free_count">>,
<<"pooler.test_pool_1.in_use_count">>,
<<"pooler.test_pool_1.killed_free_count">>,
<<"pooler.test_pool_1.killed_in_use_count">>,
<<"pooler.test_pool_1.take_rate">>,
<<"pooler.test_pool_1.queue_count">>]),
Metrics = fake_metrics:get_metrics(),
GotKeys = lists:usort([ Name || {Name, _, _} <- Metrics ]),
?assertEqual(ExpectKeys, GotKeys)
end},
{"accept bad member is handled",
fun() ->
Bad = spawn(fun() -> ok end),
FakeStarter = spawn(fun() -> starter end),
?assertEqual(ok, pooler:accept_member(test_pool_1, {FakeStarter, Bad}))
end},
{"utilization returns sane results",
fun() ->
#pool{max_count = MaxCount, queue_max = QueueMax} = Pool = sys:get_state(test_pool_1),
?assertEqual(MaxCount, ?gv(max_count, pooler:pool_utilization(test_pool_1))),
?assertEqual(0, ?gv(in_use_count, pooler:pool_utilization(test_pool_1))),
?assertEqual(2, ?gv(free_count, pooler:pool_utilization(test_pool_1))),
?assertEqual(0, ?gv(queued_count, pooler:pool_utilization(test_pool_1))),
?assertEqual(QueueMax, ?gv(queue_max, pooler:pool_utilization(test_pool_1)))
end}
].
pooler_groups_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
fun() ->
Pools = [[{name, test_pool_1},
{group, group_1},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-1-1"}]}}],
[{name, test_pool_2},
{group, group_1},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-1-2"}]}}],
[{name, test_pool_3},
{group, undefined},
{max_count, 3},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-3"}]}}]
],
application:set_env(pooler, pools, Pools),
error_logger : ) ,
pg2:start(),
application:start(pooler)
end,
fun(_X) ->
application:stop(pooler),
application:stop(pg2)
end,
[
{"take and return one group member (repeated)",
fun() ->
Types = [ begin
Pid = pooler:take_group_member(group_1),
{Type, _} = pooled_gs:get_id(Pid),
?assertMatch("type-1" ++ _, Type),
ok = pooler:return_group_member(group_1, Pid, ok),
Type
end
|| _I <- lists:seq(1, 50) ],
Type_1_1 = [ X || "type-1-1" = X <- Types ],
Type_1_2 = [ X || "type-1-2" = X <- Types ],
?assert(length(Type_1_1) > 0),
?assert(length(Type_1_2) > 0)
end},
{"take member from unknown group",
fun() ->
?assertEqual({error_no_group, not_a_group},
pooler:take_group_member(not_a_group))
end},
{"return member to unknown group",
fun() ->
Pid = pooler:take_group_member(group_1),
?assertEqual(ok, pooler:return_group_member(no_such_group, Pid))
end},
{"return member to wrong group",
fun() ->
Pid = pooler:take_member(test_pool_3),
?assertEqual(ok, pooler:return_group_member(group_1, Pid))
end},
{"return member with something which is not a pid",
fun() ->
?assertException(error, _, pooler:return_group_member(group_1, not_pid))
end},
{"take member from empty group",
fun() ->
[ pg2:leave(group_1, M) || M <- pg2:get_members(group_1) ],
?assertEqual(error_no_members, pooler:take_group_member(group_1))
end},
{"return member to group, implied ok",
fun() ->
Pid = pooler:take_group_member(group_1),
?assertEqual(ok, pooler:return_group_member(group_1, Pid))
end},
{"return error_no_member to group",
fun() ->
?assertEqual(ok, pooler:return_group_member(group_1, error_no_members))
end},
{"exhaust pools in group",
fun() ->
Pids = get_n_pids_group(group_1, 6, []),
[ begin
{Type, _} = pooled_gs:get_id(P),
?assertMatch("type-1" ++ _, Type),
ok
end || P <- Pids ],
[error_no_members,
error_no_members,
error_no_members] = [ pooler:take_group_member(group_1)
|| _I <- lists:seq(1, 3) ]
end},
{"rm_group with nonexisting group",
fun() ->
?assertEqual(ok, pooler:rm_group(i_dont_exist))
end},
{"rm_group with existing empty group",
fun() ->
?assertEqual(ok, pooler:rm_pool(test_pool_1)),
?assertEqual(ok, pooler:rm_pool(test_pool_2)),
?assertEqual(error_no_members, pooler:take_group_member(group_1)),
?assertEqual(ok, pooler:rm_group(group_1)),
?assertExit({noproc, _}, pooler:take_member(test_pool_1)),
?assertExit({noproc, _}, pooler:take_member(test_pool_2)),
?assertEqual({error_no_group, group_1},
pooler:take_group_member(group_1))
end},
{"rm_group with existing non-empty group",
fun() ->
MemberPid = pooler:take_group_member(group_1),
?assert(is_pid(MemberPid)),
pooler:return_group_member(group_1, MemberPid),
Pool1Pid = pooler:take_member(test_pool_1),
?assert(is_pid(Pool1Pid)),
pooler:return_member(test_pool_1, Pool1Pid),
Pool2Pid = pooler:take_member(test_pool_2),
?assert(is_pid(Pool2Pid)),
pooler:return_member(test_pool_2, Pool2Pid),
?assertEqual(ok, pooler:rm_group(group_1)),
?assertExit({noproc, _}, pooler:take_member(test_pool_1)),
?assertExit({noproc, _}, pooler:take_member(test_pool_2)),
?assertEqual({error_no_group, group_1},
pooler:take_group_member(group_1))
end}
]}}.
pooler_limit_failed_adds_test_() ->
{setup,
fun() ->
Pools = [[{name, test_pool_1},
{max_count, 10},
{init_count, 10},
{start_mfa,
{pooled_gs, start_link, [crash]}}]],
application:set_env(pooler, pools, Pools)
end,
fun(_) ->
application:stop(pooler)
end,
fun() ->
application:start(pooler),
?assertEqual(error_no_members, pooler:take_member(test_pool_1)),
?assertEqual(error_no_members, pooler:take_member(test_pool_1))
end}.
pooler_scheduled_cull_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link(),
Pools = [[{name, test_pool_1},
{max_count, 10},
{init_count, 2},
{start_mfa, {pooled_gs, start_link, [{"type-0"}]}},
{cull_interval, {200, ms}},
{max_age, {0, min}}]],
application:set_env(pooler, pools, Pools),
error_logger : ) ,
application:start(pooler)
end,
fun(_X) ->
fake_metrics:stop(),
application:stop(pooler)
end,
[
{foreach,
fun() ->
Pids = get_n_pids(test_pool_1, 10, []),
?assertEqual(10, length(pooler:pool_stats(test_pool_1))),
?assertEqual(10, length(Pids)),
Pids
end,
fun(Pids) ->
[ pooler:return_member(test_pool_1, P) || P <- Pids ]
end,
[
fun(Pids) ->
{"excess members are culled run 1",
fun() ->
[ pooler:return_member(test_pool_1, P) || P <- Pids ],
timer:sleep(250),
?assertEqual(2, length(pooler:pool_stats(test_pool_1))),
?assertEqual(2, ?gv(free_count,pooler:pool_utilization(test_pool_1)))
end}
end,
fun(Pids) ->
{"excess members are culled run 2",
fun() ->
[ pooler:return_member(test_pool_1, P) || P <- Pids ],
timer:sleep(250),
?assertEqual(2, length(pooler:pool_stats(test_pool_1))),
?assertEqual(2, ?gv(free_count,pooler:pool_utilization(test_pool_1)))
end}
end,
fun(Pids) -> in_use_members_not_culled(Pids, 1) end,
fun(Pids) -> in_use_members_not_culled(Pids, 2) end,
fun(Pids) -> in_use_members_not_culled(Pids, 3) end,
fun(Pids) -> in_use_members_not_culled(Pids, 4) end,
fun(Pids) -> in_use_members_not_culled(Pids, 5) end,
fun(Pids) -> in_use_members_not_culled(Pids, 6) end
]},
{"no cull when init_count matches max_count",
fun() ->
Config = [{name, test_static_pool_1},
{max_count, 2},
{init_count, 2},
{start_mfa, {pooled_gs, start_link, [{"static-0"}]}},
pooler:new_pool(Config),
P = pooler:take_member(test_static_pool_1),
?assertMatch({"static-0", _}, pooled_gs:get_id(P)),
pooler:return_member(test_static_pool_1, P),
ok
end}
]}.
in_use_members_not_culled(Pids, N) ->
{"in-use members are not culled " ++ erlang:integer_to_list(N),
fun() ->
timer:sleep(250),
PidCount = length(Pids),
?assertEqual(PidCount,
length(pooler:pool_stats(test_pool_1))),
?assertEqual(0, ?gv(free_count,pooler:pool_utilization(test_pool_1))),
?assertEqual(PidCount, ?gv(in_use_count,pooler:pool_utilization(test_pool_1))),
Returns = lists:sublist(Pids, N),
[ pooler:return_member(test_pool_1, P)
|| P <- Returns ],
timer:sleep(250),
?assertEqual(PidCount - N,
length(pooler:pool_stats(test_pool_1)))
end}.
random_message_test_() ->
{setup,
fun() ->
Pools = [[{name, test_pool_1},
{max_count, 2},
{init_count, 1},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}]],
application:set_env(pooler, pools, Pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
spawn(fun() -> catch gen_server:call(test_pool_1, {unexpected_garbage_msg, 5}) end),
gen_server:cast(test_pool_1, {unexpected_garbage_msg, 6}),
whereis(test_pool_1) ! {unexpected_garbage_msg, 7},
ok
end,
fun(_) ->
application:stop(pooler)
end,
[
fun() ->
Pid = spawn(fun() -> ok end),
MonMsg = {'DOWN', erlang:make_ref(), process, Pid, because},
test_pool_1 ! MonMsg
end,
fun() ->
Pid = pooler:take_member(test_pool_1),
{Type, _} = pooled_gs:get_id(Pid),
?assertEqual("type-0", Type)
end,
fun() ->
RawPool = gen_server:call(test_pool_1, dump_pool),
?assertEqual(pool, element(1, RawPool))
end
]}.
pooler_integration_long_init_test_() ->
{foreach,
fun() ->
Pool = [{name, test_pool_1},
{max_count, 10},
{init_count, 0},
{member_start_timeout, {10, ms}},
{start_mfa,
{pooled_gs, start_link, [{"type-0", fun() -> timer:sleep(15) end}]}}],
application:set_env(pooler, pools, [Pool]),
application:start(pooler)
end,
fun(_) ->
application:stop(pooler)
end,
[
fun(_) ->
Accordingly , the count should go to zero once all starters
fun() ->
?assertEqual(0, children_count(pooler_test_pool_1_member_sup)),
[begin
?assertEqual(error_no_members, pooler:take_member(test_pool_1)),
?assertEqual(1, starting_members(test_pool_1))
end
|| _ <- lists:seq(1,10)],
?assertEqual(10, children_count(pooler_test_pool_1_member_sup)),
timer:sleep(150),
?assertEqual(0, children_count(pooler_test_pool_1_member_sup)),
?assertEqual(0, starting_members(test_pool_1))
end
end
]
}.
sleep_for_configured_timeout() ->
SleepTime = case application:get_env(pooler, sleep_time) of
{ok, Val} ->
Val;
_ ->
0
end,
timer:sleep(SleepTime).
pooler_integration_queueing_test_() ->
{foreach,
fun() ->
Pool = [{name, test_pool_1},
{max_count, 10},
{queue_max, 10},
{init_count, 0},
{metrics, fake_metrics},
{member_start_timeout, {5, sec}},
{start_mfa,
{pooled_gs, start_link, [
{"type-0",
fun pooler_tests:sleep_for_configured_timeout/0 }
]
}
}
],
application:set_env(pooler, pools, [Pool]),
fake_metrics:start_link(),
application:start(pooler)
end,
fun(_) ->
fake_metrics:stop(),
application:stop(pooler)
end,
[
fun(_) ->
fun() ->
?assertEqual(0, (dump_pool(test_pool_1))#pool.free_count),
Val = pooler:take_member(test_pool_1, 10),
?assert(is_pid(Val)),
pooler:return_member(test_pool_1, Val)
end
end,
fun(_) ->
fun() ->
application:set_env(pooler, sleep_time, 1),
?assertEqual(0, (dump_pool(test_pool_1))#pool.free_count),
Val = pooler:take_member(test_pool_1, 0),
?assertEqual(error_no_members, Val),
?assertEqual(0, ?gv(free_count,pooler:pool_utilization(test_pool_1))),
timer:sleep(50),
Pid = pooler:take_member(test_pool_1, 0),
?assert(is_pid(Pid)),
pooler:return_member(test_pool_1, Pid)
end
end,
fun(_) ->
fun() ->
application:set_env(pooler, sleep_time, 10),
?assertEqual(0, (dump_pool(test_pool_1))#pool.free_count),
[
?assertEqual(pooler:take_member(test_pool_1, 0), error_no_members) ||
_ <- lists:seq(1, (dump_pool(test_pool_1))#pool.max_count)],
timer:sleep(50),
Pid = pooler:take_member(test_pool_1, 0),
?assert(is_pid(Pid)),
pooler:return_member(test_pool_1, Pid)
end
end,
fun(_) ->
fun() ->
fill to queue_max , next request should return immediately with no_members
Will return a if queue is not enforced .
application:set_env(pooler, sleep_time, 100),
[ proc_lib:spawn(fun() ->
Val = pooler:take_member(test_pool_1, 200),
?assert(is_pid(Val)),
pooler:return_member(Val)
end)
|| _ <- lists:seq(1, (dump_pool(test_pool_1))#pool.max_count)
],
?assertEqual(0, ?gv(free_count,pooler:pool_utilization(test_pool_1))),
?assert(?gv(queued_count,pooler:pool_utilization(test_pool_1)) >= 1),
?assertEqual(10, ?gv(queue_max,pooler:pool_utilization(test_pool_1))),
timer:sleep(50),
?assertEqual(10, queue:len((dump_pool(test_pool_1))#pool.queued_requestors)),
?assertEqual(10, ?gv(queue_max,pooler:pool_utilization(test_pool_1))),
?assertEqual(pooler:take_member(test_pool_1, 500), error_no_members),
ExpectKeys = lists:sort([<<"pooler.test_pool_1.error_no_members_count">>,
<<"pooler.test_pool_1.events">>,
<<"pooler.test_pool_1.take_rate">>,
<<"pooler.test_pool_1.queue_count">>,
<<"pooler.test_pool_1.queue_max_reached">>]),
Metrics = fake_metrics:get_metrics(),
GotKeys = lists:usort([ Name || {Name, _, _} <- Metrics ]),
?assertEqual(ExpectKeys, GotKeys),
timer:sleep(100),
Val = pooler:take_member(test_pool_1, 500),
?assert(is_pid(Val)),
pooler:return_member(test_pool_1, Val)
end
end
]
}.
pooler_integration_queueing_return_member_test_() ->
{foreach,
fun() ->
Pool = [{name, test_pool_1},
{max_count, 10},
{queue_max, 10},
{init_count, 10},
{metrics, fake_metrics},
{member_start_timeout, {5, sec}},
{start_mfa,
{pooled_gs, start_link, [
{"type-0",
fun pooler_tests:sleep_for_configured_timeout/0 }
]
}
}
],
application:set_env(pooler, pools, [Pool]),
fake_metrics:start_link(),
application:start(pooler)
end,
fun(_) ->
fake_metrics:stop(),
application:stop(pooler)
end,
[
fun(_) ->
fun() ->
application:set_env(pooler, sleep_time, 0),
Pids = [ proc_lib:spawn_link(fun() ->
Val = pooler:take_member(test_pool_1, 200),
?assert(is_pid(Val)),
receive
_ ->
pooler:return_member(test_pool_1, Val)
after
5000 ->
pooler:return_member(test_pool_1, Val)
end
end)
|| _ <- lists:seq(1, (dump_pool(test_pool_1))#pool.max_count)
],
timer:sleep(1),
Parent = self(),
proc_lib:spawn_link(fun() ->
Val = pooler:take_member(test_pool_1, 200),
Parent ! Val
end),
[Pid ! return || Pid <- Pids],
receive
Result ->
?assert(is_pid(Result)),
pooler:return_member(test_pool_1, Result)
end,
?assertEqual((dump_pool(test_pool_1))#pool.max_count, length((dump_pool(test_pool_1))#pool.free_pids)),
?assertEqual((dump_pool(test_pool_1))#pool.max_count, (dump_pool(test_pool_1))#pool.free_count)
end
end
]
}.
pooler_integration_test_() ->
{foreach,
fun() ->
Pools = [[{name, test_pool_1},
{max_count, 10},
{init_count, 10},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}]],
application:set_env(pooler, pools, Pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
Users = [ start_user() || _X <- lists:seq(1, 10) ],
Users
end,
fun(Users) ->
[ user_stop(U) || U <- Users ],
application:stop(pooler)
end,
[
fun(Users) ->
fun() ->
TcIds = lists:sort([ user_id(UPid) || UPid <- Users ]),
?assertEqual(lists:usort(TcIds), TcIds)
end
end
,
fun(Users) ->
fun() ->
[ user_new_tc(UPid) || UPid <- Users ],
TcIds = lists:sort([ user_id(UPid) || UPid <- Users ]),
?assertEqual(lists:usort(TcIds), TcIds)
end
end
,
fun(Users) ->
fun() ->
TcIds1 = lists:sort([ user_id(UPid) || UPid <- Users ]),
[ user_crash(UPid) || UPid <- Users ],
Seq = lists:seq(1, 5),
Users2 = [ start_user() || _X <- Seq ],
TcIds2 = lists:sort([ user_id(UPid) || UPid <- Users2 ]),
Both =
sets:to_list(sets:intersection([sets:from_list(TcIds1),
sets:from_list(TcIds2)])),
?assertEqual([], Both)
end
end
]
}.
pooler_auto_grow_disabled_by_default_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
fun() ->
Pool = [{name, test_pool_1},
{max_count, 5},
{init_count, 2},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}],
application:unset_env(pooler, pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
pooler:new_pool(Pool)
end,
fun(_X) ->
application:stop(pooler)
end,
[
{"take one, and it should not auto-grow",
fun() ->
?assertEqual(2, (dump_pool(test_pool_1))#pool.free_count),
P = pooler:take_member(test_pool_1),
?assertMatch({"type-0", _Id}, pooled_gs:get_id(P)),
timer:sleep(100),
?assertEqual(1, (dump_pool(test_pool_1))#pool.free_count),
ok, pooler:return_member(test_pool_1, P)
end}
]}}.
pooler_auto_grow_enabled_test_() ->
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
fun() ->
Pool = [{name, test_pool_1},
{max_count, 5},
{init_count, 2},
{auto_grow_threshold, 1},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}],
application:unset_env(pooler, pools),
error_logger:delete_report_handler(error_logger_tty_h),
application:start(pooler),
pooler:new_pool(Pool)
end,
fun(_X) ->
application:stop(pooler)
end,
[
{"take one, and it should grow by 2",
fun() ->
?assertEqual(2, (dump_pool(test_pool_1))#pool.free_count),
P = pooler:take_member(test_pool_1),
?assertMatch({"type-0", _Id}, pooled_gs:get_id(P)),
timer:sleep(100),
?assertEqual(3, (dump_pool(test_pool_1))#pool.free_count),
ok, pooler:return_member(test_pool_1, P)
end}
]}}.
pooler_custom_stop_mfa_test_() ->
{foreach,
fun() ->
Pool = [{name, test_pool_1},
{max_count, 3},
{init_count, 2},
{cull_interval, {200, ms}},
{max_age, {0, min}},
{start_mfa, {pooled_gs, start_link, [{foo_type}]}}],
application:set_env(pooler, pools, [Pool])
end,
fun(_) ->
application:unset_env(pooler, pools)
end,
[
{"default behavior kills the pool member",
fun() ->
ok = application:start(pooler),
Reason = monitor_members_trigger_culling_and_return_reason(),
ok = application:stop(pooler),
?assertEqual(killed, Reason)
end},
{"custom callback terminates the pool member normally",
fun() ->
{ok, [Pool]} = application:get_env(pooler, pools),
Stop = {stop_mfa, {pooled_gs, stop, ['$pooler_pid']}},
application:set_env(pooler, pools, [[Stop | Pool]]),
ok = application:start(pooler),
Reason = monitor_members_trigger_culling_and_return_reason(),
ok = application:stop(pooler),
?assertEqual(normal, Reason)
end}]}.
no_error_logger_reports_after_culling_test_() ->
{foreach,
fun() ->
{ok, _Pid} = error_logger_mon:start_link(),
Pool = [{name, test_pool_1},
{max_count, 3},
{init_count, 2},
{cull_interval, {200, ms}},
{max_age, {0, min}},
{start_mfa, {pooled_gs, start_link, [{type}]}}],
application:set_env(pooler, pools, [Pool])
end,
fun(_) ->
ok = error_logger_mon:stop(),
error_logger:delete_report_handler(error_logger_pooler_h),
application:unset_env(pooler, pools)
end,
[
{"Force supervisor to report by using exit/2 instead of terminate_child",
fun() ->
{ok, [Pool]} = application:get_env(pooler, pools),
Stop = {stop_mfa, {erlang, exit, ['$pooler_pid', kill]}},
application:set_env(pooler, pools, [[Stop | Pool]]),
ok = application:start(pooler),
error_logger:add_report_handler(error_logger_pooler_h),
Reason = monitor_members_trigger_culling_and_return_reason(),
timer:sleep(250),
error_logger:delete_report_handler(error_logger_pooler_h),
ok = application:stop(pooler),
?assertEqual(killed, Reason),
?assertEqual(1, error_logger_mon:get_msg_count())
end},
{"Default MFA shouldn't generate any reports during culling",
fun() ->
ok = application:start(pooler),
error_logger:add_report_handler(error_logger_pooler_h),
Reason = monitor_members_trigger_culling_and_return_reason(),
error_logger:delete_report_handler(error_logger_pooler_h),
ok = application:stop(pooler),
?assertEqual(killed, Reason),
?assertEqual(0, error_logger_mon:get_msg_count())
end}
]}.
monitor_members_trigger_culling_and_return_reason() ->
Pids = get_n_pids(test_pool_1, 3, []),
[ erlang:monitor(process, P) || P <- Pids ],
[ pooler:return_member(test_pool_1, P) || P <- Pids ],
receive
{'DOWN', _Ref, process, _Pid, Reason} ->
Reason
after
250 -> timeout
end.
time_as_millis_test_() ->
Zeros = [ {{0, U}, 0} || U <- [min, sec, ms, mu] ],
Ones = [{{1, min}, 60000},
{{1, sec}, 1000},
{{1, ms}, 1},
{{1, mu}, 0}],
Misc = [{{3000, mu}, 3}],
Tests = Zeros ++ Ones ++ Misc,
[ ?_assertEqual(E, pooler:time_as_millis(I)) || {I, E} <- Tests ].
time_as_micros_test_() ->
Zeros = [ {{0, U}, 0} || U <- [min, sec, ms, mu] ],
Ones = [{{1, min}, 60000000},
{{1, sec}, 1000000},
{{1, ms}, 1000},
{{1, mu}, 1}],
Misc = [{{3000, mu}, 3000}],
Tests = Zeros ++ Ones ++ Misc,
[ ?_assertEqual(E, pooler:time_as_micros(I)) || {I, E} <- Tests ].
call_free_members_test_() ->
NumWorkers = 10,
PoolName = test_pool_1,
{setup,
fun() ->
application:set_env(pooler, metrics_module, fake_metrics),
fake_metrics:start_link()
end,
fun(_X) ->
fake_metrics:stop()
end,
{foreach,
fun() ->
Pool = [{name, PoolName},
{max_count, NumWorkers},
{init_count, NumWorkers},
{start_mfa,
{pooled_gs, start_link, [{"type-0"}]}}],
application:unset_env(pooler, pools),
application:start(pooler),
pooler:new_pool(Pool)
end,
fun(_X) ->
application:stop(pooler)
end,
[
{"perform a ping across the pool when all workers are free",
fun() ->
?assertEqual(NumWorkers, (dump_pool(PoolName))#pool.free_count),
Res = pooler:call_free_members(PoolName, fun pooled_gs:ping/1),
?assertEqual(NumWorkers, count_pongs(Res))
end},
{"perform a ping across the pool when two workers are taken",
fun() ->
?assertEqual(NumWorkers, (dump_pool(PoolName))#pool.free_count),
Pids = [pooler:take_member(PoolName) || _X <- lists:seq(0, 1)],
Res = pooler:call_free_members(PoolName, fun pooled_gs:ping/1),
?assertEqual(NumWorkers -2, count_pongs(Res)),
[pooler:return_member(PoolName, P) || P <- Pids]
end},
{"perform an op where the op crashes all free members",
fun() ->
?assertEqual(NumWorkers, (dump_pool(PoolName))#pool.free_count),
Res = pooler:call_free_members(PoolName,
fun pooled_gs:error_on_call/1),
?assertEqual(NumWorkers, count_errors(Res))
end}
]}}.
count_pongs(Result) ->
lists:foldl(fun({ok, pong}, Acc) -> Acc + 1;
({error, _}, Acc) -> Acc
end,
0,
Result).
count_errors(Result) ->
lists:foldl(fun({error, _}, Acc) -> Acc + 1;
({ok, _}, Acc) -> Acc
end,
0,
Result).
get_n_pids(N, Acc) ->
get_n_pids(test_pool_1, N, Acc).
get_n_pids(_Pool, 0, Acc) ->
Acc;
get_n_pids(Pool, N, Acc) ->
case pooler:take_member(Pool) of
error_no_members ->
get_n_pids(Pool, N, Acc);
Pid ->
get_n_pids(Pool, N - 1, [Pid|Acc])
end.
get_n_pids_group(_Group, 0, Acc) ->
Acc;
get_n_pids_group(Group, N, Acc) ->
case pooler:take_group_member(Group) of
error_no_members ->
get_n_pids_group(Group, N, Acc);
Pid ->
get_n_pids_group(Group, N - 1, [Pid|Acc])
end.
children_count(SupId) ->
length(supervisor:which_children(SupId)).
starting_members(PoolName) ->
length((dump_pool(PoolName))#pool.starting_members).
dump_pool(PoolName) ->
gen_server:call(PoolName, dump_pool).
|
2c615210162f963b1f0515b16f6f1bca7d44cf346e44dcbd6ea6306f748e26b6 | racket/typed-racket | shallow-deep-id-1.rkt | #lang racket/base
;; deep should protect itself from shallow
(module uuu racket/base
(provide bad-list)
(define bad-list '(X X)))
(module sss typed/racket/shallow
(require/typed (submod ".." uuu)
(bad-list (Listof (List Symbol))))
(provide f)
(: f (-> (-> (List Symbol) Symbol) (Listof Symbol)))
(define (f x)
(map x bad-list)))
(module ttt typed/racket
(require (submod ".." sss))
(: g (-> (List Symbol) Symbol))
(define (g n)
(car n))
(define (go1)
(f g))
(define (go2)
second function , to be sure all occurrences of ` f ` get a contract
(f g))
(provide go1 go2))
(require 'ttt rackunit)
(check-exn exn:fail:contract? go1)
(check-exn exn:fail:contract? go2)
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/shallow/shallow-deep-id-1.rkt | racket | deep should protect itself from shallow | #lang racket/base
(module uuu racket/base
(provide bad-list)
(define bad-list '(X X)))
(module sss typed/racket/shallow
(require/typed (submod ".." uuu)
(bad-list (Listof (List Symbol))))
(provide f)
(: f (-> (-> (List Symbol) Symbol) (Listof Symbol)))
(define (f x)
(map x bad-list)))
(module ttt typed/racket
(require (submod ".." sss))
(: g (-> (List Symbol) Symbol))
(define (g n)
(car n))
(define (go1)
(f g))
(define (go2)
second function , to be sure all occurrences of ` f ` get a contract
(f g))
(provide go1 go2))
(require 'ttt rackunit)
(check-exn exn:fail:contract? go1)
(check-exn exn:fail:contract? go2)
|
dd6e61ac1646c81470a62337b7fc3c5ce32d36b0e24c57096f8f4d08ad7b56eb | pedestal/pedestal-app | walkthrough.clj | In Pedestal , applications receive input as inform messages . An
;; inform message is a vector of event-entries. Each event-entry has
;; the form
[source event state(s)]
;; Inform messages may be received from back-end services or from the
;; user interface. For example, a button click may generate an inform
;; message like the one shown below.
[[[:ui :button :a] :click]]
This inform message has one event - entry . The source is
[:ui :button :a]
;; and the event is
:click
;; There are no states included in this message.
;; An application will need to have some code which knows what this
;; particular event means for the application. Messages which tell
;; other things to change are called transform messages. Each
transform message contains one or more transformations . A
;; transformation has the form
[target op arg(s)]
;; For example, the value of a counter should be incremented when this
;; button is clicked. The tranform message which would cause this to
;; happen is shown below.
[[[:info :counter :a] inc]]
;; In this message, the target is
[:info :counter :a]
and the op is the ` inc ` function . This transformation has no
;; arguments.
;; Messages are conveyed on core.async channels.
(require '[clojure.core.async :refer [go chan <! >! put! alts!! timeout]])
Channels which convey messages are called inform channels
;; and channels which convey transform messages are called transform
;; channels.
;; When an inform message is received, transform messages should be
;; generated which cause some part of the application to
;; change. To accomplish this we will need a function which receives
;; an inform message and produces a collection of transform messages.
(defn inc-counter-transform [inform-message]
(let [[[source event]] inform-message
[_ _ counter-id] source]
[[[[:info :counter counter-id] inc]]]))
;; This function extracts the id of the counter to increment from the source
;; of the event-entry. For simplicilty this function assumes that it
will only have one event - entry in the inform message .
;; We need some way to map inform messages to this function and then
;; put the generated transform messages on a transform channel. That
;; is the purpose of the `io.pedestal.app.map` namespace.
(require '[io.pedestal.app.map :as map])
First we need to create a configuration that will describe how to
;; dispatch inform messages to functions. The following configuration
;; will dispatch inform messages from the source [:ui :button :*] with
;; a :click event to the function `inc-counter-transform`.
(def input-config [[inc-counter-transform [:ui :button :*] :click]])
;; This config is a vector of vectors and can contain any number of
;; vectors. Each vector can have any number or source event
;; pairs. Wildcards, :* and :**, can be used in the source path and :*
can be used to match any event . :* matches exactly one element and
;; :** matches 0 or more elements.
;; Now we will create a map that has an input inform channel and an
;; output transform channel and uses the above config.
;; Create the transform channel
(def transform-chan (chan 10))
;; Create the map passing the config and transform channel and
;; returning the inform channel.
(def inform-chan (map/inform->transforms input-config transform-chan))
;; We can now send an inform message on the inform channel
(put! inform-chan [[[:ui :button :a] :click]])
;; and see the transform message come out of the transform channel.
(println (first (alts!! [transform-chan (timeout 100)])))
;; So we now have a transform message which can be used to increment
;; a value in the information model.
;; To work with the information model we use the
;; `io.pedestal.app.model` namespace.
(require '[io.pedestal.app.model :as model])
;; A transform channel sends messages to the model and an inform
;; channel sends messages which describe changes to the model. We have
;; already seen an example of the transform message which is sent to
;; a model. What does a model inform message look like? An example is
;; shown below.
[[[:info :counter :a] :updated {:info {:counter {:a 0}}} {:info {:counter {:a 1}}}]]
;; The source is the path in the model which changed. The event is
;; either :added, :updated or :removed. The states are the entire
;; old and new model values.
To create a new model , we first create the inform channel .
(def model-inform-chan (chan 10))
;; We then call `transform->inform` passing the initial model value
;; and the inform channel. This returns the transform
;; channel. Remember, for the model, transform messages go in and
;; inform messages come out.
(def model-transform-chan (model/transform->inform {:info {:counter {:a 0}}} model-inform-chan))
;; We can now send a transform message to the model
(put! model-transform-chan [[[:info :counter :a] inc]])
;; and get the inform message which describes the change to the model.
(println (first (alts!! [model-inform-chan (timeout 100)])))
;; When building an application, we will combine these parts. We can
create a pipeline of channels where input inform messages go in one
;; end and model inform messages come out of the other end.
(def model-inform-chan (chan 10))
(def input-inform-chan (->> model-inform-chan
(model/transform->inform {:info {:counter {:a 0}}})
(map/inform->transforms input-config)))
;; We can now send a button click event on the input-inform-channel
(put! input-inform-chan [[[:ui :button :a] :click]])
;; and see the update to the model on the model-inform-channel
(println (first (alts!! [model-inform-chan (timeout 100)])))
;; So what should we do with model inform messages? Something in our
;; application will most likely need to change based on the changes to
;; the information model. Once again we need to generate transforms
;; based on inform messages. This time the transform message will go
;; out to the UI so that the counter value can be displayed.
(defn counter-text-transform [inform-message]
(vector
(mapv (fn [[source _ _ new-model]]
(let [counter-id (last source)]
[[:ui :number counter-id] :set-value (get-in new-model source)]))
inform-message)))
In the function above , one transformation is created for each
event - entry . If more than one counter is updated during a
;; transaction on the info model then a single transform will be sent
;; out will all the updates to the UI. This could also be written so
;; that one transform is generated for each change.
;; Again we create a configuration which will map inform messages to
;; this function
(def output-config [[counter-text-transform [:info :counter :*] :updated]])
;; We can then create a map from this config
(def output-transform-chan (chan 10))
(def output-inform-chan (map/inform->transforms output-config output-transform-chan))
;; and send a model inform message to test it out
(put! output-inform-chan [[[:info :counter :a] :updated
{:info {:counter {:a 0}}}
{:info {:counter {:a 1}}}]])
(println (first (alts!! [output-transform-chan (timeout 100)])))
;; Now let's put it all together. Create the transform channel that
;; will send transform messages to the UI.
(def output-transform-chan (chan 10))
;; Build the pipeline that includes the model and the input and output
;; maps. This returns the inform channel that you will give to UI
;; componenets are anything which will send input to the application.
(def input-inform-chan (->> output-transform-chan
(map/inform->transforms output-config)
(model/transform->inform {:info {:counter {:a 0}}})
(map/inform->transforms input-config)))
;; Send the button click event on the input channel.
(put! input-inform-chan [[[:ui :button :a] :click]])
Consume ui transforms from the output channel .
(println (first (alts!! [output-transform-chan (timeout 100)])))
;; Try sending the :click event several times.
;; This is the basic application loop.
What if we had two counters and we wanted to have a third counter
which was always the sum of the other two ? The
;; `io.pedestal.app.flow` namespace provides dataflow capabilities.
(require '[io.pedestal.app.flow :as flow])
;; Create a function that turns info model informs into info model transforms.
(defn sum-transform [inform-message]
(let [[[_ _ _ n]] inform-message]
[[[[:info :counter :c] (constantly (+ (get-in n [:info :counter :a])
(get-in n [:info :counter :b])))]]]))
;; Create the flow config.
(def flow-config [[sum-transform [:info :counter :a] :updated [:info :counter :b] :updated]])
;; Call the `flow/transform->inform` function instead of
;; `model/transform->inform`. This function takes an additional config argument.
(def output-transform-chan (chan 10))
(def input-inform-chan
(->> output-transform-chan
(map/inform->transforms output-config)
(flow/transform->inform {:info {:counter {:a 0 :b 0 :c 0}}} flow-config)
(map/inform->transforms input-config)))
Send inform messages as if two buttons where clicked .
(put! input-inform-chan [[[:ui :button :a] :click]])
(put! input-inform-chan [[[:ui :button :b] :click]])
;; Read two inform messages from the output channel.
(println (first (alts!! [output-transform-chan (timeout 100)])))
(println (first (alts!! [output-transform-chan (timeout 100)])))
We sometimes need to route messages from one transform channel to
;; an one or more other transform channels. For this we use the
;; `io.pedestal.app.route` namespace.
(require '[io.pedestal.app.route :as route])
Suppose we have three different channels on which we would like to
;; send transform messages.
one for ui transforms
(def ui-transform-chan (chan 10))
;; one for transforms to the info model
(def info-transform-chan (chan 10))
;; and one for service transforms
(def service-transform-chan (chan 10))
;; we can create a router which will route messages from an incoming
transform channel to one of these channels . First we create the
;; transform channel which will convey messages to the router
(def router-transform-chan (chan 10))
;; then we start the router providing a name and the input channel.
(route/router [:router :x] router-transform-chan)
;; The name of this router is [:router :x] and could be any path. To
;; add transform messages to the router we send messages to it on the
;; input transform channel. In the example below, we send on transform
message with three transformations , each one adding a channel to
;; the router.
(put! router-transform-chan [[[:router :x] :add [ui-transform-chan [:ui :**] :*]]
[[:router :x] :add [info-transform-chan [:info :**] :*]]
[[:router :x] :add [service-transform-chan [:service :**] :*]]])
;; The state part of the transformation is the same kind of vector
;; that we would use to configure a map except that we have a channel
;; in the place of a function.
[ui-transform-chan [:ui :**] :*]
;; This means that any incoming transform message for any event where
the first element in the target is ` : ui ` will get put on the
;; `ui-transform-chan` channel.
;; We can now send a single transform message to this router and it
will split it into three transforms and place each one on the
;; correct outbound channel.
(put! router-transform-chan [[[:ui :number :a] :set-value 42]
[[:info :counter :a] inc]
[[:info :counter :b] inc]
[[:service :datomic] :save-value :counter-a 42]])
(println (first (alts!! [ui-transform-chan (timeout 100)])))
(println (first (alts!! [info-transform-chan (timeout 100)])))
(println (first (alts!! [service-transform-chan (timeout 100)])))
;; to remove a channel, we send the router a `:remove` transform
(put! router-transform-chan [[[:router :x] :remove [info-transform-chan [:info :**] :*]]])
;; Now when we send the same message as above, nothing will be put on
;; the `info-transform-chan`.
(put! router-transform-chan [[[:ui :number :a] :set-value 42]
[[:info :counter :a] inc]
[[:info :counter :b] inc]
[[:service :datomic] :save-value :counter-a 42]])
(println (first (alts!! [ui-transform-chan (timeout 100)])))
(println (first (alts!! [info-transform-chan (timeout 100)])))
(println (first (alts!! [service-transform-chan (timeout 100)])))
| null | https://raw.githubusercontent.com/pedestal/pedestal-app/509ab766a54921c0fbb2dd7c6a3cb20223b8e1a1/app/examples/walkthrough.clj | clojure | inform message is a vector of event-entries. Each event-entry has
the form
Inform messages may be received from back-end services or from the
user interface. For example, a button click may generate an inform
message like the one shown below.
and the event is
There are no states included in this message.
An application will need to have some code which knows what this
particular event means for the application. Messages which tell
other things to change are called transform messages. Each
transformation has the form
For example, the value of a counter should be incremented when this
button is clicked. The tranform message which would cause this to
happen is shown below.
In this message, the target is
arguments.
Messages are conveyed on core.async channels.
and channels which convey transform messages are called transform
channels.
When an inform message is received, transform messages should be
generated which cause some part of the application to
change. To accomplish this we will need a function which receives
an inform message and produces a collection of transform messages.
This function extracts the id of the counter to increment from the source
of the event-entry. For simplicilty this function assumes that it
We need some way to map inform messages to this function and then
put the generated transform messages on a transform channel. That
is the purpose of the `io.pedestal.app.map` namespace.
dispatch inform messages to functions. The following configuration
will dispatch inform messages from the source [:ui :button :*] with
a :click event to the function `inc-counter-transform`.
This config is a vector of vectors and can contain any number of
vectors. Each vector can have any number or source event
pairs. Wildcards, :* and :**, can be used in the source path and :*
:** matches 0 or more elements.
Now we will create a map that has an input inform channel and an
output transform channel and uses the above config.
Create the transform channel
Create the map passing the config and transform channel and
returning the inform channel.
We can now send an inform message on the inform channel
and see the transform message come out of the transform channel.
So we now have a transform message which can be used to increment
a value in the information model.
To work with the information model we use the
`io.pedestal.app.model` namespace.
A transform channel sends messages to the model and an inform
channel sends messages which describe changes to the model. We have
already seen an example of the transform message which is sent to
a model. What does a model inform message look like? An example is
shown below.
The source is the path in the model which changed. The event is
either :added, :updated or :removed. The states are the entire
old and new model values.
We then call `transform->inform` passing the initial model value
and the inform channel. This returns the transform
channel. Remember, for the model, transform messages go in and
inform messages come out.
We can now send a transform message to the model
and get the inform message which describes the change to the model.
When building an application, we will combine these parts. We can
end and model inform messages come out of the other end.
We can now send a button click event on the input-inform-channel
and see the update to the model on the model-inform-channel
So what should we do with model inform messages? Something in our
application will most likely need to change based on the changes to
the information model. Once again we need to generate transforms
based on inform messages. This time the transform message will go
out to the UI so that the counter value can be displayed.
transaction on the info model then a single transform will be sent
out will all the updates to the UI. This could also be written so
that one transform is generated for each change.
Again we create a configuration which will map inform messages to
this function
We can then create a map from this config
and send a model inform message to test it out
Now let's put it all together. Create the transform channel that
will send transform messages to the UI.
Build the pipeline that includes the model and the input and output
maps. This returns the inform channel that you will give to UI
componenets are anything which will send input to the application.
Send the button click event on the input channel.
Try sending the :click event several times.
This is the basic application loop.
`io.pedestal.app.flow` namespace provides dataflow capabilities.
Create a function that turns info model informs into info model transforms.
Create the flow config.
Call the `flow/transform->inform` function instead of
`model/transform->inform`. This function takes an additional config argument.
Read two inform messages from the output channel.
an one or more other transform channels. For this we use the
`io.pedestal.app.route` namespace.
send transform messages.
one for transforms to the info model
and one for service transforms
we can create a router which will route messages from an incoming
transform channel which will convey messages to the router
then we start the router providing a name and the input channel.
The name of this router is [:router :x] and could be any path. To
add transform messages to the router we send messages to it on the
input transform channel. In the example below, we send on transform
the router.
The state part of the transformation is the same kind of vector
that we would use to configure a map except that we have a channel
in the place of a function.
This means that any incoming transform message for any event where
`ui-transform-chan` channel.
We can now send a single transform message to this router and it
correct outbound channel.
to remove a channel, we send the router a `:remove` transform
Now when we send the same message as above, nothing will be put on
the `info-transform-chan`. | In Pedestal , applications receive input as inform messages . An
[source event state(s)]
[[[:ui :button :a] :click]]
This inform message has one event - entry . The source is
[:ui :button :a]
:click
transform message contains one or more transformations . A
[target op arg(s)]
[[[:info :counter :a] inc]]
[:info :counter :a]
and the op is the ` inc ` function . This transformation has no
(require '[clojure.core.async :refer [go chan <! >! put! alts!! timeout]])
Channels which convey messages are called inform channels
(defn inc-counter-transform [inform-message]
(let [[[source event]] inform-message
[_ _ counter-id] source]
[[[[:info :counter counter-id] inc]]]))
will only have one event - entry in the inform message .
(require '[io.pedestal.app.map :as map])
First we need to create a configuration that will describe how to
(def input-config [[inc-counter-transform [:ui :button :*] :click]])
can be used to match any event . :* matches exactly one element and
(def transform-chan (chan 10))
(def inform-chan (map/inform->transforms input-config transform-chan))
(put! inform-chan [[[:ui :button :a] :click]])
(println (first (alts!! [transform-chan (timeout 100)])))
(require '[io.pedestal.app.model :as model])
[[[:info :counter :a] :updated {:info {:counter {:a 0}}} {:info {:counter {:a 1}}}]]
To create a new model , we first create the inform channel .
(def model-inform-chan (chan 10))
(def model-transform-chan (model/transform->inform {:info {:counter {:a 0}}} model-inform-chan))
(put! model-transform-chan [[[:info :counter :a] inc]])
(println (first (alts!! [model-inform-chan (timeout 100)])))
create a pipeline of channels where input inform messages go in one
(def model-inform-chan (chan 10))
(def input-inform-chan (->> model-inform-chan
(model/transform->inform {:info {:counter {:a 0}}})
(map/inform->transforms input-config)))
(put! input-inform-chan [[[:ui :button :a] :click]])
(println (first (alts!! [model-inform-chan (timeout 100)])))
(defn counter-text-transform [inform-message]
(vector
(mapv (fn [[source _ _ new-model]]
(let [counter-id (last source)]
[[:ui :number counter-id] :set-value (get-in new-model source)]))
inform-message)))
In the function above , one transformation is created for each
event - entry . If more than one counter is updated during a
(def output-config [[counter-text-transform [:info :counter :*] :updated]])
(def output-transform-chan (chan 10))
(def output-inform-chan (map/inform->transforms output-config output-transform-chan))
(put! output-inform-chan [[[:info :counter :a] :updated
{:info {:counter {:a 0}}}
{:info {:counter {:a 1}}}]])
(println (first (alts!! [output-transform-chan (timeout 100)])))
(def output-transform-chan (chan 10))
(def input-inform-chan (->> output-transform-chan
(map/inform->transforms output-config)
(model/transform->inform {:info {:counter {:a 0}}})
(map/inform->transforms input-config)))
(put! input-inform-chan [[[:ui :button :a] :click]])
Consume ui transforms from the output channel .
(println (first (alts!! [output-transform-chan (timeout 100)])))
What if we had two counters and we wanted to have a third counter
which was always the sum of the other two ? The
(require '[io.pedestal.app.flow :as flow])
(defn sum-transform [inform-message]
(let [[[_ _ _ n]] inform-message]
[[[[:info :counter :c] (constantly (+ (get-in n [:info :counter :a])
(get-in n [:info :counter :b])))]]]))
(def flow-config [[sum-transform [:info :counter :a] :updated [:info :counter :b] :updated]])
(def output-transform-chan (chan 10))
(def input-inform-chan
(->> output-transform-chan
(map/inform->transforms output-config)
(flow/transform->inform {:info {:counter {:a 0 :b 0 :c 0}}} flow-config)
(map/inform->transforms input-config)))
Send inform messages as if two buttons where clicked .
(put! input-inform-chan [[[:ui :button :a] :click]])
(put! input-inform-chan [[[:ui :button :b] :click]])
(println (first (alts!! [output-transform-chan (timeout 100)])))
(println (first (alts!! [output-transform-chan (timeout 100)])))
We sometimes need to route messages from one transform channel to
(require '[io.pedestal.app.route :as route])
Suppose we have three different channels on which we would like to
one for ui transforms
(def ui-transform-chan (chan 10))
(def info-transform-chan (chan 10))
(def service-transform-chan (chan 10))
transform channel to one of these channels . First we create the
(def router-transform-chan (chan 10))
(route/router [:router :x] router-transform-chan)
message with three transformations , each one adding a channel to
(put! router-transform-chan [[[:router :x] :add [ui-transform-chan [:ui :**] :*]]
[[:router :x] :add [info-transform-chan [:info :**] :*]]
[[:router :x] :add [service-transform-chan [:service :**] :*]]])
[ui-transform-chan [:ui :**] :*]
the first element in the target is ` : ui ` will get put on the
will split it into three transforms and place each one on the
(put! router-transform-chan [[[:ui :number :a] :set-value 42]
[[:info :counter :a] inc]
[[:info :counter :b] inc]
[[:service :datomic] :save-value :counter-a 42]])
(println (first (alts!! [ui-transform-chan (timeout 100)])))
(println (first (alts!! [info-transform-chan (timeout 100)])))
(println (first (alts!! [service-transform-chan (timeout 100)])))
(put! router-transform-chan [[[:router :x] :remove [info-transform-chan [:info :**] :*]]])
(put! router-transform-chan [[[:ui :number :a] :set-value 42]
[[:info :counter :a] inc]
[[:info :counter :b] inc]
[[:service :datomic] :save-value :counter-a 42]])
(println (first (alts!! [ui-transform-chan (timeout 100)])))
(println (first (alts!! [info-transform-chan (timeout 100)])))
(println (first (alts!! [service-transform-chan (timeout 100)])))
|
174809f2fed2fd7fcbb732a06c6815001f764d4c92b8fc9b958716cd7c1c80da | Yuppiechef/cqrs-server | simple.clj | (ns cqrs-server.simple
(:require
[clojure.tools.logging :as log]
[clojure.core.async :as a]
[clojure.java.data :as data]))
;; TODO: Flow conditions do not support short-circuiting, #{:all :none} to or exception handling
(defn resolve-fn [k]
(cond
(fn? k) k
(keyword? k) (resolve (symbol (namespace k) (name k)))
:else (throw (RuntimeException. "Unsupported function value: " k))))
(defn apply-function [f p x]
(let [segments (apply f (concat p [x]))]
(cond
(map? segments) [segments]
(coll? segments) segments
:else [segments])))
(defmulti find-medium :onyx/medium)
(defmethod find-medium :default [_] nil)
(defmulti find-type :onyx/type)
(defmethod find-type :default [_] nil)
(defprotocol Task
(setup [this inchan outchan]))
(deftype FunctionTask [task-map]
Task
(setup [this inchan outchan]
(let [f (or (:onyx.core/fn task-map) (resolve-fn (:onyx/fn task-map)))
p (or (:onyx.core/params task-map) (map (partial get task-map) (:onyx/params task-map)))]
(a/pipeline 1 outchan (mapcat (partial apply-function f p)) inchan true (:simple/ex-handler task-map)))))
(defmethod find-type :function [_] ->FunctionTask)
(deftype AsyncTask [task-map]
Task
(setup [this inchan outchan]
(let [in (case (:onyx/type task-map) :input (:core.async/chan task-map) inchan)
out (case (:onyx/type task-map) :output (:core.async/chan task-map) outchan)]
(a/pipeline 1 out (map identity) in true (:simple/ex-handler task-map)))))
(defmethod find-medium :core.async [_] ->AsyncTask)
(defn construct-task [env task]
(let [name (:onyx/name task)
lifecycle-fn (get-in env [:lifecycle name] (fn [_] {}))
task (merge task (lifecycle-fn task))
ctor (or (find-medium task) (find-type task))
in-chan (a/chan 100)
out-chan (a/chan 100)]
(log/info "Constructing task:" (:onyx/name task) "-" task)
{:name (:onyx/name task)
:task (setup (ctor task) in-chan out-chan)
:taskmap task
:edges {:in in-chan :out out-chan :out-mult (a/mult out-chan)}}))
(defn construct-catalog [env catalog]
(into {} (map (fn [t] [(:onyx/name t) (construct-task env t)]) catalog)))
(defn construct-flow
"Connects the out-mult to the in-chan, pushing it through flow conditions"
[out-mult {:keys [flow/from flow/to flow/predicate] :as condition}]
(let [flow-in-chan (a/chan 100)
flow-out-chan (a/chan 100)
tap (a/tap out-mult flow-in-chan)
pfn (resolve-fn predicate)]
(log/info "Flow condition " from "->" to "via" predicate)
(a/pipeline 1 flow-out-chan (filter pfn) flow-in-chan)
(a/mult flow-out-chan)))
(defn setup-flows
[chans conditions]
(reduce construct-flow chans conditions))
(defn condition-match? [[in-name out-name :as edge] {:keys [flow/from flow/to] :as condition}]
(and
(= from in-name)
(vector? to)
(get (set to) out-name)))
(defn connect-edges [conditions ctor-catalog [in-name out-name :as edge]]
(let [in (get ctor-catalog in-name)
out (get ctor-catalog out-name)
flowconds (filter (partial condition-match? edge) conditions)
_ (log/info "Tapping " in-name "->" out-name)
flow-out (setup-flows (-> in :edges :out-mult) flowconds)
tap (a/tap flow-out (-> out :edges :in))]
(update-in ctor-catalog [out-name :edges :in-tap] conj tap)))
(defn build-pipeline [conditions ctor-catalog workflow]
(log/info "Building workflow pipeline:" workflow)
(reduce (partial connect-edges conditions) ctor-catalog workflow))
(defn build-env [cqrs]
{:lifecycle (reduce (fn [a [k v]] (if (:lifecycle v) (assoc a k (:lifecycle v)) a)) {} (:catmap cqrs))})
(defn start [cqrs]
(let [env (build-env cqrs)
ctor-catalog (construct-catalog env (:catalog cqrs))]
(build-pipeline (:conditions cqrs) ctor-catalog (:workflow cqrs))))
| null | https://raw.githubusercontent.com/Yuppiechef/cqrs-server/57621f52e8f4a9de9f2e06fff16b4b918a81228a/src/cqrs_server/simple.clj | clojure | TODO: Flow conditions do not support short-circuiting, #{:all :none} to or exception handling | (ns cqrs-server.simple
(:require
[clojure.tools.logging :as log]
[clojure.core.async :as a]
[clojure.java.data :as data]))
(defn resolve-fn [k]
(cond
(fn? k) k
(keyword? k) (resolve (symbol (namespace k) (name k)))
:else (throw (RuntimeException. "Unsupported function value: " k))))
(defn apply-function [f p x]
(let [segments (apply f (concat p [x]))]
(cond
(map? segments) [segments]
(coll? segments) segments
:else [segments])))
(defmulti find-medium :onyx/medium)
(defmethod find-medium :default [_] nil)
(defmulti find-type :onyx/type)
(defmethod find-type :default [_] nil)
(defprotocol Task
(setup [this inchan outchan]))
(deftype FunctionTask [task-map]
Task
(setup [this inchan outchan]
(let [f (or (:onyx.core/fn task-map) (resolve-fn (:onyx/fn task-map)))
p (or (:onyx.core/params task-map) (map (partial get task-map) (:onyx/params task-map)))]
(a/pipeline 1 outchan (mapcat (partial apply-function f p)) inchan true (:simple/ex-handler task-map)))))
(defmethod find-type :function [_] ->FunctionTask)
(deftype AsyncTask [task-map]
Task
(setup [this inchan outchan]
(let [in (case (:onyx/type task-map) :input (:core.async/chan task-map) inchan)
out (case (:onyx/type task-map) :output (:core.async/chan task-map) outchan)]
(a/pipeline 1 out (map identity) in true (:simple/ex-handler task-map)))))
(defmethod find-medium :core.async [_] ->AsyncTask)
(defn construct-task [env task]
(let [name (:onyx/name task)
lifecycle-fn (get-in env [:lifecycle name] (fn [_] {}))
task (merge task (lifecycle-fn task))
ctor (or (find-medium task) (find-type task))
in-chan (a/chan 100)
out-chan (a/chan 100)]
(log/info "Constructing task:" (:onyx/name task) "-" task)
{:name (:onyx/name task)
:task (setup (ctor task) in-chan out-chan)
:taskmap task
:edges {:in in-chan :out out-chan :out-mult (a/mult out-chan)}}))
(defn construct-catalog [env catalog]
(into {} (map (fn [t] [(:onyx/name t) (construct-task env t)]) catalog)))
(defn construct-flow
"Connects the out-mult to the in-chan, pushing it through flow conditions"
[out-mult {:keys [flow/from flow/to flow/predicate] :as condition}]
(let [flow-in-chan (a/chan 100)
flow-out-chan (a/chan 100)
tap (a/tap out-mult flow-in-chan)
pfn (resolve-fn predicate)]
(log/info "Flow condition " from "->" to "via" predicate)
(a/pipeline 1 flow-out-chan (filter pfn) flow-in-chan)
(a/mult flow-out-chan)))
(defn setup-flows
[chans conditions]
(reduce construct-flow chans conditions))
(defn condition-match? [[in-name out-name :as edge] {:keys [flow/from flow/to] :as condition}]
(and
(= from in-name)
(vector? to)
(get (set to) out-name)))
(defn connect-edges [conditions ctor-catalog [in-name out-name :as edge]]
(let [in (get ctor-catalog in-name)
out (get ctor-catalog out-name)
flowconds (filter (partial condition-match? edge) conditions)
_ (log/info "Tapping " in-name "->" out-name)
flow-out (setup-flows (-> in :edges :out-mult) flowconds)
tap (a/tap flow-out (-> out :edges :in))]
(update-in ctor-catalog [out-name :edges :in-tap] conj tap)))
(defn build-pipeline [conditions ctor-catalog workflow]
(log/info "Building workflow pipeline:" workflow)
(reduce (partial connect-edges conditions) ctor-catalog workflow))
(defn build-env [cqrs]
{:lifecycle (reduce (fn [a [k v]] (if (:lifecycle v) (assoc a k (:lifecycle v)) a)) {} (:catmap cqrs))})
(defn start [cqrs]
(let [env (build-env cqrs)
ctor-catalog (construct-catalog env (:catalog cqrs))]
(build-pipeline (:conditions cqrs) ctor-catalog (:workflow cqrs))))
|
c7276a2d9d1c9bb70ec9040d661060ef36d636f90b0a5aced58009ba2b5f3157 | apache/couchdb-global-changes | global_changes_sup.erl | 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(global_changes_sup).
-behavior(supervisor).
-export([start_link/0]).
-export([init/1]).
-export([handle_config_change/5]).
-export([handle_config_terminate/3]).
-define(LISTENER, global_changes_listener).
-define(SERVER, global_changes_server).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
{ok, {
{one_for_one, 5, 10}, couch_epi:register_service(global_changes_epi, [
{
config_listener_mon,
{config_listener_mon, start_link, [?MODULE, nil]},
permanent,
5000,
worker,
[config_listener_mon]
},
{
global_changes_server,
{global_changes_server, start_link, []},
permanent,
5000,
worker,
[global_changes_server]
}
])}}.
handle_config_change("global_changes", "max_event_delay", MaxDelayStr, _, _) ->
try list_to_integer(MaxDelayStr) of
MaxDelay ->
gen_server:cast(?LISTENER, {set_max_event_delay, MaxDelay})
catch error:badarg ->
ok
end,
{ok, nil};
handle_config_change("global_changes", "max_write_delay", MaxDelayStr, _, _) ->
try list_to_integer(MaxDelayStr) of
MaxDelay ->
gen_server:cast(?SERVER, {set_max_write_delay, MaxDelay})
catch error:badarg ->
ok
end,
{ok, nil};
handle_config_change("global_changes", "update_db", "false", _, _) ->
gen_server:cast(?LISTENER, {set_update_db, false}),
gen_server:cast(?SERVER, {set_update_db, false}),
{ok, nil};
handle_config_change("global_changes", "update_db", _, _, _) ->
gen_server:cast(?LISTENER, {set_update_db, true}),
gen_server:cast(?SERVER, {set_update_db, true}),
{ok, nil};
handle_config_change(_, _, _, _, _) ->
{ok, nil}.
handle_config_terminate(_Server, _Reason, _State) ->
ok.
| null | https://raw.githubusercontent.com/apache/couchdb-global-changes/4aa1fc4b20ee029c93e796309887d66432fdf959/src/global_changes_sup.erl | erlang | 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
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License. | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-module(global_changes_sup).
-behavior(supervisor).
-export([start_link/0]).
-export([init/1]).
-export([handle_config_change/5]).
-export([handle_config_terminate/3]).
-define(LISTENER, global_changes_listener).
-define(SERVER, global_changes_server).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
{ok, {
{one_for_one, 5, 10}, couch_epi:register_service(global_changes_epi, [
{
config_listener_mon,
{config_listener_mon, start_link, [?MODULE, nil]},
permanent,
5000,
worker,
[config_listener_mon]
},
{
global_changes_server,
{global_changes_server, start_link, []},
permanent,
5000,
worker,
[global_changes_server]
}
])}}.
handle_config_change("global_changes", "max_event_delay", MaxDelayStr, _, _) ->
try list_to_integer(MaxDelayStr) of
MaxDelay ->
gen_server:cast(?LISTENER, {set_max_event_delay, MaxDelay})
catch error:badarg ->
ok
end,
{ok, nil};
handle_config_change("global_changes", "max_write_delay", MaxDelayStr, _, _) ->
try list_to_integer(MaxDelayStr) of
MaxDelay ->
gen_server:cast(?SERVER, {set_max_write_delay, MaxDelay})
catch error:badarg ->
ok
end,
{ok, nil};
handle_config_change("global_changes", "update_db", "false", _, _) ->
gen_server:cast(?LISTENER, {set_update_db, false}),
gen_server:cast(?SERVER, {set_update_db, false}),
{ok, nil};
handle_config_change("global_changes", "update_db", _, _, _) ->
gen_server:cast(?LISTENER, {set_update_db, true}),
gen_server:cast(?SERVER, {set_update_db, true}),
{ok, nil};
handle_config_change(_, _, _, _, _) ->
{ok, nil}.
handle_config_terminate(_Server, _Reason, _State) ->
ok.
|
5a334f83dc52f44558272506923dbd436e452378cf260daf9c4066d33b9418af | Zilliqa/scilla | Formatter.ml |
This file is part of scilla .
Copyright ( c ) 2018 - present Zilliqa Research Pvt . Ltd.
scilla 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 .
scilla 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
scilla . If not , see < / > .
This file is part of scilla.
Copyright (c) 2018 - present Zilliqa Research Pvt. Ltd.
scilla 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.
scilla 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
scilla. If not, see </>.
*)
* code formatter
open Scilla_base
open Base
open PPrint
[@@@ocamlformat "disable"]
module Format (SR : Syntax.Rep) (ER : Syntax.Rep) (Lit : Literal.ScillaLiteral) =
struct
(* instantiated syntax extended with comments *)
module Ast = ExtendedSyntax.ExtendedScillaSyntax (SR) (ER) (Lit)
module type DOC = sig
val of_type : Ast.SType.t -> PPrint.document
val of_expr : Ast.expr_annot -> PPrint.document
val of_literal : Lit.t -> PPrint.document
val of_contract_module : Ast.cmodule -> PPrint.document
end
module Doc : DOC = struct
(* -- helpers -- *)
(* number of spaces to indent *)
let indentation = 2
let forall_kwd = !^"forall"
let empy_map_kwd = !^"Emp"
let fun_kwd = !^"fun"
let tfun_kwd = !^"tfun"
let in_kwd = !^"in"
let let_kwd = !^"let"
let map_kwd = !^"Map"
let builtin_kwd = !^"builtin"
let match_kwd = !^"match"
let with_kwd = !^"with"
let end_kwd = !^"end"
let delete_kwd = !^"delete"
let exists_kwd = !^"exists"
let accept_kwd = !^"accept"
let as_kwd = !^"as"
let send_kwd = !^"send"
let event_kwd = !^"event"
let throw_kwd = !^"throw"
let contract_kwd = !^"contract"
let field_kwd = !^"field"
let of_kwd = !^"of"
let type_kwd = !^"type"
let import_kwd = !^"import"
let library_kwd = !^"library"
let scilla_version_kwd = !^"scilla_version"
let blocknumber_kwd = !^"BLOCKNUMBER"
let chainid_kwd = !^"CHAINID"
let timestamp_kwd = !^"TIMESTAMP"
let replicate_contract_kwd = !^"REPLICATE_CONTRACT"
let arrow = !^"->"
let darrow = !^"=>"
let at = !^"@"
let pipe = !^"|"
let rev_arrow = !^"<-"
let assign = !^":="
let blockchain_arrow = !^"<-&"
* concat two documents with an unbreakable space
let ( ^^^ ) left right = left ^^ space ^^ right
let indent doc = nest indentation doc
redefine PPrint 's shorthand to allow changing indentation
let ( ^//^ ) left right = prefix indentation 1 left right
(* Add parentheses only if the condition if true *)
let parens_if cond doc = if cond then parens doc else doc
(* Wrap document in comment symbols *)
let comment = enclose !^"(*" !^"*)"
multiple comments to a single comment .
let concat_comments ?(sep=hardline) cs =
List.fold_left cs ~init:[] ~f:(fun acc c -> acc @ [comment !^c])
|> concat_map (fun c -> c ^^^ sep)
(** Add formatted [comments] around [doc]. *)
let wrap_comments comments doc =
let spaced s =
let has_prefix prefix = String.is_prefix s ~prefix in
let has_suffix suffix = String.is_suffix s ~suffix in
let s = if has_prefix " " || has_prefix "*" then s else " " ^ s in
let s = if has_suffix " " || has_suffix "*" then s else s ^ " " in
s
in
let left, above, right =
List.fold_left comments
~init:([],[],[])
~f:(fun (acc_l, acc_a, acc_r) -> function
| (_, s, Ast.ComLeft) ->
acc_l @ [comment !^(spaced s); space], acc_a, acc_r
| (_, s, Ast.ComAbove) ->
acc_l, (comment !^(spaced s))::acc_a, acc_r
| (_, s, Ast.ComRight) ->
acc_l, acc_a, [space; comment !^(spaced s)] @ acc_r)
|> fun (l, a, r) ->
let a' = if List.is_empty a then empty
else (concat_map (fun c -> c ^^^ hardline) a)
in
let l' = concat l in
let r' = concat r in
l', a', r'
in
concat [above; left; doc; right]
let of_builtin b = !^(Syntax.pp_builtin b)
let of_id id = !^(Ast.SIdentifier.as_error_string id)
let of_ann_id (id, comments) = of_id id |> wrap_comments comments
let of_ann_ids ids =
separate_map space of_ann_id ids
let rec of_type_with_prec p typ =
let open Ast.SType in
match typ with
| PrimType t -> !^(Type.PrimType.pp_prim_typ t) (* TODO: temporary solution *)
| Unit -> !^"()" (* This cannot happen in source code *)
| TypeVar tv -> !^tv
| FunType (at, vt) ->
parens_if (p > 0) @@ group ((of_type_with_prec 1 at) ^^^ arrow) ^/^ (of_type_with_prec 0 vt)
TODO : test MapType and PolyFun pretty - printing
| MapType (kt, vt) ->
parens_if (p > 0) @@ map_kwd ^//^ (of_type_with_prec 1 kt) ^/^ (of_type_with_prec 1 vt)
| PolyFun (tv, bt) ->
parens_if (p > 0) @@ forall_kwd ^^^ !^tv ^^ dot ^//^ (of_type_with_prec 0 bt)
| ADT (tid, tys) ->
let ty_cons = of_id tid in
let ty_args = separate_map space (of_type_with_prec 1) tys in
if List.is_empty tys then ty_cons
else parens_if (p > 0) @@ ty_cons ^//^ ty_args
| Address addr_kind -> of_addr_kind p addr_kind
and of_type typ = of_type_with_prec 0 typ
and of_addr_kind p kind =
parens_if (p > 0) @@
match kind with
(* Any address in use *)
| AnyAddr -> !^"ByStr20 with end"
(* Address containing a library *)
| LibAddr -> !^"ByStr20 with library end"
(* Address containing a library or contract *)
| CodeAddr -> !^"ByStr20 with _codehash end"
(* Address containing a contract *)
| ContrAddr fields_map ->
let alist = Ast.SType.IdLoc_Comp.Map.to_alist fields_map in
let contract_fields =
separate_map
(comma ^^ break 1)
(fun (f, ty) -> group (field_kwd ^/^ of_id f ^/^ colon ^/^ of_type ty))
alist
in
if List.is_empty alist then !^"ByStr20 with contract end"
else
surround indentation 1
!^"ByStr20 with contract"
contract_fields
end_kwd
(* whitespace-separated non-primitive types need to be parenthesized *)
let of_types typs ~sep =
group @@ separate_map sep (fun ty -> of_type_with_prec 1 ty) typs
let of_typed_ann_id id typ = of_ann_id id ^^^ colon ^//^ group (of_type typ)
let rec of_literal lit =
let rec walk p = function
| Lit.StringLit s ->
!^[%string "\"$(String.escaped s)\""]
| Lit.IntLit i ->
let bit_width = Int.to_string @@ Lit.int_lit_width i in
let value = Lit.string_of_int_lit i in
parens_if (p > 0) @@ !^[%string "Int$(bit_width) $value"]
| Lit.UintLit i ->
let bit_width = Int.to_string @@ Lit.uint_lit_width i in
let value = Lit.string_of_uint_lit i in
parens_if (p > 0) @@ !^[%string "Uint$(bit_width) $value"]
| Lit.BNum b ->
let value = Literal.BNumLit.get b in
parens_if (p > 0) @@ !^[%string "BNum $value"]
| Lit.ByStr _bs ->
failwith "Pretty-printing of ByStr literals in expressions cannot happen"
AFAIR , there is no way in to have ByStr literals in expressions .
We might need to print the result of evaluation but there is a pretty printer for values
We might need to print the result of evaluation but there is a pretty printer for values *)
| Lit.ByStrX bsx ->
!^[%string "$(Lit.Bystrx.hex_encoding bsx)"]
| Lit.Clo _ -> !^"<closure>"
| Lit.TAbs _ -> !^"<type_closure>"
| Lit.ADTValue (name, _tys, lits) ->
let constructor = !^(Lit.LType.TIdentifier.Name.as_error_string name) in
if List.is_empty lits then
constructor
else
let cons_params = separate_map space (walk 1) lits in
parens_if (p > 0) @@ constructor ^//^ cons_params
| Lit.Map ((key_type, value_type), table) ->
if Caml.Hashtbl.length table = 0 then
let kt = of_type key_type
and vt = of_type value_type in
(* TODO: remove unneeded parens around types *)
parens_if (p > 0) @@ empy_map_kwd ^//^ (parens kt) ^/^ (parens vt)
else
failwith "Pretty-printing of non-empty map literals cannot happen while printing expressions"
| Lit.Msg typed_assocs ->
(* we ignore type information here *)
braces (
separate_map
(semi ^^ break 1)
(fun (field, _typ, value) -> !^field ^^^ colon ^^^ of_literal value)
typed_assocs
)
in walk 0 lit
let of_payload = function
| Ast.MLit lit -> of_literal lit
| Ast.MVar id -> of_ann_id id
let of_pattern pat =
let rec of_pattern_aux ~top_parens = function
| Ast.Wildcard -> !^"_"
| Ast.Binder id -> of_ann_id id
| Ast.Constructor (constr_id, pats) ->
let constr_id = of_ann_id constr_id in
if List.is_empty pats then
constr_id
else
let constr_args = separate_map (break 1) (of_pattern_aux ~top_parens:true) pats in
parens_if top_parens (constr_id ^//^ constr_args)
in
of_pattern_aux ~top_parens:false pat
let rec of_expr (expr, _ann, comments) =
(match expr with
| Ast.Literal lit -> of_literal lit
| Ast.Var id -> of_ann_id id
| Ast.Fun (id, typ, body) ->
(* TODO: nested functions should not be indented:
fun (a : String) =>
fun (s : Uint32) => ...
vs
fun (a : String) =>
fun (s : Uint32) => ...
*)
let body = of_expr body in
fun ( $ i d : ) = >
$ body
$body *)
fun_kwd ^^^ parens (of_typed_ann_id id typ) ^^^ darrow ^^ indent (hardline ^^ body)
| Ast.App (fid, args) ->
let fid = of_ann_id fid
and args = of_ann_ids args in
fid ^//^ args
| Ast.Builtin ((builtin, _ann), _types, typed_ids) ->
let builtin = of_builtin builtin
and args = of_ann_ids typed_ids in
builtin_kwd ^^^ builtin ^//^ args
| Ast.Let (id, otyp, lhs, body) ->
let id =
match otyp with
| None -> of_ann_id id
| Some typ -> of_typed_ann_id id typ
and lhs = of_expr lhs
and body = of_expr body in
TODO :
Need special case for expressions like this one :
let succ =
let b1 = andb sum_test mul_test in
andb paired_test b1
in
...
Now these are displayed as follows :
let succ = let b1 = andb sum_test mul_test in andb paired_test b1 in ...
For instance , forcing a hard newline for LHS should work here :
let foo =
$ lhs
in
$ body
But , in general , things like
let x = Uint 42 in ...
would look weird .
TODO:
Need special case for expressions like this one:
let succ =
let b1 = andb sum_test mul_test in
andb paired_test b1
in
...
Now these are displayed as follows:
let succ = let b1 = andb sum_test mul_test in andb paired_test b1 in ...
For instance, forcing a hard newline for LHS should work here:
let foo =
$lhs
in
$body
But, in general, things like
let x = Uint 42 in ...
would look weird.
*)
(group (group (let_kwd ^^^ id ^^^ equals ^//^ lhs) ^/^ in_kwd)) ^/^ body
| Ast.TFun (ty_var, body) ->
let ty_var = of_ann_id ty_var
and body = of_expr body in
(* tfun $ty_var => $body *)
( ^/^ ) -- means concat with _ breakable _ space
tfun_kwd ^^^ ty_var ^^^ darrow ^//^ body
| Ast.TApp (id, typs) ->
let tfid = of_ann_id id
TODO : remove unnecessary parens around primitive types :
e.g. " " does not need parens but " forall ' X. ' X " needs them in type applications
e.g. "Nat" does not need parens but "forall 'X. 'X" needs them in type applications *)
and typs = separate_map space (fun typ -> parens @@ of_type typ) typs in
at ^^ tfid ^//^ typs
| Ast.MatchExpr (ident, branches) ->
match_kwd ^^^ of_ann_id ident ^^^ with_kwd ^/^
separate_map hardline
(fun (pat, e, cs) ->
let doc =
pipe ^^^ of_pattern pat ^^^ darrow
in
let doc = if not @@ List.is_empty cs then
doc ^^^ concat_comments ~sep:space cs
else doc
in
let doc = doc ^//^ group (of_expr e) in
group (doc))
branches
^^ hardline ^^ end_kwd
| Ast.Constr (id, typs, args) ->
let id = of_ann_id id
(* TODO: remove unnecessary parens around primitive types *)
and args_doc = of_ann_ids args in
if Base.List.is_empty typs then
if Base.List.is_empty args then id else id ^//^ args_doc
else
let typs = separate_map space (fun typ -> parens @@ of_type typ) typs in
if Base.List.is_empty args then
id ^//^ braces typs
else
id ^//^ braces typs ^//^ args_doc
| Ast.Message assocs ->
surround indentation 1
lbrace
(separate_map
(semi ^^ break 1)
(fun (field, value) -> !^field ^^^ colon ^^^ of_payload value)
assocs)
rbrace
| Fixpoint _ -> failwith "Fixpoints cannot appear in user contracts"
| GasExpr _ -> failwith "Gas annotations cannot appear in user contracts's expressions"
) |> wrap_comments comments
let of_map_access map keys =
let map = of_ann_id map
and keys = concat_map (fun k -> brackets @@ of_ann_id k) keys in
map ^^ keys
let rec of_stmt (stmt, _ann, comments) =
(match stmt with
| Ast.Load (id, field) ->
of_ann_id id ^^^ rev_arrow ^//^ of_ann_id field
| Ast.RemoteLoad (id, addr, field) ->
of_ann_id id ^^^ blockchain_arrow ^//^ of_ann_id addr ^^ dot ^^ of_ann_id field
| Ast.Store (field, id) ->
of_ann_id field ^^^ assign ^//^ of_ann_id id
| Ast.Bind (id, expr) ->
of_ann_id id ^^^ equals ^//^ of_expr expr
| Ast.MapUpdate (map, keys, mode) ->
(* m[k1][k2][..] := v OR delete m[k1][k2][...] *)
(match mode with
| Some value -> of_map_access map keys ^^^ assign ^//^ of_ann_id value
| None -> delete_kwd ^^^ of_map_access map keys)
| Ast.MapGet (id, map, keys, mode) ->
(* v <- m[k1][k2][...] OR b <- exists m[k1][k2][...] *)
(* If the bool is set, then we interpret this as value retrieve,
otherwise as an "exists" query. *)
if mode then
of_ann_id id ^^^ rev_arrow ^//^ of_map_access map keys
else
of_ann_id id ^^^ rev_arrow ^//^ exists_kwd ^^^ of_map_access map keys
| Ast.RemoteMapGet (id, addr, map, keys, mode) ->
(* v <-& adr.m[k1][k2][...] OR b <-& exists adr.m[k1][k2][...] *)
(* If the bool is set, then we interpret this as value retrieve,
otherwise as an "exists" query. *)
if mode then
of_ann_id id ^^^ blockchain_arrow ^//^ of_ann_id addr ^^ dot ^^ of_map_access map keys
else
of_ann_id id ^^^ blockchain_arrow ^//^ exists_kwd ^^^ of_ann_id addr ^^ dot ^^ of_map_access map keys
| Ast.MatchStmt (id, branches) ->
match_kwd ^^^ of_ann_id id ^^^ with_kwd ^/^
separate_map hardline
(fun (pat, stmts, cs) ->
let doc = pipe ^^^ of_pattern pat ^^^ darrow in
let doc = if not @@ List.is_empty cs then
doc ^^^ concat_comments ~sep:space cs
else doc
in
let doc = doc ^//^ group (of_stmts stmts) in
group (doc))
branches
^^ hardline ^^ end_kwd
| Ast.ReadFromBC (id, query) ->
let query =
match query with
| CurBlockNum -> blocknumber_kwd
| ChainID -> chainid_kwd
| Timestamp ts -> timestamp_kwd ^^ parens (of_ann_id ts)
| ReplicateContr (addr, init_params) ->
replicate_contract_kwd ^^ parens (of_ann_id addr ^^ comma ^^^ of_ann_id init_params)
in
of_ann_id id ^^^ blockchain_arrow ^//^ query
| Ast.TypeCast (id, addr, typ) ->
of_ann_id id ^^^ blockchain_arrow ^//^ of_ann_id addr ^^^ as_kwd ^^^ of_type typ
| Ast.AcceptPayment ->
accept_kwd
| Ast.Return id ->
!^"_return" ^//^ assign ^//^ of_ann_id id
| Ast.Iterate (arg_list, proc) ->
(* forall l p *)
forall_kwd ^//^ of_ann_id arg_list ^//^ of_ann_id proc
| Ast.SendMsgs msgs ->
send_kwd ^//^ of_ann_id msgs
| Ast.CreateEvnt events ->
event_kwd ^//^ of_ann_id events
| Ast.CallProc (id_opt, proc, args) ->
let call =
if List.is_empty args then of_ann_id proc
else of_ann_id proc ^//^ of_ann_ids args
in
(match id_opt with
| None -> call
| Some id -> of_ann_id id ^^^ equals ^//^ call)
| Ast.Throw oexc ->
(match oexc with
| None -> throw_kwd
| Some exc -> throw_kwd ^//^ of_ann_id exc)
| Ast.GasStmt _ -> failwith "Gas annotations cannot appear in user contracts's statements"
) |> wrap_comments comments
and of_stmts stmts =
separate_map (semi ^^ hardline) (fun s -> of_stmt s) stmts
(* contract, transition, procedure parameters *)
let of_parameters typed_params ~sep =
surround indentation 0
lparen
(separate_map
(comma ^^ sep)
(fun (p, typ) -> of_typed_ann_id p typ)
typed_params)
rparen
let of_component Ast.{comp_comments; comp_type; comp_name; comp_params; comp_body; comp_return} =
let comp_type = !^(Syntax.component_type_to_string comp_type)
and comp_name = of_ann_id comp_name
and comp_params = of_parameters comp_params ~sep:(break 1)
and comp_body = of_stmts comp_body in
let signature = match comp_return with
| None ->
(group (comp_type ^^^ comp_name ^//^ comp_params))
| Some ty ->
(group (comp_type ^^^ comp_name ^//^ comp_params ^//^ colon ^//^ of_type ty))
in
concat_comments comp_comments ^^ signature ^^
indent (hardline ^^ comp_body) ^^ hardline ^^
end_kwd
let of_ctr_def Ast.{cname; c_comments; c_arg_types} =
let constructor_name = of_ann_id cname
and constructor_args_types =
(* TODO: break sequences of long types (e.g. ByStr20 with contract ................... end Uint256 is unreadable) *)
of_types ~sep:(break 1) c_arg_types
in
if List.is_empty c_arg_types then
constructor_name
^//^ concat_comments ~sep:space c_comments
else
align (group (constructor_name ^//^ of_kwd) ^//^
constructor_args_types ^//^
concat_comments ~sep:space c_comments)
let of_lib_entry = function
| Ast.LibVar (comments, definition, otyp, expr) ->
let definition =
match otyp with
| None -> of_ann_id definition
| Some typ -> of_typed_ann_id definition typ
and expr = of_expr expr in
concat_comments comments ^^
let_kwd ^^^ definition ^^^ equals ^//^ expr
| Ast.LibTyp (comments, typ_name, constr_defs) ->
let typ_name = of_ann_id typ_name
and constr_defs =
separate_map hardline (fun cd -> pipe ^^^ of_ctr_def cd) constr_defs
in
concat_comments comments ^^
type_kwd ^^^ typ_name ^^^ equals ^^ hardline ^^
constr_defs
let of_library Ast.{lname; lentries} =
library_kwd ^^^ of_ann_id lname ^^
if List.is_empty lentries then hardline
else
let lentries =
separate_map
(twice hardline)
(fun lentry -> of_lib_entry lentry)
lentries
in
twice hardline ^^ lentries ^^ hardline
let of_contract Ast.{cname; cparams; cconstraint; cfields; ccomps} =
let cname = of_ann_id cname
and cparams = of_parameters cparams ~sep:hardline
and cconstraint =
let true_ctr = Lit.LType.TIdentifier.Name.parse_simple_name "True" in
match cconstraint with
| (Ast.Literal (Lit.ADTValue (c, [], [])), _annot, _comment) when [%equal: _] c true_ctr ->
(* trivially True contract constraint does not get rendered *)
empty
| _ ->
with_kwd ^^
indent (hardline ^^ of_expr cconstraint) ^^ hardline ^^
darrow ^^ hardline
and cfields =
if List.is_empty cfields then empty
else
separate_map
(twice hardline)
(fun (comments, field, typ, init) ->
concat_comments comments ^^
field_kwd ^^^ of_typed_ann_id field typ ^^^ equals ^//^ of_expr init)
cfields
^^ twice hardline
and ccomps =
separate_map (twice hardline) (fun c -> of_component c) ccomps
in
contract_kwd ^^^ (cname ^//^ cparams) ^^ hardline ^^
cconstraint ^^ twice hardline ^^
cfields ^^
ccomps
let of_contract_module Ast.{smver; file_comments; lib_comments; libs; elibs; contr_comments; contr} =
let imports =
let import_lib (lib, onamespace) =
match onamespace with
| None -> of_ann_id lib
| Some namespace -> of_ann_id lib ^^^ as_kwd ^^^ of_ann_id namespace
in
let imported_libs =
separate_map (hardline) (fun imp -> import_lib imp) elibs
in
if List.is_empty elibs then empty
else group (import_kwd ^//^ imported_libs) ^^ twice hardline
and contract_library =
match libs with
| Some lib -> of_library lib ^^ twice hardline
| None -> empty
in
scilla_version_kwd ^^^ !^(Int.to_string smver) ^^ hardline ^^
concat_comments file_comments ^^
hardline ^^
imports ^^
concat_comments lib_comments ^^
contract_library ^^
concat_comments contr_comments ^^
of_contract contr ^^ hardline
end
(* format width *)
let width = 80
let doc2str : PPrint.document -> string =
fun doc ->
let buffer = Buffer.create 100 in
PPrint.ToBuffer.pretty 1.0 width buffer doc;
Buffer.contents buffer
let type_to_string t = doc2str @@ Doc.of_type t
let expr_to_string e = doc2str @@ Doc.of_expr e
let contract_to_string c = doc2str @@ Doc.of_contract_module c
end
[@@@ocamlformat "enable"]
module LocalLiteralSyntax =
Format (ParserUtil.ParserRep) (ParserUtil.ParserRep) (Literal.LocalLiteral)
| null | https://raw.githubusercontent.com/Zilliqa/scilla/8880cadf4c317415dc808fce004e5e06a33492d0/src/formatter/Formatter.ml | ocaml | instantiated syntax extended with comments
-- helpers --
number of spaces to indent
Add parentheses only if the condition if true
Wrap document in comment symbols
* Add formatted [comments] around [doc].
TODO: temporary solution
This cannot happen in source code
Any address in use
Address containing a library
Address containing a library or contract
Address containing a contract
whitespace-separated non-primitive types need to be parenthesized
TODO: remove unneeded parens around types
we ignore type information here
TODO: nested functions should not be indented:
fun (a : String) =>
fun (s : Uint32) => ...
vs
fun (a : String) =>
fun (s : Uint32) => ...
tfun $ty_var => $body
TODO: remove unnecessary parens around primitive types
m[k1][k2][..] := v OR delete m[k1][k2][...]
v <- m[k1][k2][...] OR b <- exists m[k1][k2][...]
If the bool is set, then we interpret this as value retrieve,
otherwise as an "exists" query.
v <-& adr.m[k1][k2][...] OR b <-& exists adr.m[k1][k2][...]
If the bool is set, then we interpret this as value retrieve,
otherwise as an "exists" query.
forall l p
contract, transition, procedure parameters
TODO: break sequences of long types (e.g. ByStr20 with contract ................... end Uint256 is unreadable)
trivially True contract constraint does not get rendered
format width |
This file is part of scilla .
Copyright ( c ) 2018 - present Zilliqa Research Pvt . Ltd.
scilla 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 .
scilla 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
scilla . If not , see < / > .
This file is part of scilla.
Copyright (c) 2018 - present Zilliqa Research Pvt. Ltd.
scilla 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.
scilla 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
scilla. If not, see </>.
*)
* code formatter
open Scilla_base
open Base
open PPrint
[@@@ocamlformat "disable"]
module Format (SR : Syntax.Rep) (ER : Syntax.Rep) (Lit : Literal.ScillaLiteral) =
struct
module Ast = ExtendedSyntax.ExtendedScillaSyntax (SR) (ER) (Lit)
module type DOC = sig
val of_type : Ast.SType.t -> PPrint.document
val of_expr : Ast.expr_annot -> PPrint.document
val of_literal : Lit.t -> PPrint.document
val of_contract_module : Ast.cmodule -> PPrint.document
end
module Doc : DOC = struct
let indentation = 2
let forall_kwd = !^"forall"
let empy_map_kwd = !^"Emp"
let fun_kwd = !^"fun"
let tfun_kwd = !^"tfun"
let in_kwd = !^"in"
let let_kwd = !^"let"
let map_kwd = !^"Map"
let builtin_kwd = !^"builtin"
let match_kwd = !^"match"
let with_kwd = !^"with"
let end_kwd = !^"end"
let delete_kwd = !^"delete"
let exists_kwd = !^"exists"
let accept_kwd = !^"accept"
let as_kwd = !^"as"
let send_kwd = !^"send"
let event_kwd = !^"event"
let throw_kwd = !^"throw"
let contract_kwd = !^"contract"
let field_kwd = !^"field"
let of_kwd = !^"of"
let type_kwd = !^"type"
let import_kwd = !^"import"
let library_kwd = !^"library"
let scilla_version_kwd = !^"scilla_version"
let blocknumber_kwd = !^"BLOCKNUMBER"
let chainid_kwd = !^"CHAINID"
let timestamp_kwd = !^"TIMESTAMP"
let replicate_contract_kwd = !^"REPLICATE_CONTRACT"
let arrow = !^"->"
let darrow = !^"=>"
let at = !^"@"
let pipe = !^"|"
let rev_arrow = !^"<-"
let assign = !^":="
let blockchain_arrow = !^"<-&"
* concat two documents with an unbreakable space
let ( ^^^ ) left right = left ^^ space ^^ right
let indent doc = nest indentation doc
redefine PPrint 's shorthand to allow changing indentation
let ( ^//^ ) left right = prefix indentation 1 left right
let parens_if cond doc = if cond then parens doc else doc
let comment = enclose !^"(*" !^"*)"
multiple comments to a single comment .
let concat_comments ?(sep=hardline) cs =
List.fold_left cs ~init:[] ~f:(fun acc c -> acc @ [comment !^c])
|> concat_map (fun c -> c ^^^ sep)
let wrap_comments comments doc =
let spaced s =
let has_prefix prefix = String.is_prefix s ~prefix in
let has_suffix suffix = String.is_suffix s ~suffix in
let s = if has_prefix " " || has_prefix "*" then s else " " ^ s in
let s = if has_suffix " " || has_suffix "*" then s else s ^ " " in
s
in
let left, above, right =
List.fold_left comments
~init:([],[],[])
~f:(fun (acc_l, acc_a, acc_r) -> function
| (_, s, Ast.ComLeft) ->
acc_l @ [comment !^(spaced s); space], acc_a, acc_r
| (_, s, Ast.ComAbove) ->
acc_l, (comment !^(spaced s))::acc_a, acc_r
| (_, s, Ast.ComRight) ->
acc_l, acc_a, [space; comment !^(spaced s)] @ acc_r)
|> fun (l, a, r) ->
let a' = if List.is_empty a then empty
else (concat_map (fun c -> c ^^^ hardline) a)
in
let l' = concat l in
let r' = concat r in
l', a', r'
in
concat [above; left; doc; right]
let of_builtin b = !^(Syntax.pp_builtin b)
let of_id id = !^(Ast.SIdentifier.as_error_string id)
let of_ann_id (id, comments) = of_id id |> wrap_comments comments
let of_ann_ids ids =
separate_map space of_ann_id ids
let rec of_type_with_prec p typ =
let open Ast.SType in
match typ with
| TypeVar tv -> !^tv
| FunType (at, vt) ->
parens_if (p > 0) @@ group ((of_type_with_prec 1 at) ^^^ arrow) ^/^ (of_type_with_prec 0 vt)
TODO : test MapType and PolyFun pretty - printing
| MapType (kt, vt) ->
parens_if (p > 0) @@ map_kwd ^//^ (of_type_with_prec 1 kt) ^/^ (of_type_with_prec 1 vt)
| PolyFun (tv, bt) ->
parens_if (p > 0) @@ forall_kwd ^^^ !^tv ^^ dot ^//^ (of_type_with_prec 0 bt)
| ADT (tid, tys) ->
let ty_cons = of_id tid in
let ty_args = separate_map space (of_type_with_prec 1) tys in
if List.is_empty tys then ty_cons
else parens_if (p > 0) @@ ty_cons ^//^ ty_args
| Address addr_kind -> of_addr_kind p addr_kind
and of_type typ = of_type_with_prec 0 typ
and of_addr_kind p kind =
parens_if (p > 0) @@
match kind with
| AnyAddr -> !^"ByStr20 with end"
| LibAddr -> !^"ByStr20 with library end"
| CodeAddr -> !^"ByStr20 with _codehash end"
| ContrAddr fields_map ->
let alist = Ast.SType.IdLoc_Comp.Map.to_alist fields_map in
let contract_fields =
separate_map
(comma ^^ break 1)
(fun (f, ty) -> group (field_kwd ^/^ of_id f ^/^ colon ^/^ of_type ty))
alist
in
if List.is_empty alist then !^"ByStr20 with contract end"
else
surround indentation 1
!^"ByStr20 with contract"
contract_fields
end_kwd
let of_types typs ~sep =
group @@ separate_map sep (fun ty -> of_type_with_prec 1 ty) typs
let of_typed_ann_id id typ = of_ann_id id ^^^ colon ^//^ group (of_type typ)
let rec of_literal lit =
let rec walk p = function
| Lit.StringLit s ->
!^[%string "\"$(String.escaped s)\""]
| Lit.IntLit i ->
let bit_width = Int.to_string @@ Lit.int_lit_width i in
let value = Lit.string_of_int_lit i in
parens_if (p > 0) @@ !^[%string "Int$(bit_width) $value"]
| Lit.UintLit i ->
let bit_width = Int.to_string @@ Lit.uint_lit_width i in
let value = Lit.string_of_uint_lit i in
parens_if (p > 0) @@ !^[%string "Uint$(bit_width) $value"]
| Lit.BNum b ->
let value = Literal.BNumLit.get b in
parens_if (p > 0) @@ !^[%string "BNum $value"]
| Lit.ByStr _bs ->
failwith "Pretty-printing of ByStr literals in expressions cannot happen"
AFAIR , there is no way in to have ByStr literals in expressions .
We might need to print the result of evaluation but there is a pretty printer for values
We might need to print the result of evaluation but there is a pretty printer for values *)
| Lit.ByStrX bsx ->
!^[%string "$(Lit.Bystrx.hex_encoding bsx)"]
| Lit.Clo _ -> !^"<closure>"
| Lit.TAbs _ -> !^"<type_closure>"
| Lit.ADTValue (name, _tys, lits) ->
let constructor = !^(Lit.LType.TIdentifier.Name.as_error_string name) in
if List.is_empty lits then
constructor
else
let cons_params = separate_map space (walk 1) lits in
parens_if (p > 0) @@ constructor ^//^ cons_params
| Lit.Map ((key_type, value_type), table) ->
if Caml.Hashtbl.length table = 0 then
let kt = of_type key_type
and vt = of_type value_type in
parens_if (p > 0) @@ empy_map_kwd ^//^ (parens kt) ^/^ (parens vt)
else
failwith "Pretty-printing of non-empty map literals cannot happen while printing expressions"
| Lit.Msg typed_assocs ->
braces (
separate_map
(semi ^^ break 1)
(fun (field, _typ, value) -> !^field ^^^ colon ^^^ of_literal value)
typed_assocs
)
in walk 0 lit
let of_payload = function
| Ast.MLit lit -> of_literal lit
| Ast.MVar id -> of_ann_id id
let of_pattern pat =
let rec of_pattern_aux ~top_parens = function
| Ast.Wildcard -> !^"_"
| Ast.Binder id -> of_ann_id id
| Ast.Constructor (constr_id, pats) ->
let constr_id = of_ann_id constr_id in
if List.is_empty pats then
constr_id
else
let constr_args = separate_map (break 1) (of_pattern_aux ~top_parens:true) pats in
parens_if top_parens (constr_id ^//^ constr_args)
in
of_pattern_aux ~top_parens:false pat
let rec of_expr (expr, _ann, comments) =
(match expr with
| Ast.Literal lit -> of_literal lit
| Ast.Var id -> of_ann_id id
| Ast.Fun (id, typ, body) ->
let body = of_expr body in
fun ( $ i d : ) = >
$ body
$body *)
fun_kwd ^^^ parens (of_typed_ann_id id typ) ^^^ darrow ^^ indent (hardline ^^ body)
| Ast.App (fid, args) ->
let fid = of_ann_id fid
and args = of_ann_ids args in
fid ^//^ args
| Ast.Builtin ((builtin, _ann), _types, typed_ids) ->
let builtin = of_builtin builtin
and args = of_ann_ids typed_ids in
builtin_kwd ^^^ builtin ^//^ args
| Ast.Let (id, otyp, lhs, body) ->
let id =
match otyp with
| None -> of_ann_id id
| Some typ -> of_typed_ann_id id typ
and lhs = of_expr lhs
and body = of_expr body in
TODO :
Need special case for expressions like this one :
let succ =
let b1 = andb sum_test mul_test in
andb paired_test b1
in
...
Now these are displayed as follows :
let succ = let b1 = andb sum_test mul_test in andb paired_test b1 in ...
For instance , forcing a hard newline for LHS should work here :
let foo =
$ lhs
in
$ body
But , in general , things like
let x = Uint 42 in ...
would look weird .
TODO:
Need special case for expressions like this one:
let succ =
let b1 = andb sum_test mul_test in
andb paired_test b1
in
...
Now these are displayed as follows:
let succ = let b1 = andb sum_test mul_test in andb paired_test b1 in ...
For instance, forcing a hard newline for LHS should work here:
let foo =
$lhs
in
$body
But, in general, things like
let x = Uint 42 in ...
would look weird.
*)
(group (group (let_kwd ^^^ id ^^^ equals ^//^ lhs) ^/^ in_kwd)) ^/^ body
| Ast.TFun (ty_var, body) ->
let ty_var = of_ann_id ty_var
and body = of_expr body in
( ^/^ ) -- means concat with _ breakable _ space
tfun_kwd ^^^ ty_var ^^^ darrow ^//^ body
| Ast.TApp (id, typs) ->
let tfid = of_ann_id id
TODO : remove unnecessary parens around primitive types :
e.g. " " does not need parens but " forall ' X. ' X " needs them in type applications
e.g. "Nat" does not need parens but "forall 'X. 'X" needs them in type applications *)
and typs = separate_map space (fun typ -> parens @@ of_type typ) typs in
at ^^ tfid ^//^ typs
| Ast.MatchExpr (ident, branches) ->
match_kwd ^^^ of_ann_id ident ^^^ with_kwd ^/^
separate_map hardline
(fun (pat, e, cs) ->
let doc =
pipe ^^^ of_pattern pat ^^^ darrow
in
let doc = if not @@ List.is_empty cs then
doc ^^^ concat_comments ~sep:space cs
else doc
in
let doc = doc ^//^ group (of_expr e) in
group (doc))
branches
^^ hardline ^^ end_kwd
| Ast.Constr (id, typs, args) ->
let id = of_ann_id id
and args_doc = of_ann_ids args in
if Base.List.is_empty typs then
if Base.List.is_empty args then id else id ^//^ args_doc
else
let typs = separate_map space (fun typ -> parens @@ of_type typ) typs in
if Base.List.is_empty args then
id ^//^ braces typs
else
id ^//^ braces typs ^//^ args_doc
| Ast.Message assocs ->
surround indentation 1
lbrace
(separate_map
(semi ^^ break 1)
(fun (field, value) -> !^field ^^^ colon ^^^ of_payload value)
assocs)
rbrace
| Fixpoint _ -> failwith "Fixpoints cannot appear in user contracts"
| GasExpr _ -> failwith "Gas annotations cannot appear in user contracts's expressions"
) |> wrap_comments comments
let of_map_access map keys =
let map = of_ann_id map
and keys = concat_map (fun k -> brackets @@ of_ann_id k) keys in
map ^^ keys
let rec of_stmt (stmt, _ann, comments) =
(match stmt with
| Ast.Load (id, field) ->
of_ann_id id ^^^ rev_arrow ^//^ of_ann_id field
| Ast.RemoteLoad (id, addr, field) ->
of_ann_id id ^^^ blockchain_arrow ^//^ of_ann_id addr ^^ dot ^^ of_ann_id field
| Ast.Store (field, id) ->
of_ann_id field ^^^ assign ^//^ of_ann_id id
| Ast.Bind (id, expr) ->
of_ann_id id ^^^ equals ^//^ of_expr expr
| Ast.MapUpdate (map, keys, mode) ->
(match mode with
| Some value -> of_map_access map keys ^^^ assign ^//^ of_ann_id value
| None -> delete_kwd ^^^ of_map_access map keys)
| Ast.MapGet (id, map, keys, mode) ->
if mode then
of_ann_id id ^^^ rev_arrow ^//^ of_map_access map keys
else
of_ann_id id ^^^ rev_arrow ^//^ exists_kwd ^^^ of_map_access map keys
| Ast.RemoteMapGet (id, addr, map, keys, mode) ->
if mode then
of_ann_id id ^^^ blockchain_arrow ^//^ of_ann_id addr ^^ dot ^^ of_map_access map keys
else
of_ann_id id ^^^ blockchain_arrow ^//^ exists_kwd ^^^ of_ann_id addr ^^ dot ^^ of_map_access map keys
| Ast.MatchStmt (id, branches) ->
match_kwd ^^^ of_ann_id id ^^^ with_kwd ^/^
separate_map hardline
(fun (pat, stmts, cs) ->
let doc = pipe ^^^ of_pattern pat ^^^ darrow in
let doc = if not @@ List.is_empty cs then
doc ^^^ concat_comments ~sep:space cs
else doc
in
let doc = doc ^//^ group (of_stmts stmts) in
group (doc))
branches
^^ hardline ^^ end_kwd
| Ast.ReadFromBC (id, query) ->
let query =
match query with
| CurBlockNum -> blocknumber_kwd
| ChainID -> chainid_kwd
| Timestamp ts -> timestamp_kwd ^^ parens (of_ann_id ts)
| ReplicateContr (addr, init_params) ->
replicate_contract_kwd ^^ parens (of_ann_id addr ^^ comma ^^^ of_ann_id init_params)
in
of_ann_id id ^^^ blockchain_arrow ^//^ query
| Ast.TypeCast (id, addr, typ) ->
of_ann_id id ^^^ blockchain_arrow ^//^ of_ann_id addr ^^^ as_kwd ^^^ of_type typ
| Ast.AcceptPayment ->
accept_kwd
| Ast.Return id ->
!^"_return" ^//^ assign ^//^ of_ann_id id
| Ast.Iterate (arg_list, proc) ->
forall_kwd ^//^ of_ann_id arg_list ^//^ of_ann_id proc
| Ast.SendMsgs msgs ->
send_kwd ^//^ of_ann_id msgs
| Ast.CreateEvnt events ->
event_kwd ^//^ of_ann_id events
| Ast.CallProc (id_opt, proc, args) ->
let call =
if List.is_empty args then of_ann_id proc
else of_ann_id proc ^//^ of_ann_ids args
in
(match id_opt with
| None -> call
| Some id -> of_ann_id id ^^^ equals ^//^ call)
| Ast.Throw oexc ->
(match oexc with
| None -> throw_kwd
| Some exc -> throw_kwd ^//^ of_ann_id exc)
| Ast.GasStmt _ -> failwith "Gas annotations cannot appear in user contracts's statements"
) |> wrap_comments comments
and of_stmts stmts =
separate_map (semi ^^ hardline) (fun s -> of_stmt s) stmts
let of_parameters typed_params ~sep =
surround indentation 0
lparen
(separate_map
(comma ^^ sep)
(fun (p, typ) -> of_typed_ann_id p typ)
typed_params)
rparen
let of_component Ast.{comp_comments; comp_type; comp_name; comp_params; comp_body; comp_return} =
let comp_type = !^(Syntax.component_type_to_string comp_type)
and comp_name = of_ann_id comp_name
and comp_params = of_parameters comp_params ~sep:(break 1)
and comp_body = of_stmts comp_body in
let signature = match comp_return with
| None ->
(group (comp_type ^^^ comp_name ^//^ comp_params))
| Some ty ->
(group (comp_type ^^^ comp_name ^//^ comp_params ^//^ colon ^//^ of_type ty))
in
concat_comments comp_comments ^^ signature ^^
indent (hardline ^^ comp_body) ^^ hardline ^^
end_kwd
let of_ctr_def Ast.{cname; c_comments; c_arg_types} =
let constructor_name = of_ann_id cname
and constructor_args_types =
of_types ~sep:(break 1) c_arg_types
in
if List.is_empty c_arg_types then
constructor_name
^//^ concat_comments ~sep:space c_comments
else
align (group (constructor_name ^//^ of_kwd) ^//^
constructor_args_types ^//^
concat_comments ~sep:space c_comments)
let of_lib_entry = function
| Ast.LibVar (comments, definition, otyp, expr) ->
let definition =
match otyp with
| None -> of_ann_id definition
| Some typ -> of_typed_ann_id definition typ
and expr = of_expr expr in
concat_comments comments ^^
let_kwd ^^^ definition ^^^ equals ^//^ expr
| Ast.LibTyp (comments, typ_name, constr_defs) ->
let typ_name = of_ann_id typ_name
and constr_defs =
separate_map hardline (fun cd -> pipe ^^^ of_ctr_def cd) constr_defs
in
concat_comments comments ^^
type_kwd ^^^ typ_name ^^^ equals ^^ hardline ^^
constr_defs
let of_library Ast.{lname; lentries} =
library_kwd ^^^ of_ann_id lname ^^
if List.is_empty lentries then hardline
else
let lentries =
separate_map
(twice hardline)
(fun lentry -> of_lib_entry lentry)
lentries
in
twice hardline ^^ lentries ^^ hardline
let of_contract Ast.{cname; cparams; cconstraint; cfields; ccomps} =
let cname = of_ann_id cname
and cparams = of_parameters cparams ~sep:hardline
and cconstraint =
let true_ctr = Lit.LType.TIdentifier.Name.parse_simple_name "True" in
match cconstraint with
| (Ast.Literal (Lit.ADTValue (c, [], [])), _annot, _comment) when [%equal: _] c true_ctr ->
empty
| _ ->
with_kwd ^^
indent (hardline ^^ of_expr cconstraint) ^^ hardline ^^
darrow ^^ hardline
and cfields =
if List.is_empty cfields then empty
else
separate_map
(twice hardline)
(fun (comments, field, typ, init) ->
concat_comments comments ^^
field_kwd ^^^ of_typed_ann_id field typ ^^^ equals ^//^ of_expr init)
cfields
^^ twice hardline
and ccomps =
separate_map (twice hardline) (fun c -> of_component c) ccomps
in
contract_kwd ^^^ (cname ^//^ cparams) ^^ hardline ^^
cconstraint ^^ twice hardline ^^
cfields ^^
ccomps
let of_contract_module Ast.{smver; file_comments; lib_comments; libs; elibs; contr_comments; contr} =
let imports =
let import_lib (lib, onamespace) =
match onamespace with
| None -> of_ann_id lib
| Some namespace -> of_ann_id lib ^^^ as_kwd ^^^ of_ann_id namespace
in
let imported_libs =
separate_map (hardline) (fun imp -> import_lib imp) elibs
in
if List.is_empty elibs then empty
else group (import_kwd ^//^ imported_libs) ^^ twice hardline
and contract_library =
match libs with
| Some lib -> of_library lib ^^ twice hardline
| None -> empty
in
scilla_version_kwd ^^^ !^(Int.to_string smver) ^^ hardline ^^
concat_comments file_comments ^^
hardline ^^
imports ^^
concat_comments lib_comments ^^
contract_library ^^
concat_comments contr_comments ^^
of_contract contr ^^ hardline
end
let width = 80
let doc2str : PPrint.document -> string =
fun doc ->
let buffer = Buffer.create 100 in
PPrint.ToBuffer.pretty 1.0 width buffer doc;
Buffer.contents buffer
let type_to_string t = doc2str @@ Doc.of_type t
let expr_to_string e = doc2str @@ Doc.of_expr e
let contract_to_string c = doc2str @@ Doc.of_contract_module c
end
[@@@ocamlformat "enable"]
module LocalLiteralSyntax =
Format (ParserUtil.ParserRep) (ParserUtil.ParserRep) (Literal.LocalLiteral)
|
cc116de9a2a36ee234f795415aabbd0570205e1246765ae22accb5de011d7247 | rametta/retros | Move.hs | module Web.View.Columns.Move where
import Web.View.Prelude
data MoveView = MoveView { column :: Column, retros :: [Retro] }
instance View MoveView where
html MoveView {..} =
renderModal
Modal
{ modalTitle = "Move Column",
modalCloseUrl = pathTo $ ShowRetroAction $ get #retroId column,
modalFooter = Nothing,
modalContent = renderForm column retros
}
instance CanSelect Retro where
type SelectValue Retro = Id Retro
selectValue = get #id
selectLabel = get #title
renderForm :: Column -> [Retro] -> Html
renderForm column retros =
formFor'
column
(pathTo MoveColumnToRetroAction { currentRetroId = get #retroId column, columnId = get #id column })
[hsx|
{(selectField #retroId filteredRetros) { autofocus = True, required = True, fieldLabel = "Move this column to a different Retro board", labelClass = "mt-4" }}
<div class="flex mb-0 py-1">
<button type="submit" class="mr-2 bg-green-500 hover:bg-green-600 text-white font-bold py-1 px-2 rounded transition duration-300">Move column</button>
<a href={ShowRetroAction $ get #retroId column} class="mr-2 block btn-gray">Cancel</a>
</div>
|]
where
filteredRetros = filter (\r -> get #id r /= get #retroId column) retros | null | https://raw.githubusercontent.com/rametta/retros/55da48d71a409638d3a828cf48ccfe29dc4fc5d6/Web/View/Columns/Move.hs | haskell | module Web.View.Columns.Move where
import Web.View.Prelude
data MoveView = MoveView { column :: Column, retros :: [Retro] }
instance View MoveView where
html MoveView {..} =
renderModal
Modal
{ modalTitle = "Move Column",
modalCloseUrl = pathTo $ ShowRetroAction $ get #retroId column,
modalFooter = Nothing,
modalContent = renderForm column retros
}
instance CanSelect Retro where
type SelectValue Retro = Id Retro
selectValue = get #id
selectLabel = get #title
renderForm :: Column -> [Retro] -> Html
renderForm column retros =
formFor'
column
(pathTo MoveColumnToRetroAction { currentRetroId = get #retroId column, columnId = get #id column })
[hsx|
{(selectField #retroId filteredRetros) { autofocus = True, required = True, fieldLabel = "Move this column to a different Retro board", labelClass = "mt-4" }}
<div class="flex mb-0 py-1">
<button type="submit" class="mr-2 bg-green-500 hover:bg-green-600 text-white font-bold py-1 px-2 rounded transition duration-300">Move column</button>
<a href={ShowRetroAction $ get #retroId column} class="mr-2 block btn-gray">Cancel</a>
</div>
|]
where
filteredRetros = filter (\r -> get #id r /= get #retroId column) retros |
|
77a8fa82e5b6728907dfa800e9201f12a7f10707bd1586e796ad1044fe8023e8 | techascent/tvm-clj | vision.clj | (ns tvm-clj.impl.fns.topi.vision
(:require [tvm-clj.impl.tvm-ns-fns :as tvm-ns-fns]))
(tvm-ns-fns/export-tvm-functions "topi.vision") | null | https://raw.githubusercontent.com/techascent/tvm-clj/1088845bd613b4ba14b00381ffe3cdbd3d8b639e/src/tvm_clj/impl/fns/topi/vision.clj | clojure | (ns tvm-clj.impl.fns.topi.vision
(:require [tvm-clj.impl.tvm-ns-fns :as tvm-ns-fns]))
(tvm-ns-fns/export-tvm-functions "topi.vision") |
|
ff39571901ab29dd917fcc1a7f56d852e893695df122817f0ad993fe4d12a800 | modular-macros/ocaml-macros | types.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** {0 Representation of types and declarations} *)
* [ Types ] defines the representation of types and declarations ( that is , the
content of module signatures ) .
CMI files are made of marshalled types .
content of module signatures).
CMI files are made of marshalled types.
*)
* exposes basic definitions shared both by Parsetree and Types .
open Asttypes
* Type expressions for the core language .
The [ type_desc ] variant defines all the possible type expressions one can
find in OCaml . [ type_expr ] wraps this with some annotations .
The [ level ] field tracks the level of polymorphism associated to a type ,
guiding the generalization algorithm .
Put shortly , when referring to a type in a given environment , both the type
and the environment have a level . If the type has an higher level , then it
can be considered fully polymorphic ( type variables will be printed as
[ ' a ] ) , otherwise it 'll be weakly polymorphic , or non generalized ( type
variables printed as [ ' _ a ] ) .
See [ ] for more information .
Note about [ type_declaration ] : one should not make the confusion between
[ type_expr ] and [ type_declaration ] .
[ type_declaration ] refers specifically to the [ type ] construct in OCaml
language , where you create and name a new type or type alias .
[ type_expr ] is used when you refer to existing types , e.g. when annotating
the expected type of a value .
Also , as the type system of OCaml is generative , a [ type_declaration ] can
have the side - effect of introducing a new type constructor , different from
all other known types .
Whereas [ type_expr ] is a pure construct which allows referring to existing
types .
Note on mutability : TBD .
The [type_desc] variant defines all the possible type expressions one can
find in OCaml. [type_expr] wraps this with some annotations.
The [level] field tracks the level of polymorphism associated to a type,
guiding the generalization algorithm.
Put shortly, when referring to a type in a given environment, both the type
and the environment have a level. If the type has an higher level, then it
can be considered fully polymorphic (type variables will be printed as
['a]), otherwise it'll be weakly polymorphic, or non generalized (type
variables printed as ['_a]).
See [] for more information.
Note about [type_declaration]: one should not make the confusion between
[type_expr] and [type_declaration].
[type_declaration] refers specifically to the [type] construct in OCaml
language, where you create and name a new type or type alias.
[type_expr] is used when you refer to existing types, e.g. when annotating
the expected type of a value.
Also, as the type system of OCaml is generative, a [type_declaration] can
have the side-effect of introducing a new type constructor, different from
all other known types.
Whereas [type_expr] is a pure construct which allows referring to existing
types.
Note on mutability: TBD.
*)
type type_expr =
{ mutable desc: type_desc;
mutable level: int;
id: int }
and type_desc =
| Tvar of string option
(** [Tvar (Some "a")] ==> ['a] or ['_a]
[Tvar None] ==> [_] *)
| Tarrow of arg_label * type_expr * type_expr * commutable
* [ ( Nolabel , e1 , e2 , c ) ] = = > [ e1 - > e2 ]
[ ( Labelled " l " , e1 , e2 , c ) ] = = > [ l : e1 - > e2 ]
[ ( Optional " l " , e1 , e2 , c ) ] = = > [ ? l : e1 - > e2 ]
See [ commutable ] for the last argument .
[Tarrow (Labelled "l", e1, e2, c)] ==> [l:e1 -> e2]
[Tarrow (Optional "l", e1, e2, c)] ==> [?l:e1 -> e2]
See [commutable] for the last argument. *)
| Ttuple of type_expr list
* [ [ t1; ... ;tn ] ] = = > [ ( t1 * ... * tn ) ]
| Tconstr of Path.t * type_expr list * abbrev_memo ref
* [ Tconstr ( ` A.B.t ' , [ t1; ... ;tn ] , _ ) ] = = > [ ( t1, ... ,tn ) A.B.t ]
The last parameter keep tracks of known expansions , see [ abbrev_memo ] .
The last parameter keep tracks of known expansions, see [abbrev_memo]. *)
| Tobject of type_expr * (Path.t * type_expr list) option ref
* [ Tobject ( ` f1 : t1; ... ;fn : tn ' , ` None ' ) ] = = > [ < f1 : t1 ; ... ; fn : tn > ]
f1 , fn are represented as a linked list of types using and
constructors .
[ Tobject ( _ , ` Some ( ` A.ct ' , [ t1; ... ;tn ] ' ) ] = = > [ ( t1 , ... , tn ) A.ct ] .
where A.ct is the type of some class .
There are also special cases for so - called " class - types " , cf . [ ]
and [ Ctype.set_object_name ] :
[ Tobject ( Tfield(_,_, ... (Tfield(_,_,rv ) ... ) ,
Some(`A.#ct ` , [ rv;t1; ... ;tn ] ) ]
= = > [ ( t1 , ... , tn ) # A.ct ]
[ Tobject ( _ , Some(`A.#ct ` , [ Tnil;t1; ... ;tn ] ) ] = = > [ ( t1 , ... , tn ) A.ct ]
where [ rv ] is the hidden row variable .
f1, fn are represented as a linked list of types using Tfield and Tnil
constructors.
[Tobject (_, `Some (`A.ct', [t1;...;tn]')] ==> [(t1, ..., tn) A.ct].
where A.ct is the type of some class.
There are also special cases for so-called "class-types", cf. [Typeclass]
and [Ctype.set_object_name]:
[Tobject (Tfield(_,_,...(Tfield(_,_,rv)...),
Some(`A.#ct`, [rv;t1;...;tn])]
==> [(t1, ..., tn) #A.ct]
[Tobject (_, Some(`A.#ct`, [Tnil;t1;...;tn])] ==> [(t1, ..., tn) A.ct]
where [rv] is the hidden row variable.
*)
| Tfield of string * field_kind * type_expr * type_expr
* [ ( " foo " , , t , ts ) ] = = > [ < ... ; foo : t ; ts > ]
| Tnil
* [ ] = = > [ < ... ; > ]
| Tlink of type_expr
(** Indirection used by unification engine. *)
| Tsubst of type_expr (* for copying *)
(** [Tsubst] is used temporarily to store information in low-level
functions manipulating representation of types, such as
instantiation or copy.
This constructor should not appear outside of these cases. *)
| Tvariant of row_desc
(** Representation of polymorphic variants, see [row_desc]. *)
| Tunivar of string option
(** Occurrence of a type variable introduced by a
forall quantifier / [Tpoly]. *)
| Tpoly of type_expr * type_expr list
(** [Tpoly (ty,tyl)] ==> ['a1... 'an. ty],
where 'a1 ... 'an are names given to types in tyl
and occurences of those types in ty. *)
| Tpackage of Path.t * Longident.t list * type_expr list
* Type of a first - class module ( a.k.a package ) .
* [ ` X | ` Y ] ( row_closed = true )
[ < ` X | ` Y ] ( row_closed = true )
[ > ` X | ` Y ] ( row_closed = false )
[ < ` X | ` Y > ` X ] ( row_closed = true )
type t = [ > ` X ] as ' a ( row_more = Tvar a )
type t = private [ > ` X ] ( row_more = Tconstr ( t#row , [ ] , ref Mnil )
And for :
let f = function ` X - > ` X - > | ` Y - > ` X
the type of " f " will be a [ Tarrow ] whose lhs will ( basically ) be :
Tvariant { row_fields = [ ( " X " , _ ) ] ;
row_more =
Tvariant { row_fields = [ ( " Y " , _ ) ] ;
row_more =
Tvariant { row_fields = [ ] ;
row_more = _ ;
_ } ;
_ } ;
_
}
[< `X | `Y ] (row_closed = true)
[> `X | `Y ] (row_closed = false)
[< `X | `Y > `X ] (row_closed = true)
type t = [> `X ] as 'a (row_more = Tvar a)
type t = private [> `X ] (row_more = Tconstr (t#row, [], ref Mnil)
And for:
let f = function `X -> `X -> | `Y -> `X
the type of "f" will be a [Tarrow] whose lhs will (basically) be:
Tvariant { row_fields = [("X", _)];
row_more =
Tvariant { row_fields = [("Y", _)];
row_more =
Tvariant { row_fields = [];
row_more = _;
_ };
_ };
_
}
*)
and row_desc =
{ row_fields: (label * row_field) list;
row_more: type_expr;
row_bound: unit; (* kept for compatibility *)
row_closed: bool;
row_fixed: bool;
row_name: (Path.t * type_expr list) option }
and row_field =
Rpresent of type_expr option
| Reither of bool * type_expr list * bool * row_field option ref
(* 1st true denotes a constant constructor *)
2nd true denotes a tag in a pattern matching , and
is erased later
is erased later *)
| Rabsent
(** [abbrev_memo] allows one to keep track of different expansions of a type
alias. This is done for performance purposes.
For instance, when defining [type 'a pair = 'a * 'a], when one refers to an
['a pair], it is just a shortcut for the ['a * 'a] type.
This expansion will be stored in the [abbrev_memo] of the corresponding
[Tconstr] node.
In practice, [abbrev_memo] behaves like list of expansions with a mutable
tail.
Note on marshalling: [abbrev_memo] must not appear in saved types.
[Btype], with [cleanup_abbrev] and [memo], takes care of tracking and
removing abbreviations.
*)
and abbrev_memo =
| Mnil (** No known abbrevation *)
| Mcons of private_flag * Path.t * type_expr * type_expr * abbrev_memo
* Found one abbreviation .
A valid abbreviation should be at least as visible and reachable by the
same path .
The first expression is the abbreviation and the second the expansion .
A valid abbreviation should be at least as visible and reachable by the
same path.
The first expression is the abbreviation and the second the expansion. *)
| Mlink of abbrev_memo ref
(** Abbreviations can be found after this indirection *)
and field_kind =
Fvar of field_kind option ref
| Fpresent
| Fabsent
* [ commutable ] is a flag appended to every arrow type .
When typing an application , if the type of the functional is
known , its type is instantiated with [ ] arrows , otherwise as
[ Clink ( ref Cunknown ) ] .
When the type is not known , the application will be used to infer
the actual type . This is fragile in presence of labels where
there is no principal type .
Two incompatible applications relying on [ Cunknown ] arrows will
trigger an error .
let f g =
g ~a :() ~b :() ;
g ~b :() ~a :() ;
Error : This function is applied to arguments
in an order different from other calls .
This is only allowed when the real type is known .
When typing an application, if the type of the functional is
known, its type is instantiated with [Cok] arrows, otherwise as
[Clink (ref Cunknown)].
When the type is not known, the application will be used to infer
the actual type. This is fragile in presence of labels where
there is no principal type.
Two incompatible applications relying on [Cunknown] arrows will
trigger an error.
let f g =
g ~a:() ~b:();
g ~b:() ~a:();
Error: This function is applied to arguments
in an order different from other calls.
This is only allowed when the real type is known.
*)
and commutable =
Cok
| Cunknown
| Clink of commutable ref
module TypeOps : sig
type t = type_expr
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
end
(* Maps of methods and instance variables *)
module Meths : Map.S with type key = string
module Vars : Map.S with type key = string
Representation of metaprogramming phases as a non - negative integer : 0 is
runtime , 1 is compile - time .
runtime, 1 is compile-time. *)
type phase = int
(* Value descriptions *)
type value_description =
{ val_type: type_expr; (* Type of the value *)
val_kind: value_kind;
val_loc: Location.t;
val_attributes: Parsetree.attributes;
}
and value_kind =
Val_reg (* Regular value *)
| Val_prim of Primitive.description (* Primitive *)
| Val_ivar of mutable_flag * string (* Instance variable (mutable ?) *)
| Val_self of (Ident.t * type_expr) Meths.t ref *
(Ident.t * mutable_flag * virtual_flag * type_expr) Vars.t ref *
string * type_expr
(* Self *)
| Val_anc of (string * Ident.t) list * string
(* Ancestor *)
Unbound variable
| Val_macro
(* Variance *)
module Variance : sig
type t
type f = May_pos | May_neg | May_weak | Inj | Pos | Neg | Inv
val null : t (* no occurence *)
val full : t (* strictly invariant *)
val covariant : t (* strictly covariant *)
val may_inv : t (* maybe invariant *)
val union : t -> t -> t
val inter : t -> t -> t
val subset : t -> t -> bool
val set : f -> bool -> t -> t
val mem : f -> t -> bool
val conjugate : t -> t (* exchange positive and negative *)
val get_upper : t -> bool * bool (* may_pos, may_neg *)
pos , neg , inv ,
end
(* Type definitions *)
type type_declaration =
{ type_params: type_expr list;
type_arity: int;
type_kind: type_kind;
type_private: private_flag;
type_manifest: type_expr option;
type_variance: Variance.t list;
(* covariant, contravariant, weakly contravariant, injective *)
type_newtype_level: (int * int) option;
(* definition level * expansion level *)
type_loc: Location.t;
type_attributes: Parsetree.attributes;
type_immediate: bool; (* true iff type should not be a pointer *)
type_unboxed: unboxed_status;
}
and type_kind =
Type_abstract
| Type_record of label_declaration list * record_representation
| Type_variant of constructor_declaration list
| Type_open
and record_representation =
Record_regular (* All fields are boxed / tagged *)
| Record_float (* All fields are floats *)
| Record_unboxed of bool (* Unboxed single-field record, inlined or not *)
Inlined record
Inlined record under extension
and label_declaration =
{
ld_id: Ident.t;
ld_mutable: mutable_flag;
ld_type: type_expr;
ld_loc: Location.t;
ld_attributes: Parsetree.attributes;
}
and constructor_declaration =
{
cd_id: Ident.t;
cd_args: constructor_arguments;
cd_res: type_expr option;
cd_loc: Location.t;
cd_attributes: Parsetree.attributes;
}
and constructor_arguments =
| Cstr_tuple of type_expr list
| Cstr_record of label_declaration list
and unboxed_status = private
This type must be private in order to ensure perfect sharing of the
four possible values . Otherwise , ocamlc.byte and ocamlc.opt produce
different executables .
four possible values. Otherwise, ocamlc.byte and ocamlc.opt produce
different executables. *)
{
unboxed: bool;
default: bool; (* True for unannotated unboxable types. *)
}
val unboxed_false_default_false : unboxed_status
val unboxed_false_default_true : unboxed_status
val unboxed_true_default_false : unboxed_status
val unboxed_true_default_true : unboxed_status
type extension_constructor =
{
ext_type_path: Path.t;
ext_type_params: type_expr list;
ext_args: constructor_arguments;
ext_ret_type: type_expr option;
ext_private: private_flag;
ext_loc: Location.t;
ext_attributes: Parsetree.attributes;
}
and type_transparence =
Type_public (* unrestricted expansion *)
| Type_new (* "new" type *)
| Type_private (* private type *)
(* Type expressions for the class language *)
module Concr : Set.S with type elt = string
type class_type =
Cty_constr of Path.t * type_expr list * class_type
| Cty_signature of class_signature
| Cty_arrow of arg_label * type_expr * class_type
and class_signature =
{ csig_self: type_expr;
csig_vars:
(Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr) Vars.t;
csig_concr: Concr.t;
csig_inher: (Path.t * type_expr list) list }
type class_declaration =
{ cty_params: type_expr list;
mutable cty_type: class_type;
cty_path: Path.t;
cty_new: type_expr option;
cty_variance: Variance.t list;
cty_loc: Location.t;
cty_attributes: Parsetree.attributes;
}
type class_type_declaration =
{ clty_params: type_expr list;
clty_type: class_type;
clty_path: Path.t;
clty_variance: Variance.t list;
clty_loc: Location.t;
clty_attributes: Parsetree.attributes;
}
(* Type expressions for the module language *)
type module_type =
Mty_ident of Path.t
| Mty_signature of signature
| Mty_functor of Ident.t * module_type option * module_type
| Mty_alias of alias_presence * Path.t
and alias_presence =
| Mta_present
| Mta_absent
and signature = signature_item list
and signature_item =
Sig_value of Ident.t * static_flag * value_description
| Sig_type of Ident.t * type_declaration * rec_status
| Sig_typext of Ident.t * extension_constructor * ext_status
| Sig_module of Ident.t * module_declaration * static_flag * rec_status
| Sig_modtype of Ident.t * modtype_declaration
| Sig_class of Ident.t * class_declaration * rec_status
| Sig_class_type of Ident.t * class_type_declaration * rec_status
and module_declaration =
{
md_type: module_type;
md_attributes: Parsetree.attributes;
md_loc: Location.t;
}
and modtype_declaration =
{
mtd_type: module_type option; (* None: abstract *)
mtd_attributes: Parsetree.attributes;
mtd_loc: Location.t;
}
and rec_status =
first in a nonrecursive group
first in a recursive group
not first in a recursive / nonrecursive group
and ext_status =
Text_first (* first constructor in an extension *)
not first constructor in an extension
| Text_exception
(* Constructor and record label descriptions inserted held in typing
environments *)
type constructor_description =
{ cstr_name: string; (* Constructor name *)
cstr_res: type_expr; (* Type of the result *)
cstr_existentials: type_expr list; (* list of existentials *)
cstr_args: type_expr list; (* Type of the arguments *)
cstr_arity: int; (* Number of arguments *)
cstr_tag: constructor_tag; (* Tag for heap blocks *)
cstr_consts: int; (* Number of constant constructors *)
cstr_nonconsts: int; (* Number of non-const constructors *)
Number of non generalized
Constrained return type ?
cstr_private: private_flag; (* Read-only constructor? *)
cstr_loc: Location.t;
cstr_attributes: Parsetree.attributes;
cstr_inlined: type_declaration option;
}
and constructor_tag =
Cstr_constant of int (* Constant constructor (an int) *)
| Cstr_block of int (* Regular constructor (a block) *)
Constructor of an unboxed type
| Cstr_extension of Path.t * bool (* Extension constructor
true if a constant false if a block*)
type label_description =
{ lbl_name: string; (* Short name *)
lbl_res: type_expr; (* Type of the result *)
lbl_arg: type_expr; (* Type of the argument *)
lbl_mut: mutable_flag; (* Is this a mutable field? *)
lbl_pos: int; (* Position in block *)
lbl_all: label_description array; (* All the labels in this type *)
lbl_repres: record_representation; (* Representation for this record *)
lbl_private: private_flag; (* Read-only field? *)
lbl_loc: Location.t;
lbl_attributes: Parsetree.attributes;
}
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/typing/types.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* {0 Representation of types and declarations}
* [Tvar (Some "a")] ==> ['a] or ['_a]
[Tvar None] ==> [_]
* Indirection used by unification engine.
for copying
* [Tsubst] is used temporarily to store information in low-level
functions manipulating representation of types, such as
instantiation or copy.
This constructor should not appear outside of these cases.
* Representation of polymorphic variants, see [row_desc].
* Occurrence of a type variable introduced by a
forall quantifier / [Tpoly].
* [Tpoly (ty,tyl)] ==> ['a1... 'an. ty],
where 'a1 ... 'an are names given to types in tyl
and occurences of those types in ty.
kept for compatibility
1st true denotes a constant constructor
* [abbrev_memo] allows one to keep track of different expansions of a type
alias. This is done for performance purposes.
For instance, when defining [type 'a pair = 'a * 'a], when one refers to an
['a pair], it is just a shortcut for the ['a * 'a] type.
This expansion will be stored in the [abbrev_memo] of the corresponding
[Tconstr] node.
In practice, [abbrev_memo] behaves like list of expansions with a mutable
tail.
Note on marshalling: [abbrev_memo] must not appear in saved types.
[Btype], with [cleanup_abbrev] and [memo], takes care of tracking and
removing abbreviations.
* No known abbrevation
* Abbreviations can be found after this indirection
Maps of methods and instance variables
Value descriptions
Type of the value
Regular value
Primitive
Instance variable (mutable ?)
Self
Ancestor
Variance
no occurence
strictly invariant
strictly covariant
maybe invariant
exchange positive and negative
may_pos, may_neg
Type definitions
covariant, contravariant, weakly contravariant, injective
definition level * expansion level
true iff type should not be a pointer
All fields are boxed / tagged
All fields are floats
Unboxed single-field record, inlined or not
True for unannotated unboxable types.
unrestricted expansion
"new" type
private type
Type expressions for the class language
Type expressions for the module language
None: abstract
first constructor in an extension
Constructor and record label descriptions inserted held in typing
environments
Constructor name
Type of the result
list of existentials
Type of the arguments
Number of arguments
Tag for heap blocks
Number of constant constructors
Number of non-const constructors
Read-only constructor?
Constant constructor (an int)
Regular constructor (a block)
Extension constructor
true if a constant false if a block
Short name
Type of the result
Type of the argument
Is this a mutable field?
Position in block
All the labels in this type
Representation for this record
Read-only field? | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
* [ Types ] defines the representation of types and declarations ( that is , the
content of module signatures ) .
CMI files are made of marshalled types .
content of module signatures).
CMI files are made of marshalled types.
*)
* exposes basic definitions shared both by Parsetree and Types .
open Asttypes
* Type expressions for the core language .
The [ type_desc ] variant defines all the possible type expressions one can
find in OCaml . [ type_expr ] wraps this with some annotations .
The [ level ] field tracks the level of polymorphism associated to a type ,
guiding the generalization algorithm .
Put shortly , when referring to a type in a given environment , both the type
and the environment have a level . If the type has an higher level , then it
can be considered fully polymorphic ( type variables will be printed as
[ ' a ] ) , otherwise it 'll be weakly polymorphic , or non generalized ( type
variables printed as [ ' _ a ] ) .
See [ ] for more information .
Note about [ type_declaration ] : one should not make the confusion between
[ type_expr ] and [ type_declaration ] .
[ type_declaration ] refers specifically to the [ type ] construct in OCaml
language , where you create and name a new type or type alias .
[ type_expr ] is used when you refer to existing types , e.g. when annotating
the expected type of a value .
Also , as the type system of OCaml is generative , a [ type_declaration ] can
have the side - effect of introducing a new type constructor , different from
all other known types .
Whereas [ type_expr ] is a pure construct which allows referring to existing
types .
Note on mutability : TBD .
The [type_desc] variant defines all the possible type expressions one can
find in OCaml. [type_expr] wraps this with some annotations.
The [level] field tracks the level of polymorphism associated to a type,
guiding the generalization algorithm.
Put shortly, when referring to a type in a given environment, both the type
and the environment have a level. If the type has an higher level, then it
can be considered fully polymorphic (type variables will be printed as
['a]), otherwise it'll be weakly polymorphic, or non generalized (type
variables printed as ['_a]).
See [] for more information.
Note about [type_declaration]: one should not make the confusion between
[type_expr] and [type_declaration].
[type_declaration] refers specifically to the [type] construct in OCaml
language, where you create and name a new type or type alias.
[type_expr] is used when you refer to existing types, e.g. when annotating
the expected type of a value.
Also, as the type system of OCaml is generative, a [type_declaration] can
have the side-effect of introducing a new type constructor, different from
all other known types.
Whereas [type_expr] is a pure construct which allows referring to existing
types.
Note on mutability: TBD.
*)
type type_expr =
{ mutable desc: type_desc;
mutable level: int;
id: int }
and type_desc =
| Tvar of string option
| Tarrow of arg_label * type_expr * type_expr * commutable
* [ ( Nolabel , e1 , e2 , c ) ] = = > [ e1 - > e2 ]
[ ( Labelled " l " , e1 , e2 , c ) ] = = > [ l : e1 - > e2 ]
[ ( Optional " l " , e1 , e2 , c ) ] = = > [ ? l : e1 - > e2 ]
See [ commutable ] for the last argument .
[Tarrow (Labelled "l", e1, e2, c)] ==> [l:e1 -> e2]
[Tarrow (Optional "l", e1, e2, c)] ==> [?l:e1 -> e2]
See [commutable] for the last argument. *)
| Ttuple of type_expr list
* [ [ t1; ... ;tn ] ] = = > [ ( t1 * ... * tn ) ]
| Tconstr of Path.t * type_expr list * abbrev_memo ref
* [ Tconstr ( ` A.B.t ' , [ t1; ... ;tn ] , _ ) ] = = > [ ( t1, ... ,tn ) A.B.t ]
The last parameter keep tracks of known expansions , see [ abbrev_memo ] .
The last parameter keep tracks of known expansions, see [abbrev_memo]. *)
| Tobject of type_expr * (Path.t * type_expr list) option ref
* [ Tobject ( ` f1 : t1; ... ;fn : tn ' , ` None ' ) ] = = > [ < f1 : t1 ; ... ; fn : tn > ]
f1 , fn are represented as a linked list of types using and
constructors .
[ Tobject ( _ , ` Some ( ` A.ct ' , [ t1; ... ;tn ] ' ) ] = = > [ ( t1 , ... , tn ) A.ct ] .
where A.ct is the type of some class .
There are also special cases for so - called " class - types " , cf . [ ]
and [ Ctype.set_object_name ] :
[ Tobject ( Tfield(_,_, ... (Tfield(_,_,rv ) ... ) ,
Some(`A.#ct ` , [ rv;t1; ... ;tn ] ) ]
= = > [ ( t1 , ... , tn ) # A.ct ]
[ Tobject ( _ , Some(`A.#ct ` , [ Tnil;t1; ... ;tn ] ) ] = = > [ ( t1 , ... , tn ) A.ct ]
where [ rv ] is the hidden row variable .
f1, fn are represented as a linked list of types using Tfield and Tnil
constructors.
[Tobject (_, `Some (`A.ct', [t1;...;tn]')] ==> [(t1, ..., tn) A.ct].
where A.ct is the type of some class.
There are also special cases for so-called "class-types", cf. [Typeclass]
and [Ctype.set_object_name]:
[Tobject (Tfield(_,_,...(Tfield(_,_,rv)...),
Some(`A.#ct`, [rv;t1;...;tn])]
==> [(t1, ..., tn) #A.ct]
[Tobject (_, Some(`A.#ct`, [Tnil;t1;...;tn])] ==> [(t1, ..., tn) A.ct]
where [rv] is the hidden row variable.
*)
| Tfield of string * field_kind * type_expr * type_expr
* [ ( " foo " , , t , ts ) ] = = > [ < ... ; foo : t ; ts > ]
| Tnil
* [ ] = = > [ < ... ; > ]
| Tlink of type_expr
| Tvariant of row_desc
| Tunivar of string option
| Tpoly of type_expr * type_expr list
| Tpackage of Path.t * Longident.t list * type_expr list
* Type of a first - class module ( a.k.a package ) .
* [ ` X | ` Y ] ( row_closed = true )
[ < ` X | ` Y ] ( row_closed = true )
[ > ` X | ` Y ] ( row_closed = false )
[ < ` X | ` Y > ` X ] ( row_closed = true )
type t = [ > ` X ] as ' a ( row_more = Tvar a )
type t = private [ > ` X ] ( row_more = Tconstr ( t#row , [ ] , ref Mnil )
And for :
let f = function ` X - > ` X - > | ` Y - > ` X
the type of " f " will be a [ Tarrow ] whose lhs will ( basically ) be :
Tvariant { row_fields = [ ( " X " , _ ) ] ;
row_more =
Tvariant { row_fields = [ ( " Y " , _ ) ] ;
row_more =
Tvariant { row_fields = [ ] ;
row_more = _ ;
_ } ;
_ } ;
_
}
[< `X | `Y ] (row_closed = true)
[> `X | `Y ] (row_closed = false)
[< `X | `Y > `X ] (row_closed = true)
type t = [> `X ] as 'a (row_more = Tvar a)
type t = private [> `X ] (row_more = Tconstr (t#row, [], ref Mnil)
And for:
let f = function `X -> `X -> | `Y -> `X
the type of "f" will be a [Tarrow] whose lhs will (basically) be:
Tvariant { row_fields = [("X", _)];
row_more =
Tvariant { row_fields = [("Y", _)];
row_more =
Tvariant { row_fields = [];
row_more = _;
_ };
_ };
_
}
*)
and row_desc =
{ row_fields: (label * row_field) list;
row_more: type_expr;
row_closed: bool;
row_fixed: bool;
row_name: (Path.t * type_expr list) option }
and row_field =
Rpresent of type_expr option
| Reither of bool * type_expr list * bool * row_field option ref
2nd true denotes a tag in a pattern matching , and
is erased later
is erased later *)
| Rabsent
and abbrev_memo =
| Mcons of private_flag * Path.t * type_expr * type_expr * abbrev_memo
* Found one abbreviation .
A valid abbreviation should be at least as visible and reachable by the
same path .
The first expression is the abbreviation and the second the expansion .
A valid abbreviation should be at least as visible and reachable by the
same path.
The first expression is the abbreviation and the second the expansion. *)
| Mlink of abbrev_memo ref
and field_kind =
Fvar of field_kind option ref
| Fpresent
| Fabsent
* [ commutable ] is a flag appended to every arrow type .
When typing an application , if the type of the functional is
known , its type is instantiated with [ ] arrows , otherwise as
[ Clink ( ref Cunknown ) ] .
When the type is not known , the application will be used to infer
the actual type . This is fragile in presence of labels where
there is no principal type .
Two incompatible applications relying on [ Cunknown ] arrows will
trigger an error .
let f g =
g ~a :() ~b :() ;
g ~b :() ~a :() ;
Error : This function is applied to arguments
in an order different from other calls .
This is only allowed when the real type is known .
When typing an application, if the type of the functional is
known, its type is instantiated with [Cok] arrows, otherwise as
[Clink (ref Cunknown)].
When the type is not known, the application will be used to infer
the actual type. This is fragile in presence of labels where
there is no principal type.
Two incompatible applications relying on [Cunknown] arrows will
trigger an error.
let f g =
g ~a:() ~b:();
g ~b:() ~a:();
Error: This function is applied to arguments
in an order different from other calls.
This is only allowed when the real type is known.
*)
and commutable =
Cok
| Cunknown
| Clink of commutable ref
module TypeOps : sig
type t = type_expr
val compare : t -> t -> int
val equal : t -> t -> bool
val hash : t -> int
end
module Meths : Map.S with type key = string
module Vars : Map.S with type key = string
Representation of metaprogramming phases as a non - negative integer : 0 is
runtime , 1 is compile - time .
runtime, 1 is compile-time. *)
type phase = int
type value_description =
val_kind: value_kind;
val_loc: Location.t;
val_attributes: Parsetree.attributes;
}
and value_kind =
| Val_self of (Ident.t * type_expr) Meths.t ref *
(Ident.t * mutable_flag * virtual_flag * type_expr) Vars.t ref *
string * type_expr
| Val_anc of (string * Ident.t) list * string
Unbound variable
| Val_macro
module Variance : sig
type t
type f = May_pos | May_neg | May_weak | Inj | Pos | Neg | Inv
val union : t -> t -> t
val inter : t -> t -> t
val subset : t -> t -> bool
val set : f -> bool -> t -> t
val mem : f -> t -> bool
pos , neg , inv ,
end
type type_declaration =
{ type_params: type_expr list;
type_arity: int;
type_kind: type_kind;
type_private: private_flag;
type_manifest: type_expr option;
type_variance: Variance.t list;
type_newtype_level: (int * int) option;
type_loc: Location.t;
type_attributes: Parsetree.attributes;
type_unboxed: unboxed_status;
}
and type_kind =
Type_abstract
| Type_record of label_declaration list * record_representation
| Type_variant of constructor_declaration list
| Type_open
and record_representation =
Inlined record
Inlined record under extension
and label_declaration =
{
ld_id: Ident.t;
ld_mutable: mutable_flag;
ld_type: type_expr;
ld_loc: Location.t;
ld_attributes: Parsetree.attributes;
}
and constructor_declaration =
{
cd_id: Ident.t;
cd_args: constructor_arguments;
cd_res: type_expr option;
cd_loc: Location.t;
cd_attributes: Parsetree.attributes;
}
and constructor_arguments =
| Cstr_tuple of type_expr list
| Cstr_record of label_declaration list
and unboxed_status = private
This type must be private in order to ensure perfect sharing of the
four possible values . Otherwise , ocamlc.byte and ocamlc.opt produce
different executables .
four possible values. Otherwise, ocamlc.byte and ocamlc.opt produce
different executables. *)
{
unboxed: bool;
}
val unboxed_false_default_false : unboxed_status
val unboxed_false_default_true : unboxed_status
val unboxed_true_default_false : unboxed_status
val unboxed_true_default_true : unboxed_status
type extension_constructor =
{
ext_type_path: Path.t;
ext_type_params: type_expr list;
ext_args: constructor_arguments;
ext_ret_type: type_expr option;
ext_private: private_flag;
ext_loc: Location.t;
ext_attributes: Parsetree.attributes;
}
and type_transparence =
module Concr : Set.S with type elt = string
type class_type =
Cty_constr of Path.t * type_expr list * class_type
| Cty_signature of class_signature
| Cty_arrow of arg_label * type_expr * class_type
and class_signature =
{ csig_self: type_expr;
csig_vars:
(Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr) Vars.t;
csig_concr: Concr.t;
csig_inher: (Path.t * type_expr list) list }
type class_declaration =
{ cty_params: type_expr list;
mutable cty_type: class_type;
cty_path: Path.t;
cty_new: type_expr option;
cty_variance: Variance.t list;
cty_loc: Location.t;
cty_attributes: Parsetree.attributes;
}
type class_type_declaration =
{ clty_params: type_expr list;
clty_type: class_type;
clty_path: Path.t;
clty_variance: Variance.t list;
clty_loc: Location.t;
clty_attributes: Parsetree.attributes;
}
type module_type =
Mty_ident of Path.t
| Mty_signature of signature
| Mty_functor of Ident.t * module_type option * module_type
| Mty_alias of alias_presence * Path.t
and alias_presence =
| Mta_present
| Mta_absent
and signature = signature_item list
and signature_item =
Sig_value of Ident.t * static_flag * value_description
| Sig_type of Ident.t * type_declaration * rec_status
| Sig_typext of Ident.t * extension_constructor * ext_status
| Sig_module of Ident.t * module_declaration * static_flag * rec_status
| Sig_modtype of Ident.t * modtype_declaration
| Sig_class of Ident.t * class_declaration * rec_status
| Sig_class_type of Ident.t * class_type_declaration * rec_status
and module_declaration =
{
md_type: module_type;
md_attributes: Parsetree.attributes;
md_loc: Location.t;
}
and modtype_declaration =
{
mtd_attributes: Parsetree.attributes;
mtd_loc: Location.t;
}
and rec_status =
first in a nonrecursive group
first in a recursive group
not first in a recursive / nonrecursive group
and ext_status =
not first constructor in an extension
| Text_exception
type constructor_description =
Number of non generalized
Constrained return type ?
cstr_loc: Location.t;
cstr_attributes: Parsetree.attributes;
cstr_inlined: type_declaration option;
}
and constructor_tag =
Constructor of an unboxed type
type label_description =
lbl_loc: Location.t;
lbl_attributes: Parsetree.attributes;
}
|
879f2859687495c85b28c6732950b39d1b881d6569bc77553c5287f9997158cd | Clozure/ccl | arrays-fry.lisp | -*- Mode : Lisp ; Package : CCL ; -*-
;;;
Copyright 1994 - 2009 Clozure Associates
;;;
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.
(in-package "CCL")
(defun bit (bit-array &rest subscripts)
"Return the bit from the BIT-ARRAY at the specified SUBSCRIPTS."
(declare (dynamic-extent subscripts))
(unless (eq (array-element-type bit-array) 'bit)
(report-bad-arg bit-array '(array bit)))
(apply #'aref bit-array subscripts))
(defun %bitset (bit-array &rest stuff)
(declare (dynamic-extent stuff))
(unless (eq (array-element-type bit-array) 'bit)
(report-bad-arg bit-array '(array bit)))
(apply #'aset bit-array stuff))
(defun sbit (v &optional (sub0 nil sub0-p) &rest others)
"Return the bit from SIMPLE-BIT-ARRAY at the specified SUBSCRIPTS."
(declare (dynamic-extent others))
(if sub0-p
(if others
(apply #'bit v sub0 others)
( sbit (require-type v 'simple-bit-vector) sub0))
(bit v)))
(defun %sbitset (v sub0 &optional (newval nil newval-p) &rest newval-was-really-sub1)
(declare (dynamic-extent newval-was-really-sub1))
(if newval-p
(if newval-was-really-sub1
(apply #'%bitset v sub0 newval newval-was-really-sub1)
(progn
(unless (typep v 'simple-bit-vector)
(report-bad-arg v 'simple-bit-vector))
(uvset v sub0 newval)))
(%bitset v sub0)))
(defun bit-and (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGAND on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-and bit-array1 bit-array2 result-bit-array))
(defun bit-ior (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGIOR on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-ior bit-array1 bit-array2 result-bit-array))
(defun bit-xor (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGXOR on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-xor bit-array1 bit-array2 result-bit-array))
(defun bit-eqv (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGEQV on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-eqv bit-array1 bit-array2 result-bit-array))
(defun bit-nand (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGNAND on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-nand bit-array1 bit-array2 result-bit-array))
(defun bit-nor (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGNOR on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-nor bit-array1 bit-array2 result-bit-array))
(defun bit-andc1 (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGANDC1 on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-andc1 bit-array1 bit-array2 result-bit-array))
(defun bit-andc2 (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGANDC2 on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-andc2 bit-array1 bit-array2 result-bit-array))
(defun bit-orc1 (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGORC1 on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-orc1 bit-array1 bit-array2 result-bit-array))
(defun bit-orc2 (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGORC2 on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-orc2 bit-array1 bit-array2 result-bit-array))
(defun bit-not (bit-array &optional result-bit-array)
"Performs a bit-wise logical NOT on the elements of BIT-ARRAY,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. Both arrays must have the same rank and dimensions."
(bit-boole boole-nor bit-array bit-array result-bit-array))
(defun result-bit-array (bit-array-1 bit-array-2 result)
Check that the two bit - array args are bit - arrays with
; compatible dimensions. If "result" is specified as T,
; return bit-array-1. If result is unspecified, return
; a new bit-array of the same dimensions as bit-array-2.
; Otherwise, make sure that result is a bit-array of the
same dimensions as the other two arguments and return
; it.
(let* ((typecode-1 (typecode bit-array-1))
(typecode-2 (typecode bit-array-2)))
(declare (fixnum typecode-1 typecode-2))
(flet ((bit-array-dimensions (bit-array typecode)
(declare (fixnum typecode))
(if (= typecode target::subtag-bit-vector)
(uvsize bit-array)
(let* ((array-p (= typecode target::subtag-arrayH))
(vector-p (= typecode target::subtag-vectorH)))
(if (and (or array-p vector-p)
(= (the fixnum (%array-header-subtype bit-array)) target::subtag-bit-vector))
(if vector-p
(array-dimension bit-array 0)
(array-dimensions bit-array))
(report-bad-arg bit-array '(array bit))))))
(check-matching-dimensions (a1 d1 a2 d2)
(unless (equal d1 d2)
(error "~s and ~s have different dimensions." a1 a2))
a2))
(let* ((dims-1 (bit-array-dimensions bit-array-1 typecode-1))
(dims-2 (bit-array-dimensions bit-array-2 typecode-2)))
(check-matching-dimensions bit-array-1 dims-1 bit-array-2 dims-2)
(if result
(if (eq result t)
bit-array-1
(check-matching-dimensions bit-array-2 dims-2 result (bit-array-dimensions result (typecode result))))
(make-array dims-2 :element-type 'bit :initial-element 0))))))
(defun bit-boole (opcode array1 array2 result-array)
(unless (eql opcode (logand 15 opcode))
(setq opcode (require-type opcode '(mod 16))))
(let* ((result (result-bit-array array1 array2 result-array)))
(if (and (typep array1 'simple-bit-vector)
(typep array2 'simple-bit-vector)
(typep result 'simple-bit-vector))
(%simple-bit-boole opcode array1 array2 result)
(multiple-value-bind (v1 i1) (array-data-and-offset array1)
(declare (simple-bit-vector v1) (fixnum i1))
(multiple-value-bind (v2 i2) (array-data-and-offset array2)
(declare (simple-bit-vector v2) (fixnum i2))
(multiple-value-bind (v3 i3) (array-data-and-offset result)
(declare (simple-bit-vector v3) (fixnum i3))
(let* ((e3 (+ i3 (the fixnum (array-total-size result)))))
(declare (fixnum e3))
(do* ( )
((= i3 e3) result)
(setf (sbit v3 i3)
(logand (boole opcode (sbit v1 i1) (sbit v2 i2)) 1))
(incf i1)
(incf i2)
(incf i3)))))))))
; shrink-vector is called only in sequences-2. None of the calls depend on
; the side affect of setting the passed-in symbol to the [possibly new]
; returned vector
Since there has n't been such a thing as sequences-2 in about 7 years ,
; this is especially puzzling.
(eval-when (:compile-toplevel :execute :load-toplevel)
(defmacro shrink-vector (vector to-size)
`(setq ,vector (%shrink-vector ,vector ,to-size)))
)
; new and faulty def
(defun %shrink-vector (vector to-size)
(cond ((eq (length vector) to-size)
vector)
((array-has-fill-pointer-p vector)
(setf (fill-pointer vector) to-size)
vector)
(t (subseq vector 0 to-size))))
this could be put into print - db as it was in ccl - pr-4.2
; Or it (and print-db) could just be flushed ... tough one.
(defun multi-dimension-array-to-list (array)
"Produces a nested list of the elements in array."
(mdal-aux array (array-dimensions array) nil
(array-dimensions array)))
(defun mdal-aux (array all-dimensions use-dimensions
remaining-dimensions)
(if (= (length all-dimensions) (length use-dimensions))
(apply 'aref array use-dimensions)
(do ((index 0 (1+ index))
(d-length (car remaining-dimensions))
(result nil))
((= d-length index) result)
(setq result
(append result (list (mdal-aux array all-dimensions
(append use-dimensions
(list index))
(cdr remaining-dimensions))))))))
(defun adjust-array (array dims
&key (element-type nil element-type-p)
(initial-element nil initial-element-p)
(initial-contents nil initial-contents-p)
(fill-pointer nil fill-pointer-p)
displaced-to
displaced-index-offset
&aux (subtype (array-element-subtype array)))
"Adjust ARRAY's dimensions to the given DIMENSIONS and stuff."
(when (and element-type-p
(neq (element-type-subtype element-type) subtype))
(error "~S is not of element type ~S" array element-type))
(when (integerp dims)(setq dims (list dims))) ; because %displace-array wants the list
(if (neq (list-length dims)(array-rank array))
(error "~S has wrong rank for adjusting to dimensions ~S" array dims))
(let ((size 1)
(explicitp nil))
(dolist (dim dims)
(when (< dim 0)(report-bad-arg dims '(integer 0 *)))
(setq size (* size dim)))
(when (and (neq fill-pointer t)
(array-has-fill-pointer-p array)
(< size (or fill-pointer (fill-pointer array))))
(error "Cannot adjust array ~S to size less than fill pointer ~S"
array (or fill-pointer (fill-pointer array))))
(when (and fill-pointer (not (array-has-fill-pointer-p array)))
(error "~S does not have a fill pointer" array))
(when (and displaced-index-offset (null displaced-to))
(error "Cannot specify ~S without ~S" :displaced-index-offset :displaced-to))
(when (and initial-element-p initial-contents-p)
(error "Cannot specify both ~S and ~S" :initial-element :initial-contents))
(cond
((not (adjustable-array-p array))
(let ((new-array (make-array-1 dims
(array-element-type array) T
displaced-to
displaced-index-offset
nil
(or fill-pointer
(and (array-has-fill-pointer-p array)
(fill-pointer array)))
initial-element initial-element-p
initial-contents initial-contents-p
size)))
(when (and (null initial-contents-p)
(null displaced-to))
(multiple-value-bind (array-data offs) (array-data-and-offset array)
(let ((new-array-data (array-data-and-offset new-array)))
(cond ((null dims)
(uvset new-array-data 0 (uvref array-data offs)))
(T
(init-array-data array-data offs (array-dimensions array)
new-array-data 0 dims))))))
(setq array new-array)))
(T (cond
(displaced-to
(if (and displaced-index-offset
(or (not (fixnump displaced-index-offset))
(< displaced-index-offset 0)))
(report-bad-arg displaced-index-offset '(integer 0 #.most-positive-fixnum)))
(when (or initial-element-p initial-contents-p)
(error "Cannot specify initial values for displaced arrays"))
(unless (eq subtype (array-element-subtype displaced-to))
(error "~S is not of element type ~S"
displaced-to (array-element-type array)))
(do* ((vec displaced-to (displaced-array-p vec)))
((null vec) ())
(when (eq vec array)
(error "Array cannot be displaced to itself.")))
(setq explicitp t))
(T
(setq displaced-to (%alloc-misc size subtype))
(cond (initial-element-p
(dotimes (i (the fixnum size)) (uvset displaced-to i initial-element)))
(initial-contents-p
(if (null dims) (uvset displaced-to 0 initial-contents)
(init-uvector-contents displaced-to 0 dims initial-contents))))
(cond ((null dims)
(uvset displaced-to 0 (aref array)))
((not initial-contents-p)
(multiple-value-bind (vec offs) (array-data-and-offset array)
(init-array-data vec offs (array-dimensions array) displaced-to 0 dims))))))
(%displace-array array dims size displaced-to (or displaced-index-offset 0) explicitp)))
(when fill-pointer-p
(cond
((eq fill-pointer t)
(set-fill-pointer array size))
(fill-pointer
(set-fill-pointer array fill-pointer))))
array))
(defun array-dims-sizes (dims)
(if (or (atom dims) (null (%cdr dims))) dims
(let ((ndims (array-dims-sizes (%cdr dims))))
(cons (* (%car dims) (%car ndims)) ndims))))
(defun init-array-data (vec off dims nvec noff ndims)
(init-array-data-aux vec off dims (array-dims-sizes (cdr dims))
nvec noff ndims (array-dims-sizes (cdr ndims))))
(defun init-array-data-aux (vec off dims siz nvec noff ndims nsiz)
(when (null siz)
(return-from init-array-data-aux
(init-vector-data vec off (car dims) nvec noff (car ndims))))
(let ((count (pop dims))
(size (pop siz))
(ncount (pop ndims))
(nsize (pop nsiz)))
(dotimes (i (if (%i< count ncount) count ncount))
(declare (fixnum i))
(init-array-data-aux vec off dims siz nvec noff ndims nsiz)
(setq off (%i+ off size) noff (%i+ noff nsize)))))
(defun init-vector-data (vec off len nvec noff nlen)
(dotimes (i (if (%i< len nlen) len nlen))
(declare (fixnum i))
(uvset nvec noff (uvref vec off))
(setq off (%i+ off 1) noff (%i+ noff 1))))
;;; only caller is adjust-array
(defun %displace-array (array dims size data offset explicitp)
(let* ((typecode (typecode array))
(array-p (eql typecode target::subtag-arrayH))
(vector-p (eql typecode target::subtag-vectorH)))
(unless (or array-p vector-p)
(error "Array ~S cannot be displaced" array))
(unless (fixnump offset) (report-bad-arg offset '(integer 0 #.most-positive-fixnum)))
(unless (adjustable-array-p data)
(multiple-value-bind (ndata noffset) (displaced-array-p data)
(if ndata (setq data ndata offset (%i+ offset noffset)))))
(unless (and (fixnump size) (%i<= (%i+ offset size) (array-total-size data)))
(error "Offset ~S + size ~S must be less than size of array displaced-to" offset size))
(let* ((flags (%svref array target::vectorH.flags-cell)))
(declare (fixnum flags))
(setf (%svref array target::vectorH.flags-cell)
(if (> (the fixnum (typecode data)) target::subtag-vectorH)
(bitclr $arh_disp_bit flags)
(bitset $arh_disp_bit flags)))
(setf (%svref array target::vectorH.flags-cell)
(if explicitp
(bitset $arh_exp_disp_bit flags)
(bitclr $arh_exp_disp_bit flags)))
(setf (%svref array target::arrayH.data-vector-cell) data)
(if array-p
(progn
(do ((i target::arrayH.dim0-cell (1+ i)))
((null dims))
(declare (fixnum i))
(setf (%svref array i) (pop dims)))
(setf (%svref array target::arrayH.physsize-cell) size)
(setf (%svref array target::arrayH.displacement-cell) offset))
(progn
(if (or (not (logbitp $arh_fill_bit flags))
(> (the fixnum (%svref array target::vectorH.logsize-cell)) size))
(setf (%svref array target::vectorH.logsize-cell) size))
(setf (%svref array target::vectorH.physsize-cell) size)
(setf (%svref array target::vectorH.displacement-cell) offset)))
array)))
(defun array-row-major-index (array &lexpr subscripts)
(let ((rank (array-rank array))
(nsubs (%lexpr-count subscripts))
(sum 0))
(declare (fixnum sum rank))
(unless (eql rank nsubs)
(%err-disp $xndims array nsubs))
(if (eql 0 rank)
0
(do* ((i (1- rank) (1- i))
(dim (array-dimension array i) (array-dimension array i))
(last-size 1 size)
(size dim (* dim size)))
(nil)
(declare (fixnum i last-size size))
(let ((s (%lexpr-ref subscripts nsubs i)))
(unless (fixnump s)
(setq s (require-type s 'fixnum)))
(when (or (< s 0) (>= s dim))
(%err-disp $XARROOB (%apply-lexpr 'list subscripts) array))
(incf sum (the fixnum (* s last-size)))
(when (eql i 0) (return sum)))))))
(defun array-in-bounds-p (array &lexpr subscripts)
"Return T if the SUBSCIPTS are in bounds for the ARRAY, NIL otherwise."
(let ((rank (array-rank array))
(nsubs (%lexpr-count subscripts)))
(declare (fixnum nsubs rank))
(if (not (eql nsubs rank))
(%err-disp $xndims array nsubs)
(if (eql 0 rank)
0
(do* ((i (1- rank) (1- i))
(dim (array-dimension array i) (array-dimension array i)))
(nil)
(declare (fixnum i dim))
(let ((s (%lexpr-ref subscripts nsubs i)))
(if (typep s 'fixnum)
(locally (declare (fixnum s))
(if (or (< s 0)(>= s dim)) (return nil)))
(if (typep s 'bignum)
(return nil)
(report-bad-arg s 'integer)))
(when (eql i 0) (return t))))))))
(defun row-major-aref (array index)
"Return the element of array corressponding to the row-major index. This is
SETF'able."
(multiple-value-bind (displaced-to offset) (displaced-array-p array)
(aref (or displaced-to array) (+ index offset))))
(defun row-major-aset (array index new)
(multiple-value-bind (displaced-to offset) (displaced-array-p array)
(setf (aref (or displaced-to array) (+ index offset)) new)))
(defsetf row-major-aref row-major-aset)
; end
| null | https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/lib/arrays-fry.lisp | lisp | Package : CCL ; -*-
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.
compatible dimensions. If "result" is specified as T,
return bit-array-1. If result is unspecified, return
a new bit-array of the same dimensions as bit-array-2.
Otherwise, make sure that result is a bit-array of the
it.
shrink-vector is called only in sequences-2. None of the calls depend on
the side affect of setting the passed-in symbol to the [possibly new]
returned vector
this is especially puzzling.
new and faulty def
Or it (and print-db) could just be flushed ... tough one.
because %displace-array wants the list
only caller is adjust-array
end | Copyright 1994 - 2009 Clozure Associates
distributed under the License is distributed on an " AS IS " BASIS ,
(in-package "CCL")
(defun bit (bit-array &rest subscripts)
"Return the bit from the BIT-ARRAY at the specified SUBSCRIPTS."
(declare (dynamic-extent subscripts))
(unless (eq (array-element-type bit-array) 'bit)
(report-bad-arg bit-array '(array bit)))
(apply #'aref bit-array subscripts))
(defun %bitset (bit-array &rest stuff)
(declare (dynamic-extent stuff))
(unless (eq (array-element-type bit-array) 'bit)
(report-bad-arg bit-array '(array bit)))
(apply #'aset bit-array stuff))
(defun sbit (v &optional (sub0 nil sub0-p) &rest others)
"Return the bit from SIMPLE-BIT-ARRAY at the specified SUBSCRIPTS."
(declare (dynamic-extent others))
(if sub0-p
(if others
(apply #'bit v sub0 others)
( sbit (require-type v 'simple-bit-vector) sub0))
(bit v)))
(defun %sbitset (v sub0 &optional (newval nil newval-p) &rest newval-was-really-sub1)
(declare (dynamic-extent newval-was-really-sub1))
(if newval-p
(if newval-was-really-sub1
(apply #'%bitset v sub0 newval newval-was-really-sub1)
(progn
(unless (typep v 'simple-bit-vector)
(report-bad-arg v 'simple-bit-vector))
(uvset v sub0 newval)))
(%bitset v sub0)))
(defun bit-and (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGAND on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-and bit-array1 bit-array2 result-bit-array))
(defun bit-ior (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGIOR on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-ior bit-array1 bit-array2 result-bit-array))
(defun bit-xor (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGXOR on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-xor bit-array1 bit-array2 result-bit-array))
(defun bit-eqv (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGEQV on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-eqv bit-array1 bit-array2 result-bit-array))
(defun bit-nand (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGNAND on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-nand bit-array1 bit-array2 result-bit-array))
(defun bit-nor (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGNOR on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-nor bit-array1 bit-array2 result-bit-array))
(defun bit-andc1 (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGANDC1 on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-andc1 bit-array1 bit-array2 result-bit-array))
(defun bit-andc2 (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGANDC2 on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-andc2 bit-array1 bit-array2 result-bit-array))
(defun bit-orc1 (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGORC1 on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-orc1 bit-array1 bit-array2 result-bit-array))
(defun bit-orc2 (bit-array1 bit-array2 &optional result-bit-array)
"Perform a bit-wise LOGORC2 on the elements of BIT-ARRAY-1 and BIT-ARRAY-2,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY-1 is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. All the arrays must have the same rank and dimensions."
(bit-boole boole-orc2 bit-array1 bit-array2 result-bit-array))
(defun bit-not (bit-array &optional result-bit-array)
"Performs a bit-wise logical NOT on the elements of BIT-ARRAY,
putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
BIT-ARRAY is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
created. Both arrays must have the same rank and dimensions."
(bit-boole boole-nor bit-array bit-array result-bit-array))
(defun result-bit-array (bit-array-1 bit-array-2 result)
Check that the two bit - array args are bit - arrays with
same dimensions as the other two arguments and return
(let* ((typecode-1 (typecode bit-array-1))
(typecode-2 (typecode bit-array-2)))
(declare (fixnum typecode-1 typecode-2))
(flet ((bit-array-dimensions (bit-array typecode)
(declare (fixnum typecode))
(if (= typecode target::subtag-bit-vector)
(uvsize bit-array)
(let* ((array-p (= typecode target::subtag-arrayH))
(vector-p (= typecode target::subtag-vectorH)))
(if (and (or array-p vector-p)
(= (the fixnum (%array-header-subtype bit-array)) target::subtag-bit-vector))
(if vector-p
(array-dimension bit-array 0)
(array-dimensions bit-array))
(report-bad-arg bit-array '(array bit))))))
(check-matching-dimensions (a1 d1 a2 d2)
(unless (equal d1 d2)
(error "~s and ~s have different dimensions." a1 a2))
a2))
(let* ((dims-1 (bit-array-dimensions bit-array-1 typecode-1))
(dims-2 (bit-array-dimensions bit-array-2 typecode-2)))
(check-matching-dimensions bit-array-1 dims-1 bit-array-2 dims-2)
(if result
(if (eq result t)
bit-array-1
(check-matching-dimensions bit-array-2 dims-2 result (bit-array-dimensions result (typecode result))))
(make-array dims-2 :element-type 'bit :initial-element 0))))))
(defun bit-boole (opcode array1 array2 result-array)
(unless (eql opcode (logand 15 opcode))
(setq opcode (require-type opcode '(mod 16))))
(let* ((result (result-bit-array array1 array2 result-array)))
(if (and (typep array1 'simple-bit-vector)
(typep array2 'simple-bit-vector)
(typep result 'simple-bit-vector))
(%simple-bit-boole opcode array1 array2 result)
(multiple-value-bind (v1 i1) (array-data-and-offset array1)
(declare (simple-bit-vector v1) (fixnum i1))
(multiple-value-bind (v2 i2) (array-data-and-offset array2)
(declare (simple-bit-vector v2) (fixnum i2))
(multiple-value-bind (v3 i3) (array-data-and-offset result)
(declare (simple-bit-vector v3) (fixnum i3))
(let* ((e3 (+ i3 (the fixnum (array-total-size result)))))
(declare (fixnum e3))
(do* ( )
((= i3 e3) result)
(setf (sbit v3 i3)
(logand (boole opcode (sbit v1 i1) (sbit v2 i2)) 1))
(incf i1)
(incf i2)
(incf i3)))))))))
Since there has n't been such a thing as sequences-2 in about 7 years ,
(eval-when (:compile-toplevel :execute :load-toplevel)
(defmacro shrink-vector (vector to-size)
`(setq ,vector (%shrink-vector ,vector ,to-size)))
)
(defun %shrink-vector (vector to-size)
(cond ((eq (length vector) to-size)
vector)
((array-has-fill-pointer-p vector)
(setf (fill-pointer vector) to-size)
vector)
(t (subseq vector 0 to-size))))
this could be put into print - db as it was in ccl - pr-4.2
(defun multi-dimension-array-to-list (array)
"Produces a nested list of the elements in array."
(mdal-aux array (array-dimensions array) nil
(array-dimensions array)))
(defun mdal-aux (array all-dimensions use-dimensions
remaining-dimensions)
(if (= (length all-dimensions) (length use-dimensions))
(apply 'aref array use-dimensions)
(do ((index 0 (1+ index))
(d-length (car remaining-dimensions))
(result nil))
((= d-length index) result)
(setq result
(append result (list (mdal-aux array all-dimensions
(append use-dimensions
(list index))
(cdr remaining-dimensions))))))))
(defun adjust-array (array dims
&key (element-type nil element-type-p)
(initial-element nil initial-element-p)
(initial-contents nil initial-contents-p)
(fill-pointer nil fill-pointer-p)
displaced-to
displaced-index-offset
&aux (subtype (array-element-subtype array)))
"Adjust ARRAY's dimensions to the given DIMENSIONS and stuff."
(when (and element-type-p
(neq (element-type-subtype element-type) subtype))
(error "~S is not of element type ~S" array element-type))
(if (neq (list-length dims)(array-rank array))
(error "~S has wrong rank for adjusting to dimensions ~S" array dims))
(let ((size 1)
(explicitp nil))
(dolist (dim dims)
(when (< dim 0)(report-bad-arg dims '(integer 0 *)))
(setq size (* size dim)))
(when (and (neq fill-pointer t)
(array-has-fill-pointer-p array)
(< size (or fill-pointer (fill-pointer array))))
(error "Cannot adjust array ~S to size less than fill pointer ~S"
array (or fill-pointer (fill-pointer array))))
(when (and fill-pointer (not (array-has-fill-pointer-p array)))
(error "~S does not have a fill pointer" array))
(when (and displaced-index-offset (null displaced-to))
(error "Cannot specify ~S without ~S" :displaced-index-offset :displaced-to))
(when (and initial-element-p initial-contents-p)
(error "Cannot specify both ~S and ~S" :initial-element :initial-contents))
(cond
((not (adjustable-array-p array))
(let ((new-array (make-array-1 dims
(array-element-type array) T
displaced-to
displaced-index-offset
nil
(or fill-pointer
(and (array-has-fill-pointer-p array)
(fill-pointer array)))
initial-element initial-element-p
initial-contents initial-contents-p
size)))
(when (and (null initial-contents-p)
(null displaced-to))
(multiple-value-bind (array-data offs) (array-data-and-offset array)
(let ((new-array-data (array-data-and-offset new-array)))
(cond ((null dims)
(uvset new-array-data 0 (uvref array-data offs)))
(T
(init-array-data array-data offs (array-dimensions array)
new-array-data 0 dims))))))
(setq array new-array)))
(T (cond
(displaced-to
(if (and displaced-index-offset
(or (not (fixnump displaced-index-offset))
(< displaced-index-offset 0)))
(report-bad-arg displaced-index-offset '(integer 0 #.most-positive-fixnum)))
(when (or initial-element-p initial-contents-p)
(error "Cannot specify initial values for displaced arrays"))
(unless (eq subtype (array-element-subtype displaced-to))
(error "~S is not of element type ~S"
displaced-to (array-element-type array)))
(do* ((vec displaced-to (displaced-array-p vec)))
((null vec) ())
(when (eq vec array)
(error "Array cannot be displaced to itself.")))
(setq explicitp t))
(T
(setq displaced-to (%alloc-misc size subtype))
(cond (initial-element-p
(dotimes (i (the fixnum size)) (uvset displaced-to i initial-element)))
(initial-contents-p
(if (null dims) (uvset displaced-to 0 initial-contents)
(init-uvector-contents displaced-to 0 dims initial-contents))))
(cond ((null dims)
(uvset displaced-to 0 (aref array)))
((not initial-contents-p)
(multiple-value-bind (vec offs) (array-data-and-offset array)
(init-array-data vec offs (array-dimensions array) displaced-to 0 dims))))))
(%displace-array array dims size displaced-to (or displaced-index-offset 0) explicitp)))
(when fill-pointer-p
(cond
((eq fill-pointer t)
(set-fill-pointer array size))
(fill-pointer
(set-fill-pointer array fill-pointer))))
array))
(defun array-dims-sizes (dims)
(if (or (atom dims) (null (%cdr dims))) dims
(let ((ndims (array-dims-sizes (%cdr dims))))
(cons (* (%car dims) (%car ndims)) ndims))))
(defun init-array-data (vec off dims nvec noff ndims)
(init-array-data-aux vec off dims (array-dims-sizes (cdr dims))
nvec noff ndims (array-dims-sizes (cdr ndims))))
(defun init-array-data-aux (vec off dims siz nvec noff ndims nsiz)
(when (null siz)
(return-from init-array-data-aux
(init-vector-data vec off (car dims) nvec noff (car ndims))))
(let ((count (pop dims))
(size (pop siz))
(ncount (pop ndims))
(nsize (pop nsiz)))
(dotimes (i (if (%i< count ncount) count ncount))
(declare (fixnum i))
(init-array-data-aux vec off dims siz nvec noff ndims nsiz)
(setq off (%i+ off size) noff (%i+ noff nsize)))))
(defun init-vector-data (vec off len nvec noff nlen)
(dotimes (i (if (%i< len nlen) len nlen))
(declare (fixnum i))
(uvset nvec noff (uvref vec off))
(setq off (%i+ off 1) noff (%i+ noff 1))))
(defun %displace-array (array dims size data offset explicitp)
(let* ((typecode (typecode array))
(array-p (eql typecode target::subtag-arrayH))
(vector-p (eql typecode target::subtag-vectorH)))
(unless (or array-p vector-p)
(error "Array ~S cannot be displaced" array))
(unless (fixnump offset) (report-bad-arg offset '(integer 0 #.most-positive-fixnum)))
(unless (adjustable-array-p data)
(multiple-value-bind (ndata noffset) (displaced-array-p data)
(if ndata (setq data ndata offset (%i+ offset noffset)))))
(unless (and (fixnump size) (%i<= (%i+ offset size) (array-total-size data)))
(error "Offset ~S + size ~S must be less than size of array displaced-to" offset size))
(let* ((flags (%svref array target::vectorH.flags-cell)))
(declare (fixnum flags))
(setf (%svref array target::vectorH.flags-cell)
(if (> (the fixnum (typecode data)) target::subtag-vectorH)
(bitclr $arh_disp_bit flags)
(bitset $arh_disp_bit flags)))
(setf (%svref array target::vectorH.flags-cell)
(if explicitp
(bitset $arh_exp_disp_bit flags)
(bitclr $arh_exp_disp_bit flags)))
(setf (%svref array target::arrayH.data-vector-cell) data)
(if array-p
(progn
(do ((i target::arrayH.dim0-cell (1+ i)))
((null dims))
(declare (fixnum i))
(setf (%svref array i) (pop dims)))
(setf (%svref array target::arrayH.physsize-cell) size)
(setf (%svref array target::arrayH.displacement-cell) offset))
(progn
(if (or (not (logbitp $arh_fill_bit flags))
(> (the fixnum (%svref array target::vectorH.logsize-cell)) size))
(setf (%svref array target::vectorH.logsize-cell) size))
(setf (%svref array target::vectorH.physsize-cell) size)
(setf (%svref array target::vectorH.displacement-cell) offset)))
array)))
(defun array-row-major-index (array &lexpr subscripts)
(let ((rank (array-rank array))
(nsubs (%lexpr-count subscripts))
(sum 0))
(declare (fixnum sum rank))
(unless (eql rank nsubs)
(%err-disp $xndims array nsubs))
(if (eql 0 rank)
0
(do* ((i (1- rank) (1- i))
(dim (array-dimension array i) (array-dimension array i))
(last-size 1 size)
(size dim (* dim size)))
(nil)
(declare (fixnum i last-size size))
(let ((s (%lexpr-ref subscripts nsubs i)))
(unless (fixnump s)
(setq s (require-type s 'fixnum)))
(when (or (< s 0) (>= s dim))
(%err-disp $XARROOB (%apply-lexpr 'list subscripts) array))
(incf sum (the fixnum (* s last-size)))
(when (eql i 0) (return sum)))))))
(defun array-in-bounds-p (array &lexpr subscripts)
"Return T if the SUBSCIPTS are in bounds for the ARRAY, NIL otherwise."
(let ((rank (array-rank array))
(nsubs (%lexpr-count subscripts)))
(declare (fixnum nsubs rank))
(if (not (eql nsubs rank))
(%err-disp $xndims array nsubs)
(if (eql 0 rank)
0
(do* ((i (1- rank) (1- i))
(dim (array-dimension array i) (array-dimension array i)))
(nil)
(declare (fixnum i dim))
(let ((s (%lexpr-ref subscripts nsubs i)))
(if (typep s 'fixnum)
(locally (declare (fixnum s))
(if (or (< s 0)(>= s dim)) (return nil)))
(if (typep s 'bignum)
(return nil)
(report-bad-arg s 'integer)))
(when (eql i 0) (return t))))))))
(defun row-major-aref (array index)
"Return the element of array corressponding to the row-major index. This is
SETF'able."
(multiple-value-bind (displaced-to offset) (displaced-array-p array)
(aref (or displaced-to array) (+ index offset))))
(defun row-major-aset (array index new)
(multiple-value-bind (displaced-to offset) (displaced-array-p array)
(setf (aref (or displaced-to array) (+ index offset)) new)))
(defsetf row-major-aref row-major-aset)
|
309883dad71496d1ce26640c5bbe48826edfcfb51044f3ffdaa49982b6954cb4 | rlepigre/pml | buckets.mli | (** Simple buckets in which a key is associated to multiple values. The keys
are compared with the equality function specified upon the creation of a
new structure. *)
(** Type of a bucket. *)
type ('a, 'b) t
(** Synonym of [('a, 'b) t]. *)
type ('a, 'b) buckets = ('a, 'b) t
(** [empty eq] creates an empty bucket using the given equality function for
comparing keys. *)
val empty : ('a -> 'a -> bool) -> ('a, 'b) t
(** [add key v bcks] maps the value [v] to the [key] in [bcks]. *)
val add : 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t
(** [find key bcks] obtains the list of all the values associated to [key].
Note that this operation cannot fails and returns [[]] in the case where
no value is assocaited to [key] in [bcks]. *)
val find : 'a -> ('a, 'b) t -> 'b list
(** length of the buckets *)
val length : ('a, 'b) t -> int
| null | https://raw.githubusercontent.com/rlepigre/pml/cdfdea0eecc6767b16edc6a7bef917bc9dd746ed/src/util/buckets.mli | ocaml | * Simple buckets in which a key is associated to multiple values. The keys
are compared with the equality function specified upon the creation of a
new structure.
* Type of a bucket.
* Synonym of [('a, 'b) t].
* [empty eq] creates an empty bucket using the given equality function for
comparing keys.
* [add key v bcks] maps the value [v] to the [key] in [bcks].
* [find key bcks] obtains the list of all the values associated to [key].
Note that this operation cannot fails and returns [[]] in the case where
no value is assocaited to [key] in [bcks].
* length of the buckets |
type ('a, 'b) t
type ('a, 'b) buckets = ('a, 'b) t
val empty : ('a -> 'a -> bool) -> ('a, 'b) t
val add : 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t
val find : 'a -> ('a, 'b) t -> 'b list
val length : ('a, 'b) t -> int
|
bf79a2644608fb322a59e787ac9efb3511c9ddf4fe51f7a5fc67db58bb2ef93e | rnons/shadowsocks-haskell | benchmark.hs | #!/usr/bin/env runhaskell
{-# LANGUAGE OverloadedStrings #-}
import Crypto.Hash.MD5 (hash)
import Data.Binary.Get (runGet, getWord64le)
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.List (sortBy)
import Data.IntMap.Strict (fromList, (!))
import Data.Word (Word8, Word64)
aPoem :: ByteString
aPoem = "First they came for the Socialists, and I did not speak out-- Because I was not a Socialist. Then they came for the Trade Unionists, and I did not speak out-- Because I was not a Trade Unionist. Then they came for the Jews, and I did not speak out-- Because I was not a Jew. Then they came for me--and there was no one left to speak for me."
getTable :: ByteString -> [Word8]
getTable key = do
let s = L.fromStrict $ hash key
a = runGet getWord64le s
table = [0..255]
map fromIntegral $ sortTable 1 a table
sortTable :: Word64 -> Word64 -> [Word64] -> [Word64]
sortTable 1024 _ table = table
sortTable i a table = sortTable (i+1) a $ sortBy cmp table
where
cmp x y = compare (a `mod` (x + i)) (a `mod` (y + i))
main :: IO ()
main = do
encrypted <- encrypt aPoem
decrypted <- decrypt encrypted
print $ aPoem == decrypted
where
table = getTable "Don't panic!"
encryptTable = fromList $ zip [0..255] table
decryptTable = fromList $ zip (map fromIntegral table) [0..255]
encrypt :: ByteString -> IO ByteString
encrypt buf = return $
S.pack $ map (\b -> encryptTable ! fromIntegral b) $ S.unpack buf
decrypt :: ByteString -> IO ByteString
decrypt buf = return $
S.pack $ map (\b -> decryptTable ! fromIntegral b) $ S.unpack buf
| null | https://raw.githubusercontent.com/rnons/shadowsocks-haskell/5d73db35e0a9f186b74a9e746ad9c9c6b41fb94d/benchmark/benchmark.hs | haskell | # LANGUAGE OverloadedStrings # | #!/usr/bin/env runhaskell
import Crypto.Hash.MD5 (hash)
import Data.Binary.Get (runGet, getWord64le)
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.List (sortBy)
import Data.IntMap.Strict (fromList, (!))
import Data.Word (Word8, Word64)
aPoem :: ByteString
aPoem = "First they came for the Socialists, and I did not speak out-- Because I was not a Socialist. Then they came for the Trade Unionists, and I did not speak out-- Because I was not a Trade Unionist. Then they came for the Jews, and I did not speak out-- Because I was not a Jew. Then they came for me--and there was no one left to speak for me."
getTable :: ByteString -> [Word8]
getTable key = do
let s = L.fromStrict $ hash key
a = runGet getWord64le s
table = [0..255]
map fromIntegral $ sortTable 1 a table
sortTable :: Word64 -> Word64 -> [Word64] -> [Word64]
sortTable 1024 _ table = table
sortTable i a table = sortTable (i+1) a $ sortBy cmp table
where
cmp x y = compare (a `mod` (x + i)) (a `mod` (y + i))
main :: IO ()
main = do
encrypted <- encrypt aPoem
decrypted <- decrypt encrypted
print $ aPoem == decrypted
where
table = getTable "Don't panic!"
encryptTable = fromList $ zip [0..255] table
decryptTable = fromList $ zip (map fromIntegral table) [0..255]
encrypt :: ByteString -> IO ByteString
encrypt buf = return $
S.pack $ map (\b -> encryptTable ! fromIntegral b) $ S.unpack buf
decrypt :: ByteString -> IO ByteString
decrypt buf = return $
S.pack $ map (\b -> decryptTable ! fromIntegral b) $ S.unpack buf
|
08b5f5d005910d1fe858e0a5d5354b45b23c0e610d67ec1235d6fbe711016b25 | AccelerateHS/accelerate-io | Internal.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
-- |
-- Module : Data.Array.Accelerate.IO.Data.Array.Internal
Copyright : [ 2017 .. 2020 ] The Accelerate Team
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
module Data.Array.Accelerate.IO.Data.Array.Internal
where
import Data.Array.Accelerate.Error
import Data.Array.Accelerate.Representation.Type
import Data.Array.Accelerate.Sugar.Elt
import Data.Array.Accelerate.Sugar.Shape
import Data.Array.Accelerate.Type
type family IxShapeRepr e where
IxShapeRepr () = ()
IxShapeRepr Int = ((),Int)
IxShapeRepr (t,h) = (IxShapeRepr t, h)
fromIxShapeRepr
:: forall ix sh. (HasCallStack, IxShapeRepr (EltR ix) ~ EltR sh, Shape sh, Elt ix)
=> sh
-> ix
fromIxShapeRepr sh = toElt (go (eltR @ix) (fromElt sh))
where
go :: forall ix'. TypeR ix' -> IxShapeRepr ix' -> ix'
go TupRunit () = ()
go (TupRpair tt _) (t, h) = (go tt t, h)
go (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt{})))) ((),h) = h
go _ _ =
internalError "not a valid IArray.Ix"
toIxShapeRepr
:: forall ix sh. (HasCallStack, IxShapeRepr (EltR ix) ~ EltR sh, Shape sh, Elt ix)
=> ix
-> sh
toIxShapeRepr ix = toElt (go (eltR @ix) (fromElt ix))
where
go :: forall ix'. TypeR ix' -> ix' -> IxShapeRepr ix'
go TupRunit () = ()
go (TupRpair tt _) (t, h) = (go tt t, h)
go (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt{})))) h = ((),h)
go _ _ =
internalError "not a valid IArray.Ix"
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-io/9d72bfb041ee2c9ffdb844b479f082e8993767f8/accelerate-io-array/src/Data/Array/Accelerate/IO/Data/Array/Internal.hs | haskell | # LANGUAGE OverloadedStrings #
|
Module : Data.Array.Accelerate.IO.Data.Array.Internal
License : BSD3
Stability : experimental
| # LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
Copyright : [ 2017 .. 2020 ] The Accelerate Team
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Data.Array.Accelerate.IO.Data.Array.Internal
where
import Data.Array.Accelerate.Error
import Data.Array.Accelerate.Representation.Type
import Data.Array.Accelerate.Sugar.Elt
import Data.Array.Accelerate.Sugar.Shape
import Data.Array.Accelerate.Type
type family IxShapeRepr e where
IxShapeRepr () = ()
IxShapeRepr Int = ((),Int)
IxShapeRepr (t,h) = (IxShapeRepr t, h)
fromIxShapeRepr
:: forall ix sh. (HasCallStack, IxShapeRepr (EltR ix) ~ EltR sh, Shape sh, Elt ix)
=> sh
-> ix
fromIxShapeRepr sh = toElt (go (eltR @ix) (fromElt sh))
where
go :: forall ix'. TypeR ix' -> IxShapeRepr ix' -> ix'
go TupRunit () = ()
go (TupRpair tt _) (t, h) = (go tt t, h)
go (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt{})))) ((),h) = h
go _ _ =
internalError "not a valid IArray.Ix"
toIxShapeRepr
:: forall ix sh. (HasCallStack, IxShapeRepr (EltR ix) ~ EltR sh, Shape sh, Elt ix)
=> ix
-> sh
toIxShapeRepr ix = toElt (go (eltR @ix) (fromElt ix))
where
go :: forall ix'. TypeR ix' -> ix' -> IxShapeRepr ix'
go TupRunit () = ()
go (TupRpair tt _) (t, h) = (go tt t, h)
go (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt{})))) h = ((),h)
go _ _ =
internalError "not a valid IArray.Ix"
|
4ae9dbb2446d0b9a7f1c9e5fff124eb7bfd527963f1202f33700436c3df11dac | nasa/Common-Metadata-Repository | tool_association.clj | (ns cmr.metadata-db.data.oracle.concepts.tool-association
"Implements multi-method variations for tools"
(:require
[cmr.metadata-db.data.oracle.concepts :as c]))
(defmethod c/db-result->concept-map :tool-association
[concept-type db provider-id result]
(some-> (c/db-result->concept-map :default db provider-id result)
(assoc :concept-type :tool-association)
(assoc-in [:extra-fields :associated-concept-id] (:associated_concept_id result))
(assoc-in [:extra-fields :associated-revision-id]
(when-let [ari (:associated_revision_id result)]
(long ari)))
(assoc-in [:extra-fields :tool-concept-id] (:source_concept_identifier result))
(assoc :user-id (:user_id result))))
(defn- var-assoc-concept->insert-args
[concept]
(let [{{:keys [associated-concept-id associated-revision-id tool-concept-id]} :extra-fields
:keys [user-id]} concept
[cols values] (c/concept->common-insert-args concept)]
[(concat cols ["associated_concept_id" "associated_revision_id" "source_concept_identifier" "user_id" "association_type"])
(concat values [associated-concept-id associated-revision-id tool-concept-id user-id "TOOL-COLLECTION"])]))
(defmethod c/concept->insert-args [:tool-association false]
[concept _]
(var-assoc-concept->insert-args concept))
(defmethod c/concept->insert-args [:tool-association true]
[concept _]
(var-assoc-concept->insert-args concept))
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/f189d55ded0c235f19fbfc3597e772e22e4498ad/metadata-db-app/src/cmr/metadata_db/data/oracle/concepts/tool_association.clj | clojure | (ns cmr.metadata-db.data.oracle.concepts.tool-association
"Implements multi-method variations for tools"
(:require
[cmr.metadata-db.data.oracle.concepts :as c]))
(defmethod c/db-result->concept-map :tool-association
[concept-type db provider-id result]
(some-> (c/db-result->concept-map :default db provider-id result)
(assoc :concept-type :tool-association)
(assoc-in [:extra-fields :associated-concept-id] (:associated_concept_id result))
(assoc-in [:extra-fields :associated-revision-id]
(when-let [ari (:associated_revision_id result)]
(long ari)))
(assoc-in [:extra-fields :tool-concept-id] (:source_concept_identifier result))
(assoc :user-id (:user_id result))))
(defn- var-assoc-concept->insert-args
[concept]
(let [{{:keys [associated-concept-id associated-revision-id tool-concept-id]} :extra-fields
:keys [user-id]} concept
[cols values] (c/concept->common-insert-args concept)]
[(concat cols ["associated_concept_id" "associated_revision_id" "source_concept_identifier" "user_id" "association_type"])
(concat values [associated-concept-id associated-revision-id tool-concept-id user-id "TOOL-COLLECTION"])]))
(defmethod c/concept->insert-args [:tool-association false]
[concept _]
(var-assoc-concept->insert-args concept))
(defmethod c/concept->insert-args [:tool-association true]
[concept _]
(var-assoc-concept->insert-args concept))
|
|
1e0a45a42f530f96d45da52860ff849725b94fc99accf7f3210f8fcf4cd9ddb4 | arrdem/blather | core.clj | (ns irregular.core
"Regular expressions.
As data structures.
It's a rite of passage I guess."
(:refer-clojure :exclude [empty? class?]))
(defn tag-dx
"Dispatch by :tag, :type, :ingeger for chars and ints,
otherwise :default."
[tagged-or-raw]
(cond (map? tagged-or-raw)
(:type tagged-or-raw
(:tag tagged-or-raw :default))
(char? tagged-or-raw)
::character
(string? tagged-or-raw)
::string
(keyword? tagged-or-raw)
tagged-or-raw
:default
(type tagged-or-raw)))
(defn pairwise-dx
"A dispatching function for pairs of records."
[x y]
[(tag-dx x) (tag-dx y)])
(defn derive!
"Although hierarchies are mostly used by indirection as
vars (`defmulti` supports the `:hierarchy` argument for using
hierarchies other than the default global one), and
although `(derive child parent)` implicitly side-effects the global
hierarchy, `(derive h child parent)` is a pure function of a
hierarchy as a map structure which doesn't behave nicely when given
a var.
Wrap it up with an alter-var-root so it makes sense."
[h child parent]
{:pre [(var? h)]}
(alter-var-root h derive child parent))
(def h
"NOT FOR PUBLIC CONSUMPTION.
The hierarchy used to structure irregular ASTs."
(make-hierarchy))
;; The dispatch hierarchy is as follows:
;; ::any
;; - ::empty
;; - ::not-empty
;; - <all other tags must be children of not-empty>
;;
This allows us to coherently special case arithmetic with empty , and only have one empty in the
;; algebra as everything else can normalize to the sentinel empty.
(defmulti multibyte?
"Determines whether a given value requires multibyte pattern matching."
#'tag-dx
:hierarchy #'h)
(defmulti score
"Attempts to score the simplicity of an expression by counting terms.
Lower scores are simpler. Scores of products must accumulate.
Used when attempting to compute simplifications to determine when an
equivalent computation is no simpler than original computation."
#'tag-dx
:hierarchy #'h)
(defmulti children
"For any given node, returns the sequence if its sub-terms."
#'tag-dx
:hierarchy #'h)
;; Forward declaration to help out writing the component fragments
(declare ->empty ->union ->subtraction ->intersection ->range)
;; Union
;;------------------------------------------------
(defmulti union*
"Extension point.
Implements union between a pair of character set values of possibly
different types.
Note to the implementer: Most character set structures cannot be
unioned to concrete values. Consequently, the default behavior for
this method should be to produce a union structure such as
{:tag ::union
:terms #{...}}
The union of unions is the union (possibly but not necessarily
simplified), and for some specific representations unions within the
representation may reduce."
#'pairwise-dx
:hierarchy #'h)
(defn union
"Union on character sets.
This method should be preferred to `#'union*` in client code.
By default, produces an empty union structure."
[& sets]
(reduce union* (->empty) sets))
;; Intersection
;;------------------------------------------------
(defmulti intersection*
"Extension point
Implements intersection between character set values of possibly
different types.
Note to the implementer: Most character set structures cannot be
intersected by value. Consequently, the default behavior for this
function should be to produce a symbolic intersection structure such
as
{:tag ::intersection
:a <term>
:bs #{<term>}}
Note that a set is usable since intersection is order-independent."
#'pairwise-dx
:hierarchy #'h)
(defn intersection
"Intersection on character sets.
This method should be preferred to `#'intersection*` in client
code."
[set & sets]
(reduce intersection* set sets))
(defmulti intersects?
"Predicate. Extension point.
Returns `true` if and only if the two argument structures can be
determined to intersect. If there is not a trivial intersection,
returns `false`.
Note to the implementer: False negatives are acceptable. False
positives are not."
#'pairwise-dx
:hierarchy #'h)
;; Subtraction
;;------------------------------------------------
(defmulti subtraction*
"Extension point.
Implements subtraction between character set types.
Note to the implementer: Most character set structures cannot be
subtracted by value. Consequently, the default behavior for this
function should be to produce a symbolic structure such as
{:tag ::subtraction
:a <term>
:bs #{<term>}}
Where :a is the value to be subtracted from, and :bs is the values
to subtract."
#'pairwise-dx
:hierarchy #'h)
(defn subtraction
"Subtraction on character sets.
This method should be preferred to `#'subtraction*` in client code."
[set & sets]
(reduce subtraction* set sets))
;; A helper since I'm gonna write lots of binary ops.
(defn- reversev [seq]
(vec (reverse seq)))
(defmacro ^:private defmethod-commutative
"Helper macro for defining multimethod implementations where the method is BINARY and COMMUTATIVE.
Cheats by only defining the explicitly listed dispatch constant with
the listed function body, and defining the other by self-calling the
multimethod.."
[method constant args & fn-body]
{:pre [(every? symbol? args)]}
`(do (defmethod ~method ~constant ~args ~@fn-body)
(defmethod ~method ~(reversev constant) ~(reversev args) (~method ~@args))))
;; Special terminals
(def EOF
"End Of File (input)"
::eof)
(defmethod multibyte? ::eof [_] false)
(def SOF
"Start Of File (input)"
::sof)
(defmethod multibyte? ::sof [_] false)
Load up the fragmented implementation because multimethods are imperative .
;;--------------------------------------------------------------------------------------------------
(load "core_empty")
(load "core_union")
(load "core_subtraction")
(load "core_intersection")
(load "core_equiv")
(load "core_collation")
(load "core_class")
(load "core_char")
(load "core_range")
| null | https://raw.githubusercontent.com/arrdem/blather/76fc860f26ae2fb7f0d2240da42cf85b0cb1169d/src/main/clj/irregular/core.clj | clojure | The dispatch hierarchy is as follows:
::any
- ::empty
- ::not-empty
- <all other tags must be children of not-empty>
algebra as everything else can normalize to the sentinel empty.
Forward declaration to help out writing the component fragments
Union
------------------------------------------------
Intersection
------------------------------------------------
Subtraction
------------------------------------------------
A helper since I'm gonna write lots of binary ops.
Special terminals
-------------------------------------------------------------------------------------------------- | (ns irregular.core
"Regular expressions.
As data structures.
It's a rite of passage I guess."
(:refer-clojure :exclude [empty? class?]))
(defn tag-dx
"Dispatch by :tag, :type, :ingeger for chars and ints,
otherwise :default."
[tagged-or-raw]
(cond (map? tagged-or-raw)
(:type tagged-or-raw
(:tag tagged-or-raw :default))
(char? tagged-or-raw)
::character
(string? tagged-or-raw)
::string
(keyword? tagged-or-raw)
tagged-or-raw
:default
(type tagged-or-raw)))
(defn pairwise-dx
"A dispatching function for pairs of records."
[x y]
[(tag-dx x) (tag-dx y)])
(defn derive!
"Although hierarchies are mostly used by indirection as
vars (`defmulti` supports the `:hierarchy` argument for using
hierarchies other than the default global one), and
although `(derive child parent)` implicitly side-effects the global
hierarchy, `(derive h child parent)` is a pure function of a
hierarchy as a map structure which doesn't behave nicely when given
a var.
Wrap it up with an alter-var-root so it makes sense."
[h child parent]
{:pre [(var? h)]}
(alter-var-root h derive child parent))
(def h
"NOT FOR PUBLIC CONSUMPTION.
The hierarchy used to structure irregular ASTs."
(make-hierarchy))
This allows us to coherently special case arithmetic with empty , and only have one empty in the
(defmulti multibyte?
"Determines whether a given value requires multibyte pattern matching."
#'tag-dx
:hierarchy #'h)
(defmulti score
"Attempts to score the simplicity of an expression by counting terms.
Lower scores are simpler. Scores of products must accumulate.
Used when attempting to compute simplifications to determine when an
equivalent computation is no simpler than original computation."
#'tag-dx
:hierarchy #'h)
(defmulti children
"For any given node, returns the sequence if its sub-terms."
#'tag-dx
:hierarchy #'h)
(declare ->empty ->union ->subtraction ->intersection ->range)
(defmulti union*
"Extension point.
Implements union between a pair of character set values of possibly
different types.
Note to the implementer: Most character set structures cannot be
unioned to concrete values. Consequently, the default behavior for
this method should be to produce a union structure such as
{:tag ::union
:terms #{...}}
The union of unions is the union (possibly but not necessarily
simplified), and for some specific representations unions within the
representation may reduce."
#'pairwise-dx
:hierarchy #'h)
(defn union
"Union on character sets.
This method should be preferred to `#'union*` in client code.
By default, produces an empty union structure."
[& sets]
(reduce union* (->empty) sets))
(defmulti intersection*
"Extension point
Implements intersection between character set values of possibly
different types.
Note to the implementer: Most character set structures cannot be
intersected by value. Consequently, the default behavior for this
function should be to produce a symbolic intersection structure such
as
{:tag ::intersection
:a <term>
:bs #{<term>}}
Note that a set is usable since intersection is order-independent."
#'pairwise-dx
:hierarchy #'h)
(defn intersection
"Intersection on character sets.
This method should be preferred to `#'intersection*` in client
code."
[set & sets]
(reduce intersection* set sets))
(defmulti intersects?
"Predicate. Extension point.
Returns `true` if and only if the two argument structures can be
determined to intersect. If there is not a trivial intersection,
returns `false`.
Note to the implementer: False negatives are acceptable. False
positives are not."
#'pairwise-dx
:hierarchy #'h)
(defmulti subtraction*
"Extension point.
Implements subtraction between character set types.
Note to the implementer: Most character set structures cannot be
subtracted by value. Consequently, the default behavior for this
function should be to produce a symbolic structure such as
{:tag ::subtraction
:a <term>
:bs #{<term>}}
Where :a is the value to be subtracted from, and :bs is the values
to subtract."
#'pairwise-dx
:hierarchy #'h)
(defn subtraction
"Subtraction on character sets.
This method should be preferred to `#'subtraction*` in client code."
[set & sets]
(reduce subtraction* set sets))
(defn- reversev [seq]
(vec (reverse seq)))
(defmacro ^:private defmethod-commutative
"Helper macro for defining multimethod implementations where the method is BINARY and COMMUTATIVE.
Cheats by only defining the explicitly listed dispatch constant with
the listed function body, and defining the other by self-calling the
multimethod.."
[method constant args & fn-body]
{:pre [(every? symbol? args)]}
`(do (defmethod ~method ~constant ~args ~@fn-body)
(defmethod ~method ~(reversev constant) ~(reversev args) (~method ~@args))))
(def EOF
"End Of File (input)"
::eof)
(defmethod multibyte? ::eof [_] false)
(def SOF
"Start Of File (input)"
::sof)
(defmethod multibyte? ::sof [_] false)
Load up the fragmented implementation because multimethods are imperative .
(load "core_empty")
(load "core_union")
(load "core_subtraction")
(load "core_intersection")
(load "core_equiv")
(load "core_collation")
(load "core_class")
(load "core_char")
(load "core_range")
|
2320bcd2dce4d9e5fdcb39a5b36a72dd8304f09547260f933c239ca315a7f122 | tiredpixel/isoxya-api | ApexSpec.hs | module Isoxya.API.Endpoint.ApexSpec (spec) where
import Isoxya.API.Test
spec :: Spec
spec = snapAPI $
describe "apex" $
it "=> 200" $ do
let req = get "/" emptyP
res <- runRequest req
rspStatus res `shouldBe` 200
b <- getResponseBody res
b ^. key "time" . _String `shouldContain` "T"
b ^. key "version" . _String `shouldBe` "0.0.0"
b ^. _Object `shouldMeasure` 2
| null | https://raw.githubusercontent.com/tiredpixel/isoxya-api/1022ee6db77f744c77541c53ef6f15f56884f939/test/Isoxya/API/Endpoint/ApexSpec.hs | haskell | module Isoxya.API.Endpoint.ApexSpec (spec) where
import Isoxya.API.Test
spec :: Spec
spec = snapAPI $
describe "apex" $
it "=> 200" $ do
let req = get "/" emptyP
res <- runRequest req
rspStatus res `shouldBe` 200
b <- getResponseBody res
b ^. key "time" . _String `shouldContain` "T"
b ^. key "version" . _String `shouldBe` "0.0.0"
b ^. _Object `shouldMeasure` 2
|
|
87ec0dbc8ad3f50225c0f6d1e4fd12508f51b0c0f20b298a32ed1cd1e9ff5806 | metametadata/carry | actions.cljs | (ns unit.actions
(:require
[friend-list.core :as friend-list]
[schema-generators.generators :as g]
[clojure.test :refer [deftest is]]))
(deftest
sets-query
(let [{:keys [initial-model on-action]} (friend-list/new-blueprint :_history :_search)]
(is (= "new query"
(:query (on-action initial-model [:set-query "new query"]))))))
(deftest
sets-friends
(let [{:keys [initial-model on-action]} (friend-list/new-blueprint :_history :_search)
new-friends (g/sample 3 friend-list/Friend)]
(is (= new-friends
(:friends (on-action initial-model [:set-friends new-friends])))))) | null | https://raw.githubusercontent.com/metametadata/carry/fa5c7cd0d8f1b71edca70330acc97c6245638efb/examples/friend-list/test/unit/actions.cljs | clojure | (ns unit.actions
(:require
[friend-list.core :as friend-list]
[schema-generators.generators :as g]
[clojure.test :refer [deftest is]]))
(deftest
sets-query
(let [{:keys [initial-model on-action]} (friend-list/new-blueprint :_history :_search)]
(is (= "new query"
(:query (on-action initial-model [:set-query "new query"]))))))
(deftest
sets-friends
(let [{:keys [initial-model on-action]} (friend-list/new-blueprint :_history :_search)
new-friends (g/sample 3 friend-list/Friend)]
(is (= new-friends
(:friends (on-action initial-model [:set-friends new-friends])))))) |
|
2de8dbe46210b3ee8c5aa697cc0752beb2c81ac30a76bfb4347c895f4b2ba1de | eslick/cl-registry | lam-tv-widget.lisp | (in-package :registry)
;;
LAM TV Video Popup
;;
(defun/cc do-lamtv-video ()
(do-dialog "LAM TV Video: LAMsight Presentation"
(make-instance 'lamtv-video)))
;;
Custom widget for LAM TV plugin
;;
(defwidget lamtv-video (flash)
()
(:default-initargs
:name "LAM TV Video"
:src ""
:width "480"
:height "390"
:id "video_div_1"
:params '(("flashvars" . "file=lta%2Flta-summit-2008-09-13-ianeslick.flv&streamscript=http%3A%2F%2Fv1.apebble.com%2Fflvstream.php&autostart=true"))))
;;
;; Render frame then base class widget
;;
(defmethod render-widget-body :around ((widget lamtv-video) &rest args)
(declare (ignore args))
(with-html
(:p "Filmed September 13th, 2008 at the TSA/LTA
Global Partnership Summit in Brighton, England")
(call-next-method)
(render-link (f* (answer widget)) "Return to the Home Page")))
;; (:object :type "application/x-shockwave-flash"
;; :data
: width " 480 "
: height " 390 "
;; :id "video_div_1"
(: param : name " flashvars "
;; :value "file=lta%2Flta-summit-2008-09-13-ianeslick.flv&streamscript=http%3A%2F%2Fv1.apebble.com%2Fflvstream.php&autostart=true"))
| null | https://raw.githubusercontent.com/eslick/cl-registry/d4015c400dc6abf0eeaf908ed9056aac956eee82/src/plugins/patient-home/lam-tv-widget.lisp | lisp |
Render frame then base class widget
(:object :type "application/x-shockwave-flash"
:data
:id "video_div_1"
:value "file=lta%2Flta-summit-2008-09-13-ianeslick.flv&streamscript=http%3A%2F%2Fv1.apebble.com%2Fflvstream.php&autostart=true")) | (in-package :registry)
LAM TV Video Popup
(defun/cc do-lamtv-video ()
(do-dialog "LAM TV Video: LAMsight Presentation"
(make-instance 'lamtv-video)))
Custom widget for LAM TV plugin
(defwidget lamtv-video (flash)
()
(:default-initargs
:name "LAM TV Video"
:src ""
:width "480"
:height "390"
:id "video_div_1"
:params '(("flashvars" . "file=lta%2Flta-summit-2008-09-13-ianeslick.flv&streamscript=http%3A%2F%2Fv1.apebble.com%2Fflvstream.php&autostart=true"))))
(defmethod render-widget-body :around ((widget lamtv-video) &rest args)
(declare (ignore args))
(with-html
(:p "Filmed September 13th, 2008 at the TSA/LTA
Global Partnership Summit in Brighton, England")
(call-next-method)
(render-link (f* (answer widget)) "Return to the Home Page")))
: width " 480 "
: height " 390 "
(: param : name " flashvars "
|
81494b5a5c3a20e1db82a688b491642438999a0851bf0cc495e1fe79e7600b74 | NorfairKing/cursor | Map.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TypeFamilies #
module Cursor.Map
( MapCursor (..),
makeMapCursor,
makeMapCursorWithSelection,
singletonMapCursorKey,
singletonMapCursorValue,
rebuildMapCursor,
mapMapCursor,
mapCursorNonEmptyCursorL,
mapCursorElemL,
mapCursorElemSelection,
mapCursorSelectKey,
mapCursorSelectValue,
mapCursorToggleSelected,
mapCursorSelectPrev,
mapCursorSelectNext,
mapCursorSelectFirst,
mapCursorSelectLast,
mapCursorSelection,
mapCursorSelectIndex,
mapCursorInsert,
mapCursorAppend,
mapCursorInsertAndSelectKey,
mapCursorAppendAndSelectKey,
mapCursorInsertAndSelectValue,
mapCursorAppendAndSelectValue,
mapCursorRemoveElemAndSelectPrev,
mapCursorDeleteElemAndSelectNext,
mapCursorRemoveElem,
mapCursorDeleteElem,
mapCursorSearch,
mapCursorSelectOrAdd,
traverseMapCursor,
mapCursorTraverseKeyCase,
mapCursorTraverseValueCase,
foldMapCursor,
module Cursor.Map.KeyValue,
)
where
import Control.DeepSeq
import Cursor.List.NonEmpty
import Cursor.Map.KeyValue
import Cursor.Types
import Data.List.NonEmpty (NonEmpty (..))
import Data.Maybe
import Data.Validity
import Data.Validity.Tree ()
import GHC.Generics (Generic)
import Lens.Micro
newtype MapCursor kc vc k v = MapCursor
{ mapCursorList :: NonEmptyCursor (KeyValueCursor kc vc k v) (k, v)
}
deriving (Show, Eq, Generic)
instance (Validity kc, Validity vc, Validity k, Validity v) => Validity (MapCursor kc vc k v)
instance (NFData kc, NFData vc, NFData k, NFData v) => NFData (MapCursor kc vc k v)
makeMapCursor :: (k -> kc) -> NonEmpty (k, v) -> MapCursor kc vc k v
makeMapCursor h = fromJust . makeMapCursorWithSelection h 0
makeMapCursorWithSelection :: (k -> kc) -> Int -> NonEmpty (k, v) -> Maybe (MapCursor kc vc k v)
makeMapCursorWithSelection h i ne =
MapCursor <$> makeNonEmptyCursorWithSelection (\(k, v) -> makeKeyValueCursorKey (h k) v) i ne
singletonMapCursorKey :: kc -> v -> MapCursor kc vc k v
singletonMapCursorKey kc v =
MapCursor {mapCursorList = singletonNonEmptyCursor $ makeKeyValueCursorKey kc v}
singletonMapCursorValue :: k -> vc -> MapCursor kc vc k v
singletonMapCursorValue k vc =
MapCursor {mapCursorList = singletonNonEmptyCursor $ makeKeyValueCursorValue k vc}
rebuildMapCursor :: (kc -> k) -> (vc -> v) -> MapCursor kc vc k v -> NonEmpty (k, v)
rebuildMapCursor f g = rebuildNonEmptyCursor (rebuildKeyValueCursor f g) . mapCursorList
mapMapCursor ::
(kc -> lc) -> (vc -> wc) -> (k -> l) -> (v -> w) -> MapCursor kc vc k v -> MapCursor lc wc l w
mapMapCursor a b c d =
mapCursorNonEmptyCursorL %~ mapNonEmptyCursor (mapKeyValueCursor a b c d) (\(k, v) -> (c k, d v))
mapCursorNonEmptyCursorL ::
Lens
(MapCursor kc vc k v)
(MapCursor lc wc l w)
( NonEmptyCursor
(KeyValueCursor kc vc k v)
( k,
v
)
)
( NonEmptyCursor
(KeyValueCursor lc wc l w)
( l,
w
)
)
mapCursorNonEmptyCursorL = lens mapCursorList $ \mc ne -> mc {mapCursorList = ne}
mapCursorElemL ::
Lens (MapCursor kc vc k v) (MapCursor kc' vc' k v) (KeyValueCursor kc vc k v) (KeyValueCursor kc' vc' k v)
mapCursorElemL = mapCursorNonEmptyCursorL . nonEmptyCursorElemL
mapCursorElemSelection :: MapCursor kc vc k v -> KeyValueToggle
mapCursorElemSelection mc = keyValueCursorSelection $ mc ^. mapCursorElemL
mapCursorSelectKey :: (k -> kc) -> (vc -> v) -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorSelectKey g h = mapCursorElemL %~ keyValueCursorSelectKey g h
mapCursorSelectValue :: (kc -> k) -> (v -> vc) -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorSelectValue f i = mapCursorElemL %~ keyValueCursorSelectValue f i
mapCursorToggleSelected ::
(kc -> k) -> (k -> kc) -> (vc -> v) -> (v -> vc) -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorToggleSelected f g h i = mapCursorElemL %~ keyValueCursorToggleSelected f g h i
mapCursorSelectPrev ::
(kc -> k) -> (k -> kc) -> (vc -> v) -> MapCursor kc vc k v -> Maybe (MapCursor kc vc k v)
mapCursorSelectPrev f g h =
mapCursorNonEmptyCursorL $ nonEmptyCursorSelectPrev (rebuild f h) (make g)
mapCursorSelectNext ::
(kc -> k) -> (k -> kc) -> (vc -> v) -> MapCursor kc vc k v -> Maybe (MapCursor kc vc k v)
mapCursorSelectNext f g h =
mapCursorNonEmptyCursorL $ nonEmptyCursorSelectNext (rebuild f h) (make g)
mapCursorSelectFirst ::
(kc -> k) -> (k -> kc) -> (vc -> v) -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorSelectFirst f g h =
mapCursorNonEmptyCursorL %~ nonEmptyCursorSelectFirst (rebuild f h) (make g)
mapCursorSelectLast ::
(kc -> k) -> (k -> kc) -> (vc -> v) -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorSelectLast f g h =
mapCursorNonEmptyCursorL %~ nonEmptyCursorSelectLast (rebuild f h) (make g)
mapCursorSelection :: MapCursor kc vc k v -> Int
mapCursorSelection = nonEmptyCursorSelection . mapCursorList
mapCursorSelectIndex ::
(kc -> k) ->
(k -> kc) ->
(vc -> v) ->
Int ->
MapCursor kc vc k v ->
Maybe (MapCursor kc vc k v)
mapCursorSelectIndex f g h i =
mapCursorNonEmptyCursorL (nonEmptyCursorSelectIndex (rebuild f h) (make g) i)
mapCursorInsert :: k -> v -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorInsert k v = mapCursorNonEmptyCursorL %~ nonEmptyCursorInsert (k, v)
mapCursorAppend :: k -> v -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorAppend k v = mapCursorNonEmptyCursorL %~ nonEmptyCursorAppend (k, v)
mapCursorInsertAndSelectKey ::
(kc -> k) -> (vc -> v) -> kc -> v -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorInsertAndSelectKey f h kc v =
mapCursorNonEmptyCursorL
%~ nonEmptyCursorInsertAndSelect (rebuild f h) (makeKeyValueCursorKey kc v)
mapCursorAppendAndSelectKey ::
(kc -> k) -> (vc -> v) -> kc -> v -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorAppendAndSelectKey f h kc v =
mapCursorNonEmptyCursorL
%~ nonEmptyCursorAppendAndSelect (rebuild f h) (makeKeyValueCursorKey kc v)
mapCursorInsertAndSelectValue ::
(kc -> k) -> (vc -> v) -> k -> vc -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorInsertAndSelectValue f h k vc =
mapCursorNonEmptyCursorL
%~ nonEmptyCursorInsertAndSelect (rebuild f h) (makeKeyValueCursorValue k vc)
mapCursorAppendAndSelectValue ::
(kc -> k) -> (vc -> v) -> k -> vc -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorAppendAndSelectValue f h k vc =
mapCursorNonEmptyCursorL
%~ nonEmptyCursorAppendAndSelect (rebuild f h) (makeKeyValueCursorValue k vc)
mapCursorRemoveElemAndSelectPrev ::
(k -> kc) -> MapCursor kc vc k v -> Maybe (DeleteOrUpdate (MapCursor kc vc k v))
mapCursorRemoveElemAndSelectPrev g =
focusPossibleDeleteOrUpdate mapCursorNonEmptyCursorL $
nonEmptyCursorRemoveElemAndSelectPrev (make g)
mapCursorDeleteElemAndSelectNext ::
(k -> kc) -> MapCursor kc vc k v -> Maybe (DeleteOrUpdate (MapCursor kc vc k v))
mapCursorDeleteElemAndSelectNext g =
focusPossibleDeleteOrUpdate mapCursorNonEmptyCursorL $
nonEmptyCursorDeleteElemAndSelectNext (make g)
mapCursorRemoveElem :: (k -> kc) -> MapCursor kc vc k v -> DeleteOrUpdate (MapCursor kc vc k v)
mapCursorRemoveElem g = mapCursorNonEmptyCursorL $ nonEmptyCursorRemoveElem (make g)
mapCursorDeleteElem :: (k -> kc) -> MapCursor kc vc k v -> DeleteOrUpdate (MapCursor kc vc k v)
mapCursorDeleteElem g = mapCursorNonEmptyCursorL $ nonEmptyCursorDeleteElem (make g)
mapCursorSearch ::
(kc -> k) ->
(k -> kc) ->
(vc -> v) ->
(k -> v -> Bool) ->
MapCursor kc vc k v ->
Maybe (MapCursor kc vc k v)
mapCursorSearch f g h p =
mapCursorNonEmptyCursorL $ nonEmptyCursorSearch (rebuild f h) (make g) (uncurry p . rebuild f h)
mapCursorSelectOrAdd ::
(kc -> k) ->
(k -> kc) ->
(vc -> v) ->
(k -> v -> Bool) ->
KeyValueCursor kc vc k v ->
MapCursor kc vc k v ->
MapCursor kc vc k v
mapCursorSelectOrAdd f g h p kvc =
mapCursorNonEmptyCursorL
%~ nonEmptyCursorSelectOrAdd (rebuild f h) (make g) (uncurry p . rebuild f h) kvc
rebuild :: (kc -> k) -> (vc -> v) -> KeyValueCursor kc vc k v -> (k, v)
rebuild = rebuildKeyValueCursor
make :: (k -> kc) -> (k, v) -> KeyValueCursor kc vc k v
make g (k, v) = makeKeyValueCursorKey (g k) v
traverseMapCursor ::
([(k, v)] -> KeyValueCursor kc vc k v -> [(k, v)] -> f c) -> MapCursor kc vc k v -> f c
traverseMapCursor combFunc = foldNonEmptyCursor combFunc . mapCursorList
mapCursorTraverseKeyCase ::
Applicative f => (kc -> v -> f (kc', v)) -> MapCursor kc vc k v -> f (MapCursor kc' vc k v)
mapCursorTraverseKeyCase func = mapCursorElemL $ keyValueCursorTraverseKeyCase func
mapCursorTraverseValueCase ::
Applicative f => (k -> vc -> f (k, vc')) -> MapCursor kc vc k v -> f (MapCursor kc vc' k v)
mapCursorTraverseValueCase func = mapCursorElemL $ keyValueCursorTraverseValueCase func
foldMapCursor :: ([(k, v)] -> KeyValueCursor kc vc k v -> [(k, v)] -> c) -> MapCursor kc vc k v -> c
foldMapCursor combFunc = foldNonEmptyCursor combFunc . mapCursorList
| null | https://raw.githubusercontent.com/NorfairKing/cursor/ff27e78281430c298a25a7805c9c61ca1e69f4c5/cursor/src/Cursor/Map.hs | haskell | # LANGUAGE RankNTypes # | # LANGUAGE DeriveGeneric #
# LANGUAGE TypeFamilies #
module Cursor.Map
( MapCursor (..),
makeMapCursor,
makeMapCursorWithSelection,
singletonMapCursorKey,
singletonMapCursorValue,
rebuildMapCursor,
mapMapCursor,
mapCursorNonEmptyCursorL,
mapCursorElemL,
mapCursorElemSelection,
mapCursorSelectKey,
mapCursorSelectValue,
mapCursorToggleSelected,
mapCursorSelectPrev,
mapCursorSelectNext,
mapCursorSelectFirst,
mapCursorSelectLast,
mapCursorSelection,
mapCursorSelectIndex,
mapCursorInsert,
mapCursorAppend,
mapCursorInsertAndSelectKey,
mapCursorAppendAndSelectKey,
mapCursorInsertAndSelectValue,
mapCursorAppendAndSelectValue,
mapCursorRemoveElemAndSelectPrev,
mapCursorDeleteElemAndSelectNext,
mapCursorRemoveElem,
mapCursorDeleteElem,
mapCursorSearch,
mapCursorSelectOrAdd,
traverseMapCursor,
mapCursorTraverseKeyCase,
mapCursorTraverseValueCase,
foldMapCursor,
module Cursor.Map.KeyValue,
)
where
import Control.DeepSeq
import Cursor.List.NonEmpty
import Cursor.Map.KeyValue
import Cursor.Types
import Data.List.NonEmpty (NonEmpty (..))
import Data.Maybe
import Data.Validity
import Data.Validity.Tree ()
import GHC.Generics (Generic)
import Lens.Micro
newtype MapCursor kc vc k v = MapCursor
{ mapCursorList :: NonEmptyCursor (KeyValueCursor kc vc k v) (k, v)
}
deriving (Show, Eq, Generic)
instance (Validity kc, Validity vc, Validity k, Validity v) => Validity (MapCursor kc vc k v)
instance (NFData kc, NFData vc, NFData k, NFData v) => NFData (MapCursor kc vc k v)
makeMapCursor :: (k -> kc) -> NonEmpty (k, v) -> MapCursor kc vc k v
makeMapCursor h = fromJust . makeMapCursorWithSelection h 0
makeMapCursorWithSelection :: (k -> kc) -> Int -> NonEmpty (k, v) -> Maybe (MapCursor kc vc k v)
makeMapCursorWithSelection h i ne =
MapCursor <$> makeNonEmptyCursorWithSelection (\(k, v) -> makeKeyValueCursorKey (h k) v) i ne
singletonMapCursorKey :: kc -> v -> MapCursor kc vc k v
singletonMapCursorKey kc v =
MapCursor {mapCursorList = singletonNonEmptyCursor $ makeKeyValueCursorKey kc v}
singletonMapCursorValue :: k -> vc -> MapCursor kc vc k v
singletonMapCursorValue k vc =
MapCursor {mapCursorList = singletonNonEmptyCursor $ makeKeyValueCursorValue k vc}
rebuildMapCursor :: (kc -> k) -> (vc -> v) -> MapCursor kc vc k v -> NonEmpty (k, v)
rebuildMapCursor f g = rebuildNonEmptyCursor (rebuildKeyValueCursor f g) . mapCursorList
mapMapCursor ::
(kc -> lc) -> (vc -> wc) -> (k -> l) -> (v -> w) -> MapCursor kc vc k v -> MapCursor lc wc l w
mapMapCursor a b c d =
mapCursorNonEmptyCursorL %~ mapNonEmptyCursor (mapKeyValueCursor a b c d) (\(k, v) -> (c k, d v))
mapCursorNonEmptyCursorL ::
Lens
(MapCursor kc vc k v)
(MapCursor lc wc l w)
( NonEmptyCursor
(KeyValueCursor kc vc k v)
( k,
v
)
)
( NonEmptyCursor
(KeyValueCursor lc wc l w)
( l,
w
)
)
mapCursorNonEmptyCursorL = lens mapCursorList $ \mc ne -> mc {mapCursorList = ne}
mapCursorElemL ::
Lens (MapCursor kc vc k v) (MapCursor kc' vc' k v) (KeyValueCursor kc vc k v) (KeyValueCursor kc' vc' k v)
mapCursorElemL = mapCursorNonEmptyCursorL . nonEmptyCursorElemL
mapCursorElemSelection :: MapCursor kc vc k v -> KeyValueToggle
mapCursorElemSelection mc = keyValueCursorSelection $ mc ^. mapCursorElemL
mapCursorSelectKey :: (k -> kc) -> (vc -> v) -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorSelectKey g h = mapCursorElemL %~ keyValueCursorSelectKey g h
mapCursorSelectValue :: (kc -> k) -> (v -> vc) -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorSelectValue f i = mapCursorElemL %~ keyValueCursorSelectValue f i
mapCursorToggleSelected ::
(kc -> k) -> (k -> kc) -> (vc -> v) -> (v -> vc) -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorToggleSelected f g h i = mapCursorElemL %~ keyValueCursorToggleSelected f g h i
mapCursorSelectPrev ::
(kc -> k) -> (k -> kc) -> (vc -> v) -> MapCursor kc vc k v -> Maybe (MapCursor kc vc k v)
mapCursorSelectPrev f g h =
mapCursorNonEmptyCursorL $ nonEmptyCursorSelectPrev (rebuild f h) (make g)
mapCursorSelectNext ::
(kc -> k) -> (k -> kc) -> (vc -> v) -> MapCursor kc vc k v -> Maybe (MapCursor kc vc k v)
mapCursorSelectNext f g h =
mapCursorNonEmptyCursorL $ nonEmptyCursorSelectNext (rebuild f h) (make g)
mapCursorSelectFirst ::
(kc -> k) -> (k -> kc) -> (vc -> v) -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorSelectFirst f g h =
mapCursorNonEmptyCursorL %~ nonEmptyCursorSelectFirst (rebuild f h) (make g)
mapCursorSelectLast ::
(kc -> k) -> (k -> kc) -> (vc -> v) -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorSelectLast f g h =
mapCursorNonEmptyCursorL %~ nonEmptyCursorSelectLast (rebuild f h) (make g)
mapCursorSelection :: MapCursor kc vc k v -> Int
mapCursorSelection = nonEmptyCursorSelection . mapCursorList
mapCursorSelectIndex ::
(kc -> k) ->
(k -> kc) ->
(vc -> v) ->
Int ->
MapCursor kc vc k v ->
Maybe (MapCursor kc vc k v)
mapCursorSelectIndex f g h i =
mapCursorNonEmptyCursorL (nonEmptyCursorSelectIndex (rebuild f h) (make g) i)
mapCursorInsert :: k -> v -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorInsert k v = mapCursorNonEmptyCursorL %~ nonEmptyCursorInsert (k, v)
mapCursorAppend :: k -> v -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorAppend k v = mapCursorNonEmptyCursorL %~ nonEmptyCursorAppend (k, v)
mapCursorInsertAndSelectKey ::
(kc -> k) -> (vc -> v) -> kc -> v -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorInsertAndSelectKey f h kc v =
mapCursorNonEmptyCursorL
%~ nonEmptyCursorInsertAndSelect (rebuild f h) (makeKeyValueCursorKey kc v)
mapCursorAppendAndSelectKey ::
(kc -> k) -> (vc -> v) -> kc -> v -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorAppendAndSelectKey f h kc v =
mapCursorNonEmptyCursorL
%~ nonEmptyCursorAppendAndSelect (rebuild f h) (makeKeyValueCursorKey kc v)
mapCursorInsertAndSelectValue ::
(kc -> k) -> (vc -> v) -> k -> vc -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorInsertAndSelectValue f h k vc =
mapCursorNonEmptyCursorL
%~ nonEmptyCursorInsertAndSelect (rebuild f h) (makeKeyValueCursorValue k vc)
mapCursorAppendAndSelectValue ::
(kc -> k) -> (vc -> v) -> k -> vc -> MapCursor kc vc k v -> MapCursor kc vc k v
mapCursorAppendAndSelectValue f h k vc =
mapCursorNonEmptyCursorL
%~ nonEmptyCursorAppendAndSelect (rebuild f h) (makeKeyValueCursorValue k vc)
mapCursorRemoveElemAndSelectPrev ::
(k -> kc) -> MapCursor kc vc k v -> Maybe (DeleteOrUpdate (MapCursor kc vc k v))
mapCursorRemoveElemAndSelectPrev g =
focusPossibleDeleteOrUpdate mapCursorNonEmptyCursorL $
nonEmptyCursorRemoveElemAndSelectPrev (make g)
mapCursorDeleteElemAndSelectNext ::
(k -> kc) -> MapCursor kc vc k v -> Maybe (DeleteOrUpdate (MapCursor kc vc k v))
mapCursorDeleteElemAndSelectNext g =
focusPossibleDeleteOrUpdate mapCursorNonEmptyCursorL $
nonEmptyCursorDeleteElemAndSelectNext (make g)
mapCursorRemoveElem :: (k -> kc) -> MapCursor kc vc k v -> DeleteOrUpdate (MapCursor kc vc k v)
mapCursorRemoveElem g = mapCursorNonEmptyCursorL $ nonEmptyCursorRemoveElem (make g)
mapCursorDeleteElem :: (k -> kc) -> MapCursor kc vc k v -> DeleteOrUpdate (MapCursor kc vc k v)
mapCursorDeleteElem g = mapCursorNonEmptyCursorL $ nonEmptyCursorDeleteElem (make g)
mapCursorSearch ::
(kc -> k) ->
(k -> kc) ->
(vc -> v) ->
(k -> v -> Bool) ->
MapCursor kc vc k v ->
Maybe (MapCursor kc vc k v)
mapCursorSearch f g h p =
mapCursorNonEmptyCursorL $ nonEmptyCursorSearch (rebuild f h) (make g) (uncurry p . rebuild f h)
mapCursorSelectOrAdd ::
(kc -> k) ->
(k -> kc) ->
(vc -> v) ->
(k -> v -> Bool) ->
KeyValueCursor kc vc k v ->
MapCursor kc vc k v ->
MapCursor kc vc k v
mapCursorSelectOrAdd f g h p kvc =
mapCursorNonEmptyCursorL
%~ nonEmptyCursorSelectOrAdd (rebuild f h) (make g) (uncurry p . rebuild f h) kvc
rebuild :: (kc -> k) -> (vc -> v) -> KeyValueCursor kc vc k v -> (k, v)
rebuild = rebuildKeyValueCursor
make :: (k -> kc) -> (k, v) -> KeyValueCursor kc vc k v
make g (k, v) = makeKeyValueCursorKey (g k) v
traverseMapCursor ::
([(k, v)] -> KeyValueCursor kc vc k v -> [(k, v)] -> f c) -> MapCursor kc vc k v -> f c
traverseMapCursor combFunc = foldNonEmptyCursor combFunc . mapCursorList
mapCursorTraverseKeyCase ::
Applicative f => (kc -> v -> f (kc', v)) -> MapCursor kc vc k v -> f (MapCursor kc' vc k v)
mapCursorTraverseKeyCase func = mapCursorElemL $ keyValueCursorTraverseKeyCase func
mapCursorTraverseValueCase ::
Applicative f => (k -> vc -> f (k, vc')) -> MapCursor kc vc k v -> f (MapCursor kc vc' k v)
mapCursorTraverseValueCase func = mapCursorElemL $ keyValueCursorTraverseValueCase func
foldMapCursor :: ([(k, v)] -> KeyValueCursor kc vc k v -> [(k, v)] -> c) -> MapCursor kc vc k v -> c
foldMapCursor combFunc = foldNonEmptyCursor combFunc . mapCursorList
|
1a4da5ba01df8a5222070a8425451e9e0947002f5b60254b4b2b26c91ba28dd8 | tezos-checker/checker | testTez.ml | open OUnit2
open TestLib
TODO : Would be nice to have randomized tests , and even check the bounds
* tightly . Perhaps we should consider doing something similar for the other
* types ( Lqt , Kit , ) .
* tightly. Perhaps we should consider doing something similar for the other
* types (Lqt, Kit, Ctez). *)
let suite =
"TezTests" >::: [
"tez arithmetic" >::
(fun _ ->
assert_tez_equal
~expected:(Ligo.tez_from_literal "8_000_000mutez")
~real:(Ligo.add_tez_tez (Ligo.tez_from_literal "5_000_000mutez") (Ligo.tez_from_literal "3_000_000mutez"));
assert_tez_equal
~expected:(Ligo.tez_from_literal "2_000_000mutez")
~real:(Ligo.sub_tez_tez (Ligo.tez_from_literal "5_000_000mutez") (Ligo.tez_from_literal "3_000_000mutez"));
assert_tez_equal
~expected:(Ligo.tez_from_literal "5_000_000mutez")
~real:(max (Ligo.tez_from_literal "5_000_000mutez") (Ligo.tez_from_literal "3_000_000mutez"));
assert_string_equal
~expected:"50309951mutez"
~real:(Ligo.string_of_tez (Ligo.tez_from_literal "50_309_951mutez"));
)
]
let () =
run_test_tt_main
suite
| null | https://raw.githubusercontent.com/tezos-checker/checker/2fa79837c80beb3818af166d85ae02ffc7651c49/tests/testTez.ml | ocaml | open OUnit2
open TestLib
TODO : Would be nice to have randomized tests , and even check the bounds
* tightly . Perhaps we should consider doing something similar for the other
* types ( Lqt , Kit , ) .
* tightly. Perhaps we should consider doing something similar for the other
* types (Lqt, Kit, Ctez). *)
let suite =
"TezTests" >::: [
"tez arithmetic" >::
(fun _ ->
assert_tez_equal
~expected:(Ligo.tez_from_literal "8_000_000mutez")
~real:(Ligo.add_tez_tez (Ligo.tez_from_literal "5_000_000mutez") (Ligo.tez_from_literal "3_000_000mutez"));
assert_tez_equal
~expected:(Ligo.tez_from_literal "2_000_000mutez")
~real:(Ligo.sub_tez_tez (Ligo.tez_from_literal "5_000_000mutez") (Ligo.tez_from_literal "3_000_000mutez"));
assert_tez_equal
~expected:(Ligo.tez_from_literal "5_000_000mutez")
~real:(max (Ligo.tez_from_literal "5_000_000mutez") (Ligo.tez_from_literal "3_000_000mutez"));
assert_string_equal
~expected:"50309951mutez"
~real:(Ligo.string_of_tez (Ligo.tez_from_literal "50_309_951mutez"));
)
]
let () =
run_test_tt_main
suite
|
|
c5f80a39c60b6ef484b98cc1fbcd925ab82a8dc25e8a3afec9ba6c37925dbedc | csabahruska/jhc-components | BitSet.hs | {-# LANGUAGE BangPatterns #-}
module Util.BitSet(
BitSet(),
EnumBitSet(..),
toWord,
fromWord
) where
import Data.List(foldl')
import Data.Bits
import Data.Word
import Data.Monoid
import Util.SetLike
import Util.HasSize
newtype BitSet = BitSet Word
deriving(Eq,Ord)
instance Monoid BitSet where
mempty = BitSet 0
mappend (BitSet a) (BitSet b) = BitSet (a .|. b)
mconcat ss = foldl' mappend mempty ss
instance Unionize BitSet where
BitSet a `difference` BitSet b = BitSet (a .&. complement b)
BitSet a `intersection` BitSet b = BitSet (a .&. b)
type instance Elem BitSet = Int
instance Collection BitSet where
type = Int
singleton i = BitSet (bit i)
fromList ts = BitSet (foldl' setBit 0 ts)
toList (BitSet w) = f w 0 where
f 0 _ = []
f w n = if even w then f (w `shiftR` 1) (n + 1) else n:f (w `shiftR` 1) (n + 1)
type instance Key BitSet = Elem BitSet
instance SetLike BitSet where
keys bs = toList bs
delete i (BitSet v) = BitSet (clearBit v i)
member i (BitSet v) = testBit v i
insert i (BitSet v) = BitSet (v .|. bit i)
sfilter fn (BitSet w) = f w 0 0 where
f 0 _ r = BitSet r
f w n r = if even w || not (fn n) then f w1 n1 r else f w1 n1 (setBit r n) where
!n1 = n + 1
!w1 = w `shiftR` 1
spartition = error "BitSet.spartition: not impl."
instance IsEmpty BitSet where
isEmpty (BitSet n) = n == 0
instance HasSize BitSet where
size (BitSet n) = f 0 n where
f !c 0 = c
f !c !v = f (c + 1) (v .&. (v - 1))
instance SetLike BitSet where
BitSet a ` difference ` BitSet b = BitSet ( a . & . complement b )
BitSet a ` intersection ` BitSet b = BitSet ( a . & . b )
BitSet a ` disjoint ` BitSet b = ( ( a . & . b ) = = 0 )
BitSet a ` isSubsetOf ` BitSet b = ( a .| . b ) = = b
sempty = BitSet 0
union ( BitSet a ) ( BitSet b ) = BitSet ( a .| . b )
unions ss = foldl ' union sempty ss
instance BuildSet Int BitSet where
insert i ( BitSet v ) = BitSet ( v .| . bit i )
singleton i = BitSet ( bit i )
fromList ts = BitSet ( foldl ' setBit 0 ts )
instance ModifySet Int BitSet where
delete i ( BitSet v ) = BitSet ( clearBit v i )
member i ( BitSet v ) = testBit v i
toList ( BitSet w ) = f w 0 where
f 0 _ = [ ]
f w n = if even w then f ( w ` shiftR ` 1 ) ( n + 1 ) else n : f ( w ` shiftR ` 1 ) ( n + 1 )
sfilter fn ( BitSet w ) = f w 0 0 where
f 0 _ r = BitSet r
f w n r = if even w || not ( fn n ) then f w1 n1 r else f w1 n1 ( setBit r n ) where
! n1 = n + 1
! w1 = w ` shiftR ` 1
instance SetLike BitSet where
BitSet a `difference` BitSet b = BitSet (a .&. complement b)
BitSet a `intersection` BitSet b = BitSet (a .&. b)
BitSet a `disjoint` BitSet b = ((a .&. b) == 0)
BitSet a `isSubsetOf` BitSet b = (a .|. b) == b
sempty = BitSet 0
union (BitSet a) (BitSet b) = BitSet (a .|. b)
unions ss = foldl' union sempty ss
instance BuildSet Int BitSet where
insert i (BitSet v) = BitSet (v .|. bit i)
singleton i = BitSet (bit i)
fromList ts = BitSet (foldl' setBit 0 ts)
instance ModifySet Int BitSet where
delete i (BitSet v) = BitSet (clearBit v i)
member i (BitSet v) = testBit v i
toList (BitSet w) = f w 0 where
f 0 _ = []
f w n = if even w then f (w `shiftR` 1) (n + 1) else n:f (w `shiftR` 1) (n + 1)
sfilter fn (BitSet w) = f w 0 0 where
f 0 _ r = BitSet r
f w n r = if even w || not (fn n) then f w1 n1 r else f w1 n1 (setBit r n) where
!n1 = n + 1
!w1 = w `shiftR` 1
-}
instance Show BitSet where
showsPrec n bs = showsPrec n (toList bs)
newtype EnumBitSet a = EBS BitSet
deriving(Monoid,Unionize,HasSize,Eq,Ord,IsEmpty)
type instance Elem (EnumBitSet a) = a
instance Enum a => Collection (EnumBitSet a) where
singleton i = EBS $ singleton (fromEnum i)
fromList ts = EBS $ fromList (map fromEnum ts)
toList (EBS w) = map toEnum $ toList w
type instance Key (EnumBitSet a) = Elem (EnumBitSet a)
instance Enum a => SetLike (EnumBitSet a) where
delete (fromEnum -> i) (EBS v) = EBS $ delete i v
member (fromEnum -> i) (EBS v) = member i v
insert (fromEnum -> i) (EBS v) = EBS $ insert i v
sfilter f (EBS v) = EBS $ sfilter (f . toEnum) v
keys = error "EnumBitSet.keys: not impl."
spartition = error "EnumBitSet.spartition: not impl."
instance a = > BuildSet a ( EnumBitSet a ) where
fromList xs = EnumBitSet $ fromList ( map fromEnum xs )
insert x ( EnumBitSet s ) = EnumBitSet $ insert ( fromEnum x ) s
singleton x = EnumBitSet $ singleton ( fromEnum x )
instance a = > ModifySet a ( EnumBitSet a ) where
toList ( EnumBitSet s ) = map toEnum $ toList s
member x ( EnumBitSet s ) = member ( fromEnum x ) s
delete x ( EnumBitSet s ) = EnumBitSet $ delete ( fromEnum x ) s
sfilter fn ( EnumBitSet s ) = EnumBitSet $ sfilter ( fn . ) s
instance ( a , Show a ) = > Show ( EnumBitSet a ) where
showsPrec n bs = showsPrec n ( toList bs )
instance Enum a => BuildSet a (EnumBitSet a) where
fromList xs = EnumBitSet $ fromList (map fromEnum xs)
insert x (EnumBitSet s) = EnumBitSet $ insert (fromEnum x) s
singleton x = EnumBitSet $ singleton (fromEnum x)
instance Enum a => ModifySet a (EnumBitSet a) where
toList (EnumBitSet s) = map toEnum $ toList s
member x (EnumBitSet s) = member (fromEnum x) s
delete x (EnumBitSet s) = EnumBitSet $ delete (fromEnum x) s
sfilter fn (EnumBitSet s) = EnumBitSet $ sfilter (fn . toEnum) s
instance (Enum a,Show a) => Show (EnumBitSet a) where
showsPrec n bs = showsPrec n (toList bs)
-}
toWord :: BitSet -> Word
toWord (BitSet w) = w
fromWord :: Word -> BitSet
fromWord w = BitSet w
| null | https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/jhc-common/src/Util/BitSet.hs | haskell | # LANGUAGE BangPatterns # | module Util.BitSet(
BitSet(),
EnumBitSet(..),
toWord,
fromWord
) where
import Data.List(foldl')
import Data.Bits
import Data.Word
import Data.Monoid
import Util.SetLike
import Util.HasSize
newtype BitSet = BitSet Word
deriving(Eq,Ord)
instance Monoid BitSet where
mempty = BitSet 0
mappend (BitSet a) (BitSet b) = BitSet (a .|. b)
mconcat ss = foldl' mappend mempty ss
instance Unionize BitSet where
BitSet a `difference` BitSet b = BitSet (a .&. complement b)
BitSet a `intersection` BitSet b = BitSet (a .&. b)
type instance Elem BitSet = Int
instance Collection BitSet where
type = Int
singleton i = BitSet (bit i)
fromList ts = BitSet (foldl' setBit 0 ts)
toList (BitSet w) = f w 0 where
f 0 _ = []
f w n = if even w then f (w `shiftR` 1) (n + 1) else n:f (w `shiftR` 1) (n + 1)
type instance Key BitSet = Elem BitSet
instance SetLike BitSet where
keys bs = toList bs
delete i (BitSet v) = BitSet (clearBit v i)
member i (BitSet v) = testBit v i
insert i (BitSet v) = BitSet (v .|. bit i)
sfilter fn (BitSet w) = f w 0 0 where
f 0 _ r = BitSet r
f w n r = if even w || not (fn n) then f w1 n1 r else f w1 n1 (setBit r n) where
!n1 = n + 1
!w1 = w `shiftR` 1
spartition = error "BitSet.spartition: not impl."
instance IsEmpty BitSet where
isEmpty (BitSet n) = n == 0
instance HasSize BitSet where
size (BitSet n) = f 0 n where
f !c 0 = c
f !c !v = f (c + 1) (v .&. (v - 1))
instance SetLike BitSet where
BitSet a ` difference ` BitSet b = BitSet ( a . & . complement b )
BitSet a ` intersection ` BitSet b = BitSet ( a . & . b )
BitSet a ` disjoint ` BitSet b = ( ( a . & . b ) = = 0 )
BitSet a ` isSubsetOf ` BitSet b = ( a .| . b ) = = b
sempty = BitSet 0
union ( BitSet a ) ( BitSet b ) = BitSet ( a .| . b )
unions ss = foldl ' union sempty ss
instance BuildSet Int BitSet where
insert i ( BitSet v ) = BitSet ( v .| . bit i )
singleton i = BitSet ( bit i )
fromList ts = BitSet ( foldl ' setBit 0 ts )
instance ModifySet Int BitSet where
delete i ( BitSet v ) = BitSet ( clearBit v i )
member i ( BitSet v ) = testBit v i
toList ( BitSet w ) = f w 0 where
f 0 _ = [ ]
f w n = if even w then f ( w ` shiftR ` 1 ) ( n + 1 ) else n : f ( w ` shiftR ` 1 ) ( n + 1 )
sfilter fn ( BitSet w ) = f w 0 0 where
f 0 _ r = BitSet r
f w n r = if even w || not ( fn n ) then f w1 n1 r else f w1 n1 ( setBit r n ) where
! n1 = n + 1
! w1 = w ` shiftR ` 1
instance SetLike BitSet where
BitSet a `difference` BitSet b = BitSet (a .&. complement b)
BitSet a `intersection` BitSet b = BitSet (a .&. b)
BitSet a `disjoint` BitSet b = ((a .&. b) == 0)
BitSet a `isSubsetOf` BitSet b = (a .|. b) == b
sempty = BitSet 0
union (BitSet a) (BitSet b) = BitSet (a .|. b)
unions ss = foldl' union sempty ss
instance BuildSet Int BitSet where
insert i (BitSet v) = BitSet (v .|. bit i)
singleton i = BitSet (bit i)
fromList ts = BitSet (foldl' setBit 0 ts)
instance ModifySet Int BitSet where
delete i (BitSet v) = BitSet (clearBit v i)
member i (BitSet v) = testBit v i
toList (BitSet w) = f w 0 where
f 0 _ = []
f w n = if even w then f (w `shiftR` 1) (n + 1) else n:f (w `shiftR` 1) (n + 1)
sfilter fn (BitSet w) = f w 0 0 where
f 0 _ r = BitSet r
f w n r = if even w || not (fn n) then f w1 n1 r else f w1 n1 (setBit r n) where
!n1 = n + 1
!w1 = w `shiftR` 1
-}
instance Show BitSet where
showsPrec n bs = showsPrec n (toList bs)
newtype EnumBitSet a = EBS BitSet
deriving(Monoid,Unionize,HasSize,Eq,Ord,IsEmpty)
type instance Elem (EnumBitSet a) = a
instance Enum a => Collection (EnumBitSet a) where
singleton i = EBS $ singleton (fromEnum i)
fromList ts = EBS $ fromList (map fromEnum ts)
toList (EBS w) = map toEnum $ toList w
type instance Key (EnumBitSet a) = Elem (EnumBitSet a)
instance Enum a => SetLike (EnumBitSet a) where
delete (fromEnum -> i) (EBS v) = EBS $ delete i v
member (fromEnum -> i) (EBS v) = member i v
insert (fromEnum -> i) (EBS v) = EBS $ insert i v
sfilter f (EBS v) = EBS $ sfilter (f . toEnum) v
keys = error "EnumBitSet.keys: not impl."
spartition = error "EnumBitSet.spartition: not impl."
instance a = > BuildSet a ( EnumBitSet a ) where
fromList xs = EnumBitSet $ fromList ( map fromEnum xs )
insert x ( EnumBitSet s ) = EnumBitSet $ insert ( fromEnum x ) s
singleton x = EnumBitSet $ singleton ( fromEnum x )
instance a = > ModifySet a ( EnumBitSet a ) where
toList ( EnumBitSet s ) = map toEnum $ toList s
member x ( EnumBitSet s ) = member ( fromEnum x ) s
delete x ( EnumBitSet s ) = EnumBitSet $ delete ( fromEnum x ) s
sfilter fn ( EnumBitSet s ) = EnumBitSet $ sfilter ( fn . ) s
instance ( a , Show a ) = > Show ( EnumBitSet a ) where
showsPrec n bs = showsPrec n ( toList bs )
instance Enum a => BuildSet a (EnumBitSet a) where
fromList xs = EnumBitSet $ fromList (map fromEnum xs)
insert x (EnumBitSet s) = EnumBitSet $ insert (fromEnum x) s
singleton x = EnumBitSet $ singleton (fromEnum x)
instance Enum a => ModifySet a (EnumBitSet a) where
toList (EnumBitSet s) = map toEnum $ toList s
member x (EnumBitSet s) = member (fromEnum x) s
delete x (EnumBitSet s) = EnumBitSet $ delete (fromEnum x) s
sfilter fn (EnumBitSet s) = EnumBitSet $ sfilter (fn . toEnum) s
instance (Enum a,Show a) => Show (EnumBitSet a) where
showsPrec n bs = showsPrec n (toList bs)
-}
toWord :: BitSet -> Word
toWord (BitSet w) = w
fromWord :: Word -> BitSet
fromWord w = BitSet w
|
2c74c3e5abcaffceea41aa7784b7e7f5c7366ea9f86a2f3828fdc8c4947b0744 | manuel-serrano/bigloo | rawmidi.scm | ;*=====================================================================*/
* ... /prgm / project / bigloo / bigloo / api / alsa / src / Llib / rawmidi.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Mon Mar 4 08:15:55 2019 * /
* Last change : We d Mar 13 08:15:55 2019 ( serrano ) * /
* Copyright : 2019 * /
;* ------------------------------------------------------------- */
;* ALSA rawmidi wrapper */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __alsa_rawmidi
(library multimedia)
(include "alsa.sch")
(import __alsa_alsa
__alsa_control)
(extern (macro $u8vector->bytes::void*
(::u8vector) "BGL_SVECTOR_TO_PTR")
(macro $bstring->bytes::void*
(::bstring) "(void *)BSTRING_TO_STRING"))
(export (class alsa-snd-rawmidi::alsa-object
($builtin::$snd-rawmidi read-only (default (%$snd-rawmidi-nil))))
(%$snd-rawmidi-nil)
(alsa-snd-rawmidi-open-output::alsa-snd-rawmidi ::bstring ::symbol)
(alsa-snd-rawmidi-close ::alsa-snd-rawmidi)
(inline alsa-snd-rawmidi-input?::bool ::alsa-snd-ctl ::int ::int)
(inline alsa-snd-rawmidi-output?::bool ::alsa-snd-ctl ::int ::int)
(inline alsa-snd-rawmidi-write-byte ::alsa-snd-rawmidi ::uint8)
(inline alsa-snd-rawmidi-write-bytes ::alsa-snd-rawmidi ::u8vector)
(alsa-snd-rawmidi-write-string ::alsa-snd-rawmidi ::bstring)
(inline alsa-snd-rawmidi-drain ::alsa-snd-rawmidi)
(inline alsa-snd-rawmidi-drop ::alsa-snd-rawmidi)))
;*---------------------------------------------------------------------*/
* % $ snd - rawmidi - nil ... * /
;*---------------------------------------------------------------------*/
(define (%$snd-rawmidi-nil)
($snd-rawmidi-nil))
;*---------------------------------------------------------------------*/
;* alsa-snd-rawmidi-open-output ... */
;*---------------------------------------------------------------------*/
(define (alsa-snd-rawmidi-open-output name flag)
(define (flag->rawmidi-mode flag)
(case flag
((append) $snd-rawmidi-append)
((nonblock) $snd-rawmidi-nonblock)
((sync) $snd-rawmidi-sync)
(else (error "alsa-snd-rawmidi-open-output" "Illegal flag" flag))))
(let ((o (instantiate::alsa-snd-rawmidi)))
($bgl-snd-rawmidi-open-output o name (flag->rawmidi-mode flag))
o))
;*---------------------------------------------------------------------*/
;* alsa-snd-rawmidi-close ... */
;*---------------------------------------------------------------------*/
(define (alsa-snd-rawmidi-close rm::alsa-snd-rawmidi)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-close $builtin)))
;*---------------------------------------------------------------------*/
;* alsa-snd-rawmidi-input? ... */
;*---------------------------------------------------------------------*/
(define-inline (alsa-snd-rawmidi-input?::bool ctl device sub)
($bgl-snd-rawmidi-isdir ctl device sub $snd-rawmidi-stream-input))
;*---------------------------------------------------------------------*/
;* alsa-snd-rawmidi-output? ... */
;*---------------------------------------------------------------------*/
(define-inline (alsa-snd-rawmidi-output?::bool ctl device sub)
($bgl-snd-rawmidi-isdir ctl device sub $snd-rawmidi-stream-output))
;*---------------------------------------------------------------------*/
;* alsa-snd-rawmidi-drain ... */
;*---------------------------------------------------------------------*/
(define-inline (alsa-snd-rawmidi-drain rm::alsa-snd-rawmidi)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-drain $builtin)))
;*---------------------------------------------------------------------*/
;* alsa-snd-rawmidi-drop ... */
;*---------------------------------------------------------------------*/
(define-inline (alsa-snd-rawmidi-drop rm::alsa-snd-rawmidi)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-drop $builtin)))
;*---------------------------------------------------------------------*/
;* alsa-snd-rawmidi-write-byte ... */
;*---------------------------------------------------------------------*/
(define-inline (alsa-snd-rawmidi-write-byte rm::alsa-snd-rawmidi byte)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-write $builtin (pragma::void* "&($1)" byte) 1)))
;*---------------------------------------------------------------------*/
;* alsa-snd-rawmidi-write-bytes ... */
;*---------------------------------------------------------------------*/
(define-inline (alsa-snd-rawmidi-write-bytes rm::alsa-snd-rawmidi bytes)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-write $builtin ($u8vector->bytes bytes)
(u8vector-length bytes))))
;*---------------------------------------------------------------------*/
;* alsa-snd-rawmidi-write-string ... */
;*---------------------------------------------------------------------*/
(define (alsa-snd-rawmidi-write-string rm::alsa-snd-rawmidi string)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-write $builtin ($bstring->bytes string)
(string-length string))))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/api/alsa/src/Llib/rawmidi.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* ALSA rawmidi wrapper */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* alsa-snd-rawmidi-open-output ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* alsa-snd-rawmidi-close ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* alsa-snd-rawmidi-input? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* alsa-snd-rawmidi-output? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* alsa-snd-rawmidi-drain ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* alsa-snd-rawmidi-drop ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* alsa-snd-rawmidi-write-byte ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* alsa-snd-rawmidi-write-bytes ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* alsa-snd-rawmidi-write-string ... */
*---------------------------------------------------------------------*/ | * ... /prgm / project / bigloo / bigloo / api / alsa / src / Llib / rawmidi.scm * /
* Author : * /
* Creation : Mon Mar 4 08:15:55 2019 * /
* Last change : We d Mar 13 08:15:55 2019 ( serrano ) * /
* Copyright : 2019 * /
(module __alsa_rawmidi
(library multimedia)
(include "alsa.sch")
(import __alsa_alsa
__alsa_control)
(extern (macro $u8vector->bytes::void*
(::u8vector) "BGL_SVECTOR_TO_PTR")
(macro $bstring->bytes::void*
(::bstring) "(void *)BSTRING_TO_STRING"))
(export (class alsa-snd-rawmidi::alsa-object
($builtin::$snd-rawmidi read-only (default (%$snd-rawmidi-nil))))
(%$snd-rawmidi-nil)
(alsa-snd-rawmidi-open-output::alsa-snd-rawmidi ::bstring ::symbol)
(alsa-snd-rawmidi-close ::alsa-snd-rawmidi)
(inline alsa-snd-rawmidi-input?::bool ::alsa-snd-ctl ::int ::int)
(inline alsa-snd-rawmidi-output?::bool ::alsa-snd-ctl ::int ::int)
(inline alsa-snd-rawmidi-write-byte ::alsa-snd-rawmidi ::uint8)
(inline alsa-snd-rawmidi-write-bytes ::alsa-snd-rawmidi ::u8vector)
(alsa-snd-rawmidi-write-string ::alsa-snd-rawmidi ::bstring)
(inline alsa-snd-rawmidi-drain ::alsa-snd-rawmidi)
(inline alsa-snd-rawmidi-drop ::alsa-snd-rawmidi)))
* % $ snd - rawmidi - nil ... * /
(define (%$snd-rawmidi-nil)
($snd-rawmidi-nil))
(define (alsa-snd-rawmidi-open-output name flag)
(define (flag->rawmidi-mode flag)
(case flag
((append) $snd-rawmidi-append)
((nonblock) $snd-rawmidi-nonblock)
((sync) $snd-rawmidi-sync)
(else (error "alsa-snd-rawmidi-open-output" "Illegal flag" flag))))
(let ((o (instantiate::alsa-snd-rawmidi)))
($bgl-snd-rawmidi-open-output o name (flag->rawmidi-mode flag))
o))
(define (alsa-snd-rawmidi-close rm::alsa-snd-rawmidi)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-close $builtin)))
(define-inline (alsa-snd-rawmidi-input?::bool ctl device sub)
($bgl-snd-rawmidi-isdir ctl device sub $snd-rawmidi-stream-input))
(define-inline (alsa-snd-rawmidi-output?::bool ctl device sub)
($bgl-snd-rawmidi-isdir ctl device sub $snd-rawmidi-stream-output))
(define-inline (alsa-snd-rawmidi-drain rm::alsa-snd-rawmidi)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-drain $builtin)))
(define-inline (alsa-snd-rawmidi-drop rm::alsa-snd-rawmidi)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-drop $builtin)))
(define-inline (alsa-snd-rawmidi-write-byte rm::alsa-snd-rawmidi byte)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-write $builtin (pragma::void* "&($1)" byte) 1)))
(define-inline (alsa-snd-rawmidi-write-bytes rm::alsa-snd-rawmidi bytes)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-write $builtin ($u8vector->bytes bytes)
(u8vector-length bytes))))
(define (alsa-snd-rawmidi-write-string rm::alsa-snd-rawmidi string)
(with-access::alsa-snd-rawmidi rm ($builtin)
($snd-rawmidi-write $builtin ($bstring->bytes string)
(string-length string))))
|
3dbc726e2c4f226ca49067af1fbbd09d6aad15c09152ea5c0d551edc1403f22d | soegaard/sketching | inheritance.rkt | #lang sketching
;;;
;;; Inheritance
;;;
;; A class can be defined using another class as a foundation.
In object - oriented programming terminology , one class can inherit fields and methods from another .
;; An object that inherits from another is called a subclass,
;; and the object it inherits from is called a superclass. A subclass extends the superclass.
(class Spin Object
(init-field x y speed)
(field [angle #f])
Constructor
(super-new)
(:= angle 0.0)
; Methods
(define/public (update)
(+= angle speed)))
(class SpinArm Spin
(inherit-field x y speed angle) ; bring variables into scope
Constructor
(super-new)
; (super-make-object x y speed) ; invoke super class initialization
; Methods
(define/public (display)
(stroke-weight 1)
(stroke 0)
(push-matrix)
(translate x y)
(+= angle speed)
(rotate angle)
(line 0 0 165 0)
(pop-matrix)))
(class SpinSpots Spin
(init-field dim)
(inherit-field x y speed angle)
Constructor
(super-new)
; (super-make-object x y speed)
; Methods
(define/public (display)
(no-stroke)
(push-matrix)
(translate x y)
(+= angle speed)
(rotate angle)
(ellipse (- (/ dim 2)) 0 dim dim)
(ellipse (+ (/ dim 2)) 0 dim dim)
(pop-matrix)))
(define spots #f)
(define arm #f)
(define (setup)
(size 640 360)
(frame-rate 60)
(:= arm (make-object SpinArm (/ width 2) (/ height 2) 0.01 ))
(:= spots (make-object SpinSpots
90.0 ; new field
(/ width 2) (/ height 2) -0.02))) ; super fields
(define (draw)
(background 204)
(arm.update)
(arm.display)
(spots.update)
(spots.display))
| null | https://raw.githubusercontent.com/soegaard/sketching/7fa0a354b6711345f0fe0c835241d7c6c666c044/sketching-doc/sketching-doc/manual-examples/basics/objects/inheritance.rkt | racket |
Inheritance
A class can be defined using another class as a foundation.
An object that inherits from another is called a subclass,
and the object it inherits from is called a superclass. A subclass extends the superclass.
Methods
bring variables into scope
(super-make-object x y speed) ; invoke super class initialization
Methods
(super-make-object x y speed)
Methods
new field
super fields | #lang sketching
In object - oriented programming terminology , one class can inherit fields and methods from another .
(class Spin Object
(init-field x y speed)
(field [angle #f])
Constructor
(super-new)
(:= angle 0.0)
(define/public (update)
(+= angle speed)))
(class SpinArm Spin
Constructor
(super-new)
(define/public (display)
(stroke-weight 1)
(stroke 0)
(push-matrix)
(translate x y)
(+= angle speed)
(rotate angle)
(line 0 0 165 0)
(pop-matrix)))
(class SpinSpots Spin
(init-field dim)
(inherit-field x y speed angle)
Constructor
(super-new)
(define/public (display)
(no-stroke)
(push-matrix)
(translate x y)
(+= angle speed)
(rotate angle)
(ellipse (- (/ dim 2)) 0 dim dim)
(ellipse (+ (/ dim 2)) 0 dim dim)
(pop-matrix)))
(define spots #f)
(define arm #f)
(define (setup)
(size 640 360)
(frame-rate 60)
(:= arm (make-object SpinArm (/ width 2) (/ height 2) 0.01 ))
(:= spots (make-object SpinSpots
(define (draw)
(background 204)
(arm.update)
(arm.display)
(spots.update)
(spots.display))
|
c1905c1ee453b69829097809fb2244f75db8955a9e0ad7c009a04e89c2436f19 | mschuldt/ga144 | rom-dump.rkt | #lang racket ;; -*- lexical-binding: t -*-
(require "el.rkt")
(provide (all-defined-out))
(defconst ROM-DUMP (list
'(707 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(706 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(705 152917 79017 18610 7 79056 225476 87381 2409 239325 238797 36794 182645 22218 47 22474 43 111829 22218 58 22474 59 22218 42 22474 43 155066 17 79061 79047 209115 87381 204285 131071 158234 195708 243624 159679 145057 39714 31602 141485 71093 1714 112053 23999 497 0 3072 79052 79042 79042 240818 79042 79042 243417 18930 122880 112053 194265 177881 192702 87381 79065 61630)
'(704 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(703 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(702 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(701 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 18963 12609 262142 43442 79269 70826 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(700 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71061 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(600 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(601 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(602 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(603 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(604 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(605 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(606 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(607 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(608 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(609 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(610 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(611 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(612 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(613 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(614 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(615 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(616 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(516 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(515 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(514 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(513 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(512 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(511 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(510 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(509 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(508 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(507 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(506 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(505 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(504 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(503 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(502 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(501 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(500 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(400 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(401 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(402 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(403 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(404 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(405 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(406 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(407 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(408 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(409 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(410 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(411 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(412 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(413 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(414 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(415 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(416 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(316 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(315 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(314 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(313 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(312 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(311 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(310 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(309 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(308 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(307 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(306 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(305 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(304 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(303 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(302 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(301 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(300 79042 79042 222354 180738 209603 212475 2 180738 185031 16578 2 230229 179643 16 148402 217545 144082 239325 238797 158394 32442 141490 79052 158394 60592 159956 10837 20334 65536 240117 239280 210261 79017 158234 195708 243624 159679 145057 39714 31602 141485 71045 18954 12709 2482 111795 19899 261509 245682 111798 128176 18666 389 193877 79038 194238 177854 192699 87381 79038 61627 87381 153280 79040)
'(200 240117 239280 210261 179643 16 148402 217545 144073 239325 238797 79043 140398 239322 210261 238677 151011 180717 79567 179642 17 150002 191920 151216 112347 240818 128724 150005 132066 159956 150005 141459 179642 17 8706 111782 239322 209057 158293 238713 158293 79017 71045 23978 373 421 19347 349 19898 183 196026 16 8706 112005 240306 70817 194206 177822 192699 87381 79006 61627 87381 20329 65536)
'(201 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(202 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(203 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(204 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(205 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(206 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(207 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(208 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(209 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(210 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(211 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(212 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(213 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(214 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(215 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(216 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(116 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(115 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(114 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(113 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(112 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(111 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(110 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(109 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(108 18610 4761 79018 128194 79018 22188 66560 79018 22188 32769 79018 79018 22188 32770 79018 79018 22188 33 79018 79018 22188 16384 79018 70830 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71077 23125 78848 23085 23112 23218 78848 22188 32771 79018 18610 120 23218 78848 100 10674 14890 128183 70830 241845 23218 78848 70830)
'(107 19378 277 23298 14770 158501 79018 17378 132096 48426 23117 158466 19378 277 23333 22187 19202 349 222317 192434 79317 134322 16562 2048 103643 190898 79173 158130 243663 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71077 149698 198594 198594 198594 111801 16530 32767 17330 98304 48426 23112 16538 24576 16469 1023 131506 70831 79018 17378 164864 48426 23115)
'(106 23330 245077 70840 79034 79026 153528 79034 70839 243640 137150 153534 133306 240797 202069 226645 131949 132016 111827 151013 21845 1 131951 251859 251858 111834 148429 148309 132858 235448 260024 79024 210261 103647 148309 251832 207346 210872 79017 79017 79017 79017 71077 78908 5461 18933 1 153260 137130 18933 262143 194224 159666 78910 38229 79028 79022 194222 161109 194226 161109 23298 153941 194234 161109)
'(105 1 194233 79035 161109 194233 79039 161109 79020 153265 243370 153516 148589 244550 239709 153260 194239 160459 194235 161742 79033 194512 153260 194239 161713 79033 103643 243647 243628 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71077 18933 262143 23330 22186 23301 182710 136874 23333 22206 136874 79020 70833 136874 135090 70836 23301 54968 23331 18871 40226 79028 18933)
'(104 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(103 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(102 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(101 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(100 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(0 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71061 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(1 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 18963 12609 262142 43442 79269 70826 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(2 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(3 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(4 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(5 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(6 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(7 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71093 13653 23338 87381 23381 83285 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017)
'(8 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71093 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017)
'(9 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71093 23474 251221 15170 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017)
'(10 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(11 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(12 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(13 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(14 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(15 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(16 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(17 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71061 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(117 159714 141746 121778 121637 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 149690 134346 247999 341)
'(217 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(317 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(417 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(517 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(617 159714 141746 121778 121637 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 149690 134346 247999 341)
'(717 159714 141746 121778 121637 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71061 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 149690 134346 247999 341)
'(716 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(715 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(714 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(713 159714 141746 121778 121637 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 149690 134346 247999 341)
'(712 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(711 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(710 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(709 159714 141746 121778 121637 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 149690 134346 247999 341)
'(708 2411 180856 71093 180890 206677 153275 134594 247986 2409 180856 5461 79038 79038 153285 79059 79056 243397 79058 79059 79060 190362 131858 131072 254850 194504 190898 225621 190898 201045 79017 79017 79017 79017 158234 195708 243624 159679 145057 39714 31602 141485 71093 18954 12709 2482 111800 79051 239794 79051 240306 79051 239741 87381 79051 243837 87381 245178 437 193877 180738 111803 180821 150859 231098)
))
| null | https://raw.githubusercontent.com/mschuldt/ga144/5b327b958f5d35cf5a015044e6ee62f46446169f/src/rom-dump.rkt | racket | -*- lexical-binding: t -*- | (require "el.rkt")
(provide (all-defined-out))
(defconst ROM-DUMP (list
'(707 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(706 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(705 152917 79017 18610 7 79056 225476 87381 2409 239325 238797 36794 182645 22218 47 22474 43 111829 22218 58 22474 59 22218 42 22474 43 155066 17 79061 79047 209115 87381 204285 131071 158234 195708 243624 159679 145057 39714 31602 141485 71093 1714 112053 23999 497 0 3072 79052 79042 79042 240818 79042 79042 243417 18930 122880 112053 194265 177881 192702 87381 79065 61630)
'(704 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(703 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(702 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(701 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 18963 12609 262142 43442 79269 70826 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(700 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71061 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(600 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(601 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(602 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(603 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(604 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(605 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(606 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(607 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(608 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(609 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(610 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(611 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(612 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(613 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(614 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(615 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(616 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(516 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(515 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(514 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(513 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(512 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(511 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(510 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(509 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(508 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(507 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(506 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(505 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(504 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(503 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(502 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(501 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(500 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(400 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(401 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(402 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(403 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(404 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(405 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(406 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(407 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(408 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(409 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(410 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(411 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(412 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(413 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(414 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(415 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(416 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(316 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(315 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(314 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(313 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(312 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(311 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(310 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(309 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(308 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(307 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(306 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(305 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(304 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(303 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(302 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(301 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(300 79042 79042 222354 180738 209603 212475 2 180738 185031 16578 2 230229 179643 16 148402 217545 144082 239325 238797 158394 32442 141490 79052 158394 60592 159956 10837 20334 65536 240117 239280 210261 79017 158234 195708 243624 159679 145057 39714 31602 141485 71045 18954 12709 2482 111795 19899 261509 245682 111798 128176 18666 389 193877 79038 194238 177854 192699 87381 79038 61627 87381 153280 79040)
'(200 240117 239280 210261 179643 16 148402 217545 144073 239325 238797 79043 140398 239322 210261 238677 151011 180717 79567 179642 17 150002 191920 151216 112347 240818 128724 150005 132066 159956 150005 141459 179642 17 8706 111782 239322 209057 158293 238713 158293 79017 71045 23978 373 421 19347 349 19898 183 196026 16 8706 112005 240306 70817 194206 177822 192699 87381 79006 61627 87381 20329 65536)
'(201 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(202 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(203 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(204 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(205 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(206 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(207 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(208 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(209 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(210 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(211 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(212 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(213 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(214 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(215 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(216 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(116 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(115 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(114 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(113 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(112 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(111 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(110 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(109 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(108 18610 4761 79018 128194 79018 22188 66560 79018 22188 32769 79018 79018 22188 32770 79018 79018 22188 33 79018 79018 22188 16384 79018 70830 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71077 23125 78848 23085 23112 23218 78848 22188 32771 79018 18610 120 23218 78848 100 10674 14890 128183 70830 241845 23218 78848 70830)
'(107 19378 277 23298 14770 158501 79018 17378 132096 48426 23117 158466 19378 277 23333 22187 19202 349 222317 192434 79317 134322 16562 2048 103643 190898 79173 158130 243663 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71077 149698 198594 198594 198594 111801 16530 32767 17330 98304 48426 23112 16538 24576 16469 1023 131506 70831 79018 17378 164864 48426 23115)
'(106 23330 245077 70840 79034 79026 153528 79034 70839 243640 137150 153534 133306 240797 202069 226645 131949 132016 111827 151013 21845 1 131951 251859 251858 111834 148429 148309 132858 235448 260024 79024 210261 103647 148309 251832 207346 210872 79017 79017 79017 79017 71077 78908 5461 18933 1 153260 137130 18933 262143 194224 159666 78910 38229 79028 79022 194222 161109 194226 161109 23298 153941 194234 161109)
'(105 1 194233 79035 161109 194233 79039 161109 79020 153265 243370 153516 148589 244550 239709 153260 194239 160459 194235 161742 79033 194512 153260 194239 161713 79033 103643 243647 243628 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71077 18933 262143 23330 22186 23301 182710 136874 23333 22206 136874 79020 70833 136874 135090 70836 23301 54968 23331 18871 40226 79028 18933)
'(104 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(103 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(102 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(101 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71077 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(100 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(0 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71061 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(1 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 18963 12609 262142 43442 79269 70826 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(2 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(3 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(4 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(5 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(6 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(7 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71093 13653 23338 87381 23381 83285 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017)
'(8 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71093 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017)
'(9 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 71093 23474 251221 15170 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017 79017)
'(10 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(11 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(12 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(13 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(14 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(15 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(16 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(17 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71061 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(117 159714 141746 121778 121637 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 149690 134346 247999 341)
'(217 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(317 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(417 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(517 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(617 159714 141746 121778 121637 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71045 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 149690 134346 247999 341)
'(717 159714 141746 121778 121637 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71061 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 149690 134346 247999 341)
'(716 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(715 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(714 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(713 159714 141746 121778 121637 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 149690 134346 247999 341)
'(712 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(711 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(710 158394 60592 159933 10837 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 158394 32442 141490 79024)
'(709 159714 141746 121778 121637 149690 133554 201130 256027 26288 208043 148402 217530 240816 87381 20329 65536 240117 239280 210261 151011 180717 79571 179642 17 150002 191920 151216 112350 240760 150005 132066 159960 150005 158234 195708 243624 159679 145057 39714 31602 141485 71093 158394 28338 194231 158232 143532 193877 179643 16 148402 217545 144054 239325 238797 79024 140395 239322 210261 238677 149690 134346 247999 341)
'(708 2411 180856 71093 180890 206677 153275 134594 247986 2409 180856 5461 79038 79038 153285 79059 79056 243397 79058 79059 79060 190362 131858 131072 254850 194504 190898 225621 190898 201045 79017 79017 79017 79017 158234 195708 243624 159679 145057 39714 31602 141485 71093 18954 12709 2482 111800 79051 239794 79051 240306 79051 239741 87381 79051 243837 87381 245178 437 193877 180738 111803 180821 150859 231098)
))
|
fa3d924dd60e7e90acd4723e99dd4ea30bc3bd256441c45182adf7190cf7ff34 | webyrd/n-grams-for-synthesis | default.scm | ;;; The default comparator
;; The unknown-object comparator, used as a fallback to everything else
(define unknown-object-comparator
(make-comparator
(lambda (obj) #t)
(lambda (a b) #t)
(lambda (a b) 0)
(lambda (obj) 0)))
Next index for added comparator
(define first-comparator-index 9)
(define *next-comparator-index* 9)
(define *registered-comparators* (list unknown-object-comparator))
;; Register a new comparator for use by the default comparator.
(define (comparator-register-default! comparator)
(set! *registered-comparators* (cons comparator *registered-comparators*))
(set! *next-comparator-index* (+ *next-comparator-index* 1)))
;; Return ordinal for object types: null sorts before pairs, which sort
;; before booleans, etc. Implementations can extend this.
;; People who call comparator-register-default! effectively do extend it.
(define (object-type obj)
(cond
((null? obj) 0)
((pair? obj) 1)
((boolean? obj) 2)
((char? obj) 3)
((string? obj) 4)
((symbol? obj) 5)
((number? obj) 6)
((vector? obj) 7)
((bytevector? obj) 8)
; Add more here if you want: be sure to update comparator-index variables
(else (registered-index obj))))
;; Return the index for the registered type of obj.
(define (registered-index obj)
(let loop ((i 0) (registry *registered-comparators*))
(cond
((null? registry) (+ first-comparator-index i))
((comparator-test-type (car registry) obj) (+ first-comparator-index i))
(else (loop (+ i 1) (cdr registry))))))
;; Given an index, retrieve a registered conductor.
Index must be > = first - comparator - index .
(define (registered-comparator i)
(list-ref *registered-comparators* (- i first-comparator-index)))
(define (dispatch-equality type a b)
(case type
((0) 0) ; All empty lists are equal
((1) (= (pair-comparison a b) 0))
((2) (= (boolean-comparison a b) 0))
((3) (= (char-comparison a b) 0))
((4) (= (string-comparison a b) 0))
((5) (= (symbol-comparison a b) 0))
((6) (= (complex-comparison a b) 0))
((7) (= (vector-comparison a b) 0))
((8) (= (bytevector-comparison a b) 0))
; Add more here
(else (comparator-equal? (registered-comparator type) a b))))
(define (dispatch-comparison type a b)
(case type
((0) 0) ; All empty lists are equal
((1) (pair-comparison a b))
((2) (boolean-comparison a b))
((3) (char-comparison a b))
((4) (string-comparison a b))
((5) (symbol-comparison a b))
((6) (complex-comparison a b))
((7) (vector-comparison a b))
((8) (bytevector-comparison a b))
; Add more here
(else (comparator-compare (registered-comparator type) a b))))
(define (default-hash-function obj)
(case (object-type obj)
((0) 0)
((1) (pair-hash obj))
((2) (boolean-hash obj))
((3) (char-hash obj))
((4) (string-hash obj))
((5) (symbol-hash obj))
((6) (number-hash obj))
((7) (vector-hash obj))
((8) (bytevector-hash obj))
; Add more here
(else (comparator-hash (registered-comparator (object-type obj)) obj))))
(define (default-comparison a b)
(let ((a-type (object-type a))
(b-type (object-type b)))
(cond
((< a-type b-type) -1)
((> a-type b-type) 1)
(else (dispatch-comparison a-type a b)))))
(define (default-equality a b)
(let ((a-type (object-type a))
(b-type (object-type b)))
(if (= a-type b-type) (dispatch-equality a-type a b) #f)))
(define default-comparator
(make-comparator
#t
default-equality
default-comparison
default-hash-function))
| null | https://raw.githubusercontent.com/webyrd/n-grams-for-synthesis/b53b071e53445337d3fe20db0249363aeb9f3e51/datasets/srfi/srfi-114/comparators/default.scm | scheme | The default comparator
The unknown-object comparator, used as a fallback to everything else
Register a new comparator for use by the default comparator.
Return ordinal for object types: null sorts before pairs, which sort
before booleans, etc. Implementations can extend this.
People who call comparator-register-default! effectively do extend it.
Add more here if you want: be sure to update comparator-index variables
Return the index for the registered type of obj.
Given an index, retrieve a registered conductor.
All empty lists are equal
Add more here
All empty lists are equal
Add more here
Add more here |
(define unknown-object-comparator
(make-comparator
(lambda (obj) #t)
(lambda (a b) #t)
(lambda (a b) 0)
(lambda (obj) 0)))
Next index for added comparator
(define first-comparator-index 9)
(define *next-comparator-index* 9)
(define *registered-comparators* (list unknown-object-comparator))
(define (comparator-register-default! comparator)
(set! *registered-comparators* (cons comparator *registered-comparators*))
(set! *next-comparator-index* (+ *next-comparator-index* 1)))
(define (object-type obj)
(cond
((null? obj) 0)
((pair? obj) 1)
((boolean? obj) 2)
((char? obj) 3)
((string? obj) 4)
((symbol? obj) 5)
((number? obj) 6)
((vector? obj) 7)
((bytevector? obj) 8)
(else (registered-index obj))))
(define (registered-index obj)
(let loop ((i 0) (registry *registered-comparators*))
(cond
((null? registry) (+ first-comparator-index i))
((comparator-test-type (car registry) obj) (+ first-comparator-index i))
(else (loop (+ i 1) (cdr registry))))))
Index must be > = first - comparator - index .
(define (registered-comparator i)
(list-ref *registered-comparators* (- i first-comparator-index)))
(define (dispatch-equality type a b)
(case type
((1) (= (pair-comparison a b) 0))
((2) (= (boolean-comparison a b) 0))
((3) (= (char-comparison a b) 0))
((4) (= (string-comparison a b) 0))
((5) (= (symbol-comparison a b) 0))
((6) (= (complex-comparison a b) 0))
((7) (= (vector-comparison a b) 0))
((8) (= (bytevector-comparison a b) 0))
(else (comparator-equal? (registered-comparator type) a b))))
(define (dispatch-comparison type a b)
(case type
((1) (pair-comparison a b))
((2) (boolean-comparison a b))
((3) (char-comparison a b))
((4) (string-comparison a b))
((5) (symbol-comparison a b))
((6) (complex-comparison a b))
((7) (vector-comparison a b))
((8) (bytevector-comparison a b))
(else (comparator-compare (registered-comparator type) a b))))
(define (default-hash-function obj)
(case (object-type obj)
((0) 0)
((1) (pair-hash obj))
((2) (boolean-hash obj))
((3) (char-hash obj))
((4) (string-hash obj))
((5) (symbol-hash obj))
((6) (number-hash obj))
((7) (vector-hash obj))
((8) (bytevector-hash obj))
(else (comparator-hash (registered-comparator (object-type obj)) obj))))
(define (default-comparison a b)
(let ((a-type (object-type a))
(b-type (object-type b)))
(cond
((< a-type b-type) -1)
((> a-type b-type) 1)
(else (dispatch-comparison a-type a b)))))
(define (default-equality a b)
(let ((a-type (object-type a))
(b-type (object-type b)))
(if (= a-type b-type) (dispatch-equality a-type a b) #f)))
(define default-comparator
(make-comparator
#t
default-equality
default-comparison
default-hash-function))
|
9763d1fec46b8085148ec4894a983d65c621412525dc625aa04601c0e7b6df2c | lightquake/milagos | Settings.hs | -- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
In addition , you can configure a number of different aspects of Yesod
by overriding methods in the Yesod typeclass . That instance is
declared in the Foundation.hs file .
module Settings
( widgetFile
, PersistConfig
, staticRoot
, staticDir
, themeRoot
, themeDir
, Extra (..)
, parseExtra
) where
import Prelude
import Text.Shakespeare.Text (st)
import Language.Haskell.TH.Syntax
import Database.Persist.Sqlite (SqliteConf)
import Yesod.Default.Config
import qualified Yesod.Default.Util
import Data.Text (Text)
import Data.Yaml
import Control.Applicative
-- | Which Persistent backend this site is using.
type PersistConfig = SqliteConf
-- Static setting below. Changing these requires a recompile
-- | The location of static files on your system. This is a file system
-- path. The default value works properly with your scaffolded site.
staticDir, themeDir :: FilePath
staticDir = "static"
themeDir = "themes"
-- | The base URL for your static files. As you can see by the default
-- value, this can simply be "static" appended to your application root.
-- A powerful optimization can be serving static files from a separate
-- domain name. This allows you to use a web server optimized for static
-- files, more easily set expires and cache values, and avoid possibly
-- costly transference of cookies on static files. For more information,
-- please see:
-- -speed/docs/request.html#ServeFromCookielessDomain
--
If you change the resource pattern for StaticR in Foundation.hs , you will
-- have to make a corresponding change here.
--
To see how this value is used , see urlRenderOverride in Foundation.hs
staticRoot, themeRoot :: AppConfig DefaultEnv x -> Text
staticRoot conf = [st|#{appRoot conf}/static|]
themeRoot conf = [st|#{appRoot conf}/themes|]
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
#if DEVELOPMENT
widgetFile = Yesod.Default.Util.widgetFileReload
#else
widgetFile = Yesod.Default.Util.widgetFileNoReload
#endif
data Extra = Extra
{ extraTitle :: Text
, extraAnalytics :: Maybe Text
, extraTheme :: Text
} deriving Show
parseExtra :: DefaultEnv -> Object -> Parser Extra
parseExtra _ o = Extra
<$> o .: "title"
<*> o .:? "analytics"
<*> o .: "theme"
| null | https://raw.githubusercontent.com/lightquake/milagos/bcb052969f727a515fb5ac4d5fbbadff92ae4e4d/Settings.hs | haskell | | Settings are centralized, as much as possible, into this file. This
includes database connection settings, static file locations, etc.
| Which Persistent backend this site is using.
Static setting below. Changing these requires a recompile
| The location of static files on your system. This is a file system
path. The default value works properly with your scaffolded site.
| The base URL for your static files. As you can see by the default
value, this can simply be "static" appended to your application root.
A powerful optimization can be serving static files from a separate
domain name. This allows you to use a web server optimized for static
files, more easily set expires and cache values, and avoid possibly
costly transference of cookies on static files. For more information,
please see:
-speed/docs/request.html#ServeFromCookielessDomain
have to make a corresponding change here.
The rest of this file contains settings which rarely need changing by a
user. | In addition , you can configure a number of different aspects of Yesod
by overriding methods in the Yesod typeclass . That instance is
declared in the Foundation.hs file .
module Settings
( widgetFile
, PersistConfig
, staticRoot
, staticDir
, themeRoot
, themeDir
, Extra (..)
, parseExtra
) where
import Prelude
import Text.Shakespeare.Text (st)
import Language.Haskell.TH.Syntax
import Database.Persist.Sqlite (SqliteConf)
import Yesod.Default.Config
import qualified Yesod.Default.Util
import Data.Text (Text)
import Data.Yaml
import Control.Applicative
type PersistConfig = SqliteConf
staticDir, themeDir :: FilePath
staticDir = "static"
themeDir = "themes"
If you change the resource pattern for StaticR in Foundation.hs , you will
To see how this value is used , see urlRenderOverride in Foundation.hs
staticRoot, themeRoot :: AppConfig DefaultEnv x -> Text
staticRoot conf = [st|#{appRoot conf}/static|]
themeRoot conf = [st|#{appRoot conf}/themes|]
widgetFile :: String -> Q Exp
#if DEVELOPMENT
widgetFile = Yesod.Default.Util.widgetFileReload
#else
widgetFile = Yesod.Default.Util.widgetFileNoReload
#endif
data Extra = Extra
{ extraTitle :: Text
, extraAnalytics :: Maybe Text
, extraTheme :: Text
} deriving Show
parseExtra :: DefaultEnv -> Object -> Parser Extra
parseExtra _ o = Extra
<$> o .: "title"
<*> o .:? "analytics"
<*> o .: "theme"
|
5ff0720ce86b360b6dc9af0e3c88fee1987a3c43f59e2a3fecc819d5faceae7f | ice1000/learn | pig-atinlay.hs | module Kata(pigLatin) where
pigLatin :: String -> String
pigLatin [] = []
pigLatin [a] = [a]
pigLatin [a, b] = [a, b]
pigLatin [a, b, c] = [a, b, c]
pigLatin (a : b) = b ++ [a] ++ "ay"
| null | https://raw.githubusercontent.com/ice1000/learn/4ce5ea1897c97f7b5b3aee46ccd994e3613a58dd/Haskell/CW-Kata/pig-atinlay.hs | haskell | module Kata(pigLatin) where
pigLatin :: String -> String
pigLatin [] = []
pigLatin [a] = [a]
pigLatin [a, b] = [a, b]
pigLatin [a, b, c] = [a, b, c]
pigLatin (a : b) = b ++ [a] ++ "ay"
|
|
260f3ac5dda369179c6d6f1f85ba48a07968d052428a1d3cc696ec9964109213 | LaurentMazare/ocaml-minipy | bc_eval.mli | open Base
type filename_and_lineno =
{ filename : string
; lineno : int option
}
[@@deriving sexp]
type backtrace = filename_and_lineno list [@@deriving sexp]
exception Exn_with_backtrace of Exn.t * backtrace
val eval : Bc_value.code -> unit
| null | https://raw.githubusercontent.com/LaurentMazare/ocaml-minipy/e83d4bfad55819a27195109d401437faa0f65f69/src/bc_eval.mli | ocaml | open Base
type filename_and_lineno =
{ filename : string
; lineno : int option
}
[@@deriving sexp]
type backtrace = filename_and_lineno list [@@deriving sexp]
exception Exn_with_backtrace of Exn.t * backtrace
val eval : Bc_value.code -> unit
|
|
cc2e589cd00b4bb24a3eacf855bf327cca5d8f200253206e3ab36a79ebe9e4a9 | mtolly/onyxite-customs | Crypt.hs | |
WoR encryption from by Quidrex
GH3 encryption from by Invo aka NvNv12
GHWT / GH5 encryption from GHWT Importer by Buldy , originally from GHWT All in One mod by .ocz
WoR encryption from FsbDecrypt.java by Quidrex
GH3 encryption from GHIII FSB Decryptor by Invo aka NvNv12
GHWT/GH5 encryption from GHWT Importer by Buldy, originally from GHWT All in One mod by .ocz
-}
{-# LANGUAGE OverloadedStrings #-}
module Onyx.Neversoft.Crypt where
import Control.Applicative ((<|>))
import Control.Monad (forM, guard)
import Control.Monad.ST
import Control.Monad.Trans.Resource (MonadResource)
import Crypto.Cipher.AES
import Crypto.Cipher.Types
import Crypto.Error
import Data.Bits
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Conduit.Audio as CA
import Data.Maybe (fromMaybe)
import Data.STRef
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Word
import Onyx.Audio (audioIO)
import Onyx.Audio.FSB
import Onyx.FFMPEG (ffSource)
import Onyx.Neversoft.CRC
import Onyx.Util.Handle (byteStringSimpleHandle,
makeHandle)
import System.FilePath (takeFileName)
ghworKeys :: [B.ByteString]
ghworKeys = map B.pack
[ [0x52, 0xaa, 0xa1, 0x32, 0x01, 0x75, 0x9c, 0x0f, 0x5d, 0x5e, 0x7d, 0x7c, 0x23, 0xc8, 0x1d, 0x3c]
, [0xb7, 0x5c, 0xb8, 0x9c, 0xf6, 0xd5, 0x49, 0xb8, 0x98, 0x1d, 0xf4, 0xb6, 0xf7, 0xb8, 0xc6, 0x65]
, [0x66, 0x48, 0x87, 0x0d, 0x9a, 0x5c, 0x02, 0x92, 0x98, 0x0a, 0xdc, 0xfb, 0xa9, 0x32, 0xae, 0x37]
, [0x55, 0xe3, 0x2b, 0x01, 0x56, 0x4e, 0xe0, 0xda, 0xbf, 0x0d, 0x16, 0x94, 0x72, 0x13, 0x26, 0x51]
, [0xd5, 0xae, 0x03, 0x0f, 0xda, 0x7d, 0x3e, 0xee, 0x8c, 0x71, 0x12, 0x03, 0xbc, 0x99, 0xea, 0xdb]
, [0x16, 0xb1, 0x71, 0xce, 0x24, 0x36, 0xac, 0x6e, 0xad, 0xee, 0x18, 0x29, 0x09, 0x06, 0x58, 0x61]
, [0x2a, 0x28, 0x65, 0x4a, 0xfe, 0xfd, 0xb6, 0x8f, 0x31, 0xb6, 0x76, 0x9b, 0xcc, 0x0a, 0xf6, 0x2f]
, [0xd3, 0x2f, 0x95, 0x9d, 0x7c, 0xb3, 0x67, 0x25, 0xf4, 0x2e, 0x73, 0xa5, 0xd2, 0x90, 0x8b, 0x45]
, [0xad, 0x1d, 0x56, 0x58, 0xfe, 0x67, 0x70, 0x57, 0xc5, 0x90, 0x18, 0x06, 0x25, 0x09, 0xd6, 0x05]
, [0xd4, 0xfd, 0x8b, 0x1b, 0x79, 0x53, 0xe6, 0x1a, 0xb8, 0x63, 0x25, 0x65, 0xea, 0x32, 0xfe, 0x56]
, [0x17, 0x67, 0x02, 0xee, 0xf5, 0x6e, 0xf8, 0xb9, 0xfa, 0xfd, 0xe3, 0xa1, 0x49, 0xb8, 0xf4, 0x51]
, [0x02, 0x51, 0xa8, 0xe1, 0x77, 0x23, 0x6b, 0xdd, 0x95, 0x88, 0x20, 0x5a, 0xd2, 0x49, 0x97, 0x98]
, [0xcd, 0xab, 0xf1, 0x72, 0x25, 0x96, 0x2e, 0x42, 0xec, 0x8a, 0x8f, 0x3c, 0x8f, 0x77, 0x6a, 0xb0]
, [0x4e, 0x23, 0x00, 0xd0, 0xd9, 0x2c, 0x71, 0x95, 0x2b, 0xf7, 0x17, 0xea, 0x10, 0x4f, 0xce, 0x11]
, [0x4c, 0x5d, 0xcf, 0xd8, 0xf6, 0x0b, 0x06, 0xf5, 0x87, 0x56, 0x7a, 0xa3, 0x5e, 0xab, 0xd8, 0xdf]
, [0x44, 0x95, 0xb4, 0xd8, 0xd2, 0xc1, 0x81, 0xff, 0x3a, 0x8f, 0x03, 0x1f, 0x03, 0xf2, 0xbb, 0x7f]
, [0xeb, 0xcc, 0x7d, 0xe4, 0xf5, 0xc3, 0xaf, 0xaa, 0x85, 0x7c, 0x67, 0xdb, 0x15, 0xdf, 0x14, 0xa7]
, [0x84, 0x52, 0x71, 0xcd, 0xff, 0x12, 0x31, 0x61, 0xde, 0x64, 0x23, 0x01, 0x03, 0x2f, 0xc4, 0xdf]
, [0xfe, 0xf3, 0x2e, 0x40, 0x06, 0xd7, 0x92, 0x24, 0xda, 0x65, 0x74, 0xd3, 0xdb, 0xef, 0x67, 0xa6]
, [0x99, 0xf1, 0xd6, 0xa9, 0x4c, 0x80, 0x66, 0xdf, 0xf7, 0x3d, 0xc2, 0xd3, 0x6a, 0x1b, 0x00, 0xf5]
, [0x7e, 0x61, 0x97, 0x6a, 0xb5, 0x89, 0xc2, 0x31, 0x4d, 0xab, 0x77, 0x0e, 0x3f, 0xf1, 0xbb, 0xb5]
, [0x27, 0x94, 0x2e, 0xf1, 0xb8, 0xab, 0xb5, 0xda, 0x57, 0x58, 0x03, 0x74, 0x19, 0x9c, 0x9b, 0x90]
, [0xdc, 0x13, 0xb0, 0xda, 0x49, 0xc3, 0x44, 0xfb, 0xec, 0x82, 0x64, 0x56, 0x45, 0xc6, 0xb6, 0xd2]
, [0xe2, 0x68, 0x01, 0x47, 0xf9, 0x51, 0x66, 0x80, 0x7a, 0xe7, 0x3e, 0x43, 0xb8, 0x34, 0x84, 0xa5]
, [0xdb, 0x75, 0x10, 0x80, 0x4e, 0x20, 0xaf, 0x0e, 0x04, 0xa3, 0xcd, 0x15, 0xed, 0x2e, 0x5a, 0xb8]
, [0xd3, 0x72, 0x39, 0x72, 0x75, 0x86, 0xe4, 0x63, 0xdf, 0xe2, 0x70, 0x35, 0xb0, 0x52, 0x17, 0x55]
, [0x4c, 0xce, 0x2f, 0xc6, 0xae, 0x40, 0x1c, 0x2f, 0x40, 0xb9, 0xda, 0x78, 0x02, 0x77, 0xd2, 0x5d]
, [0x7b, 0xff, 0x02, 0xda, 0xa8, 0x43, 0xe7, 0x43, 0x86, 0x39, 0xa9, 0x0f, 0x1c, 0x81, 0xd0, 0x7a]
, [0x7c, 0xe5, 0x85, 0x9b, 0xaf, 0x8e, 0xc6, 0x83, 0x7d, 0x4a, 0x53, 0xb1, 0x2c, 0xd5, 0x1e, 0x65]
, [0xef, 0x7f, 0xbb, 0xb8, 0x75, 0xfc, 0xdc, 0xc2, 0x52, 0x61, 0xd4, 0xe9, 0x9a, 0x86, 0xd0, 0x58]
, [0x52, 0x25, 0x59, 0xfb, 0x6f, 0x62, 0x54, 0xdf, 0x16, 0x7b, 0x0a, 0x94, 0xf0, 0x61, 0x26, 0x7c]
, [0xd8, 0x69, 0xd0, 0x33, 0x8b, 0x0a, 0xa5, 0xf8, 0xd5, 0xdc, 0xda, 0x4e, 0x14, 0xf2, 0x6a, 0xfe]
, [0x0f, 0x7f, 0x33, 0xc8, 0xd5, 0x1d, 0xe6, 0xe6, 0x16, 0x6e, 0x61, 0xea, 0xb0, 0xf4, 0x14, 0xea]
, [0x1b, 0x57, 0x3f, 0x92, 0xbc, 0xf3, 0x6c, 0xf3, 0xc0, 0x10, 0xae, 0x5f, 0x8b, 0xf6, 0xe5, 0x5e]
, [0x79, 0x19, 0xca, 0xf6, 0x07, 0x5e, 0xd4, 0xe2, 0x15, 0x45, 0x60, 0x0d, 0x2f, 0xb8, 0x05, 0x7e]
, [0x31, 0x8e, 0x95, 0x4f, 0x77, 0xbe, 0xb8, 0xa9, 0xd5, 0xb1, 0x10, 0x80, 0xb3, 0x24, 0xdd, 0x4f]
, [0x91, 0x9e, 0x4d, 0x54, 0x9d, 0xd5, 0x6c, 0x9c, 0x3e, 0x26, 0x7a, 0x33, 0xd3, 0x16, 0xe8, 0x87]
, [0x4d, 0x43, 0xa0, 0xff, 0xf6, 0xd4, 0x13, 0x7d, 0xe9, 0xfd, 0x6d, 0xd5, 0x9d, 0x21, 0xd3, 0x98]
, [0x90, 0xc5, 0x14, 0x65, 0xdb, 0xa7, 0xb3, 0x68, 0xaa, 0xbc, 0x5a, 0x46, 0xee, 0xc9, 0x08, 0x36]
, [0x66, 0xb8, 0x25, 0xf7, 0x3e, 0xd3, 0x5b, 0x55, 0xfc, 0x3a, 0x5e, 0xc5, 0xe9, 0x9a, 0x76, 0x2a]
, [0x03, 0x94, 0x20, 0x25, 0x85, 0xb6, 0x18, 0xc8, 0x30, 0xe4, 0x38, 0x2d, 0x95, 0x9e, 0xec, 0x2a]
, [0xdf, 0x23, 0xa6, 0xbb, 0x25, 0x8b, 0x86, 0xdc, 0x8c, 0xe0, 0xd8, 0xc1, 0xc9, 0xb3, 0xcd, 0xe5]
, [0xd1, 0xbe, 0x7b, 0x1c, 0x2f, 0x3d, 0xdd, 0x35, 0xab, 0xcf, 0x9f, 0xe8, 0x56, 0x8e, 0x8b, 0x34]
, [0x5f, 0x8b, 0x3f, 0x45, 0x02, 0xdd, 0xa4, 0x2a, 0xe6, 0x9f, 0x89, 0x0f, 0xbf, 0x5a, 0xbb, 0xad]
, [0x98, 0x76, 0x9f, 0x42, 0x71, 0xee, 0xff, 0xf6, 0xc1, 0x0e, 0x78, 0x9a, 0xc5, 0x74, 0xbc, 0x03]
, [0x94, 0xa8, 0xca, 0x5a, 0xb1, 0x91, 0xd6, 0xec, 0x11, 0x2e, 0x83, 0x36, 0xd3, 0xe8, 0x25, 0x70]
, [0x4e, 0x90, 0x4b, 0xfe, 0x1c, 0x49, 0xc5, 0x32, 0x7b, 0x95, 0x53, 0x2b, 0x0d, 0x63, 0x67, 0xa0]
, [0x62, 0x0f, 0xc1, 0x1c, 0x07, 0xc6, 0x2a, 0x2a, 0x3e, 0xe2, 0x6a, 0x08, 0xc6, 0xf1, 0x2e, 0xdf]
, [0x3c, 0x76, 0x0e, 0x4a, 0x0b, 0xe7, 0x93, 0x79, 0xef, 0xf5, 0x0e, 0xae, 0x45, 0x1e, 0x10, 0x05]
, [0x60, 0x2b, 0xdf, 0xd2, 0x5a, 0xd8, 0xf9, 0x03, 0x78, 0x0f, 0x63, 0xfe, 0xec, 0xae, 0x98, 0x7b]
, [0xb2, 0x16, 0xc7, 0x9d, 0xc4, 0x34, 0x82, 0x11, 0xbe, 0xa9, 0x53, 0xc8, 0x07, 0x40, 0xdc, 0x27]
, [0x1f, 0x1c, 0x78, 0x45, 0x91, 0x88, 0xf7, 0x8a, 0x3d, 0x2a, 0x29, 0x3d, 0x19, 0xf3, 0x66, 0xb0]
, [0x2a, 0xba, 0xdf, 0x5f, 0xe5, 0x0a, 0xbe, 0xc5, 0xaa, 0x75, 0x15, 0xb8, 0x12, 0xf7, 0xee, 0xfd]
, [0x53, 0xe8, 0x58, 0xb9, 0x29, 0x1e, 0xdf, 0x01, 0xdc, 0x45, 0x79, 0x3c, 0x80, 0xf8, 0x62, 0x7c]
, [0x72, 0xca, 0x86, 0x31, 0x55, 0x97, 0x14, 0xbc, 0xdb, 0x9f, 0xb9, 0x4e, 0x61, 0xf7, 0xd3, 0x2c]
, [0x66, 0x3b, 0x7d, 0xac, 0x09, 0xba, 0x0f, 0x49, 0x73, 0x05, 0x04, 0x51, 0x6f, 0x6a, 0xaf, 0x51]
, [0x88, 0xd6, 0xc3, 0xe7, 0x42, 0x46, 0xfe, 0x6b, 0x85, 0x88, 0x63, 0x7e, 0x85, 0x3b, 0xc9, 0xb8]
, [0x26, 0x7a, 0x43, 0x39, 0xed, 0xaa, 0xb6, 0xfb, 0x03, 0xdd, 0x2a, 0x47, 0x74, 0xd6, 0x06, 0x32]
, [0x20, 0x94, 0x04, 0xae, 0xe1, 0x7e, 0xb4, 0x1d, 0x7c, 0xce, 0xea, 0x85, 0x2f, 0x07, 0x88, 0x31]
, [0x08, 0x63, 0x47, 0x94, 0x58, 0xcc, 0xe3, 0x74, 0x7e, 0x4b, 0xb3, 0x25, 0xb8, 0x25, 0x34, 0xa6]
, [0x3d, 0x62, 0x5c, 0xfc, 0xd5, 0x2c, 0xad, 0x46, 0x38, 0xdf, 0x76, 0x1e, 0x84, 0x08, 0x56, 0x27]
, [0xaf, 0x8e, 0x2d, 0xbb, 0x5c, 0xb9, 0xba, 0x47, 0x6f, 0xaa, 0x72, 0xed, 0x8a, 0x2b, 0xe8, 0x88]
, [0x34, 0xcb, 0xb0, 0x59, 0x6b, 0xb1, 0xd9, 0xdc, 0x1e, 0x1b, 0xa1, 0xb9, 0xbc, 0xd1, 0x83, 0xce]
, [0x6c, 0xc6, 0x80, 0xbc, 0x8f, 0x70, 0x6d, 0x67, 0xc1, 0xe3, 0x1b, 0x56, 0x01, 0xa4, 0x89, 0x90]
, [0xef, 0x24, 0x71, 0xbd, 0x4d, 0x58, 0x15, 0x55, 0x1e, 0x2d, 0x38, 0x02, 0x15, 0x5b, 0x77, 0xb2]
, [0x66, 0x51, 0xef, 0x6c, 0x29, 0x9b, 0x93, 0x8f, 0xe0, 0xac, 0x11, 0xfb, 0x7a, 0xa3, 0xc7, 0xc2]
, [0x3b, 0x55, 0x86, 0xd3, 0x00, 0xd9, 0x50, 0x64, 0x43, 0xc7, 0xbe, 0x68, 0x0f, 0x9e, 0xd7, 0xae]
, [0xc9, 0x99, 0x15, 0x97, 0xd3, 0xa3, 0x46, 0xf4, 0xee, 0xc7, 0xc4, 0x37, 0x14, 0xe7, 0xc9, 0x25]
, [0x33, 0xe1, 0xf4, 0xce, 0xdc, 0x4c, 0xc9, 0x9f, 0xb0, 0x7d, 0x5a, 0x47, 0x29, 0x30, 0x90, 0xf4]
, [0x60, 0x18, 0x5e, 0x79, 0x10, 0x8f, 0x27, 0x90, 0x10, 0xea, 0xdf, 0x45, 0xa3, 0xa1, 0x8e, 0x89]
, [0xe3, 0x54, 0x8b, 0xa3, 0x18, 0xf6, 0x00, 0x86, 0xba, 0xac, 0x46, 0x5a, 0x99, 0x34, 0xc4, 0x54]
, [0xd1, 0xb0, 0x43, 0xb3, 0xd4, 0x28, 0x7e, 0x28, 0xdb, 0xd4, 0x17, 0x82, 0x7d, 0x3f, 0x24, 0x45]
, [0xca, 0x14, 0x87, 0xfd, 0x11, 0xec, 0xae, 0xd9, 0x33, 0x02, 0x96, 0x61, 0xd1, 0xe5, 0x44, 0xc3]
, [0x79, 0x9a, 0x5a, 0xb2, 0xa1, 0x38, 0x6a, 0xac, 0x69, 0x3e, 0xbc, 0x86, 0x7b, 0xe1, 0xf0, 0xb8]
, [0xf5, 0xd3, 0x3e, 0x01, 0xcd, 0xce, 0x13, 0x05, 0x8a, 0xc2, 0x99, 0xdc, 0xca, 0x9b, 0x7d, 0xef]
, [0xd4, 0x2d, 0xdd, 0xe3, 0x2c, 0x9d, 0xba, 0xbe, 0xbf, 0xca, 0x15, 0xa5, 0x1d, 0x94, 0x91, 0x03]
, [0xdf, 0xbf, 0x74, 0x27, 0x86, 0xc7, 0x06, 0x25, 0x0a, 0xba, 0x7d, 0xf7, 0x1e, 0xd6, 0x41, 0x26]
, [0xfc, 0x88, 0x53, 0xf3, 0x40, 0xb1, 0xfc, 0x34, 0x11, 0xdd, 0xdb, 0x4e, 0xb7, 0x53, 0xf0, 0x82]
, [0x0f, 0xcd, 0x21, 0x05, 0xf6, 0x76, 0xdf, 0x2e, 0xb2, 0xf9, 0xf2, 0x21, 0x19, 0xb6, 0x08, 0x67]
, [0x50, 0xfb, 0x12, 0x8f, 0x12, 0xd6, 0xaa, 0xa8, 0x75, 0x43, 0x01, 0xef, 0xd3, 0xab, 0x80, 0x94]
, [0x9a, 0xee, 0x72, 0xa8, 0x71, 0xc8, 0xa5, 0xf2, 0xcc, 0x12, 0x59, 0x0b, 0x0e, 0xfe, 0x2e, 0xf4]
, [0x53, 0x2a, 0x35, 0xd6, 0x9c, 0x74, 0x4b, 0x26, 0x0f, 0x6f, 0xbc, 0xc1, 0x7d, 0x66, 0xf6, 0x83]
, [0x35, 0x67, 0x04, 0xda, 0xf2, 0xef, 0x07, 0x9d, 0x6b, 0x9b, 0xf4, 0x40, 0x8e, 0x6f, 0x51, 0x0d]
, [0x0c, 0x6d, 0x31, 0x7f, 0x01, 0xd2, 0x45, 0x95, 0x30, 0xad, 0xf6, 0x78, 0x8e, 0xa0, 0xaa, 0x2b]
, [0x03, 0xb2, 0x79, 0x10, 0x04, 0x24, 0xeb, 0xe5, 0x58, 0x3e, 0xa6, 0x30, 0xda, 0x1b, 0x9e, 0x1c]
, [0x8b, 0x5d, 0x28, 0x53, 0x9f, 0x63, 0xee, 0x78, 0x9f, 0x01, 0x86, 0x4c, 0xe3, 0xb3, 0x99, 0x8c]
, [0xfa, 0xf5, 0x14, 0x58, 0xc5, 0x43, 0x6b, 0x98, 0x32, 0x44, 0x5b, 0x7b, 0x1f, 0xcb, 0xe5, 0xb4]
, [0x9c, 0xc9, 0x80, 0x30, 0x7e, 0x2a, 0xce, 0x25, 0xaf, 0xa7, 0x28, 0x02, 0x85, 0xe6, 0x88, 0xd8]
, [0x07, 0x5d, 0x7c, 0xc0, 0xbd, 0x2a, 0x64, 0xfa, 0xf8, 0x1b, 0x1a, 0xe5, 0x50, 0xb7, 0x83, 0xc1]
, [0xaf, 0x1a, 0x21, 0xe3, 0xfd, 0x7f, 0x4c, 0x39, 0xc1, 0x86, 0x55, 0xb0, 0x14, 0x0c, 0xbc, 0x2c]
, [0x50, 0x0a, 0xd1, 0xa6, 0x48, 0x49, 0x83, 0x26, 0x94, 0x7e, 0x5a, 0x2d, 0x17, 0xf4, 0xb3, 0x05]
, [0xe6, 0x31, 0x11, 0xf6, 0x7d, 0xe9, 0x64, 0x3e, 0xcd, 0x30, 0xc9, 0xf3, 0xcc, 0x58, 0x62, 0xfe]
, [0x12, 0xbf, 0xda, 0x34, 0xbb, 0x16, 0x08, 0x6f, 0x73, 0xb1, 0x64, 0xf0, 0x82, 0xa3, 0x46, 0xe6]
, [0x92, 0xe7, 0xc0, 0x46, 0x16, 0x4f, 0xbc, 0x4e, 0xb9, 0x8e, 0x70, 0xad, 0xd5, 0x6c, 0xe6, 0xa6]
, [0x9a, 0x97, 0xf3, 0xc2, 0x2e, 0x4e, 0x0b, 0x01, 0xfd, 0x75, 0xdb, 0x89, 0x18, 0xad, 0xb5, 0xda]
, [0x33, 0x2b, 0xc7, 0xf5, 0x5a, 0x64, 0xb2, 0x37, 0xd9, 0x15, 0xd2, 0xd9, 0x01, 0x58, 0xf6, 0x82]
, [0xe4, 0x10, 0xc9, 0x5e, 0x5d, 0x79, 0xbf, 0xf5, 0xfe, 0x94, 0x47, 0xc9, 0x8e, 0x2e, 0x7d, 0x0f]
, [0xbe, 0xd2, 0x7b, 0x06, 0xf1, 0xf2, 0x0b, 0xe8, 0x63, 0x7c, 0xcd, 0x17, 0x94, 0x36, 0xdb, 0x53]
, [0xfd, 0x59, 0xde, 0xa3, 0x57, 0xd5, 0x65, 0xc5, 0xca, 0x9e, 0x49, 0xcc, 0xe2, 0x10, 0xa4, 0xd8]
, [0x92, 0xf0, 0x8c, 0xb6, 0x90, 0x0a, 0xc1, 0x08, 0x1e, 0xdd, 0x3d, 0xfe, 0xc4, 0x10, 0xb8, 0xea]
, [0x0a, 0xc2, 0xc0, 0xa8, 0xdb, 0xee, 0x2c, 0xcc, 0x1a, 0x58, 0x64, 0x64, 0x3f, 0x54, 0xcc, 0x14]
, [0x8a, 0x80, 0x15, 0xcd, 0x8e, 0xf5, 0x6f, 0x84, 0xed, 0x06, 0xdf, 0xc0, 0xfe, 0xe7, 0x17, 0x52]
, [0x68, 0x3b, 0x78, 0xcd, 0xfb, 0xb0, 0x21, 0xb0, 0x66, 0x3f, 0xfb, 0x5d, 0xef, 0xa1, 0x19, 0xc8]
, [0xda, 0x19, 0xf4, 0xee, 0x21, 0xde, 0x15, 0x09, 0xb8, 0x2f, 0xb6, 0x13, 0x08, 0xb8, 0x6c, 0x5b]
, [0x5b, 0x67, 0xb7, 0x2f, 0xd5, 0x5f, 0x74, 0x85, 0x63, 0x58, 0xdf, 0x7b, 0x90, 0x3b, 0xf9, 0x90]
, [0x5f, 0xd3, 0x63, 0x64, 0xbc, 0xf4, 0x61, 0x5d, 0x80, 0xe9, 0x05, 0x83, 0x4a, 0x5e, 0xa3, 0xae]
, [0x40, 0x19, 0x9b, 0xb7, 0xf9, 0xc1, 0x1e, 0x38, 0x9f, 0x62, 0x5c, 0x34, 0xed, 0x62, 0x80, 0x0f]
, [0x0a, 0x7c, 0xc1, 0xfd, 0x08, 0xcf, 0x4b, 0x3e, 0xca, 0x78, 0xb4, 0x77, 0xe7, 0xba, 0x68, 0x02]
, [0xd4, 0xc3, 0x03, 0xc5, 0x8e, 0xc4, 0x7d, 0x70, 0xd1, 0xa6, 0x60, 0xb8, 0x25, 0x1f, 0xcf, 0xe6]
, [0x26, 0xb1, 0x14, 0xdf, 0x0b, 0xda, 0x7c, 0x42, 0x20, 0x4a, 0x96, 0x9a, 0x11, 0x87, 0xfc, 0x42]
, [0x36, 0x1e, 0xa5, 0xd6, 0x82, 0x25, 0xdb, 0x71, 0xc2, 0xa9, 0x88, 0x17, 0xf5, 0xce, 0xd8, 0xf4]
, [0x50, 0xf3, 0x4c, 0x9a, 0xd2, 0x9f, 0xd3, 0x8e, 0x77, 0x19, 0x2e, 0xa1, 0xee, 0xf8, 0x75, 0x31]
, [0x89, 0x8d, 0x56, 0x79, 0x97, 0xfa, 0x0e, 0xd4, 0xe0, 0x71, 0x36, 0xb2, 0xb2, 0x81, 0x24, 0xc1]
, [0x1a, 0xab, 0x79, 0x73, 0x6e, 0xe5, 0xf4, 0xc6, 0x7d, 0xf4, 0x31, 0x57, 0x6b, 0x22, 0xe4, 0xce]
, [0x93, 0x7f, 0x01, 0x38, 0xd7, 0x48, 0x56, 0x94, 0x69, 0x86, 0x28, 0xd7, 0x5d, 0x6d, 0x44, 0x99]
, [0xee, 0x5e, 0x3d, 0x04, 0x70, 0x50, 0xa3, 0xfa, 0x64, 0x9b, 0x82, 0xa4, 0x1f, 0xe3, 0x5e, 0x11]
, [0x93, 0x7d, 0x16, 0x68, 0x00, 0x59, 0xd1, 0x7f, 0x2d, 0x69, 0x40, 0x64, 0x95, 0x46, 0x8c, 0xe2]
, [0x2c, 0xfa, 0x80, 0x23, 0xd0, 0x9c, 0xf8, 0xde, 0xd7, 0x1b, 0xc1, 0x66, 0x64, 0xe6, 0xe4, 0xfe]
, [0xd9, 0x30, 0x76, 0xfc, 0x25, 0xf7, 0x9d, 0x83, 0x1b, 0xc0, 0xdb, 0x60, 0xab, 0x41, 0x84, 0x27]
, [0x6f, 0x0f, 0x68, 0x50, 0xf7, 0xa4, 0xc7, 0xb1, 0xc5, 0xbb, 0x59, 0x98, 0x5e, 0xcf, 0x7f, 0x0c]
, [0x75, 0x26, 0xb4, 0xe0, 0xc6, 0xd2, 0x6b, 0x2e, 0xb7, 0xc3, 0xba, 0x72, 0x5c, 0x2f, 0x2a, 0x4d]
, [0x14, 0x96, 0x11, 0xf2, 0xcc, 0x8e, 0x5f, 0xdd, 0xa5, 0x70, 0xf4, 0x0a, 0x2f, 0x5e, 0x6f, 0x32]
, [0x0a, 0x3b, 0x33, 0x0b, 0x99, 0xd0, 0x47, 0x31, 0xe1, 0x19, 0xc5, 0x94, 0x06, 0x97, 0x5f, 0xd1]
, [0x1d, 0x74, 0x30, 0xf1, 0x8f, 0xa9, 0x85, 0x32, 0xb8, 0x2b, 0x84, 0xb2, 0x5a, 0x4e, 0xf7, 0x22]
, [0xf6, 0x36, 0xc4, 0xdf, 0x6d, 0xa4, 0x45, 0xc1, 0x5f, 0xa0, 0xd1, 0x35, 0xbe, 0xba, 0x2b, 0xc9]
, [0xb5, 0x30, 0x94, 0x84, 0xa6, 0xb4, 0xdd, 0xa5, 0x33, 0x1a, 0xf5, 0xde, 0x5c, 0x78, 0xb1, 0xb9]
, [0xfe, 0x28, 0xa5, 0x26, 0xf8, 0xd8, 0x4d, 0x2a, 0x49, 0x1d, 0x52, 0xfd, 0x8e, 0xd4, 0x56, 0x17]
, [0xfb, 0x81, 0x73, 0x10, 0x99, 0x89, 0xdb, 0x2b, 0xde, 0x12, 0xa1, 0xe0, 0x20, 0x08, 0x4b, 0x5d]
, [0xa5, 0x8e, 0x8e, 0x10, 0x21, 0x1d, 0x3c, 0x68, 0x38, 0xab, 0x7a, 0x01, 0x48, 0x08, 0xcb, 0xf0]
, [0xbe, 0x1b, 0xa9, 0x30, 0x41, 0x05, 0xb6, 0x0a, 0x42, 0xe9, 0xfc, 0xfb, 0xad, 0x4d, 0x79, 0x88]
, [0xea, 0x2c, 0x4f, 0x33, 0x48, 0xdb, 0x52, 0x92, 0x9a, 0x87, 0xe3, 0x8f, 0x20, 0x12, 0x3a, 0xc4]
, [0xe7, 0x89, 0x77, 0x08, 0x0b, 0x5c, 0xee, 0xe8, 0x69, 0x27, 0x37, 0x58, 0x81, 0xc0, 0x8f, 0x98]
, [0x6c, 0x26, 0xa6, 0xe2, 0x5f, 0x59, 0xf0, 0x82, 0x95, 0xd3, 0x66, 0xa8, 0xc6, 0x22, 0xfb, 0xa8]
, [0x89, 0x4c, 0x97, 0x40, 0x36, 0x83, 0x7f, 0xb0, 0xb2, 0x04, 0x18, 0x77, 0x17, 0x21, 0x2a, 0x7e]
, [0x07, 0x03, 0x37, 0x18, 0x64, 0xb5, 0xfb, 0x30, 0x7a, 0xb2, 0x3f, 0x55, 0x96, 0x93, 0x5a, 0x2c]
, [0x83, 0xd1, 0xd2, 0x59, 0xe5, 0x0f, 0x4c, 0xcb, 0x9b, 0xad, 0xbc, 0xa5, 0xbe, 0x23, 0x68, 0x76]
, [0x4e, 0x27, 0xf8, 0xa0, 0x14, 0x70, 0x3a, 0x9e, 0x51, 0xd8, 0x35, 0x17, 0x0e, 0xca, 0xb6, 0x43]
, [0x13, 0x67, 0x40, 0x5f, 0xcd, 0xd9, 0x1c, 0x55, 0x4e, 0xdb, 0x24, 0xa1, 0x28, 0x83, 0x59, 0x51]
, [0x2d, 0xb2, 0x91, 0x40, 0xc5, 0x2b, 0xf1, 0x77, 0xd0, 0xcd, 0xba, 0xc6, 0x8e, 0x53, 0xbd, 0x7b]
, [0x59, 0xa6, 0x5c, 0xf3, 0x0f, 0xa0, 0xf3, 0x32, 0x92, 0xf1, 0xee, 0xbd, 0x5b, 0xf9, 0x06, 0x32]
, [0x8e, 0x28, 0x34, 0x93, 0x79, 0xcc, 0xc1, 0x1b, 0x2e, 0xee, 0x15, 0x43, 0xc4, 0x6f, 0xf6, 0x39]
, [0x1f, 0x2a, 0xbe, 0x72, 0x35, 0x55, 0xc8, 0x5f, 0x5b, 0xa3, 0x2d, 0xaf, 0x47, 0xae, 0x3c, 0x59]
, [0xaf, 0xce, 0x3c, 0x8e, 0x51, 0x7d, 0xf0, 0x3a, 0xea, 0xaa, 0xfd, 0x0d, 0x81, 0x86, 0x00, 0x9b]
, [0x65, 0xae, 0x29, 0x6b, 0x6d, 0xbe, 0x8f, 0xd5, 0x95, 0x68, 0x4a, 0x14, 0x4a, 0xb2, 0x15, 0x25]
, [0x39, 0xd6, 0xe2, 0xc4, 0x9a, 0x9a, 0x91, 0xa0, 0x6f, 0x0f, 0xc4, 0x29, 0xe2, 0x0b, 0x62, 0x27]
, [0x15, 0x84, 0x54, 0x98, 0x2f, 0x34, 0x87, 0x49, 0xa5, 0x8f, 0xff, 0xd1, 0xdc, 0xc9, 0x5a, 0xdb]
, [0xdd, 0xed, 0xca, 0x47, 0x3f, 0x1b, 0x26, 0x02, 0xa9, 0x29, 0xdc, 0xf0, 0x9c, 0x8f, 0xa2, 0x3e]
, [0xfc, 0x2f, 0x5a, 0xb0, 0x93, 0xa2, 0x14, 0xbe, 0x7e, 0x32, 0x3b, 0xd5, 0x38, 0x43, 0x34, 0x7d]
, [0x1b, 0x53, 0x73, 0xc7, 0xc1, 0x8e, 0xcb, 0x87, 0xc8, 0xe3, 0xae, 0xb9, 0x73, 0x6a, 0xcd, 0x09]
, [0xfa, 0x32, 0xc4, 0x5c, 0x3e, 0x73, 0x09, 0xf2, 0x0a, 0xb3, 0xde, 0xa0, 0x01, 0xf6, 0x26, 0xae]
, [0x26, 0x82, 0x4c, 0x75, 0xc6, 0xc7, 0x46, 0x7c, 0x47, 0xfd, 0xcc, 0xef, 0x8f, 0xc2, 0xe9, 0x89]
, [0x12, 0x9a, 0xe0, 0xdd, 0x18, 0x08, 0x55, 0xde, 0x16, 0x60, 0x1a, 0xe5, 0xa6, 0xa5, 0x30, 0x72]
, [0xc8, 0xe9, 0x14, 0xd4, 0xd6, 0xeb, 0x91, 0x9b, 0xfb, 0x9f, 0xca, 0x46, 0x07, 0xd5, 0x8d, 0xf5]
, [0xbf, 0x99, 0xd7, 0x90, 0x52, 0xef, 0xe0, 0xf6, 0x08, 0x52, 0x85, 0xfb, 0x5a, 0x4b, 0xbf, 0xa1]
, [0xee, 0xb8, 0x2d, 0x31, 0xa6, 0xbe, 0x48, 0x7b, 0x81, 0xfb, 0xf7, 0x1e, 0x1e, 0xc3, 0xed, 0xa9]
, [0x4a, 0xde, 0x6d, 0x4c, 0xf0, 0x23, 0x36, 0x24, 0xb4, 0x88, 0xb7, 0x56, 0x6e, 0xd8, 0xde, 0x4a]
, [0x9f, 0x80, 0x9b, 0x6d, 0x24, 0xf1, 0xfc, 0x99, 0xde, 0x02, 0x32, 0x1d, 0xd6, 0xa9, 0x3e, 0xd5]
, [0x02, 0xa8, 0x75, 0x65, 0xc4, 0x92, 0xbf, 0x60, 0x3f, 0xb4, 0xc4, 0xc1, 0xe8, 0x09, 0xdc, 0x8f]
, [0xc9, 0x9e, 0x9d, 0x53, 0xa8, 0x7f, 0xb0, 0x9c, 0xd9, 0x36, 0x50, 0x1b, 0x0b, 0xd9, 0x07, 0x1a]
, [0x45, 0x2e, 0xab, 0xe3, 0x6e, 0xbb, 0xa8, 0xac, 0x56, 0x6f, 0x66, 0x2a, 0xf8, 0xdd, 0x7c, 0x6f]
, [0xd1, 0x08, 0x4f, 0xbe, 0x9b, 0x27, 0x89, 0x41, 0x85, 0x0e, 0xa1, 0x25, 0x81, 0x82, 0x2f, 0x39]
, [0xeb, 0xa5, 0xfd, 0xba, 0x2f, 0x33, 0xc9, 0x52, 0x60, 0xa0, 0x97, 0x3a, 0xfd, 0xed, 0x94, 0xa5]
, [0x07, 0xa2, 0x79, 0xf8, 0x18, 0xd7, 0x87, 0x4c, 0x13, 0xb2, 0xd7, 0x9a, 0x45, 0xfa, 0xfb, 0x81]
, [0xfd, 0xe2, 0xec, 0x3a, 0x8a, 0x23, 0xa5, 0x78, 0xdc, 0x07, 0x1e, 0xe4, 0xeb, 0x5b, 0x95, 0x2e]
, [0xd7, 0x50, 0x2c, 0x14, 0x2c, 0x10, 0x38, 0x84, 0x57, 0xec, 0x1c, 0x4d, 0x49, 0x9f, 0x58, 0x19]
, [0xeb, 0xb5, 0x2f, 0x80, 0xb4, 0x05, 0x0b, 0xf2, 0x04, 0x64, 0x4e, 0x11, 0x89, 0x88, 0x2d, 0x6e]
, [0xfd, 0x5b, 0xe5, 0x23, 0x32, 0x9e, 0x59, 0xa0, 0x1e, 0x8b, 0x17, 0x5e, 0xfb, 0x96, 0x27, 0x8d]
, [0xb7, 0x0e, 0x59, 0xa3, 0xda, 0xed, 0x89, 0xc7, 0x29, 0x98, 0x4f, 0xaa, 0x37, 0x4c, 0x59, 0xce]
, [0x5b, 0x3f, 0x55, 0xcb, 0x2a, 0xfc, 0x4f, 0x90, 0x94, 0x98, 0x38, 0x15, 0x51, 0xd4, 0x01, 0x09]
, [0xb5, 0x63, 0xcb, 0xd2, 0xd2, 0xbc, 0x23, 0x1c, 0x45, 0xf9, 0x60, 0x2d, 0xa6, 0x83, 0xf5, 0x79]
, [0xc5, 0xf5, 0x3f, 0x4f, 0x56, 0xdb, 0x3f, 0x7f, 0xe0, 0xe3, 0x03, 0xf7, 0xc8, 0x15, 0xd7, 0x93]
, [0xbb, 0x92, 0x34, 0x05, 0xf4, 0x02, 0x08, 0xd7, 0x10, 0x1e, 0x8b, 0x57, 0xec, 0x26, 0x0d, 0xa8]
, [0x1f, 0xe3, 0xa7, 0x42, 0x1b, 0x84, 0xcb, 0xa5, 0x69, 0x22, 0x69, 0xbe, 0x47, 0x30, 0xbb, 0xbd]
, [0xf2, 0x6f, 0xd5, 0x78, 0x59, 0x0c, 0x0c, 0x14, 0x13, 0x51, 0xd0, 0xb4, 0xc1, 0x49, 0xc1, 0x28]
, [0x07, 0x51, 0x5d, 0x0d, 0x59, 0x6b, 0x44, 0x19, 0xc8, 0xbb, 0x07, 0x19, 0x74, 0x1f, 0xa2, 0x82]
, [0x60, 0x99, 0x07, 0xb1, 0x8c, 0xc6, 0xc9, 0xa2, 0x55, 0x04, 0xe2, 0x67, 0xe7, 0x89, 0x0a, 0xa6]
, [0x7a, 0x6f, 0x0f, 0x03, 0xa6, 0x44, 0x17, 0x23, 0x8a, 0x81, 0x06, 0x74, 0x24, 0x10, 0x87, 0xd5]
, [0x6c, 0xa5, 0x59, 0x1b, 0x32, 0x12, 0xca, 0x74, 0x1d, 0x2f, 0xdc, 0x24, 0x7a, 0x59, 0xc3, 0x29]
, [0x57, 0x93, 0xb2, 0x30, 0x59, 0x63, 0xd0, 0x0e, 0xb7, 0x4c, 0x62, 0x7a, 0x4f, 0x3d, 0x02, 0x5e]
, [0xab, 0xa3, 0x28, 0x2a, 0xa6, 0x4a, 0xa6, 0xf8, 0x19, 0xbe, 0x07, 0x13, 0x88, 0xa9, 0x57, 0x49]
, [0x12, 0xad, 0x3b, 0xfc, 0xd4, 0xe5, 0x1d, 0xc4, 0xcb, 0xa0, 0x9c, 0x50, 0x0c, 0xb1, 0xe1, 0xc0]
, [0x57, 0xc4, 0xea, 0x82, 0xc0, 0x3c, 0x30, 0xb3, 0x0e, 0x20, 0xd4, 0x09, 0x03, 0x61, 0x49, 0x49]
, [0x87, 0xf2, 0x12, 0xf7, 0x27, 0x17, 0xdf, 0x3b, 0x2f, 0x78, 0x16, 0x70, 0x20, 0x60, 0x5a, 0x3b]
, [0xc8, 0xa3, 0xb7, 0x19, 0xbc, 0xd4, 0x7f, 0xc0, 0x2a, 0x3b, 0xaa, 0xb9, 0x48, 0x90, 0x46, 0x67]
, [0xed, 0x53, 0x93, 0xf2, 0x5c, 0x29, 0x46, 0xe9, 0x7f, 0xbc, 0x78, 0x3b, 0x99, 0x77, 0x84, 0xa0]
, [0xa8, 0x3c, 0xa3, 0x94, 0x57, 0xc2, 0x69, 0x8b, 0x2b, 0x30, 0x3c, 0x09, 0x28, 0xe9, 0x4b, 0xe4]
, [0x6d, 0xb5, 0x49, 0xaa, 0xae, 0x77, 0xef, 0x64, 0x0d, 0x8a, 0x66, 0x46, 0x38, 0x73, 0x28, 0x2f]
, [0x1d, 0xfa, 0x04, 0x63, 0x27, 0xa3, 0xb1, 0xf3, 0xa6, 0x16, 0xe4, 0x28, 0x7a, 0x2e, 0xc5, 0xe1]
, [0x51, 0xf9, 0xab, 0xff, 0xb0, 0xaa, 0xc5, 0xd4, 0xbf, 0x9c, 0xcb, 0xec, 0x04, 0x71, 0x60, 0x5a]
, [0xc8, 0x80, 0xac, 0xa2, 0x74, 0x90, 0x86, 0xb6, 0xbe, 0xaa, 0x4d, 0x29, 0x6f, 0x48, 0xff, 0x21]
, [0x23, 0xe3, 0x2e, 0x57, 0x2b, 0x11, 0x8f, 0x57, 0x0a, 0x0e, 0x03, 0x78, 0xd1, 0x21, 0x02, 0x05]
, [0x0b, 0x4b, 0x43, 0x00, 0xe6, 0x06, 0x0b, 0x65, 0x11, 0x24, 0x87, 0x35, 0x0a, 0xe1, 0x5e, 0xbd]
, [0xf2, 0xae, 0x1e, 0x21, 0x53, 0xc1, 0x15, 0x9f, 0x38, 0x75, 0x35, 0xda, 0xc2, 0xa1, 0xc3, 0x8f]
, [0x10, 0x3f, 0xe3, 0xfc, 0xbd, 0xb4, 0x54, 0x8c, 0xa3, 0x89, 0x43, 0x52, 0x26, 0xb1, 0xe8, 0x36]
, [0xab, 0xc3, 0x9c, 0x66, 0x10, 0x36, 0xab, 0xa7, 0x95, 0x7c, 0x49, 0x59, 0x55, 0x68, 0xf6, 0xef]
, [0xf0, 0x79, 0x03, 0x32, 0xad, 0xd4, 0xd1, 0x48, 0xfe, 0xec, 0xcd, 0x6d, 0xff, 0xd9, 0x9b, 0x74]
, [0xa3, 0x0c, 0xac, 0xe7, 0x7b, 0x50, 0xd8, 0x6d, 0x17, 0x8d, 0x59, 0x28, 0xe1, 0x2f, 0x7c, 0xae]
, [0x5e, 0x5b, 0x63, 0x0d, 0xa6, 0x23, 0x8e, 0x00, 0x0b, 0x57, 0x89, 0xda, 0x9c, 0x93, 0x7b, 0xe8]
, [0x9d, 0xbf, 0xe6, 0x9e, 0xef, 0xb8, 0x37, 0xa6, 0xeb, 0xe5, 0x44, 0x00, 0x55, 0x2e, 0x86, 0x5d]
, [0x4f, 0x63, 0x7c, 0xe9, 0xdf, 0x28, 0x7e, 0x59, 0x93, 0x40, 0x91, 0x4d, 0xd6, 0x4b, 0x59, 0x75]
, [0xc9, 0xb8, 0xa1, 0x58, 0x9a, 0x7f, 0x48, 0x22, 0x69, 0x9c, 0xe8, 0x81, 0xb4, 0x3a, 0xff, 0x52]
, [0xc0, 0x53, 0x2e, 0xe6, 0xd0, 0x89, 0x1e, 0xec, 0x6f, 0x14, 0x2d, 0x7f, 0xfa, 0xb3, 0xf9, 0xdf]
, [0x32, 0x4d, 0x73, 0x4e, 0x0a, 0x9a, 0xf0, 0x73, 0x5a, 0xe1, 0xfa, 0x73, 0x19, 0xc4, 0x64, 0x71]
, [0x3e, 0xc2, 0x8b, 0x91, 0x6f, 0x36, 0xd0, 0xde, 0x9f, 0xb8, 0x37, 0xb1, 0x98, 0xb1, 0xe2, 0xfd]
, [0x85, 0x7c, 0x3f, 0x7b, 0x41, 0x05, 0xcd, 0xac, 0xb2, 0x14, 0xb9, 0xc7, 0x52, 0xfd, 0x72, 0xff]
, [0x39, 0xff, 0xb0, 0x7b, 0x44, 0x23, 0xab, 0x84, 0x66, 0x62, 0xb2, 0x27, 0xe9, 0x39, 0xdf, 0x83]
, [0x5d, 0x85, 0xcf, 0x3c, 0x60, 0x5d, 0x95, 0x08, 0xd1, 0x73, 0x34, 0x0a, 0x20, 0x2d, 0xe1, 0xfd]
, [0xd6, 0x06, 0x89, 0xae, 0xec, 0x14, 0x57, 0x20, 0x59, 0xa2, 0xc8, 0xc6, 0x07, 0x8e, 0x2e, 0xb2]
, [0x15, 0x30, 0x5d, 0xcc, 0xdf, 0xce, 0xe8, 0x19, 0x85, 0x93, 0xab, 0x6b, 0x25, 0xfe, 0x8b, 0x8e]
, [0x61, 0xf4, 0x96, 0x25, 0xc2, 0x30, 0xfa, 0xbd, 0x2e, 0x04, 0x54, 0x37, 0x7e, 0x46, 0xa5, 0x54]
, [0x30, 0x86, 0xaf, 0x94, 0xe4, 0x7d, 0xfd, 0x9a, 0x1e, 0x4e, 0x9d, 0x17, 0x84, 0x5b, 0xc8, 0x24]
, [0x24, 0x49, 0xd5, 0x6e, 0x3d, 0x53, 0xb6, 0x84, 0x4d, 0x40, 0x5c, 0xe7, 0xb6, 0x54, 0xe8, 0x4d]
, [0xb6, 0x15, 0x81, 0x36, 0x3d, 0x78, 0xc8, 0x7d, 0xd5, 0xd1, 0xe7, 0x49, 0xfd, 0x87, 0x2f, 0x48]
, [0x5b, 0x5c, 0x4e, 0x3c, 0x0e, 0xd1, 0xc6, 0x9a, 0x5d, 0x18, 0x9d, 0x51, 0xe0, 0xaf, 0x98, 0x3c]
, [0x3c, 0x0a, 0x38, 0x3f, 0x9f, 0x27, 0x7a, 0xa8, 0x16, 0xda, 0x98, 0xd0, 0x3f, 0x6c, 0x7e, 0x19]
, [0xbb, 0x0c, 0x5a, 0xa1, 0xb0, 0xec, 0x04, 0x08, 0xe1, 0xc5, 0xfb, 0xe9, 0x17, 0xf9, 0x92, 0x14]
, [0x10, 0x51, 0x56, 0x85, 0x8e, 0xc9, 0xeb, 0x98, 0x9e, 0x49, 0x67, 0xca, 0xcd, 0x13, 0x0c, 0x86]
, [0xf0, 0x57, 0x6a, 0xb8, 0x06, 0x03, 0x95, 0xde, 0x98, 0xeb, 0x5f, 0x8e, 0x5e, 0x9b, 0x9c, 0xcd]
, [0x97, 0x70, 0xe7, 0x8d, 0xca, 0x39, 0x66, 0xe9, 0x94, 0xe0, 0xad, 0x07, 0x2a, 0x7e, 0xac, 0x19]
, [0xfe, 0x3d, 0xe7, 0x65, 0x2f, 0xaa, 0x55, 0x32, 0xbb, 0x8e, 0xae, 0xe1, 0x5f, 0xa1, 0x14, 0x7f]
, [0xa7, 0xfd, 0x75, 0xfd, 0x40, 0x0b, 0x23, 0xc8, 0x51, 0x1b, 0xdf, 0x77, 0xa3, 0xa1, 0xe7, 0xf1]
, [0xb6, 0x63, 0x42, 0x97, 0x04, 0x0d, 0x88, 0x73, 0x55, 0xbd, 0x52, 0x88, 0x62, 0xd0, 0xdb, 0x25]
, [0x56, 0xa9, 0xc3, 0x17, 0xe4, 0xef, 0xee, 0x2c, 0x0f, 0x40, 0xd4, 0x8e, 0x3b, 0x52, 0xf9, 0x52]
, [0xd1, 0xf6, 0x05, 0x69, 0xf7, 0xd6, 0xc3, 0x1f, 0xd5, 0xfe, 0x14, 0x3d, 0xd0, 0xd9, 0x03, 0x38]
, [0xab, 0x61, 0xbd, 0x21, 0x66, 0xc6, 0xc2, 0xf7, 0x93, 0xcf, 0xb7, 0x52, 0x1f, 0x41, 0x64, 0x40]
, [0xe0, 0x24, 0x72, 0x1d, 0xb8, 0xa6, 0x1f, 0x68, 0xc4, 0xbc, 0x1f, 0xca, 0x31, 0x37, 0x2e, 0x53]
, [0xfa, 0x13, 0x85, 0xea, 0xb9, 0x9e, 0x83, 0x6f, 0x52, 0xff, 0x5f, 0xb7, 0x57, 0xb0, 0x0c, 0xfb]
, [0x7c, 0x0c, 0x96, 0xad, 0xa2, 0x8d, 0x81, 0xa2, 0x3f, 0xdd, 0x52, 0xa0, 0xfe, 0xba, 0x18, 0xfa]
, [0x41, 0x46, 0xdb, 0x75, 0x42, 0xaa, 0xb7, 0xa3, 0x39, 0x2c, 0x4a, 0xf7, 0x0d, 0xb7, 0x7e, 0xe2]
, [0x5c, 0x00, 0xcd, 0xe9, 0x6e, 0x13, 0x87, 0xaa, 0x83, 0xdb, 0x41, 0x44, 0xfc, 0x4f, 0x22, 0x6f]
, [0xd6, 0xf2, 0xcb, 0x1c, 0xf4, 0x27, 0x46, 0xe5, 0x2d, 0xc9, 0x19, 0x36, 0x57, 0xbf, 0xa6, 0x3b]
, [0xb3, 0xd0, 0xe8, 0xe7, 0x8b, 0x78, 0x5c, 0x8a, 0x73, 0x26, 0x12, 0xa6, 0x29, 0xe9, 0xd5, 0x9c]
, [0x03, 0x90, 0x39, 0x76, 0x74, 0x91, 0xb6, 0xd1, 0xe6, 0xcc, 0xf4, 0x13, 0x19, 0x87, 0x5f, 0x77]
, [0x98, 0xe4, 0x0a, 0xaa, 0x07, 0x5b, 0x32, 0x96, 0xb7, 0xcf, 0x08, 0x8c, 0xb9, 0xd1, 0xff, 0xc3]
, [0x1d, 0x4c, 0x48, 0x18, 0xc4, 0xd0, 0x3c, 0xfe, 0xde, 0xbf, 0xe1, 0xc6, 0x74, 0xc1, 0x54, 0xa5]
, [0xf0, 0x09, 0x1b, 0x5f, 0xc7, 0x88, 0xef, 0x33, 0x57, 0x93, 0x33, 0x8e, 0x04, 0x60, 0x02, 0x30]
, [0xdb, 0xb4, 0xf2, 0x81, 0x22, 0x1e, 0x8e, 0xa9, 0xa4, 0xe5, 0x78, 0x99, 0xf2, 0x4a, 0xc9, 0x6e]
, [0x27, 0xb3, 0x0f, 0x4c, 0x9c, 0x61, 0x19, 0x65, 0xd2, 0x80, 0xdf, 0xde, 0xf6, 0x42, 0xca, 0x19]
, [0xc1, 0xe2, 0x1b, 0x80, 0x4f, 0xa0, 0x55, 0xdc, 0x61, 0x29, 0xa7, 0xef, 0x4b, 0x39, 0x42, 0xbd]
, [0x27, 0x47, 0x9b, 0xd4, 0xd6, 0xb2, 0x22, 0x93, 0xd6, 0x27, 0x16, 0x53, 0xfc, 0x73, 0xb3, 0xf7]
, [0x61, 0x5e, 0x34, 0x76, 0x6a, 0x66, 0x34, 0x3b, 0xbb, 0x6b, 0xc0, 0xe0, 0x36, 0xba, 0x8f, 0x36]
, [0x4d, 0x43, 0x11, 0xc0, 0x7c, 0x93, 0x28, 0xa6, 0xd7, 0xb7, 0x6b, 0xbe, 0xbd, 0x08, 0xf6, 0x56]
, [0xc4, 0x03, 0xdc, 0x2c, 0xf9, 0x62, 0x39, 0xf7, 0xd4, 0x37, 0x62, 0x08, 0x82, 0xd0, 0xd5, 0x40]
, [0x79, 0xee, 0xd5, 0xfa, 0x9c, 0x5a, 0xc8, 0x3d, 0x97, 0x2c, 0x73, 0xed, 0xa6, 0xfc, 0xe2, 0x84]
, [0x18, 0x0e, 0xd3, 0x27, 0xba, 0x6d, 0x76, 0xd4, 0x2e, 0xf7, 0x96, 0x02, 0xdf, 0xd9, 0x23, 0x61]
, [0xd4, 0x12, 0x73, 0x28, 0xa6, 0x2f, 0x95, 0x50, 0x19, 0x33, 0x60, 0x3f, 0xad, 0xf2, 0xd1, 0x59]
, [0x92, 0xa0, 0xba, 0x33, 0x48, 0xfc, 0xb0, 0x56, 0x3f, 0xbf, 0x73, 0xd2, 0x7b, 0x1e, 0xfd, 0x38]
, [0x95, 0x2b, 0x46, 0xf3, 0x64, 0x87, 0xe2, 0xb9, 0xce, 0x11, 0x48, 0x17, 0x02, 0xf1, 0xbb, 0x49]
, [0x4a, 0x81, 0x6b, 0x05, 0x5f, 0x89, 0x1a, 0x4f, 0xf0, 0x82, 0xac, 0xe3, 0x69, 0x5d, 0x3c, 0x13]
, [0xcb, 0x76, 0x1b, 0xb8, 0x7b, 0xff, 0x03, 0x58, 0x83, 0x69, 0xa9, 0xa8, 0x2e, 0x0f, 0xfa, 0x2e]
, [0x06, 0x6d, 0xc2, 0x70, 0x0d, 0xe0, 0xdf, 0x11, 0xf2, 0xa3, 0xb7, 0xd3, 0xe9, 0x1f, 0x53, 0x17]
, [0x27, 0x3b, 0xa4, 0xff, 0x21, 0x25, 0x8c, 0xf9, 0x37, 0xaf, 0xb1, 0xe8, 0x5e, 0x91, 0x7a, 0x42]
, [0x11, 0x2c, 0x0a, 0xe1, 0x3f, 0x74, 0x92, 0xd2, 0xac, 0x2b, 0xfa, 0xd7, 0xfd, 0x04, 0xb7, 0xef]
, [0x99, 0x70, 0x5f, 0x50, 0x20, 0xca, 0xb0, 0xf6, 0xb0, 0x95, 0x3f, 0xaa, 0xe9, 0x67, 0x55, 0x59]
, [0xf4, 0x79, 0xd4, 0x3a, 0xb7, 0x75, 0x83, 0xa4, 0x12, 0xbb, 0x09, 0x69, 0x83, 0x72, 0x80, 0x0c]
, [0x83, 0x0c, 0x2b, 0x6f, 0x44, 0x71, 0x77, 0xfb, 0xd1, 0x6c, 0x0e, 0x7c, 0x63, 0x83, 0x7b, 0x18]
]
checkFSB :: BL.ByteString -> Maybe BL.ByteString
checkFSB b = guard ("FSB" `BL.isPrefixOf` b) >> return b
ghworDecrypt :: B.ByteString -> Maybe BL.ByteString
ghworDecrypt bs = do
guard $ B.length bs >= 0x800
let (cipherData, cipherFooter) = B.splitAt (B.length bs - 0x800) bs
makeKey k = case cipherInit k of
CryptoPassed cipher -> Just (cipher :: AES128)
_ -> Nothing
iv <- makeIV $ B.replicate 16 0
cipher <- makeKey $ head ghworKeys
let footer = ctrCombine cipher iv cipherFooter
keyIndex = sum $ map (B.index footer) [4..7]
key <- makeKey $ ghworKeys !! fromIntegral keyIndex
checkFSB $ BL.fromStrict $ ctrCombine key iv cipherData
ghworEncrypt :: B.ByteString -> Maybe B.ByteString
ghworEncrypt bs = do
let makeKey k = case cipherInit k of
CryptoPassed cipher -> Just (cipher :: AES128)
_ -> Nothing
iv <- makeIV $ B.replicate 16 0
cipher <- makeKey $ head ghworKeys
let footer = ctrCombine cipher iv ghworCipher
keyIndex = sum $ map (B.index footer) [4..7]
key <- makeKey $ ghworKeys !! fromIntegral keyIndex
return $ ctrCombine key iv bs <> ghworCipher
readFSBXMA :: (MonadResource m) => BL.ByteString -> IO (CA.AudioSource m Float)
readFSBXMA dec = let
dec' = BL.concat
[ BL.take 0x62 dec
this is a hack so ffmpeg recognizes the fsb 's xma encoding . TODO send a PR to fix
, BL.drop 0x63 dec
]
readable = makeHandle "decoded FSB audio" $ byteStringSimpleHandle dec'
in ffSource $ Left readable
readFSB :: (MonadResource m) => BL.ByteString -> IO (CA.AudioSource m Float)
readFSB dec = do
fsb <- parseFSB dec
let song = head $ either fsb3Songs fsb4Songs $ fsbHeader fsb
case fsbExtra song of
Left _xma -> readFSBXMA dec
Right _mp3 -> do
let numStreams = case quotRem (fromIntegral $ fsbSongChannels song) 2 of
(x, y) -> x + y
mp3s <- splitInterleavedMP3 numStreams $ head $ fsbSongData fsb
srcs <- forM mp3s $ \mp3 -> ffSource $ Left $ makeHandle "decoded FSB audio" $ byteStringSimpleHandle mp3
return $ foldl1 CA.merge srcs
decryptFSB' :: FilePath -> B.ByteString -> Maybe BL.ByteString
decryptFSB' name enc = let
lazy = BL.fromStrict enc
in ghworDecrypt enc
<|> ghwtDecrypt name lazy
<|> gh3Decrypt lazy
decryptFSB :: FilePath -> IO (Maybe BL.ByteString)
decryptFSB fin = decryptFSB' fin <$> B.readFile fin
convertAudio :: FilePath -> FilePath -> IO ()
convertAudio fin fout = do
dec <- decryptFSB fin >>= maybe (error "Couldn't decrypt GH .fsb.xen audio") return
src <- readFSB dec
audioIO Nothing src fout
reverseMapping :: B.ByteString
reverseMapping = B.pack $ flip map [0 .. 0xFF] $ \i -> foldr (.|.) 0
-- i is a Word8 so shiftR fills with zeroes, matching the Java >>>
[ i `shiftR` 7
, (i `shiftR` 5) .&. 0x02
, (i `shiftR` 3) .&. 0x04
, (i `shiftR` 1) .&. 0x08
, (i `shiftL` 7)
, (i `shiftL` 5) .&. 0x40
, (i `shiftL` 3) .&. 0x20
, (i `shiftL` 1) .&. 0x10
]
revByte :: Word8 -> Word8
revByte = B.index reverseMapping . fromIntegral
revBytes :: BL.ByteString -> BL.ByteString
revBytes = BL.map revByte
Taken from adlc783_1.fsb.xen ( Paramore - Ignorance , drums audio )
-- Not sure what is special about it, different keys aren't song specific,
but IIRC , trying to encode with an all zero key failed .
ghworCipher :: B.ByteString
ghworCipher = B.pack
[ 92,113,247,179,25,193,117,66,167,59,75,58,1,210,26,194,9,38,141,132,150,92,120,247,226,143,171,243,28,185,93,157,49,7,58,194,84,150,212,254,87,141,129,31,172,252,4,191,246,142,195,58,4,155,217,59,135,3,205,241,10,92,52,35,113,116,248,191,13,100,143,134,50,77,86,43,55,104,222,156,123,12,76,103,220,9,197,105,85,255,112,48,56,197,206,60,217,26,93,242,227,195,79,50,157,202,107,236,84,174,49,155,181,214,226,248,33,236,17,67,166,38,200,232,229,29,77,43,47,147,198,156,242,222,46,34,184,115,108,93,240,232,173,172,15,192,242,35,180,140,40,72,147,81,245,165,216,155,30,248,152,105,36,35,235,134,180,121,58,178,96,17,91,83,220,96,166,21,24,251,5,213,250,79,137,146,232,150,100,167,74,131,212,100,192,156,132,133,38,71,177,244,191,70,192,172,179,14,96,93,36,195,253,149,16,111,117,29,254,110,214,46,139,230,106,127,140,154,239,69,81,163,147,226,55,131,170,65,224,166,161,72,235,5,109,184
, 43,18,239,44,43,17,169,159,211,47,130,215,77,156,97,21,234,185,55,10,163,129,21,169,200,36,129,2,24,118,160,144,170,162,53,181,164,87,33,96,239,212,76,133,201,197,103,35,121,76,214,43,156,174,180,111,248,68,188,38,34,208,3,136,237,168,214,50,168,184,51,19,70,184,149,177,94,213,23,230,197,30,80,115,251,46,32,184,150,212,42,206,214,44,142,144,77,41,231,16,42,121,218,1,245,99,130,207,52,118,104,208,228,35,195,68,173,59,220,31,184,98,208,4,82,246,210,28,189,161,94,179,14,61,77,227,19,49,117,91,144,183,155,49,11,113,38,158,176,106,220,75,132,83,185,255,153,193,131,64,106,105,252,233,30,99,138,189,64,5,30,145,1,30,6,145,67,78,182,206,117,70,102,47,21,238,203,254,217,201,38,222,136,127,165,228,170,19,147,205,222,247,118,188,88,226,35,132,166,138,199,248,250,25,139,171,29,94,91,81,176,181,175,213,22,199,19,37,57,51,32,156,107,194,159,220,113,64,22,50,10,128,247,248,157,38,140
, 30,146,168,34,243,133,106,248,83,8,234,90,163,183,73,235,168,83,8,48,51,162,220,183,132,252,86,68,26,157,46,147,126,201,60,29,141,145,7,34,129,214,22,133,41,208,218,235,123,244,39,22,148,115,63,133,175,163,9,172,80,94,181,57,249,165,67,73,122,194,85,178,52,43,47,168,163,241,199,240,129,134,232,123,81,192,78,37,8,70,101,64,180,146,169,168,14,116,26,28,101,236,101,208,178,216,98,178,184,231,121,107,99,62,190,253,41,245,205,220,189,192,225,191,105,210,15,17,191,153,160,169,75,144,193,117,43,36,97,118,45,33,55,202,12,27,179,109,38,167,100,154,10,62,206,34,111,86,205,126,129,48,40,18,223,100,161,58,201,167,207,51,43,5,19,100,223,169,156,194,6,249,221,28,141,201,184,179,169,40,23,86,163,161,68,12,91,151,234,64,32,39,65,101,171,185,171,79,212,76,144,70,197,147,149,5,160,104,114,80,89,60,123,27,190,78,56,11,68,1,34,68,79,64,50,109,123,132,84,203,169,79,38,105,154,183,251,118
, 70,192,236,228,104,28,130,150,27,111,77,74,78,208,36,206,201,45,99,20,120,216,1,49,147,48,237,127,244,166,7,126,72,142,68,210,150,63,193,113,77,173,102,26,56,184,230,158,66,35,174,100,102,240,5,13,118,127,250,147,173,196,216,114,31,137,234,3,110,170,160,115,155,247,94,219,16,76,190,77,134,81,122,76,206,136,222,70,41,132,74,50,94,95,255,73,36,136,35,165,2,64,246,87,41,88,53,166,9,47,234,68,5,189,38,249,179,223,203,204,156,145,161,158,205,57,117,184,215,130,5,117,79,103,197,27,105,94,221,197,137,120,14,144,85,206,94,81,249,146,239,156,38,236,77,32,232,102,127,192,208,44,129,66,124,127,188,119,122,243,20,148,233,133,137,187,115,49,12,217,110,27,191,191,67,42,9,235,176,3,183,99,34,68,191,231,247,72,89,18,99,169,19,231,124,98,220,191,235,134,27,25,91,146,168,252,128,93,236,185,150,83,98,119,151,80,234,102,27,254,76,4,175,229,134,73,29,167,112,123,92,129,249,111,188,89,218
, 242,32,107,251,6,199,132,131,86,2,66,100,98,107,232,238,229,213,193,54,32,211,210,219,70,92,231,233,206,17,119,250,12,207,200,85,27,72,53,116,206,76,46,79,122,119,149,237,42,127,158,232,214,153,0,19,220,195,157,11,61,154,73,164,56,113,175,111,214,145,22,150,186,127,179,209,172,223,176,222,206,188,54,40,79,196,190,135,29,231,243,166,174,24,145,212,67,18,233,34,34,15,35,80,95,237,184,34,167,166,102,187,198,169,6,14,10,24,20,203,219,223,222,194,52,107,175,173,252,214,10,36,19,187,210,119,47,253,204,49,236,158,49,96,79,88,26,165,32,152,189,35,218,37,70,103,14,19,93,255,193,47,159,145,20,4,108,129,139,21,184,114,19,203,82,0,144,124,200,201,64,143,151,218,201,24,50,213,81,101,186,237,216,243,121,43,44,126,156,140,72,255,18,15,147,87,75,151,65,74,76,175,34,11,37,221,249,55,38,67,206,239,126,106,12,242,141,215,105,157,222,9,136,79,127,219,146,129,80,91,239,9,189,141,47,240,199
, 180,63,234,102,151,4,228,208,194,11,233,228,239,107,127,224,143,120,171,35,1,4,160,250,171,245,212,25,204,245,137,63,16,34,19,199,145,116,211,170,22,19,40,129,119,4,202,9,141,212,187,230,47,195,21,134,61,24,146,95,81,8,146,35,146,15,31,166,6,25,85,209,186,9,146,175,68,237,61,175,51,186,95,72,156,121,203,16,85,162,182,241,102,35,20,66,210,200,230,29,158,235,24,120,165,9,45,107,213,187,193,247,101,60,197,129,218,3,159,40,206,81,61,83,109,221,197,235,88,7,145,169,154,233,195,59,109,195,248,192,82,135,246,183,0,237,70,163,136,99,237,117,170,185,175,155,193,194,167,138,146,128,9,123,45,31,188,204,116,107,191,131,202,175,167,92,57,212,115,222,203,148,193,184,154,255,217,255,182,208,169,156,53,189,15,185,175,101,137,29,242,222,187,207,64,36,29,106,127,171,239,237,195,35,159,126,30,113,183,170,125,15,176,114,70,12,23,101,215,80,87,171,182,32,158,88,158,69,90,193,26,242,56,169
, 56,45,89,236,212,10,67,209,52,23,147,247,90,96,216,169,122,96,144,184,122,73,247,91,55,240,57,134,36,206,4,151,129,114,24,35,28,100,186,27,235,136,146,253,253,71,212,146,142,127,238,100,5,244,37,149,98,8,118,137,158,169,37,82,169,44,54,7,130,26,127,70,69,22,188,6,126,89,237,247,221,69,34,92,58,190,49,141,107,230,101,108,153,33,91,49,58,129,127,121,234,252,232,124,159,211,40,248,235,159,224,234,162,98,90,88,187,89,243,184,187,85,150,65,97,155,120,56,214,179,56,248,201,251,50,37,29,0,9,168,78,70,180,5,108,133,91,98,126,158,27,12,186,154,213,41,95,93,75,180,105,169,240,249,138,184,227,54,27,228,62,132,218,199,5,50,16,8,12,73,71,45,79,170,226,14,5,241,214,203,14,183,223,221,137,133,13,128,6,137,219,36,226,66,57,45,20,105,41,177,171,6,130,102,82,57,110,7,160,153,120,57,34,172,195,108,49,251,12,214,37,78,179,115,238,100,153,185,76,81,253,84,128,234,252,128,46,141,137,184,218
, 106,69,182,7,14,32,208,174,195,70,150,160,231,59,102,108,115,63,181,164,122,79,73,127,159,188,53,20,218,245,24,92,32,134,228,16,111,95,170,0,194,110,186,109,236,207,74,88,16,24,132,228,182,87,42,11,122,220,117,222,112,16,169,248,70,201,252,72,48,157,228,131,121,164,211,60,136,95,18,27,35,180,174,238,43,31,205,172,135,227,114,113,129,191,139,186,227,213,212,137,225,103,40,189,197,10,149,150,194,23,149,171,38,56,57,155,91,133,234,95,16,86,46,33,97,122,242,143,2,28,193,56,2,233,5,223,198,183,215,190,92,133,167,231,7,125,35,77,217,55,101,142,238,121,225,235,59,155,162,152,30,243,180,58,155,32,12,140,168,139,68,89,145,67,231,155,245,85,15,79,126,201,159,174,152,165,247,39,66,149,221,181,106,36,137,29,193,186,62,82,255,68,124,165,45,121,216,5,0,0,172,34,195,255,250,242,171,47,194,14,10,152,0,170,3,25,109,174,216,127,65,63,66,91,126,12,98,198,30,193,224,51,35,146,159,134,198
, 119,107,103,108,251,112,175,8,121,194,82,175,219,141,22,24,168,79,171,153,98,246,185,26,164,139,78,44,178,99,185,238,214,5,94,188,83,231,133,59,94,116,234,124,88,164,110,194,43,230,204,143,238,213,206,227,212,54,149,128,111,112,157,104,41,18,198,149,158,254,186
]
gh3Decrypt :: BL.ByteString -> Maybe BL.ByteString
gh3Decrypt bs = let
cipher = cycle $ BL.unpack "5atu6w4zaw"
in checkFSB $ BL.pack $ map revByte $ zipWith xor (BL.unpack bs) cipher
gh3Encrypt :: BL.ByteString -> BL.ByteString
gh3Encrypt bs = let
cipher = cycle $ BL.unpack "5atu6w4zaw"
in BL.pack $ zipWith xor (BL.unpack $ revBytes bs) cipher
GHWT = =
ghwtKey :: B.ByteString -> B.ByteString
ghwtKey str = runST $ do
let ncycle = 32
vxor <- newSTRef (0xFFFFFFFF :: Word32)
encstr <- fmap B.pack $ forM [0 .. ncycle - 1] $ \i -> do
let ch = B.index str $ i `rem` B.length str
crc = qbKeyCRC $ B.singleton ch
xorOld <- readSTRef vxor
let xorNew = crc `xor` xorOld
writeSTRef vxor xorNew
let index = fromIntegral $ xorNew `rem` fromIntegral (B.length str)
return $ B.index str index
key <- forM [0 .. ncycle - 2] $ \i -> do
let ch = B.index encstr i
crc = qbKeyCRC $ B.singleton ch
xorOld <- readSTRef vxor
let xorNew1 = crc `xor` xorOld
c = i .&. 3
xorNew2 = xorNew1 `shiftR` c
writeSTRef vxor xorNew2
return $ fromIntegral xorNew2
return $ B.pack $ takeWhile (/= 0) key
ghwtKeyFromFile :: FilePath -> B.ByteString
ghwtKeyFromFile f = ghwtKey $ let
s1 = T.toLower $ T.pack $ takeFileName f
s2 = fromMaybe s1 $ T.stripSuffix ".xen" s1
s3 = fromMaybe s2 $ T.stripSuffix ".fsb" s2
s4 = case T.stripPrefix "adlc" s3 of
Nothing -> s3
Just s -> "dlc" <> s
in TE.encodeUtf8 s4
ghwtDecrypt :: FilePath -> BL.ByteString -> Maybe BL.ByteString
ghwtDecrypt name bs = checkFSB $ BL.pack $ zipWith xor
(map revByte $ BL.unpack bs)
(cycle $ B.unpack $ ghwtKeyFromFile name)
ghwtEncrypt :: FilePath -> BL.ByteString -> BL.ByteString
ghwtEncrypt name bs = revBytes $ BL.pack $ zipWith xor
(BL.unpack bs)
(cycle $ B.unpack $ ghwtKeyFromFile name)
| null | https://raw.githubusercontent.com/mtolly/onyxite-customs/0c8acd6248fe92ea0d994b18b551973816adf85b/haskell/packages/onyx-lib/src/Onyx/Neversoft/Crypt.hs | haskell | # LANGUAGE OverloadedStrings #
i is a Word8 so shiftR fills with zeroes, matching the Java >>>
Not sure what is special about it, different keys aren't song specific, | |
WoR encryption from by Quidrex
GH3 encryption from by Invo aka NvNv12
GHWT / GH5 encryption from GHWT Importer by Buldy , originally from GHWT All in One mod by .ocz
WoR encryption from FsbDecrypt.java by Quidrex
GH3 encryption from GHIII FSB Decryptor by Invo aka NvNv12
GHWT/GH5 encryption from GHWT Importer by Buldy, originally from GHWT All in One mod by .ocz
-}
module Onyx.Neversoft.Crypt where
import Control.Applicative ((<|>))
import Control.Monad (forM, guard)
import Control.Monad.ST
import Control.Monad.Trans.Resource (MonadResource)
import Crypto.Cipher.AES
import Crypto.Cipher.Types
import Crypto.Error
import Data.Bits
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Conduit.Audio as CA
import Data.Maybe (fromMaybe)
import Data.STRef
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Word
import Onyx.Audio (audioIO)
import Onyx.Audio.FSB
import Onyx.FFMPEG (ffSource)
import Onyx.Neversoft.CRC
import Onyx.Util.Handle (byteStringSimpleHandle,
makeHandle)
import System.FilePath (takeFileName)
ghworKeys :: [B.ByteString]
ghworKeys = map B.pack
[ [0x52, 0xaa, 0xa1, 0x32, 0x01, 0x75, 0x9c, 0x0f, 0x5d, 0x5e, 0x7d, 0x7c, 0x23, 0xc8, 0x1d, 0x3c]
, [0xb7, 0x5c, 0xb8, 0x9c, 0xf6, 0xd5, 0x49, 0xb8, 0x98, 0x1d, 0xf4, 0xb6, 0xf7, 0xb8, 0xc6, 0x65]
, [0x66, 0x48, 0x87, 0x0d, 0x9a, 0x5c, 0x02, 0x92, 0x98, 0x0a, 0xdc, 0xfb, 0xa9, 0x32, 0xae, 0x37]
, [0x55, 0xe3, 0x2b, 0x01, 0x56, 0x4e, 0xe0, 0xda, 0xbf, 0x0d, 0x16, 0x94, 0x72, 0x13, 0x26, 0x51]
, [0xd5, 0xae, 0x03, 0x0f, 0xda, 0x7d, 0x3e, 0xee, 0x8c, 0x71, 0x12, 0x03, 0xbc, 0x99, 0xea, 0xdb]
, [0x16, 0xb1, 0x71, 0xce, 0x24, 0x36, 0xac, 0x6e, 0xad, 0xee, 0x18, 0x29, 0x09, 0x06, 0x58, 0x61]
, [0x2a, 0x28, 0x65, 0x4a, 0xfe, 0xfd, 0xb6, 0x8f, 0x31, 0xb6, 0x76, 0x9b, 0xcc, 0x0a, 0xf6, 0x2f]
, [0xd3, 0x2f, 0x95, 0x9d, 0x7c, 0xb3, 0x67, 0x25, 0xf4, 0x2e, 0x73, 0xa5, 0xd2, 0x90, 0x8b, 0x45]
, [0xad, 0x1d, 0x56, 0x58, 0xfe, 0x67, 0x70, 0x57, 0xc5, 0x90, 0x18, 0x06, 0x25, 0x09, 0xd6, 0x05]
, [0xd4, 0xfd, 0x8b, 0x1b, 0x79, 0x53, 0xe6, 0x1a, 0xb8, 0x63, 0x25, 0x65, 0xea, 0x32, 0xfe, 0x56]
, [0x17, 0x67, 0x02, 0xee, 0xf5, 0x6e, 0xf8, 0xb9, 0xfa, 0xfd, 0xe3, 0xa1, 0x49, 0xb8, 0xf4, 0x51]
, [0x02, 0x51, 0xa8, 0xe1, 0x77, 0x23, 0x6b, 0xdd, 0x95, 0x88, 0x20, 0x5a, 0xd2, 0x49, 0x97, 0x98]
, [0xcd, 0xab, 0xf1, 0x72, 0x25, 0x96, 0x2e, 0x42, 0xec, 0x8a, 0x8f, 0x3c, 0x8f, 0x77, 0x6a, 0xb0]
, [0x4e, 0x23, 0x00, 0xd0, 0xd9, 0x2c, 0x71, 0x95, 0x2b, 0xf7, 0x17, 0xea, 0x10, 0x4f, 0xce, 0x11]
, [0x4c, 0x5d, 0xcf, 0xd8, 0xf6, 0x0b, 0x06, 0xf5, 0x87, 0x56, 0x7a, 0xa3, 0x5e, 0xab, 0xd8, 0xdf]
, [0x44, 0x95, 0xb4, 0xd8, 0xd2, 0xc1, 0x81, 0xff, 0x3a, 0x8f, 0x03, 0x1f, 0x03, 0xf2, 0xbb, 0x7f]
, [0xeb, 0xcc, 0x7d, 0xe4, 0xf5, 0xc3, 0xaf, 0xaa, 0x85, 0x7c, 0x67, 0xdb, 0x15, 0xdf, 0x14, 0xa7]
, [0x84, 0x52, 0x71, 0xcd, 0xff, 0x12, 0x31, 0x61, 0xde, 0x64, 0x23, 0x01, 0x03, 0x2f, 0xc4, 0xdf]
, [0xfe, 0xf3, 0x2e, 0x40, 0x06, 0xd7, 0x92, 0x24, 0xda, 0x65, 0x74, 0xd3, 0xdb, 0xef, 0x67, 0xa6]
, [0x99, 0xf1, 0xd6, 0xa9, 0x4c, 0x80, 0x66, 0xdf, 0xf7, 0x3d, 0xc2, 0xd3, 0x6a, 0x1b, 0x00, 0xf5]
, [0x7e, 0x61, 0x97, 0x6a, 0xb5, 0x89, 0xc2, 0x31, 0x4d, 0xab, 0x77, 0x0e, 0x3f, 0xf1, 0xbb, 0xb5]
, [0x27, 0x94, 0x2e, 0xf1, 0xb8, 0xab, 0xb5, 0xda, 0x57, 0x58, 0x03, 0x74, 0x19, 0x9c, 0x9b, 0x90]
, [0xdc, 0x13, 0xb0, 0xda, 0x49, 0xc3, 0x44, 0xfb, 0xec, 0x82, 0x64, 0x56, 0x45, 0xc6, 0xb6, 0xd2]
, [0xe2, 0x68, 0x01, 0x47, 0xf9, 0x51, 0x66, 0x80, 0x7a, 0xe7, 0x3e, 0x43, 0xb8, 0x34, 0x84, 0xa5]
, [0xdb, 0x75, 0x10, 0x80, 0x4e, 0x20, 0xaf, 0x0e, 0x04, 0xa3, 0xcd, 0x15, 0xed, 0x2e, 0x5a, 0xb8]
, [0xd3, 0x72, 0x39, 0x72, 0x75, 0x86, 0xe4, 0x63, 0xdf, 0xe2, 0x70, 0x35, 0xb0, 0x52, 0x17, 0x55]
, [0x4c, 0xce, 0x2f, 0xc6, 0xae, 0x40, 0x1c, 0x2f, 0x40, 0xb9, 0xda, 0x78, 0x02, 0x77, 0xd2, 0x5d]
, [0x7b, 0xff, 0x02, 0xda, 0xa8, 0x43, 0xe7, 0x43, 0x86, 0x39, 0xa9, 0x0f, 0x1c, 0x81, 0xd0, 0x7a]
, [0x7c, 0xe5, 0x85, 0x9b, 0xaf, 0x8e, 0xc6, 0x83, 0x7d, 0x4a, 0x53, 0xb1, 0x2c, 0xd5, 0x1e, 0x65]
, [0xef, 0x7f, 0xbb, 0xb8, 0x75, 0xfc, 0xdc, 0xc2, 0x52, 0x61, 0xd4, 0xe9, 0x9a, 0x86, 0xd0, 0x58]
, [0x52, 0x25, 0x59, 0xfb, 0x6f, 0x62, 0x54, 0xdf, 0x16, 0x7b, 0x0a, 0x94, 0xf0, 0x61, 0x26, 0x7c]
, [0xd8, 0x69, 0xd0, 0x33, 0x8b, 0x0a, 0xa5, 0xf8, 0xd5, 0xdc, 0xda, 0x4e, 0x14, 0xf2, 0x6a, 0xfe]
, [0x0f, 0x7f, 0x33, 0xc8, 0xd5, 0x1d, 0xe6, 0xe6, 0x16, 0x6e, 0x61, 0xea, 0xb0, 0xf4, 0x14, 0xea]
, [0x1b, 0x57, 0x3f, 0x92, 0xbc, 0xf3, 0x6c, 0xf3, 0xc0, 0x10, 0xae, 0x5f, 0x8b, 0xf6, 0xe5, 0x5e]
, [0x79, 0x19, 0xca, 0xf6, 0x07, 0x5e, 0xd4, 0xe2, 0x15, 0x45, 0x60, 0x0d, 0x2f, 0xb8, 0x05, 0x7e]
, [0x31, 0x8e, 0x95, 0x4f, 0x77, 0xbe, 0xb8, 0xa9, 0xd5, 0xb1, 0x10, 0x80, 0xb3, 0x24, 0xdd, 0x4f]
, [0x91, 0x9e, 0x4d, 0x54, 0x9d, 0xd5, 0x6c, 0x9c, 0x3e, 0x26, 0x7a, 0x33, 0xd3, 0x16, 0xe8, 0x87]
, [0x4d, 0x43, 0xa0, 0xff, 0xf6, 0xd4, 0x13, 0x7d, 0xe9, 0xfd, 0x6d, 0xd5, 0x9d, 0x21, 0xd3, 0x98]
, [0x90, 0xc5, 0x14, 0x65, 0xdb, 0xa7, 0xb3, 0x68, 0xaa, 0xbc, 0x5a, 0x46, 0xee, 0xc9, 0x08, 0x36]
, [0x66, 0xb8, 0x25, 0xf7, 0x3e, 0xd3, 0x5b, 0x55, 0xfc, 0x3a, 0x5e, 0xc5, 0xe9, 0x9a, 0x76, 0x2a]
, [0x03, 0x94, 0x20, 0x25, 0x85, 0xb6, 0x18, 0xc8, 0x30, 0xe4, 0x38, 0x2d, 0x95, 0x9e, 0xec, 0x2a]
, [0xdf, 0x23, 0xa6, 0xbb, 0x25, 0x8b, 0x86, 0xdc, 0x8c, 0xe0, 0xd8, 0xc1, 0xc9, 0xb3, 0xcd, 0xe5]
, [0xd1, 0xbe, 0x7b, 0x1c, 0x2f, 0x3d, 0xdd, 0x35, 0xab, 0xcf, 0x9f, 0xe8, 0x56, 0x8e, 0x8b, 0x34]
, [0x5f, 0x8b, 0x3f, 0x45, 0x02, 0xdd, 0xa4, 0x2a, 0xe6, 0x9f, 0x89, 0x0f, 0xbf, 0x5a, 0xbb, 0xad]
, [0x98, 0x76, 0x9f, 0x42, 0x71, 0xee, 0xff, 0xf6, 0xc1, 0x0e, 0x78, 0x9a, 0xc5, 0x74, 0xbc, 0x03]
, [0x94, 0xa8, 0xca, 0x5a, 0xb1, 0x91, 0xd6, 0xec, 0x11, 0x2e, 0x83, 0x36, 0xd3, 0xe8, 0x25, 0x70]
, [0x4e, 0x90, 0x4b, 0xfe, 0x1c, 0x49, 0xc5, 0x32, 0x7b, 0x95, 0x53, 0x2b, 0x0d, 0x63, 0x67, 0xa0]
, [0x62, 0x0f, 0xc1, 0x1c, 0x07, 0xc6, 0x2a, 0x2a, 0x3e, 0xe2, 0x6a, 0x08, 0xc6, 0xf1, 0x2e, 0xdf]
, [0x3c, 0x76, 0x0e, 0x4a, 0x0b, 0xe7, 0x93, 0x79, 0xef, 0xf5, 0x0e, 0xae, 0x45, 0x1e, 0x10, 0x05]
, [0x60, 0x2b, 0xdf, 0xd2, 0x5a, 0xd8, 0xf9, 0x03, 0x78, 0x0f, 0x63, 0xfe, 0xec, 0xae, 0x98, 0x7b]
, [0xb2, 0x16, 0xc7, 0x9d, 0xc4, 0x34, 0x82, 0x11, 0xbe, 0xa9, 0x53, 0xc8, 0x07, 0x40, 0xdc, 0x27]
, [0x1f, 0x1c, 0x78, 0x45, 0x91, 0x88, 0xf7, 0x8a, 0x3d, 0x2a, 0x29, 0x3d, 0x19, 0xf3, 0x66, 0xb0]
, [0x2a, 0xba, 0xdf, 0x5f, 0xe5, 0x0a, 0xbe, 0xc5, 0xaa, 0x75, 0x15, 0xb8, 0x12, 0xf7, 0xee, 0xfd]
, [0x53, 0xe8, 0x58, 0xb9, 0x29, 0x1e, 0xdf, 0x01, 0xdc, 0x45, 0x79, 0x3c, 0x80, 0xf8, 0x62, 0x7c]
, [0x72, 0xca, 0x86, 0x31, 0x55, 0x97, 0x14, 0xbc, 0xdb, 0x9f, 0xb9, 0x4e, 0x61, 0xf7, 0xd3, 0x2c]
, [0x66, 0x3b, 0x7d, 0xac, 0x09, 0xba, 0x0f, 0x49, 0x73, 0x05, 0x04, 0x51, 0x6f, 0x6a, 0xaf, 0x51]
, [0x88, 0xd6, 0xc3, 0xe7, 0x42, 0x46, 0xfe, 0x6b, 0x85, 0x88, 0x63, 0x7e, 0x85, 0x3b, 0xc9, 0xb8]
, [0x26, 0x7a, 0x43, 0x39, 0xed, 0xaa, 0xb6, 0xfb, 0x03, 0xdd, 0x2a, 0x47, 0x74, 0xd6, 0x06, 0x32]
, [0x20, 0x94, 0x04, 0xae, 0xe1, 0x7e, 0xb4, 0x1d, 0x7c, 0xce, 0xea, 0x85, 0x2f, 0x07, 0x88, 0x31]
, [0x08, 0x63, 0x47, 0x94, 0x58, 0xcc, 0xe3, 0x74, 0x7e, 0x4b, 0xb3, 0x25, 0xb8, 0x25, 0x34, 0xa6]
, [0x3d, 0x62, 0x5c, 0xfc, 0xd5, 0x2c, 0xad, 0x46, 0x38, 0xdf, 0x76, 0x1e, 0x84, 0x08, 0x56, 0x27]
, [0xaf, 0x8e, 0x2d, 0xbb, 0x5c, 0xb9, 0xba, 0x47, 0x6f, 0xaa, 0x72, 0xed, 0x8a, 0x2b, 0xe8, 0x88]
, [0x34, 0xcb, 0xb0, 0x59, 0x6b, 0xb1, 0xd9, 0xdc, 0x1e, 0x1b, 0xa1, 0xb9, 0xbc, 0xd1, 0x83, 0xce]
, [0x6c, 0xc6, 0x80, 0xbc, 0x8f, 0x70, 0x6d, 0x67, 0xc1, 0xe3, 0x1b, 0x56, 0x01, 0xa4, 0x89, 0x90]
, [0xef, 0x24, 0x71, 0xbd, 0x4d, 0x58, 0x15, 0x55, 0x1e, 0x2d, 0x38, 0x02, 0x15, 0x5b, 0x77, 0xb2]
, [0x66, 0x51, 0xef, 0x6c, 0x29, 0x9b, 0x93, 0x8f, 0xe0, 0xac, 0x11, 0xfb, 0x7a, 0xa3, 0xc7, 0xc2]
, [0x3b, 0x55, 0x86, 0xd3, 0x00, 0xd9, 0x50, 0x64, 0x43, 0xc7, 0xbe, 0x68, 0x0f, 0x9e, 0xd7, 0xae]
, [0xc9, 0x99, 0x15, 0x97, 0xd3, 0xa3, 0x46, 0xf4, 0xee, 0xc7, 0xc4, 0x37, 0x14, 0xe7, 0xc9, 0x25]
, [0x33, 0xe1, 0xf4, 0xce, 0xdc, 0x4c, 0xc9, 0x9f, 0xb0, 0x7d, 0x5a, 0x47, 0x29, 0x30, 0x90, 0xf4]
, [0x60, 0x18, 0x5e, 0x79, 0x10, 0x8f, 0x27, 0x90, 0x10, 0xea, 0xdf, 0x45, 0xa3, 0xa1, 0x8e, 0x89]
, [0xe3, 0x54, 0x8b, 0xa3, 0x18, 0xf6, 0x00, 0x86, 0xba, 0xac, 0x46, 0x5a, 0x99, 0x34, 0xc4, 0x54]
, [0xd1, 0xb0, 0x43, 0xb3, 0xd4, 0x28, 0x7e, 0x28, 0xdb, 0xd4, 0x17, 0x82, 0x7d, 0x3f, 0x24, 0x45]
, [0xca, 0x14, 0x87, 0xfd, 0x11, 0xec, 0xae, 0xd9, 0x33, 0x02, 0x96, 0x61, 0xd1, 0xe5, 0x44, 0xc3]
, [0x79, 0x9a, 0x5a, 0xb2, 0xa1, 0x38, 0x6a, 0xac, 0x69, 0x3e, 0xbc, 0x86, 0x7b, 0xe1, 0xf0, 0xb8]
, [0xf5, 0xd3, 0x3e, 0x01, 0xcd, 0xce, 0x13, 0x05, 0x8a, 0xc2, 0x99, 0xdc, 0xca, 0x9b, 0x7d, 0xef]
, [0xd4, 0x2d, 0xdd, 0xe3, 0x2c, 0x9d, 0xba, 0xbe, 0xbf, 0xca, 0x15, 0xa5, 0x1d, 0x94, 0x91, 0x03]
, [0xdf, 0xbf, 0x74, 0x27, 0x86, 0xc7, 0x06, 0x25, 0x0a, 0xba, 0x7d, 0xf7, 0x1e, 0xd6, 0x41, 0x26]
, [0xfc, 0x88, 0x53, 0xf3, 0x40, 0xb1, 0xfc, 0x34, 0x11, 0xdd, 0xdb, 0x4e, 0xb7, 0x53, 0xf0, 0x82]
, [0x0f, 0xcd, 0x21, 0x05, 0xf6, 0x76, 0xdf, 0x2e, 0xb2, 0xf9, 0xf2, 0x21, 0x19, 0xb6, 0x08, 0x67]
, [0x50, 0xfb, 0x12, 0x8f, 0x12, 0xd6, 0xaa, 0xa8, 0x75, 0x43, 0x01, 0xef, 0xd3, 0xab, 0x80, 0x94]
, [0x9a, 0xee, 0x72, 0xa8, 0x71, 0xc8, 0xa5, 0xf2, 0xcc, 0x12, 0x59, 0x0b, 0x0e, 0xfe, 0x2e, 0xf4]
, [0x53, 0x2a, 0x35, 0xd6, 0x9c, 0x74, 0x4b, 0x26, 0x0f, 0x6f, 0xbc, 0xc1, 0x7d, 0x66, 0xf6, 0x83]
, [0x35, 0x67, 0x04, 0xda, 0xf2, 0xef, 0x07, 0x9d, 0x6b, 0x9b, 0xf4, 0x40, 0x8e, 0x6f, 0x51, 0x0d]
, [0x0c, 0x6d, 0x31, 0x7f, 0x01, 0xd2, 0x45, 0x95, 0x30, 0xad, 0xf6, 0x78, 0x8e, 0xa0, 0xaa, 0x2b]
, [0x03, 0xb2, 0x79, 0x10, 0x04, 0x24, 0xeb, 0xe5, 0x58, 0x3e, 0xa6, 0x30, 0xda, 0x1b, 0x9e, 0x1c]
, [0x8b, 0x5d, 0x28, 0x53, 0x9f, 0x63, 0xee, 0x78, 0x9f, 0x01, 0x86, 0x4c, 0xe3, 0xb3, 0x99, 0x8c]
, [0xfa, 0xf5, 0x14, 0x58, 0xc5, 0x43, 0x6b, 0x98, 0x32, 0x44, 0x5b, 0x7b, 0x1f, 0xcb, 0xe5, 0xb4]
, [0x9c, 0xc9, 0x80, 0x30, 0x7e, 0x2a, 0xce, 0x25, 0xaf, 0xa7, 0x28, 0x02, 0x85, 0xe6, 0x88, 0xd8]
, [0x07, 0x5d, 0x7c, 0xc0, 0xbd, 0x2a, 0x64, 0xfa, 0xf8, 0x1b, 0x1a, 0xe5, 0x50, 0xb7, 0x83, 0xc1]
, [0xaf, 0x1a, 0x21, 0xe3, 0xfd, 0x7f, 0x4c, 0x39, 0xc1, 0x86, 0x55, 0xb0, 0x14, 0x0c, 0xbc, 0x2c]
, [0x50, 0x0a, 0xd1, 0xa6, 0x48, 0x49, 0x83, 0x26, 0x94, 0x7e, 0x5a, 0x2d, 0x17, 0xf4, 0xb3, 0x05]
, [0xe6, 0x31, 0x11, 0xf6, 0x7d, 0xe9, 0x64, 0x3e, 0xcd, 0x30, 0xc9, 0xf3, 0xcc, 0x58, 0x62, 0xfe]
, [0x12, 0xbf, 0xda, 0x34, 0xbb, 0x16, 0x08, 0x6f, 0x73, 0xb1, 0x64, 0xf0, 0x82, 0xa3, 0x46, 0xe6]
, [0x92, 0xe7, 0xc0, 0x46, 0x16, 0x4f, 0xbc, 0x4e, 0xb9, 0x8e, 0x70, 0xad, 0xd5, 0x6c, 0xe6, 0xa6]
, [0x9a, 0x97, 0xf3, 0xc2, 0x2e, 0x4e, 0x0b, 0x01, 0xfd, 0x75, 0xdb, 0x89, 0x18, 0xad, 0xb5, 0xda]
, [0x33, 0x2b, 0xc7, 0xf5, 0x5a, 0x64, 0xb2, 0x37, 0xd9, 0x15, 0xd2, 0xd9, 0x01, 0x58, 0xf6, 0x82]
, [0xe4, 0x10, 0xc9, 0x5e, 0x5d, 0x79, 0xbf, 0xf5, 0xfe, 0x94, 0x47, 0xc9, 0x8e, 0x2e, 0x7d, 0x0f]
, [0xbe, 0xd2, 0x7b, 0x06, 0xf1, 0xf2, 0x0b, 0xe8, 0x63, 0x7c, 0xcd, 0x17, 0x94, 0x36, 0xdb, 0x53]
, [0xfd, 0x59, 0xde, 0xa3, 0x57, 0xd5, 0x65, 0xc5, 0xca, 0x9e, 0x49, 0xcc, 0xe2, 0x10, 0xa4, 0xd8]
, [0x92, 0xf0, 0x8c, 0xb6, 0x90, 0x0a, 0xc1, 0x08, 0x1e, 0xdd, 0x3d, 0xfe, 0xc4, 0x10, 0xb8, 0xea]
, [0x0a, 0xc2, 0xc0, 0xa8, 0xdb, 0xee, 0x2c, 0xcc, 0x1a, 0x58, 0x64, 0x64, 0x3f, 0x54, 0xcc, 0x14]
, [0x8a, 0x80, 0x15, 0xcd, 0x8e, 0xf5, 0x6f, 0x84, 0xed, 0x06, 0xdf, 0xc0, 0xfe, 0xe7, 0x17, 0x52]
, [0x68, 0x3b, 0x78, 0xcd, 0xfb, 0xb0, 0x21, 0xb0, 0x66, 0x3f, 0xfb, 0x5d, 0xef, 0xa1, 0x19, 0xc8]
, [0xda, 0x19, 0xf4, 0xee, 0x21, 0xde, 0x15, 0x09, 0xb8, 0x2f, 0xb6, 0x13, 0x08, 0xb8, 0x6c, 0x5b]
, [0x5b, 0x67, 0xb7, 0x2f, 0xd5, 0x5f, 0x74, 0x85, 0x63, 0x58, 0xdf, 0x7b, 0x90, 0x3b, 0xf9, 0x90]
, [0x5f, 0xd3, 0x63, 0x64, 0xbc, 0xf4, 0x61, 0x5d, 0x80, 0xe9, 0x05, 0x83, 0x4a, 0x5e, 0xa3, 0xae]
, [0x40, 0x19, 0x9b, 0xb7, 0xf9, 0xc1, 0x1e, 0x38, 0x9f, 0x62, 0x5c, 0x34, 0xed, 0x62, 0x80, 0x0f]
, [0x0a, 0x7c, 0xc1, 0xfd, 0x08, 0xcf, 0x4b, 0x3e, 0xca, 0x78, 0xb4, 0x77, 0xe7, 0xba, 0x68, 0x02]
, [0xd4, 0xc3, 0x03, 0xc5, 0x8e, 0xc4, 0x7d, 0x70, 0xd1, 0xa6, 0x60, 0xb8, 0x25, 0x1f, 0xcf, 0xe6]
, [0x26, 0xb1, 0x14, 0xdf, 0x0b, 0xda, 0x7c, 0x42, 0x20, 0x4a, 0x96, 0x9a, 0x11, 0x87, 0xfc, 0x42]
, [0x36, 0x1e, 0xa5, 0xd6, 0x82, 0x25, 0xdb, 0x71, 0xc2, 0xa9, 0x88, 0x17, 0xf5, 0xce, 0xd8, 0xf4]
, [0x50, 0xf3, 0x4c, 0x9a, 0xd2, 0x9f, 0xd3, 0x8e, 0x77, 0x19, 0x2e, 0xa1, 0xee, 0xf8, 0x75, 0x31]
, [0x89, 0x8d, 0x56, 0x79, 0x97, 0xfa, 0x0e, 0xd4, 0xe0, 0x71, 0x36, 0xb2, 0xb2, 0x81, 0x24, 0xc1]
, [0x1a, 0xab, 0x79, 0x73, 0x6e, 0xe5, 0xf4, 0xc6, 0x7d, 0xf4, 0x31, 0x57, 0x6b, 0x22, 0xe4, 0xce]
, [0x93, 0x7f, 0x01, 0x38, 0xd7, 0x48, 0x56, 0x94, 0x69, 0x86, 0x28, 0xd7, 0x5d, 0x6d, 0x44, 0x99]
, [0xee, 0x5e, 0x3d, 0x04, 0x70, 0x50, 0xa3, 0xfa, 0x64, 0x9b, 0x82, 0xa4, 0x1f, 0xe3, 0x5e, 0x11]
, [0x93, 0x7d, 0x16, 0x68, 0x00, 0x59, 0xd1, 0x7f, 0x2d, 0x69, 0x40, 0x64, 0x95, 0x46, 0x8c, 0xe2]
, [0x2c, 0xfa, 0x80, 0x23, 0xd0, 0x9c, 0xf8, 0xde, 0xd7, 0x1b, 0xc1, 0x66, 0x64, 0xe6, 0xe4, 0xfe]
, [0xd9, 0x30, 0x76, 0xfc, 0x25, 0xf7, 0x9d, 0x83, 0x1b, 0xc0, 0xdb, 0x60, 0xab, 0x41, 0x84, 0x27]
, [0x6f, 0x0f, 0x68, 0x50, 0xf7, 0xa4, 0xc7, 0xb1, 0xc5, 0xbb, 0x59, 0x98, 0x5e, 0xcf, 0x7f, 0x0c]
, [0x75, 0x26, 0xb4, 0xe0, 0xc6, 0xd2, 0x6b, 0x2e, 0xb7, 0xc3, 0xba, 0x72, 0x5c, 0x2f, 0x2a, 0x4d]
, [0x14, 0x96, 0x11, 0xf2, 0xcc, 0x8e, 0x5f, 0xdd, 0xa5, 0x70, 0xf4, 0x0a, 0x2f, 0x5e, 0x6f, 0x32]
, [0x0a, 0x3b, 0x33, 0x0b, 0x99, 0xd0, 0x47, 0x31, 0xe1, 0x19, 0xc5, 0x94, 0x06, 0x97, 0x5f, 0xd1]
, [0x1d, 0x74, 0x30, 0xf1, 0x8f, 0xa9, 0x85, 0x32, 0xb8, 0x2b, 0x84, 0xb2, 0x5a, 0x4e, 0xf7, 0x22]
, [0xf6, 0x36, 0xc4, 0xdf, 0x6d, 0xa4, 0x45, 0xc1, 0x5f, 0xa0, 0xd1, 0x35, 0xbe, 0xba, 0x2b, 0xc9]
, [0xb5, 0x30, 0x94, 0x84, 0xa6, 0xb4, 0xdd, 0xa5, 0x33, 0x1a, 0xf5, 0xde, 0x5c, 0x78, 0xb1, 0xb9]
, [0xfe, 0x28, 0xa5, 0x26, 0xf8, 0xd8, 0x4d, 0x2a, 0x49, 0x1d, 0x52, 0xfd, 0x8e, 0xd4, 0x56, 0x17]
, [0xfb, 0x81, 0x73, 0x10, 0x99, 0x89, 0xdb, 0x2b, 0xde, 0x12, 0xa1, 0xe0, 0x20, 0x08, 0x4b, 0x5d]
, [0xa5, 0x8e, 0x8e, 0x10, 0x21, 0x1d, 0x3c, 0x68, 0x38, 0xab, 0x7a, 0x01, 0x48, 0x08, 0xcb, 0xf0]
, [0xbe, 0x1b, 0xa9, 0x30, 0x41, 0x05, 0xb6, 0x0a, 0x42, 0xe9, 0xfc, 0xfb, 0xad, 0x4d, 0x79, 0x88]
, [0xea, 0x2c, 0x4f, 0x33, 0x48, 0xdb, 0x52, 0x92, 0x9a, 0x87, 0xe3, 0x8f, 0x20, 0x12, 0x3a, 0xc4]
, [0xe7, 0x89, 0x77, 0x08, 0x0b, 0x5c, 0xee, 0xe8, 0x69, 0x27, 0x37, 0x58, 0x81, 0xc0, 0x8f, 0x98]
, [0x6c, 0x26, 0xa6, 0xe2, 0x5f, 0x59, 0xf0, 0x82, 0x95, 0xd3, 0x66, 0xa8, 0xc6, 0x22, 0xfb, 0xa8]
, [0x89, 0x4c, 0x97, 0x40, 0x36, 0x83, 0x7f, 0xb0, 0xb2, 0x04, 0x18, 0x77, 0x17, 0x21, 0x2a, 0x7e]
, [0x07, 0x03, 0x37, 0x18, 0x64, 0xb5, 0xfb, 0x30, 0x7a, 0xb2, 0x3f, 0x55, 0x96, 0x93, 0x5a, 0x2c]
, [0x83, 0xd1, 0xd2, 0x59, 0xe5, 0x0f, 0x4c, 0xcb, 0x9b, 0xad, 0xbc, 0xa5, 0xbe, 0x23, 0x68, 0x76]
, [0x4e, 0x27, 0xf8, 0xa0, 0x14, 0x70, 0x3a, 0x9e, 0x51, 0xd8, 0x35, 0x17, 0x0e, 0xca, 0xb6, 0x43]
, [0x13, 0x67, 0x40, 0x5f, 0xcd, 0xd9, 0x1c, 0x55, 0x4e, 0xdb, 0x24, 0xa1, 0x28, 0x83, 0x59, 0x51]
, [0x2d, 0xb2, 0x91, 0x40, 0xc5, 0x2b, 0xf1, 0x77, 0xd0, 0xcd, 0xba, 0xc6, 0x8e, 0x53, 0xbd, 0x7b]
, [0x59, 0xa6, 0x5c, 0xf3, 0x0f, 0xa0, 0xf3, 0x32, 0x92, 0xf1, 0xee, 0xbd, 0x5b, 0xf9, 0x06, 0x32]
, [0x8e, 0x28, 0x34, 0x93, 0x79, 0xcc, 0xc1, 0x1b, 0x2e, 0xee, 0x15, 0x43, 0xc4, 0x6f, 0xf6, 0x39]
, [0x1f, 0x2a, 0xbe, 0x72, 0x35, 0x55, 0xc8, 0x5f, 0x5b, 0xa3, 0x2d, 0xaf, 0x47, 0xae, 0x3c, 0x59]
, [0xaf, 0xce, 0x3c, 0x8e, 0x51, 0x7d, 0xf0, 0x3a, 0xea, 0xaa, 0xfd, 0x0d, 0x81, 0x86, 0x00, 0x9b]
, [0x65, 0xae, 0x29, 0x6b, 0x6d, 0xbe, 0x8f, 0xd5, 0x95, 0x68, 0x4a, 0x14, 0x4a, 0xb2, 0x15, 0x25]
, [0x39, 0xd6, 0xe2, 0xc4, 0x9a, 0x9a, 0x91, 0xa0, 0x6f, 0x0f, 0xc4, 0x29, 0xe2, 0x0b, 0x62, 0x27]
, [0x15, 0x84, 0x54, 0x98, 0x2f, 0x34, 0x87, 0x49, 0xa5, 0x8f, 0xff, 0xd1, 0xdc, 0xc9, 0x5a, 0xdb]
, [0xdd, 0xed, 0xca, 0x47, 0x3f, 0x1b, 0x26, 0x02, 0xa9, 0x29, 0xdc, 0xf0, 0x9c, 0x8f, 0xa2, 0x3e]
, [0xfc, 0x2f, 0x5a, 0xb0, 0x93, 0xa2, 0x14, 0xbe, 0x7e, 0x32, 0x3b, 0xd5, 0x38, 0x43, 0x34, 0x7d]
, [0x1b, 0x53, 0x73, 0xc7, 0xc1, 0x8e, 0xcb, 0x87, 0xc8, 0xe3, 0xae, 0xb9, 0x73, 0x6a, 0xcd, 0x09]
, [0xfa, 0x32, 0xc4, 0x5c, 0x3e, 0x73, 0x09, 0xf2, 0x0a, 0xb3, 0xde, 0xa0, 0x01, 0xf6, 0x26, 0xae]
, [0x26, 0x82, 0x4c, 0x75, 0xc6, 0xc7, 0x46, 0x7c, 0x47, 0xfd, 0xcc, 0xef, 0x8f, 0xc2, 0xe9, 0x89]
, [0x12, 0x9a, 0xe0, 0xdd, 0x18, 0x08, 0x55, 0xde, 0x16, 0x60, 0x1a, 0xe5, 0xa6, 0xa5, 0x30, 0x72]
, [0xc8, 0xe9, 0x14, 0xd4, 0xd6, 0xeb, 0x91, 0x9b, 0xfb, 0x9f, 0xca, 0x46, 0x07, 0xd5, 0x8d, 0xf5]
, [0xbf, 0x99, 0xd7, 0x90, 0x52, 0xef, 0xe0, 0xf6, 0x08, 0x52, 0x85, 0xfb, 0x5a, 0x4b, 0xbf, 0xa1]
, [0xee, 0xb8, 0x2d, 0x31, 0xa6, 0xbe, 0x48, 0x7b, 0x81, 0xfb, 0xf7, 0x1e, 0x1e, 0xc3, 0xed, 0xa9]
, [0x4a, 0xde, 0x6d, 0x4c, 0xf0, 0x23, 0x36, 0x24, 0xb4, 0x88, 0xb7, 0x56, 0x6e, 0xd8, 0xde, 0x4a]
, [0x9f, 0x80, 0x9b, 0x6d, 0x24, 0xf1, 0xfc, 0x99, 0xde, 0x02, 0x32, 0x1d, 0xd6, 0xa9, 0x3e, 0xd5]
, [0x02, 0xa8, 0x75, 0x65, 0xc4, 0x92, 0xbf, 0x60, 0x3f, 0xb4, 0xc4, 0xc1, 0xe8, 0x09, 0xdc, 0x8f]
, [0xc9, 0x9e, 0x9d, 0x53, 0xa8, 0x7f, 0xb0, 0x9c, 0xd9, 0x36, 0x50, 0x1b, 0x0b, 0xd9, 0x07, 0x1a]
, [0x45, 0x2e, 0xab, 0xe3, 0x6e, 0xbb, 0xa8, 0xac, 0x56, 0x6f, 0x66, 0x2a, 0xf8, 0xdd, 0x7c, 0x6f]
, [0xd1, 0x08, 0x4f, 0xbe, 0x9b, 0x27, 0x89, 0x41, 0x85, 0x0e, 0xa1, 0x25, 0x81, 0x82, 0x2f, 0x39]
, [0xeb, 0xa5, 0xfd, 0xba, 0x2f, 0x33, 0xc9, 0x52, 0x60, 0xa0, 0x97, 0x3a, 0xfd, 0xed, 0x94, 0xa5]
, [0x07, 0xa2, 0x79, 0xf8, 0x18, 0xd7, 0x87, 0x4c, 0x13, 0xb2, 0xd7, 0x9a, 0x45, 0xfa, 0xfb, 0x81]
, [0xfd, 0xe2, 0xec, 0x3a, 0x8a, 0x23, 0xa5, 0x78, 0xdc, 0x07, 0x1e, 0xe4, 0xeb, 0x5b, 0x95, 0x2e]
, [0xd7, 0x50, 0x2c, 0x14, 0x2c, 0x10, 0x38, 0x84, 0x57, 0xec, 0x1c, 0x4d, 0x49, 0x9f, 0x58, 0x19]
, [0xeb, 0xb5, 0x2f, 0x80, 0xb4, 0x05, 0x0b, 0xf2, 0x04, 0x64, 0x4e, 0x11, 0x89, 0x88, 0x2d, 0x6e]
, [0xfd, 0x5b, 0xe5, 0x23, 0x32, 0x9e, 0x59, 0xa0, 0x1e, 0x8b, 0x17, 0x5e, 0xfb, 0x96, 0x27, 0x8d]
, [0xb7, 0x0e, 0x59, 0xa3, 0xda, 0xed, 0x89, 0xc7, 0x29, 0x98, 0x4f, 0xaa, 0x37, 0x4c, 0x59, 0xce]
, [0x5b, 0x3f, 0x55, 0xcb, 0x2a, 0xfc, 0x4f, 0x90, 0x94, 0x98, 0x38, 0x15, 0x51, 0xd4, 0x01, 0x09]
, [0xb5, 0x63, 0xcb, 0xd2, 0xd2, 0xbc, 0x23, 0x1c, 0x45, 0xf9, 0x60, 0x2d, 0xa6, 0x83, 0xf5, 0x79]
, [0xc5, 0xf5, 0x3f, 0x4f, 0x56, 0xdb, 0x3f, 0x7f, 0xe0, 0xe3, 0x03, 0xf7, 0xc8, 0x15, 0xd7, 0x93]
, [0xbb, 0x92, 0x34, 0x05, 0xf4, 0x02, 0x08, 0xd7, 0x10, 0x1e, 0x8b, 0x57, 0xec, 0x26, 0x0d, 0xa8]
, [0x1f, 0xe3, 0xa7, 0x42, 0x1b, 0x84, 0xcb, 0xa5, 0x69, 0x22, 0x69, 0xbe, 0x47, 0x30, 0xbb, 0xbd]
, [0xf2, 0x6f, 0xd5, 0x78, 0x59, 0x0c, 0x0c, 0x14, 0x13, 0x51, 0xd0, 0xb4, 0xc1, 0x49, 0xc1, 0x28]
, [0x07, 0x51, 0x5d, 0x0d, 0x59, 0x6b, 0x44, 0x19, 0xc8, 0xbb, 0x07, 0x19, 0x74, 0x1f, 0xa2, 0x82]
, [0x60, 0x99, 0x07, 0xb1, 0x8c, 0xc6, 0xc9, 0xa2, 0x55, 0x04, 0xe2, 0x67, 0xe7, 0x89, 0x0a, 0xa6]
, [0x7a, 0x6f, 0x0f, 0x03, 0xa6, 0x44, 0x17, 0x23, 0x8a, 0x81, 0x06, 0x74, 0x24, 0x10, 0x87, 0xd5]
, [0x6c, 0xa5, 0x59, 0x1b, 0x32, 0x12, 0xca, 0x74, 0x1d, 0x2f, 0xdc, 0x24, 0x7a, 0x59, 0xc3, 0x29]
, [0x57, 0x93, 0xb2, 0x30, 0x59, 0x63, 0xd0, 0x0e, 0xb7, 0x4c, 0x62, 0x7a, 0x4f, 0x3d, 0x02, 0x5e]
, [0xab, 0xa3, 0x28, 0x2a, 0xa6, 0x4a, 0xa6, 0xf8, 0x19, 0xbe, 0x07, 0x13, 0x88, 0xa9, 0x57, 0x49]
, [0x12, 0xad, 0x3b, 0xfc, 0xd4, 0xe5, 0x1d, 0xc4, 0xcb, 0xa0, 0x9c, 0x50, 0x0c, 0xb1, 0xe1, 0xc0]
, [0x57, 0xc4, 0xea, 0x82, 0xc0, 0x3c, 0x30, 0xb3, 0x0e, 0x20, 0xd4, 0x09, 0x03, 0x61, 0x49, 0x49]
, [0x87, 0xf2, 0x12, 0xf7, 0x27, 0x17, 0xdf, 0x3b, 0x2f, 0x78, 0x16, 0x70, 0x20, 0x60, 0x5a, 0x3b]
, [0xc8, 0xa3, 0xb7, 0x19, 0xbc, 0xd4, 0x7f, 0xc0, 0x2a, 0x3b, 0xaa, 0xb9, 0x48, 0x90, 0x46, 0x67]
, [0xed, 0x53, 0x93, 0xf2, 0x5c, 0x29, 0x46, 0xe9, 0x7f, 0xbc, 0x78, 0x3b, 0x99, 0x77, 0x84, 0xa0]
, [0xa8, 0x3c, 0xa3, 0x94, 0x57, 0xc2, 0x69, 0x8b, 0x2b, 0x30, 0x3c, 0x09, 0x28, 0xe9, 0x4b, 0xe4]
, [0x6d, 0xb5, 0x49, 0xaa, 0xae, 0x77, 0xef, 0x64, 0x0d, 0x8a, 0x66, 0x46, 0x38, 0x73, 0x28, 0x2f]
, [0x1d, 0xfa, 0x04, 0x63, 0x27, 0xa3, 0xb1, 0xf3, 0xa6, 0x16, 0xe4, 0x28, 0x7a, 0x2e, 0xc5, 0xe1]
, [0x51, 0xf9, 0xab, 0xff, 0xb0, 0xaa, 0xc5, 0xd4, 0xbf, 0x9c, 0xcb, 0xec, 0x04, 0x71, 0x60, 0x5a]
, [0xc8, 0x80, 0xac, 0xa2, 0x74, 0x90, 0x86, 0xb6, 0xbe, 0xaa, 0x4d, 0x29, 0x6f, 0x48, 0xff, 0x21]
, [0x23, 0xe3, 0x2e, 0x57, 0x2b, 0x11, 0x8f, 0x57, 0x0a, 0x0e, 0x03, 0x78, 0xd1, 0x21, 0x02, 0x05]
, [0x0b, 0x4b, 0x43, 0x00, 0xe6, 0x06, 0x0b, 0x65, 0x11, 0x24, 0x87, 0x35, 0x0a, 0xe1, 0x5e, 0xbd]
, [0xf2, 0xae, 0x1e, 0x21, 0x53, 0xc1, 0x15, 0x9f, 0x38, 0x75, 0x35, 0xda, 0xc2, 0xa1, 0xc3, 0x8f]
, [0x10, 0x3f, 0xe3, 0xfc, 0xbd, 0xb4, 0x54, 0x8c, 0xa3, 0x89, 0x43, 0x52, 0x26, 0xb1, 0xe8, 0x36]
, [0xab, 0xc3, 0x9c, 0x66, 0x10, 0x36, 0xab, 0xa7, 0x95, 0x7c, 0x49, 0x59, 0x55, 0x68, 0xf6, 0xef]
, [0xf0, 0x79, 0x03, 0x32, 0xad, 0xd4, 0xd1, 0x48, 0xfe, 0xec, 0xcd, 0x6d, 0xff, 0xd9, 0x9b, 0x74]
, [0xa3, 0x0c, 0xac, 0xe7, 0x7b, 0x50, 0xd8, 0x6d, 0x17, 0x8d, 0x59, 0x28, 0xe1, 0x2f, 0x7c, 0xae]
, [0x5e, 0x5b, 0x63, 0x0d, 0xa6, 0x23, 0x8e, 0x00, 0x0b, 0x57, 0x89, 0xda, 0x9c, 0x93, 0x7b, 0xe8]
, [0x9d, 0xbf, 0xe6, 0x9e, 0xef, 0xb8, 0x37, 0xa6, 0xeb, 0xe5, 0x44, 0x00, 0x55, 0x2e, 0x86, 0x5d]
, [0x4f, 0x63, 0x7c, 0xe9, 0xdf, 0x28, 0x7e, 0x59, 0x93, 0x40, 0x91, 0x4d, 0xd6, 0x4b, 0x59, 0x75]
, [0xc9, 0xb8, 0xa1, 0x58, 0x9a, 0x7f, 0x48, 0x22, 0x69, 0x9c, 0xe8, 0x81, 0xb4, 0x3a, 0xff, 0x52]
, [0xc0, 0x53, 0x2e, 0xe6, 0xd0, 0x89, 0x1e, 0xec, 0x6f, 0x14, 0x2d, 0x7f, 0xfa, 0xb3, 0xf9, 0xdf]
, [0x32, 0x4d, 0x73, 0x4e, 0x0a, 0x9a, 0xf0, 0x73, 0x5a, 0xe1, 0xfa, 0x73, 0x19, 0xc4, 0x64, 0x71]
, [0x3e, 0xc2, 0x8b, 0x91, 0x6f, 0x36, 0xd0, 0xde, 0x9f, 0xb8, 0x37, 0xb1, 0x98, 0xb1, 0xe2, 0xfd]
, [0x85, 0x7c, 0x3f, 0x7b, 0x41, 0x05, 0xcd, 0xac, 0xb2, 0x14, 0xb9, 0xc7, 0x52, 0xfd, 0x72, 0xff]
, [0x39, 0xff, 0xb0, 0x7b, 0x44, 0x23, 0xab, 0x84, 0x66, 0x62, 0xb2, 0x27, 0xe9, 0x39, 0xdf, 0x83]
, [0x5d, 0x85, 0xcf, 0x3c, 0x60, 0x5d, 0x95, 0x08, 0xd1, 0x73, 0x34, 0x0a, 0x20, 0x2d, 0xe1, 0xfd]
, [0xd6, 0x06, 0x89, 0xae, 0xec, 0x14, 0x57, 0x20, 0x59, 0xa2, 0xc8, 0xc6, 0x07, 0x8e, 0x2e, 0xb2]
, [0x15, 0x30, 0x5d, 0xcc, 0xdf, 0xce, 0xe8, 0x19, 0x85, 0x93, 0xab, 0x6b, 0x25, 0xfe, 0x8b, 0x8e]
, [0x61, 0xf4, 0x96, 0x25, 0xc2, 0x30, 0xfa, 0xbd, 0x2e, 0x04, 0x54, 0x37, 0x7e, 0x46, 0xa5, 0x54]
, [0x30, 0x86, 0xaf, 0x94, 0xe4, 0x7d, 0xfd, 0x9a, 0x1e, 0x4e, 0x9d, 0x17, 0x84, 0x5b, 0xc8, 0x24]
, [0x24, 0x49, 0xd5, 0x6e, 0x3d, 0x53, 0xb6, 0x84, 0x4d, 0x40, 0x5c, 0xe7, 0xb6, 0x54, 0xe8, 0x4d]
, [0xb6, 0x15, 0x81, 0x36, 0x3d, 0x78, 0xc8, 0x7d, 0xd5, 0xd1, 0xe7, 0x49, 0xfd, 0x87, 0x2f, 0x48]
, [0x5b, 0x5c, 0x4e, 0x3c, 0x0e, 0xd1, 0xc6, 0x9a, 0x5d, 0x18, 0x9d, 0x51, 0xe0, 0xaf, 0x98, 0x3c]
, [0x3c, 0x0a, 0x38, 0x3f, 0x9f, 0x27, 0x7a, 0xa8, 0x16, 0xda, 0x98, 0xd0, 0x3f, 0x6c, 0x7e, 0x19]
, [0xbb, 0x0c, 0x5a, 0xa1, 0xb0, 0xec, 0x04, 0x08, 0xe1, 0xc5, 0xfb, 0xe9, 0x17, 0xf9, 0x92, 0x14]
, [0x10, 0x51, 0x56, 0x85, 0x8e, 0xc9, 0xeb, 0x98, 0x9e, 0x49, 0x67, 0xca, 0xcd, 0x13, 0x0c, 0x86]
, [0xf0, 0x57, 0x6a, 0xb8, 0x06, 0x03, 0x95, 0xde, 0x98, 0xeb, 0x5f, 0x8e, 0x5e, 0x9b, 0x9c, 0xcd]
, [0x97, 0x70, 0xe7, 0x8d, 0xca, 0x39, 0x66, 0xe9, 0x94, 0xe0, 0xad, 0x07, 0x2a, 0x7e, 0xac, 0x19]
, [0xfe, 0x3d, 0xe7, 0x65, 0x2f, 0xaa, 0x55, 0x32, 0xbb, 0x8e, 0xae, 0xe1, 0x5f, 0xa1, 0x14, 0x7f]
, [0xa7, 0xfd, 0x75, 0xfd, 0x40, 0x0b, 0x23, 0xc8, 0x51, 0x1b, 0xdf, 0x77, 0xa3, 0xa1, 0xe7, 0xf1]
, [0xb6, 0x63, 0x42, 0x97, 0x04, 0x0d, 0x88, 0x73, 0x55, 0xbd, 0x52, 0x88, 0x62, 0xd0, 0xdb, 0x25]
, [0x56, 0xa9, 0xc3, 0x17, 0xe4, 0xef, 0xee, 0x2c, 0x0f, 0x40, 0xd4, 0x8e, 0x3b, 0x52, 0xf9, 0x52]
, [0xd1, 0xf6, 0x05, 0x69, 0xf7, 0xd6, 0xc3, 0x1f, 0xd5, 0xfe, 0x14, 0x3d, 0xd0, 0xd9, 0x03, 0x38]
, [0xab, 0x61, 0xbd, 0x21, 0x66, 0xc6, 0xc2, 0xf7, 0x93, 0xcf, 0xb7, 0x52, 0x1f, 0x41, 0x64, 0x40]
, [0xe0, 0x24, 0x72, 0x1d, 0xb8, 0xa6, 0x1f, 0x68, 0xc4, 0xbc, 0x1f, 0xca, 0x31, 0x37, 0x2e, 0x53]
, [0xfa, 0x13, 0x85, 0xea, 0xb9, 0x9e, 0x83, 0x6f, 0x52, 0xff, 0x5f, 0xb7, 0x57, 0xb0, 0x0c, 0xfb]
, [0x7c, 0x0c, 0x96, 0xad, 0xa2, 0x8d, 0x81, 0xa2, 0x3f, 0xdd, 0x52, 0xa0, 0xfe, 0xba, 0x18, 0xfa]
, [0x41, 0x46, 0xdb, 0x75, 0x42, 0xaa, 0xb7, 0xa3, 0x39, 0x2c, 0x4a, 0xf7, 0x0d, 0xb7, 0x7e, 0xe2]
, [0x5c, 0x00, 0xcd, 0xe9, 0x6e, 0x13, 0x87, 0xaa, 0x83, 0xdb, 0x41, 0x44, 0xfc, 0x4f, 0x22, 0x6f]
, [0xd6, 0xf2, 0xcb, 0x1c, 0xf4, 0x27, 0x46, 0xe5, 0x2d, 0xc9, 0x19, 0x36, 0x57, 0xbf, 0xa6, 0x3b]
, [0xb3, 0xd0, 0xe8, 0xe7, 0x8b, 0x78, 0x5c, 0x8a, 0x73, 0x26, 0x12, 0xa6, 0x29, 0xe9, 0xd5, 0x9c]
, [0x03, 0x90, 0x39, 0x76, 0x74, 0x91, 0xb6, 0xd1, 0xe6, 0xcc, 0xf4, 0x13, 0x19, 0x87, 0x5f, 0x77]
, [0x98, 0xe4, 0x0a, 0xaa, 0x07, 0x5b, 0x32, 0x96, 0xb7, 0xcf, 0x08, 0x8c, 0xb9, 0xd1, 0xff, 0xc3]
, [0x1d, 0x4c, 0x48, 0x18, 0xc4, 0xd0, 0x3c, 0xfe, 0xde, 0xbf, 0xe1, 0xc6, 0x74, 0xc1, 0x54, 0xa5]
, [0xf0, 0x09, 0x1b, 0x5f, 0xc7, 0x88, 0xef, 0x33, 0x57, 0x93, 0x33, 0x8e, 0x04, 0x60, 0x02, 0x30]
, [0xdb, 0xb4, 0xf2, 0x81, 0x22, 0x1e, 0x8e, 0xa9, 0xa4, 0xe5, 0x78, 0x99, 0xf2, 0x4a, 0xc9, 0x6e]
, [0x27, 0xb3, 0x0f, 0x4c, 0x9c, 0x61, 0x19, 0x65, 0xd2, 0x80, 0xdf, 0xde, 0xf6, 0x42, 0xca, 0x19]
, [0xc1, 0xe2, 0x1b, 0x80, 0x4f, 0xa0, 0x55, 0xdc, 0x61, 0x29, 0xa7, 0xef, 0x4b, 0x39, 0x42, 0xbd]
, [0x27, 0x47, 0x9b, 0xd4, 0xd6, 0xb2, 0x22, 0x93, 0xd6, 0x27, 0x16, 0x53, 0xfc, 0x73, 0xb3, 0xf7]
, [0x61, 0x5e, 0x34, 0x76, 0x6a, 0x66, 0x34, 0x3b, 0xbb, 0x6b, 0xc0, 0xe0, 0x36, 0xba, 0x8f, 0x36]
, [0x4d, 0x43, 0x11, 0xc0, 0x7c, 0x93, 0x28, 0xa6, 0xd7, 0xb7, 0x6b, 0xbe, 0xbd, 0x08, 0xf6, 0x56]
, [0xc4, 0x03, 0xdc, 0x2c, 0xf9, 0x62, 0x39, 0xf7, 0xd4, 0x37, 0x62, 0x08, 0x82, 0xd0, 0xd5, 0x40]
, [0x79, 0xee, 0xd5, 0xfa, 0x9c, 0x5a, 0xc8, 0x3d, 0x97, 0x2c, 0x73, 0xed, 0xa6, 0xfc, 0xe2, 0x84]
, [0x18, 0x0e, 0xd3, 0x27, 0xba, 0x6d, 0x76, 0xd4, 0x2e, 0xf7, 0x96, 0x02, 0xdf, 0xd9, 0x23, 0x61]
, [0xd4, 0x12, 0x73, 0x28, 0xa6, 0x2f, 0x95, 0x50, 0x19, 0x33, 0x60, 0x3f, 0xad, 0xf2, 0xd1, 0x59]
, [0x92, 0xa0, 0xba, 0x33, 0x48, 0xfc, 0xb0, 0x56, 0x3f, 0xbf, 0x73, 0xd2, 0x7b, 0x1e, 0xfd, 0x38]
, [0x95, 0x2b, 0x46, 0xf3, 0x64, 0x87, 0xe2, 0xb9, 0xce, 0x11, 0x48, 0x17, 0x02, 0xf1, 0xbb, 0x49]
, [0x4a, 0x81, 0x6b, 0x05, 0x5f, 0x89, 0x1a, 0x4f, 0xf0, 0x82, 0xac, 0xe3, 0x69, 0x5d, 0x3c, 0x13]
, [0xcb, 0x76, 0x1b, 0xb8, 0x7b, 0xff, 0x03, 0x58, 0x83, 0x69, 0xa9, 0xa8, 0x2e, 0x0f, 0xfa, 0x2e]
, [0x06, 0x6d, 0xc2, 0x70, 0x0d, 0xe0, 0xdf, 0x11, 0xf2, 0xa3, 0xb7, 0xd3, 0xe9, 0x1f, 0x53, 0x17]
, [0x27, 0x3b, 0xa4, 0xff, 0x21, 0x25, 0x8c, 0xf9, 0x37, 0xaf, 0xb1, 0xe8, 0x5e, 0x91, 0x7a, 0x42]
, [0x11, 0x2c, 0x0a, 0xe1, 0x3f, 0x74, 0x92, 0xd2, 0xac, 0x2b, 0xfa, 0xd7, 0xfd, 0x04, 0xb7, 0xef]
, [0x99, 0x70, 0x5f, 0x50, 0x20, 0xca, 0xb0, 0xf6, 0xb0, 0x95, 0x3f, 0xaa, 0xe9, 0x67, 0x55, 0x59]
, [0xf4, 0x79, 0xd4, 0x3a, 0xb7, 0x75, 0x83, 0xa4, 0x12, 0xbb, 0x09, 0x69, 0x83, 0x72, 0x80, 0x0c]
, [0x83, 0x0c, 0x2b, 0x6f, 0x44, 0x71, 0x77, 0xfb, 0xd1, 0x6c, 0x0e, 0x7c, 0x63, 0x83, 0x7b, 0x18]
]
checkFSB :: BL.ByteString -> Maybe BL.ByteString
checkFSB b = guard ("FSB" `BL.isPrefixOf` b) >> return b
ghworDecrypt :: B.ByteString -> Maybe BL.ByteString
ghworDecrypt bs = do
guard $ B.length bs >= 0x800
let (cipherData, cipherFooter) = B.splitAt (B.length bs - 0x800) bs
makeKey k = case cipherInit k of
CryptoPassed cipher -> Just (cipher :: AES128)
_ -> Nothing
iv <- makeIV $ B.replicate 16 0
cipher <- makeKey $ head ghworKeys
let footer = ctrCombine cipher iv cipherFooter
keyIndex = sum $ map (B.index footer) [4..7]
key <- makeKey $ ghworKeys !! fromIntegral keyIndex
checkFSB $ BL.fromStrict $ ctrCombine key iv cipherData
ghworEncrypt :: B.ByteString -> Maybe B.ByteString
ghworEncrypt bs = do
let makeKey k = case cipherInit k of
CryptoPassed cipher -> Just (cipher :: AES128)
_ -> Nothing
iv <- makeIV $ B.replicate 16 0
cipher <- makeKey $ head ghworKeys
let footer = ctrCombine cipher iv ghworCipher
keyIndex = sum $ map (B.index footer) [4..7]
key <- makeKey $ ghworKeys !! fromIntegral keyIndex
return $ ctrCombine key iv bs <> ghworCipher
readFSBXMA :: (MonadResource m) => BL.ByteString -> IO (CA.AudioSource m Float)
readFSBXMA dec = let
dec' = BL.concat
[ BL.take 0x62 dec
this is a hack so ffmpeg recognizes the fsb 's xma encoding . TODO send a PR to fix
, BL.drop 0x63 dec
]
readable = makeHandle "decoded FSB audio" $ byteStringSimpleHandle dec'
in ffSource $ Left readable
readFSB :: (MonadResource m) => BL.ByteString -> IO (CA.AudioSource m Float)
readFSB dec = do
fsb <- parseFSB dec
let song = head $ either fsb3Songs fsb4Songs $ fsbHeader fsb
case fsbExtra song of
Left _xma -> readFSBXMA dec
Right _mp3 -> do
let numStreams = case quotRem (fromIntegral $ fsbSongChannels song) 2 of
(x, y) -> x + y
mp3s <- splitInterleavedMP3 numStreams $ head $ fsbSongData fsb
srcs <- forM mp3s $ \mp3 -> ffSource $ Left $ makeHandle "decoded FSB audio" $ byteStringSimpleHandle mp3
return $ foldl1 CA.merge srcs
decryptFSB' :: FilePath -> B.ByteString -> Maybe BL.ByteString
decryptFSB' name enc = let
lazy = BL.fromStrict enc
in ghworDecrypt enc
<|> ghwtDecrypt name lazy
<|> gh3Decrypt lazy
decryptFSB :: FilePath -> IO (Maybe BL.ByteString)
decryptFSB fin = decryptFSB' fin <$> B.readFile fin
convertAudio :: FilePath -> FilePath -> IO ()
convertAudio fin fout = do
dec <- decryptFSB fin >>= maybe (error "Couldn't decrypt GH .fsb.xen audio") return
src <- readFSB dec
audioIO Nothing src fout
reverseMapping :: B.ByteString
reverseMapping = B.pack $ flip map [0 .. 0xFF] $ \i -> foldr (.|.) 0
[ i `shiftR` 7
, (i `shiftR` 5) .&. 0x02
, (i `shiftR` 3) .&. 0x04
, (i `shiftR` 1) .&. 0x08
, (i `shiftL` 7)
, (i `shiftL` 5) .&. 0x40
, (i `shiftL` 3) .&. 0x20
, (i `shiftL` 1) .&. 0x10
]
revByte :: Word8 -> Word8
revByte = B.index reverseMapping . fromIntegral
revBytes :: BL.ByteString -> BL.ByteString
revBytes = BL.map revByte
Taken from adlc783_1.fsb.xen ( Paramore - Ignorance , drums audio )
but IIRC , trying to encode with an all zero key failed .
ghworCipher :: B.ByteString
ghworCipher = B.pack
[ 92,113,247,179,25,193,117,66,167,59,75,58,1,210,26,194,9,38,141,132,150,92,120,247,226,143,171,243,28,185,93,157,49,7,58,194,84,150,212,254,87,141,129,31,172,252,4,191,246,142,195,58,4,155,217,59,135,3,205,241,10,92,52,35,113,116,248,191,13,100,143,134,50,77,86,43,55,104,222,156,123,12,76,103,220,9,197,105,85,255,112,48,56,197,206,60,217,26,93,242,227,195,79,50,157,202,107,236,84,174,49,155,181,214,226,248,33,236,17,67,166,38,200,232,229,29,77,43,47,147,198,156,242,222,46,34,184,115,108,93,240,232,173,172,15,192,242,35,180,140,40,72,147,81,245,165,216,155,30,248,152,105,36,35,235,134,180,121,58,178,96,17,91,83,220,96,166,21,24,251,5,213,250,79,137,146,232,150,100,167,74,131,212,100,192,156,132,133,38,71,177,244,191,70,192,172,179,14,96,93,36,195,253,149,16,111,117,29,254,110,214,46,139,230,106,127,140,154,239,69,81,163,147,226,55,131,170,65,224,166,161,72,235,5,109,184
, 43,18,239,44,43,17,169,159,211,47,130,215,77,156,97,21,234,185,55,10,163,129,21,169,200,36,129,2,24,118,160,144,170,162,53,181,164,87,33,96,239,212,76,133,201,197,103,35,121,76,214,43,156,174,180,111,248,68,188,38,34,208,3,136,237,168,214,50,168,184,51,19,70,184,149,177,94,213,23,230,197,30,80,115,251,46,32,184,150,212,42,206,214,44,142,144,77,41,231,16,42,121,218,1,245,99,130,207,52,118,104,208,228,35,195,68,173,59,220,31,184,98,208,4,82,246,210,28,189,161,94,179,14,61,77,227,19,49,117,91,144,183,155,49,11,113,38,158,176,106,220,75,132,83,185,255,153,193,131,64,106,105,252,233,30,99,138,189,64,5,30,145,1,30,6,145,67,78,182,206,117,70,102,47,21,238,203,254,217,201,38,222,136,127,165,228,170,19,147,205,222,247,118,188,88,226,35,132,166,138,199,248,250,25,139,171,29,94,91,81,176,181,175,213,22,199,19,37,57,51,32,156,107,194,159,220,113,64,22,50,10,128,247,248,157,38,140
, 30,146,168,34,243,133,106,248,83,8,234,90,163,183,73,235,168,83,8,48,51,162,220,183,132,252,86,68,26,157,46,147,126,201,60,29,141,145,7,34,129,214,22,133,41,208,218,235,123,244,39,22,148,115,63,133,175,163,9,172,80,94,181,57,249,165,67,73,122,194,85,178,52,43,47,168,163,241,199,240,129,134,232,123,81,192,78,37,8,70,101,64,180,146,169,168,14,116,26,28,101,236,101,208,178,216,98,178,184,231,121,107,99,62,190,253,41,245,205,220,189,192,225,191,105,210,15,17,191,153,160,169,75,144,193,117,43,36,97,118,45,33,55,202,12,27,179,109,38,167,100,154,10,62,206,34,111,86,205,126,129,48,40,18,223,100,161,58,201,167,207,51,43,5,19,100,223,169,156,194,6,249,221,28,141,201,184,179,169,40,23,86,163,161,68,12,91,151,234,64,32,39,65,101,171,185,171,79,212,76,144,70,197,147,149,5,160,104,114,80,89,60,123,27,190,78,56,11,68,1,34,68,79,64,50,109,123,132,84,203,169,79,38,105,154,183,251,118
, 70,192,236,228,104,28,130,150,27,111,77,74,78,208,36,206,201,45,99,20,120,216,1,49,147,48,237,127,244,166,7,126,72,142,68,210,150,63,193,113,77,173,102,26,56,184,230,158,66,35,174,100,102,240,5,13,118,127,250,147,173,196,216,114,31,137,234,3,110,170,160,115,155,247,94,219,16,76,190,77,134,81,122,76,206,136,222,70,41,132,74,50,94,95,255,73,36,136,35,165,2,64,246,87,41,88,53,166,9,47,234,68,5,189,38,249,179,223,203,204,156,145,161,158,205,57,117,184,215,130,5,117,79,103,197,27,105,94,221,197,137,120,14,144,85,206,94,81,249,146,239,156,38,236,77,32,232,102,127,192,208,44,129,66,124,127,188,119,122,243,20,148,233,133,137,187,115,49,12,217,110,27,191,191,67,42,9,235,176,3,183,99,34,68,191,231,247,72,89,18,99,169,19,231,124,98,220,191,235,134,27,25,91,146,168,252,128,93,236,185,150,83,98,119,151,80,234,102,27,254,76,4,175,229,134,73,29,167,112,123,92,129,249,111,188,89,218
, 242,32,107,251,6,199,132,131,86,2,66,100,98,107,232,238,229,213,193,54,32,211,210,219,70,92,231,233,206,17,119,250,12,207,200,85,27,72,53,116,206,76,46,79,122,119,149,237,42,127,158,232,214,153,0,19,220,195,157,11,61,154,73,164,56,113,175,111,214,145,22,150,186,127,179,209,172,223,176,222,206,188,54,40,79,196,190,135,29,231,243,166,174,24,145,212,67,18,233,34,34,15,35,80,95,237,184,34,167,166,102,187,198,169,6,14,10,24,20,203,219,223,222,194,52,107,175,173,252,214,10,36,19,187,210,119,47,253,204,49,236,158,49,96,79,88,26,165,32,152,189,35,218,37,70,103,14,19,93,255,193,47,159,145,20,4,108,129,139,21,184,114,19,203,82,0,144,124,200,201,64,143,151,218,201,24,50,213,81,101,186,237,216,243,121,43,44,126,156,140,72,255,18,15,147,87,75,151,65,74,76,175,34,11,37,221,249,55,38,67,206,239,126,106,12,242,141,215,105,157,222,9,136,79,127,219,146,129,80,91,239,9,189,141,47,240,199
, 180,63,234,102,151,4,228,208,194,11,233,228,239,107,127,224,143,120,171,35,1,4,160,250,171,245,212,25,204,245,137,63,16,34,19,199,145,116,211,170,22,19,40,129,119,4,202,9,141,212,187,230,47,195,21,134,61,24,146,95,81,8,146,35,146,15,31,166,6,25,85,209,186,9,146,175,68,237,61,175,51,186,95,72,156,121,203,16,85,162,182,241,102,35,20,66,210,200,230,29,158,235,24,120,165,9,45,107,213,187,193,247,101,60,197,129,218,3,159,40,206,81,61,83,109,221,197,235,88,7,145,169,154,233,195,59,109,195,248,192,82,135,246,183,0,237,70,163,136,99,237,117,170,185,175,155,193,194,167,138,146,128,9,123,45,31,188,204,116,107,191,131,202,175,167,92,57,212,115,222,203,148,193,184,154,255,217,255,182,208,169,156,53,189,15,185,175,101,137,29,242,222,187,207,64,36,29,106,127,171,239,237,195,35,159,126,30,113,183,170,125,15,176,114,70,12,23,101,215,80,87,171,182,32,158,88,158,69,90,193,26,242,56,169
, 56,45,89,236,212,10,67,209,52,23,147,247,90,96,216,169,122,96,144,184,122,73,247,91,55,240,57,134,36,206,4,151,129,114,24,35,28,100,186,27,235,136,146,253,253,71,212,146,142,127,238,100,5,244,37,149,98,8,118,137,158,169,37,82,169,44,54,7,130,26,127,70,69,22,188,6,126,89,237,247,221,69,34,92,58,190,49,141,107,230,101,108,153,33,91,49,58,129,127,121,234,252,232,124,159,211,40,248,235,159,224,234,162,98,90,88,187,89,243,184,187,85,150,65,97,155,120,56,214,179,56,248,201,251,50,37,29,0,9,168,78,70,180,5,108,133,91,98,126,158,27,12,186,154,213,41,95,93,75,180,105,169,240,249,138,184,227,54,27,228,62,132,218,199,5,50,16,8,12,73,71,45,79,170,226,14,5,241,214,203,14,183,223,221,137,133,13,128,6,137,219,36,226,66,57,45,20,105,41,177,171,6,130,102,82,57,110,7,160,153,120,57,34,172,195,108,49,251,12,214,37,78,179,115,238,100,153,185,76,81,253,84,128,234,252,128,46,141,137,184,218
, 106,69,182,7,14,32,208,174,195,70,150,160,231,59,102,108,115,63,181,164,122,79,73,127,159,188,53,20,218,245,24,92,32,134,228,16,111,95,170,0,194,110,186,109,236,207,74,88,16,24,132,228,182,87,42,11,122,220,117,222,112,16,169,248,70,201,252,72,48,157,228,131,121,164,211,60,136,95,18,27,35,180,174,238,43,31,205,172,135,227,114,113,129,191,139,186,227,213,212,137,225,103,40,189,197,10,149,150,194,23,149,171,38,56,57,155,91,133,234,95,16,86,46,33,97,122,242,143,2,28,193,56,2,233,5,223,198,183,215,190,92,133,167,231,7,125,35,77,217,55,101,142,238,121,225,235,59,155,162,152,30,243,180,58,155,32,12,140,168,139,68,89,145,67,231,155,245,85,15,79,126,201,159,174,152,165,247,39,66,149,221,181,106,36,137,29,193,186,62,82,255,68,124,165,45,121,216,5,0,0,172,34,195,255,250,242,171,47,194,14,10,152,0,170,3,25,109,174,216,127,65,63,66,91,126,12,98,198,30,193,224,51,35,146,159,134,198
, 119,107,103,108,251,112,175,8,121,194,82,175,219,141,22,24,168,79,171,153,98,246,185,26,164,139,78,44,178,99,185,238,214,5,94,188,83,231,133,59,94,116,234,124,88,164,110,194,43,230,204,143,238,213,206,227,212,54,149,128,111,112,157,104,41,18,198,149,158,254,186
]
gh3Decrypt :: BL.ByteString -> Maybe BL.ByteString
gh3Decrypt bs = let
cipher = cycle $ BL.unpack "5atu6w4zaw"
in checkFSB $ BL.pack $ map revByte $ zipWith xor (BL.unpack bs) cipher
gh3Encrypt :: BL.ByteString -> BL.ByteString
gh3Encrypt bs = let
cipher = cycle $ BL.unpack "5atu6w4zaw"
in BL.pack $ zipWith xor (BL.unpack $ revBytes bs) cipher
GHWT = =
ghwtKey :: B.ByteString -> B.ByteString
ghwtKey str = runST $ do
let ncycle = 32
vxor <- newSTRef (0xFFFFFFFF :: Word32)
encstr <- fmap B.pack $ forM [0 .. ncycle - 1] $ \i -> do
let ch = B.index str $ i `rem` B.length str
crc = qbKeyCRC $ B.singleton ch
xorOld <- readSTRef vxor
let xorNew = crc `xor` xorOld
writeSTRef vxor xorNew
let index = fromIntegral $ xorNew `rem` fromIntegral (B.length str)
return $ B.index str index
key <- forM [0 .. ncycle - 2] $ \i -> do
let ch = B.index encstr i
crc = qbKeyCRC $ B.singleton ch
xorOld <- readSTRef vxor
let xorNew1 = crc `xor` xorOld
c = i .&. 3
xorNew2 = xorNew1 `shiftR` c
writeSTRef vxor xorNew2
return $ fromIntegral xorNew2
return $ B.pack $ takeWhile (/= 0) key
ghwtKeyFromFile :: FilePath -> B.ByteString
ghwtKeyFromFile f = ghwtKey $ let
s1 = T.toLower $ T.pack $ takeFileName f
s2 = fromMaybe s1 $ T.stripSuffix ".xen" s1
s3 = fromMaybe s2 $ T.stripSuffix ".fsb" s2
s4 = case T.stripPrefix "adlc" s3 of
Nothing -> s3
Just s -> "dlc" <> s
in TE.encodeUtf8 s4
ghwtDecrypt :: FilePath -> BL.ByteString -> Maybe BL.ByteString
ghwtDecrypt name bs = checkFSB $ BL.pack $ zipWith xor
(map revByte $ BL.unpack bs)
(cycle $ B.unpack $ ghwtKeyFromFile name)
ghwtEncrypt :: FilePath -> BL.ByteString -> BL.ByteString
ghwtEncrypt name bs = revBytes $ BL.pack $ zipWith xor
(BL.unpack bs)
(cycle $ B.unpack $ ghwtKeyFromFile name)
|
753ac0620187cd0fb0071f0ca90a42d8d8ec383fce68de1569240103dbc13770 | xapi-project/xen-api | network_monitor_thread.ml |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open Network_utils
open Xapi_stdext_pervasives
module D = Debug.Make (struct let name = "network_monitor_thread" end)
open D
let with_lock = Xapi_stdext_threads.Threadext.Mutex.execute
(** Table for bonds status. *)
let bonds_status : (string, int * int) Hashtbl.t = Hashtbl.create 10
let monitor_whitelist =
ref
[
"eth"
; "vif"
(* This includes "tap" owing to the use of standardise_name below *)
]
let xapi_rpc xml =
let open Xmlrpc_client in
XMLRPC_protocol.rpc ~srcstr:"xcp-networkd" ~dststr:"xapi"
~transport:(Unix "/var/xapi/xapi")
~http:(xmlrpc ~version:"1.0" "/")
xml
let send_bond_change_alert _dev interfaces message =
let ifaces = String.concat "+" (List.sort String.compare interfaces) in
let module XenAPI = Client.Client in
let session_id =
XenAPI.Session.login_with_password ~rpc:xapi_rpc ~uname:"" ~pwd:""
~version:"1.4"
~originator:("xcp-networkd v" ^ Xapi_version.version)
in
Pervasiveext.finally
(fun _ ->
let obj_uuid = Inventory.lookup Inventory._installation_uuid in
let body = Printf.sprintf "The status of the %s bond %s" ifaces message in
try
let name, priority = Api_messages.bond_status_changed in
let (_ : API.ref_message) =
XenAPI.Message.create ~rpc:xapi_rpc ~session_id ~name ~priority
~cls:`Host ~obj_uuid ~body
in
()
with _ -> warn "Exception sending a bond-status-change alert."
)
(fun _ -> XenAPI.Session.logout ~rpc:xapi_rpc ~session_id)
let check_for_changes ~(dev : string) ~(stat : Network_monitor.iface_stats) =
let open Network_monitor in
match Astring.String.is_prefix ~affix:"vif" dev with
| true ->
()
| false ->
if stat.nb_links > 1 then
if (* It is a bond. *)
Hashtbl.mem bonds_status dev then (
(* Seen before. *)
let nb_links_old, links_up_old = Hashtbl.find bonds_status dev in
if links_up_old <> stat.links_up then (
info "Bonds status changed: %s nb_links %d up %d up_old %d" dev
stat.nb_links stat.links_up links_up_old ;
Hashtbl.replace bonds_status dev (stat.nb_links, stat.links_up) ;
let msg =
Printf.sprintf "changed: %d/%d up (was %d/%d)" stat.links_up
stat.nb_links links_up_old nb_links_old
in
try send_bond_change_alert dev stat.interfaces msg
with e ->
debug "Error while sending alert BONDS_STATUS_CHANGED: %s\n%s"
(Printexc.to_string e)
(Printexc.get_backtrace ())
)
) else (
Seen for the first time .
Hashtbl.add bonds_status dev (stat.nb_links, stat.links_up) ;
info "New bonds status: %s nb_links %d up %d" dev stat.nb_links
stat.links_up ;
if stat.links_up <> stat.nb_links then
let msg =
Printf.sprintf "is: %d/%d up" stat.links_up stat.nb_links
in
try send_bond_change_alert dev stat.interfaces msg
with e ->
debug "Error while sending alert BONDS_STATUS_CHANGED: %s\n%s"
(Printexc.to_string e)
(Printexc.get_backtrace ())
)
let failed_again = ref false
let standardise_name name =
try
let d1, d2 = Scanf.sscanf name "tap%d.%d" (fun d1 d2 -> (d1, d2)) in
let newname = Printf.sprintf "vif%d.%d" d1 d2 in
newname
with _ -> name
let get_link_stats () =
let open Network_monitor in
let open Netlink in
let s = Socket.alloc () in
Socket.connect s Socket.NETLINK_ROUTE ;
let cache = Link.cache_alloc s in
let links = Link.cache_to_list cache in
let links =
let is_whitelisted name =
List.exists
(fun s -> Astring.String.is_prefix ~affix:s name)
!monitor_whitelist
in
let is_vlan name =
Astring.String.is_prefix ~affix:"eth" name && String.contains name '.'
in
List.map (fun link -> (standardise_name (Link.get_name link), link)) links
Only keep interfaces with prefixes on the whitelist , and exclude VLAN
devices ( ethx.y ) .
devices (ethx.y). *)
List.filter (fun (name, _) -> is_whitelisted name && not (is_vlan name))
in
let devs =
List.map
(fun (name, link) ->
let convert x = Int64.of_int (Unsigned.UInt64.to_int x) in
let eth_stat =
{
default_stats with
rx_bytes= Link.get_stat link Link.RX_BYTES |> convert
; rx_pkts= Link.get_stat link Link.RX_PACKETS |> convert
; rx_errors= Link.get_stat link Link.RX_ERRORS |> convert
; tx_bytes= Link.get_stat link Link.TX_BYTES |> convert
; tx_pkts= Link.get_stat link Link.TX_PACKETS |> convert
; tx_errors= Link.get_stat link Link.TX_ERRORS |> convert
}
in
(name, eth_stat)
)
links
in
Cache.free cache ; Socket.close s ; Socket.free s ; devs
let rec monitor dbg () =
let open Network_interface in
let open Network_monitor in
( try
let make_bond_info devs (name, interfaces) =
let devs' =
List.filter (fun (name', _) -> List.mem name' interfaces) devs
in
let eth_stat =
{
default_stats with
rx_bytes=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.rx_bytes)
0L devs'
; rx_pkts=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.rx_pkts)
0L devs'
; rx_errors=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.rx_errors)
0L devs'
; tx_bytes=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.tx_bytes)
0L devs'
; tx_pkts=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.tx_pkts)
0L devs'
; tx_errors=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.tx_errors)
0L devs'
}
in
(name, eth_stat)
in
let add_bonds bonds devs = List.map (make_bond_info devs) bonds @ devs in
let transform_taps devs =
let newdevnames =
Xapi_stdext_std.Listext.List.setify (List.map fst devs)
in
List.map
(fun name ->
let devs' = List.filter (fun (n, _) -> n = name) devs in
let tot =
List.fold_left
(fun acc (_, b) ->
{
default_stats with
rx_bytes= Int64.add acc.rx_bytes b.rx_bytes
; rx_pkts= Int64.add acc.rx_pkts b.rx_pkts
; rx_errors= Int64.add acc.rx_errors b.rx_errors
; tx_bytes= Int64.add acc.tx_bytes b.tx_bytes
; tx_pkts= Int64.add acc.tx_pkts b.tx_pkts
; tx_errors= Int64.add acc.tx_errors b.tx_errors
}
)
default_stats devs'
in
(name, tot)
)
newdevnames
in
let add_other_stats bonds devs =
List.map
(fun (dev, stat) ->
if not (Astring.String.is_prefix ~affix:"vif" dev) then (
let open Network_server.Bridge in
let bond_slaves =
if List.mem_assoc dev bonds then
get_bond_link_info () dbg ~name:dev
else
[]
in
let stat =
if bond_slaves = [] then
let carrier = Sysfs.get_carrier dev in
let speed, duplex =
if carrier then
Sysfs.get_status dev
else
(0, Duplex_unknown)
in
let pci_bus_path = Sysfs.get_pcibuspath dev in
let vendor_id, device_id = Sysfs.get_pci_ids dev in
let nb_links = 1 in
let links_up = if carrier then 1 else 0 in
let interfaces = [dev] in
{
stat with
carrier
; speed
; duplex
; pci_bus_path
; vendor_id
; device_id
; nb_links
; links_up
; interfaces
}
else
let carrier = List.exists (fun info -> info.up) bond_slaves in
let speed, duplex =
let combine_duplex = function
| Duplex_full, Duplex_full ->
Duplex_full
| Duplex_unknown, a | a, Duplex_unknown ->
a
| _ ->
Duplex_half
in
List.fold_left
(fun (speed, duplex) info ->
try
if info.active then
let speed', duplex' = Sysfs.get_status info.slave in
(speed + speed', combine_duplex (duplex, duplex'))
else
(speed, duplex)
with _ -> (speed, duplex)
)
(0, Duplex_unknown) bond_slaves
in
let pci_bus_path = "" in
let vendor_id, device_id = ("", "") in
let nb_links = List.length bond_slaves in
let links_up =
List.length (List.filter (fun info -> info.up) bond_slaves)
in
let interfaces =
List.map (fun info -> info.slave) bond_slaves
in
{
stat with
carrier
; speed
; duplex
; pci_bus_path
; vendor_id
; device_id
; nb_links
; links_up
; interfaces
}
in
check_for_changes ~dev ~stat ;
(dev, stat)
) else
(dev, stat)
)
devs
in
let from_cache = true in
let bonds : (string * string list) list =
Network_server.Bridge.get_all_bonds dbg from_cache
in
let devs =
get_link_stats ()
|> add_bonds bonds
|> transform_taps
|> add_other_stats bonds
in
( if List.length bonds <> Hashtbl.length bonds_status then
let dead_bonds =
Hashtbl.fold
(fun k _ acc -> if List.mem_assoc k bonds then acc else k :: acc)
bonds_status []
in
List.iter
(fun b ->
info "Removing bond %s" b ;
Hashtbl.remove bonds_status b
)
dead_bonds
) ;
write_stats devs ;
failed_again := false
with e ->
if not !failed_again then (
failed_again := true ;
debug
"Error while collecting stats (suppressing further errors): %s\n%s"
(Printexc.to_string e)
(Printexc.get_backtrace ())
)
) ;
Thread.delay interval ; monitor dbg ()
let watcher_m = Mutex.create ()
let watcher_pid = ref None
let signal_networking_change () =
let module XenAPI = Client.Client in
let session =
XenAPI.Session.slave_local_login_with_password ~rpc:xapi_rpc ~uname:""
~pwd:""
in
Pervasiveext.finally
(fun () ->
XenAPI.Host.signal_networking_change ~rpc:xapi_rpc ~session_id:session
)
(fun () -> XenAPI.Session.local_logout ~rpc:xapi_rpc ~session_id:session)
(* Remove all outstanding reads on a file descriptor *)
let clear_input fd =
let buf = Bytes.make 255 ' ' in
let rec loop () =
try
ignore (Unix.read fd buf 0 255) ;
loop ()
with _ -> ()
in
Unix.set_nonblock fd ; loop () ; Unix.clear_nonblock fd
let rec ip_watcher () =
let cmd = Network_utils.iproute2 in
let args = ["monitor"; "address"] in
let readme, writeme = Unix.pipe () in
with_lock watcher_m (fun () ->
watcher_pid :=
Some
(Forkhelpers.safe_close_and_exec ~env:(Unix.environment ()) None
(Some writeme) None [] cmd args
)
) ;
Unix.close writeme ;
let in_channel = Unix.in_channel_of_descr readme in
let rec loop () =
let line = input_line in_channel in
(* Do not send events for link-local IPv6 addresses, and removed IPs *)
if
Astring.String.is_infix ~affix:"inet" line
&& not (Astring.String.is_infix ~affix:"inet6 fe80" line)
then (
Ignore changes for the next second , since they usually come in bursts ,
* and signal only once .
* and signal only once. *)
Thread.delay 1. ;
clear_input readme ;
signal_networking_change ()
) ;
loop ()
in
let restart_ip_watcher () =
Unix.close readme ; Thread.delay 5.0 ; ip_watcher ()
in
while true do
try
info "(Re)started IP watcher thread" ;
loop ()
with e -> (
warn "Error in IP watcher: %s\n%s" (Printexc.to_string e)
(Printexc.get_backtrace ()) ;
match !watcher_pid with
| None ->
restart_ip_watcher ()
| Some pid ->
let quitted, _ = Forkhelpers.waitpid_nohang pid in
if quitted <> 0 then (
warn "address monitoring process quitted, try to restart it" ;
restart_ip_watcher ()
)
)
done
let start () =
let dbg = "monitor_thread" in
Debug.with_thread_associated dbg
(fun () ->
debug "Starting network monitor" ;
let (_ : Thread.t) = Thread.create (monitor dbg) () in
let (_ : Thread.t) = Thread.create ip_watcher () in
()
)
()
let stop () =
with_lock watcher_m (fun () ->
match !watcher_pid with
| None ->
()
| Some pid ->
Unix.kill (Forkhelpers.getpid pid) Sys.sigterm
)
| null | https://raw.githubusercontent.com/xapi-project/xen-api/cc7503ebe4778f5c990decbd411acd0a0445a73c/ocaml/networkd/bin/network_monitor_thread.ml | ocaml | * Table for bonds status.
This includes "tap" owing to the use of standardise_name below
It is a bond.
Seen before.
Remove all outstanding reads on a file descriptor
Do not send events for link-local IPv6 addresses, and removed IPs |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open Network_utils
open Xapi_stdext_pervasives
module D = Debug.Make (struct let name = "network_monitor_thread" end)
open D
let with_lock = Xapi_stdext_threads.Threadext.Mutex.execute
let bonds_status : (string, int * int) Hashtbl.t = Hashtbl.create 10
let monitor_whitelist =
ref
[
"eth"
; "vif"
]
let xapi_rpc xml =
let open Xmlrpc_client in
XMLRPC_protocol.rpc ~srcstr:"xcp-networkd" ~dststr:"xapi"
~transport:(Unix "/var/xapi/xapi")
~http:(xmlrpc ~version:"1.0" "/")
xml
let send_bond_change_alert _dev interfaces message =
let ifaces = String.concat "+" (List.sort String.compare interfaces) in
let module XenAPI = Client.Client in
let session_id =
XenAPI.Session.login_with_password ~rpc:xapi_rpc ~uname:"" ~pwd:""
~version:"1.4"
~originator:("xcp-networkd v" ^ Xapi_version.version)
in
Pervasiveext.finally
(fun _ ->
let obj_uuid = Inventory.lookup Inventory._installation_uuid in
let body = Printf.sprintf "The status of the %s bond %s" ifaces message in
try
let name, priority = Api_messages.bond_status_changed in
let (_ : API.ref_message) =
XenAPI.Message.create ~rpc:xapi_rpc ~session_id ~name ~priority
~cls:`Host ~obj_uuid ~body
in
()
with _ -> warn "Exception sending a bond-status-change alert."
)
(fun _ -> XenAPI.Session.logout ~rpc:xapi_rpc ~session_id)
let check_for_changes ~(dev : string) ~(stat : Network_monitor.iface_stats) =
let open Network_monitor in
match Astring.String.is_prefix ~affix:"vif" dev with
| true ->
()
| false ->
if stat.nb_links > 1 then
Hashtbl.mem bonds_status dev then (
let nb_links_old, links_up_old = Hashtbl.find bonds_status dev in
if links_up_old <> stat.links_up then (
info "Bonds status changed: %s nb_links %d up %d up_old %d" dev
stat.nb_links stat.links_up links_up_old ;
Hashtbl.replace bonds_status dev (stat.nb_links, stat.links_up) ;
let msg =
Printf.sprintf "changed: %d/%d up (was %d/%d)" stat.links_up
stat.nb_links links_up_old nb_links_old
in
try send_bond_change_alert dev stat.interfaces msg
with e ->
debug "Error while sending alert BONDS_STATUS_CHANGED: %s\n%s"
(Printexc.to_string e)
(Printexc.get_backtrace ())
)
) else (
Seen for the first time .
Hashtbl.add bonds_status dev (stat.nb_links, stat.links_up) ;
info "New bonds status: %s nb_links %d up %d" dev stat.nb_links
stat.links_up ;
if stat.links_up <> stat.nb_links then
let msg =
Printf.sprintf "is: %d/%d up" stat.links_up stat.nb_links
in
try send_bond_change_alert dev stat.interfaces msg
with e ->
debug "Error while sending alert BONDS_STATUS_CHANGED: %s\n%s"
(Printexc.to_string e)
(Printexc.get_backtrace ())
)
let failed_again = ref false
let standardise_name name =
try
let d1, d2 = Scanf.sscanf name "tap%d.%d" (fun d1 d2 -> (d1, d2)) in
let newname = Printf.sprintf "vif%d.%d" d1 d2 in
newname
with _ -> name
let get_link_stats () =
let open Network_monitor in
let open Netlink in
let s = Socket.alloc () in
Socket.connect s Socket.NETLINK_ROUTE ;
let cache = Link.cache_alloc s in
let links = Link.cache_to_list cache in
let links =
let is_whitelisted name =
List.exists
(fun s -> Astring.String.is_prefix ~affix:s name)
!monitor_whitelist
in
let is_vlan name =
Astring.String.is_prefix ~affix:"eth" name && String.contains name '.'
in
List.map (fun link -> (standardise_name (Link.get_name link), link)) links
Only keep interfaces with prefixes on the whitelist , and exclude VLAN
devices ( ethx.y ) .
devices (ethx.y). *)
List.filter (fun (name, _) -> is_whitelisted name && not (is_vlan name))
in
let devs =
List.map
(fun (name, link) ->
let convert x = Int64.of_int (Unsigned.UInt64.to_int x) in
let eth_stat =
{
default_stats with
rx_bytes= Link.get_stat link Link.RX_BYTES |> convert
; rx_pkts= Link.get_stat link Link.RX_PACKETS |> convert
; rx_errors= Link.get_stat link Link.RX_ERRORS |> convert
; tx_bytes= Link.get_stat link Link.TX_BYTES |> convert
; tx_pkts= Link.get_stat link Link.TX_PACKETS |> convert
; tx_errors= Link.get_stat link Link.TX_ERRORS |> convert
}
in
(name, eth_stat)
)
links
in
Cache.free cache ; Socket.close s ; Socket.free s ; devs
let rec monitor dbg () =
let open Network_interface in
let open Network_monitor in
( try
let make_bond_info devs (name, interfaces) =
let devs' =
List.filter (fun (name', _) -> List.mem name' interfaces) devs
in
let eth_stat =
{
default_stats with
rx_bytes=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.rx_bytes)
0L devs'
; rx_pkts=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.rx_pkts)
0L devs'
; rx_errors=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.rx_errors)
0L devs'
; tx_bytes=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.tx_bytes)
0L devs'
; tx_pkts=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.tx_pkts)
0L devs'
; tx_errors=
List.fold_left
(fun ac (_, stat) -> Int64.add ac stat.tx_errors)
0L devs'
}
in
(name, eth_stat)
in
let add_bonds bonds devs = List.map (make_bond_info devs) bonds @ devs in
let transform_taps devs =
let newdevnames =
Xapi_stdext_std.Listext.List.setify (List.map fst devs)
in
List.map
(fun name ->
let devs' = List.filter (fun (n, _) -> n = name) devs in
let tot =
List.fold_left
(fun acc (_, b) ->
{
default_stats with
rx_bytes= Int64.add acc.rx_bytes b.rx_bytes
; rx_pkts= Int64.add acc.rx_pkts b.rx_pkts
; rx_errors= Int64.add acc.rx_errors b.rx_errors
; tx_bytes= Int64.add acc.tx_bytes b.tx_bytes
; tx_pkts= Int64.add acc.tx_pkts b.tx_pkts
; tx_errors= Int64.add acc.tx_errors b.tx_errors
}
)
default_stats devs'
in
(name, tot)
)
newdevnames
in
let add_other_stats bonds devs =
List.map
(fun (dev, stat) ->
if not (Astring.String.is_prefix ~affix:"vif" dev) then (
let open Network_server.Bridge in
let bond_slaves =
if List.mem_assoc dev bonds then
get_bond_link_info () dbg ~name:dev
else
[]
in
let stat =
if bond_slaves = [] then
let carrier = Sysfs.get_carrier dev in
let speed, duplex =
if carrier then
Sysfs.get_status dev
else
(0, Duplex_unknown)
in
let pci_bus_path = Sysfs.get_pcibuspath dev in
let vendor_id, device_id = Sysfs.get_pci_ids dev in
let nb_links = 1 in
let links_up = if carrier then 1 else 0 in
let interfaces = [dev] in
{
stat with
carrier
; speed
; duplex
; pci_bus_path
; vendor_id
; device_id
; nb_links
; links_up
; interfaces
}
else
let carrier = List.exists (fun info -> info.up) bond_slaves in
let speed, duplex =
let combine_duplex = function
| Duplex_full, Duplex_full ->
Duplex_full
| Duplex_unknown, a | a, Duplex_unknown ->
a
| _ ->
Duplex_half
in
List.fold_left
(fun (speed, duplex) info ->
try
if info.active then
let speed', duplex' = Sysfs.get_status info.slave in
(speed + speed', combine_duplex (duplex, duplex'))
else
(speed, duplex)
with _ -> (speed, duplex)
)
(0, Duplex_unknown) bond_slaves
in
let pci_bus_path = "" in
let vendor_id, device_id = ("", "") in
let nb_links = List.length bond_slaves in
let links_up =
List.length (List.filter (fun info -> info.up) bond_slaves)
in
let interfaces =
List.map (fun info -> info.slave) bond_slaves
in
{
stat with
carrier
; speed
; duplex
; pci_bus_path
; vendor_id
; device_id
; nb_links
; links_up
; interfaces
}
in
check_for_changes ~dev ~stat ;
(dev, stat)
) else
(dev, stat)
)
devs
in
let from_cache = true in
let bonds : (string * string list) list =
Network_server.Bridge.get_all_bonds dbg from_cache
in
let devs =
get_link_stats ()
|> add_bonds bonds
|> transform_taps
|> add_other_stats bonds
in
( if List.length bonds <> Hashtbl.length bonds_status then
let dead_bonds =
Hashtbl.fold
(fun k _ acc -> if List.mem_assoc k bonds then acc else k :: acc)
bonds_status []
in
List.iter
(fun b ->
info "Removing bond %s" b ;
Hashtbl.remove bonds_status b
)
dead_bonds
) ;
write_stats devs ;
failed_again := false
with e ->
if not !failed_again then (
failed_again := true ;
debug
"Error while collecting stats (suppressing further errors): %s\n%s"
(Printexc.to_string e)
(Printexc.get_backtrace ())
)
) ;
Thread.delay interval ; monitor dbg ()
let watcher_m = Mutex.create ()
let watcher_pid = ref None
let signal_networking_change () =
let module XenAPI = Client.Client in
let session =
XenAPI.Session.slave_local_login_with_password ~rpc:xapi_rpc ~uname:""
~pwd:""
in
Pervasiveext.finally
(fun () ->
XenAPI.Host.signal_networking_change ~rpc:xapi_rpc ~session_id:session
)
(fun () -> XenAPI.Session.local_logout ~rpc:xapi_rpc ~session_id:session)
let clear_input fd =
let buf = Bytes.make 255 ' ' in
let rec loop () =
try
ignore (Unix.read fd buf 0 255) ;
loop ()
with _ -> ()
in
Unix.set_nonblock fd ; loop () ; Unix.clear_nonblock fd
let rec ip_watcher () =
let cmd = Network_utils.iproute2 in
let args = ["monitor"; "address"] in
let readme, writeme = Unix.pipe () in
with_lock watcher_m (fun () ->
watcher_pid :=
Some
(Forkhelpers.safe_close_and_exec ~env:(Unix.environment ()) None
(Some writeme) None [] cmd args
)
) ;
Unix.close writeme ;
let in_channel = Unix.in_channel_of_descr readme in
let rec loop () =
let line = input_line in_channel in
if
Astring.String.is_infix ~affix:"inet" line
&& not (Astring.String.is_infix ~affix:"inet6 fe80" line)
then (
Ignore changes for the next second , since they usually come in bursts ,
* and signal only once .
* and signal only once. *)
Thread.delay 1. ;
clear_input readme ;
signal_networking_change ()
) ;
loop ()
in
let restart_ip_watcher () =
Unix.close readme ; Thread.delay 5.0 ; ip_watcher ()
in
while true do
try
info "(Re)started IP watcher thread" ;
loop ()
with e -> (
warn "Error in IP watcher: %s\n%s" (Printexc.to_string e)
(Printexc.get_backtrace ()) ;
match !watcher_pid with
| None ->
restart_ip_watcher ()
| Some pid ->
let quitted, _ = Forkhelpers.waitpid_nohang pid in
if quitted <> 0 then (
warn "address monitoring process quitted, try to restart it" ;
restart_ip_watcher ()
)
)
done
let start () =
let dbg = "monitor_thread" in
Debug.with_thread_associated dbg
(fun () ->
debug "Starting network monitor" ;
let (_ : Thread.t) = Thread.create (monitor dbg) () in
let (_ : Thread.t) = Thread.create ip_watcher () in
()
)
()
let stop () =
with_lock watcher_m (fun () ->
match !watcher_pid with
| None ->
()
| Some pid ->
Unix.kill (Forkhelpers.getpid pid) Sys.sigterm
)
|
1872a0b815a94c9f3c35f1bce298bd607463b5f559aa0cd74b8e03646cd6e78f | shayan-najd/NativeMetaprogramming | T7861.hs | {-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# OPTIONS_GHC -fdefer-type-errors #-}
module Main where
doA :: (forall b. a) -> [a]
doA = undefined
f :: (forall b. a) -> a
f = doA
main = do { print "Hello 1"
; f `seq` print "Hello 2"
-- The casts are pushed inside the lambda
-- for f, so this seq succeeds fine
It does require ImpredicativeTypes , because we instantiate
-- seq's type (c->d->d) with f's type (c:= (forall b. a) -> a),
-- which is polymorphic (it has foralls).
; f (error "urk") `seq` print "Bad"
-- But when we *call* f we get a type error
}
| null | https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/typecheck/should_run/T7861.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE ImpredicativeTypes #
# OPTIONS_GHC -fdefer-type-errors #
The casts are pushed inside the lambda
for f, so this seq succeeds fine
seq's type (c->d->d) with f's type (c:= (forall b. a) -> a),
which is polymorphic (it has foralls).
But when we *call* f we get a type error | module Main where
doA :: (forall b. a) -> [a]
doA = undefined
f :: (forall b. a) -> a
f = doA
main = do { print "Hello 1"
; f `seq` print "Hello 2"
It does require ImpredicativeTypes , because we instantiate
; f (error "urk") `seq` print "Bad"
}
|
cb31c984a81ca01ad0a0eb0a4a6a72f3dda8b1cc6482adf60a8e45e6d3a0972d | b0-system/brzo | brzo_cmd_log.ml | ---------------------------------------------------------------------------
Copyright ( c ) 2018 The programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2018 The brzo programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
open B0_std
open Result.Syntax
let log c format details op_selector =
Log.if_error ~use:Brzo.Exit.some_error @@
let don't = Brzo.Conf.no_pager c || format = `Trace_event in
let log_file = Brzo.Conf.log_file c in
let* pager = B00_pager.find ~don't () in
let* () = B00_pager.page_stdout pager in
let* l = B00_cli.Memo.Log.read log_file in
B00_cli.Memo.Log.out Fmt.stdout format details op_selector ~path:log_file l;
Ok Brzo.Exit.ok
(* Command line interface *)
open Cmdliner
let cmd =
let doc = "Show build log" in
let exits = Brzo.Exit.Info.base_cmd in
let envs = B00_pager.envs () in
let man = [
`S Manpage.s_description;
`P "The $(tname) command shows build information and operations in \
various formats.";
`S B00_cli.s_output_format_options;
`S B00_cli.Op.s_selection_options;
`Blocks B00_cli.Op.query_man;
Brzo.Cli.man_see_manual; ]
in
Cmd.v (Cmd.info "log" ~doc ~exits ~envs ~man)
Term.(const log $ Brzo_tie_conf.auto_cwd_root_and_no_brzo_file $
B00_cli.Memo.Log.out_format_cli () $ B00_cli.Arg.output_format () $
B00_cli.Op.query_cli ())
---------------------------------------------------------------------------
Copyright ( c ) 2018 The programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2018 The brzo programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/b0-system/brzo/e481a39d7881d7aaf800cf3c7a9b6cd836867a90/src/brzo_cmd_log.ml | ocaml | Command line interface | ---------------------------------------------------------------------------
Copyright ( c ) 2018 The programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2018 The brzo programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
open B0_std
open Result.Syntax
let log c format details op_selector =
Log.if_error ~use:Brzo.Exit.some_error @@
let don't = Brzo.Conf.no_pager c || format = `Trace_event in
let log_file = Brzo.Conf.log_file c in
let* pager = B00_pager.find ~don't () in
let* () = B00_pager.page_stdout pager in
let* l = B00_cli.Memo.Log.read log_file in
B00_cli.Memo.Log.out Fmt.stdout format details op_selector ~path:log_file l;
Ok Brzo.Exit.ok
open Cmdliner
let cmd =
let doc = "Show build log" in
let exits = Brzo.Exit.Info.base_cmd in
let envs = B00_pager.envs () in
let man = [
`S Manpage.s_description;
`P "The $(tname) command shows build information and operations in \
various formats.";
`S B00_cli.s_output_format_options;
`S B00_cli.Op.s_selection_options;
`Blocks B00_cli.Op.query_man;
Brzo.Cli.man_see_manual; ]
in
Cmd.v (Cmd.info "log" ~doc ~exits ~envs ~man)
Term.(const log $ Brzo_tie_conf.auto_cwd_root_and_no_brzo_file $
B00_cli.Memo.Log.out_format_cli () $ B00_cli.Arg.output_format () $
B00_cli.Op.query_cli ())
---------------------------------------------------------------------------
Copyright ( c ) 2018 The programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2018 The brzo programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
|
40ae6154b7f4ba44f2e983a33af06705fe87554f0639c220b74f4503b7921aae | Chatanga/codingame-hs | SourcePackager.hs | # LANGUAGE OverloadedStrings , LambdaCase #
{-|
A small module to create monolithic sources from multiples files.
-}
module Codingame.SourcePackager
( createMonolithicSource
, createMonolithicSourceWithMode
) where
import Control.Arrow ( Arrow((&&&)) )
import Control.Monad ( foldM )
import Control.Monad.Trans.Except ( runExcept )
import Control.Exception ( tryJust )
import Data.ByteString.Char8 ( pack, unpack )
import Data.Function ( (&) )
import Data.List ( nub, nubBy )
import Hpp
( addDefinition,
emptyHppState,
expand,
preprocess,
HppOutput(HppOutput),
HppState )
import qualified Hpp.Config as C
import qualified Hpp.Types as T
import qualified Data.Map.Lazy as Map
import Data.Ord ( comparing )
import qualified Data.Text as Text
import Language.Haskell.Exts
( defaultParseMode,
getTopPragmas,
parseModuleWithMode,
prettyPrint,
Extension(EnableExtension),
KnownExtension(..),
ParseMode(extensions),
ParseResult(ParseFailed, ParseOk),
SrcLoc(srcFilename, srcLine),
SrcSpanInfo,
Decl(PatBind, TypeSig, FunBind),
ImportDecl(importModule),
Match(InfixMatch, Match),
Module(Module),
ModuleHead(ModuleHead),
ModuleName(..),
ModulePragma(LanguagePragma),
Name(Ident),
Pat(PVar) )
import System.FilePath ( (<.>), (</>), takeDirectory )
import System.IO.Error ( isDoesNotExistError )
----------------------------------------------------------------------------------------------------
type ModuleSourceMap = Map.Map FilePath ([ModulePragma SrcSpanInfo], Module SrcSpanInfo)
| Create a monolithic source by concatenating a source file and all its local
dependencies .
The result is not just a string concatenation and source files are actually parsed and processed
such as the returned source forms a valid Haskell content . Only the local content is incorporated in
the resulting source , whereas the external modules are simply kept as imported modules ( eg . the
source code of \"System . IO\ " wo n’t be included ) . An internal module is a module whose source file
can be found in the same hierachical directory as the initial file provided . Per instance , when
creating a monolithic source from \"src\/Machin.hs\ " , the source of an imported module named
\"Truc . Bidule\ " will be searched in \"src\/Truc\ " . These transformations remains rather simple and
wo n't be able to solve any name clash between functions , nor handle incompatible qualified and/or
hidden import directives .
Since this source concatenation remains pretty basic , processing directives are now supported to
help keeping the generated source compatible with Codingame , mainly by prunning any unwanted
dependencies ( the CG_ARENA identifier is automatically defined ) . This way , it becomes possible to
better integrate a bot with a development environment .
Lastly , any function named \"runMain\ " will be renamed " . It allows you to generate a new
valid program by only selecting a subset of your code base which uses another main function .
dependencies.
The result is not just a string concatenation and source files are actually parsed and processed
such as the returned source forms a valid Haskell content. Only the local content is incorporated in
the resulting source, whereas the external modules are simply kept as imported modules (eg. the
source code of \"System.IO\" won’t be included). An internal module is a module whose source file
can be found in the same hierachical directory as the initial file provided. Per instance, when
creating a monolithic source from \"src\/Machin.hs\", the source of an imported module named
\"Truc.Bidule\" will be searched in \"src\/Truc\". These transformations remains rather simple and
won't be able to solve any name clash between functions, nor handle incompatible qualified and/or
hidden import directives.
Since this source concatenation remains pretty basic, processing directives are now supported to
help keeping the generated source compatible with Codingame, mainly by prunning any unwanted
dependencies (the CG_ARENA identifier is automatically defined). This way, it becomes possible to
better integrate a bot with a development environment.
Lastly, any function named \"runMain\" will be renamed \"main\". It allows you to generate a new
valid program by only selecting a subset of your code base which uses another main function.
-}
createMonolithicSource :: FilePath -> IO String
createMonolithicSource = createMonolithicSourceWithMode defaultParseMode
| Create a monolithic source by concatenating a source file and all its local
dependencies .
This function works the same way as createMonolithicSource but offer a way to customize the parse
mode in order to deal with some parsing limitations . Indeed files are only parsed separately , not
compiled as a whole and some things are beyond the parser capability , such as operator fixities .
If you are defining you own operators in a file and use then into another , you need to declare them
by overriding the parse mode :
@
let importedFixities = infixl _ 8 [ \"|>\ " ]
fixities ' = importedFixities + + fromMaybe [ ] ( )
parseMode = defaultParseMode { fixities = Just fixities ' }
source < - createMonolithicSourceWithMode parseMode \"src / Golgoth.hs\ "
@
dependencies.
This function works the same way as createMonolithicSource but offer a way to customize the parse
mode in order to deal with some parsing limitations. Indeed files are only parsed separately, not
compiled as a whole and some things are beyond the parser capability, such as operator fixities.
If you are defining you own operators in a file and use then into another, you need to declare them
by overriding the parse mode:
@
let importedFixities = infixl_ 8 [\"|>\"]
fixities' = importedFixities ++ fromMaybe [] (fixities defaultParseMode)
parseMode = defaultParseMode{ fixities = Just fixities' }
source <- createMonolithicSourceWithMode parseMode \"src/Golgoth.hs\"
@
-}
createMonolithicSourceWithMode :: ParseMode -> FilePath -> IO String
createMonolithicSourceWithMode parseMode sourceFile = do
moduleSourceMap <- processModule parseMode Map.empty sourceFile
let contributions = fmap (getContribution moduleSourceMap) (Map.assocs moduleSourceMap)
srcLoc = error "no srcLoc"
pragmas = mergePragmas (fmap fst contributions)
importDecls = mergeImportDecls (fmap (fst . snd) contributions)
decls = fmap patchRunMain (concatMap (snd . snd) contributions)
moduleHead = Nothing
mergedCode = Module srcLoc moduleHead pragmas importDecls decls
return (prettyPrint mergedCode)
getContribution :: ModuleSourceMap
-> (FilePath, ([ModulePragma SrcSpanInfo], Module SrcSpanInfo))
-> ([ModulePragma SrcSpanInfo], ([ImportDecl SrcSpanInfo], [Decl SrcSpanInfo]))
getContribution moduleSourceMap (sourceFile, moduleSource) =
(fst moduleSource, (getExternalImportDecls importDecls, decls))
where
(Module _ (Just (ModuleHead _ moduleName _ _)) _ importDecls decls) =
snd moduleSource
srcDir = getSrcDir sourceFile (getModuleName moduleName)
getExternalImportDecls importDecls = importDecls
& fmap (id &&& (locateImport srcDir . getModuleName . importModule))
& filter (not . flip Map.member moduleSourceMap . snd)
& fmap fst
processModule :: ParseMode -> ModuleSourceMap -> FilePath -> IO ModuleSourceMap
processModule parseMode moduleSourceMap sourceFile =
if Map.member sourceFile moduleSourceMap
then return moduleSourceMap
else readAndPreProcessFile sourceFile >>= parseModuleSource parseMode moduleSourceMap sourceFile
processInternalModule :: ParseMode -> ModuleSourceMap -> FilePath -> IO ModuleSourceMap
processInternalModule parseMode moduleSourceMap sourceFile = do
let selectDoesNotExistError e = if isDoesNotExistError e then Just e else Nothing
result <- tryJust selectDoesNotExistError (processModule parseMode moduleSourceMap sourceFile)
case result of
Left _ -> return moduleSourceMap
Right moduleSourceMap' -> return moduleSourceMap'
parseModuleSource :: ParseMode -> ModuleSourceMap -> FilePath -> String -> IO ModuleSourceMap
parseModuleSource parseMode moduleSourceMap sourceFile source = do
let pragmas = case getTopPragmas source of
ParseOk pragmas
-> pragmas
ParseFailed srcLoc message
-> error (message ++ "\nAt: " ++ show srcLoc{ srcFilename = sourceFile } ++ "\n" ++ dumpSource (srcLine srcLoc))
enabledLanguageExtensions = flip concatMap pragmas $ \case
LanguagePragma _ names -> map toExtension names
_ -> []
moduleSource = case parseModuleWithMode parseMode{ extensions = enabledLanguageExtensions } source of
ParseOk moduleSource
-> moduleSource
ParseFailed srcLoc message
-> error (message ++ "\nAt: " ++ show srcLoc{ srcFilename = sourceFile } ++ "\n" ++ dumpSource (srcLine srcLoc))
TOREDO To work around the fact that SrcLoc becomes useless once HPP has been run on the source .
dumpSource lineNumber =
let radius = 5
start = max 1 (lineNumber - radius)
in concat $ zipWith (\n line -> show n ++ "\t" ++ line ++ "\n") [start..] (take (radius * 2 + 1) . drop (start - 1) $ lines source)
dependencies = getDependencies sourceFile moduleSource
-- Reserve a slot for the module with an undefined value to avoid recursion.
moduleSourceMap' = Map.insert sourceFile undefined moduleSourceMap
moduleSourceMap'' <-
foldM (processInternalModule parseMode) moduleSourceMap' (fmap snd dependencies)
return $ Map.insert sourceFile (pragmas, moduleSource) moduleSourceMap''
-- TOREDO I really don’t like this.
toExtension :: Name SrcSpanInfo -> Extension
toExtension (Ident _ "OverlappingInstances") = EnableExtension OverlappingInstances
toExtension (Ident _ "UndecidableInstances") = EnableExtension UndecidableInstances
toExtension (Ident _ "IncoherentInstances") = EnableExtension IncoherentInstances
toExtension (Ident _ "InstanceSigs") = EnableExtension InstanceSigs
toExtension (Ident _ "DoRec") = EnableExtension DoRec
toExtension (Ident _ "RecursiveDo") = EnableExtension RecursiveDo
toExtension (Ident _ "ParallelListComp") = EnableExtension ParallelListComp
toExtension (Ident _ "MultiParamTypeClasses") = EnableExtension MultiParamTypeClasses
toExtension (Ident _ "MonomorphismRestriction") = EnableExtension MonomorphismRestriction
toExtension (Ident _ "FunctionalDependencies") = EnableExtension FunctionalDependencies
toExtension (Ident _ "Rank2Types") = EnableExtension Rank2Types
toExtension (Ident _ "RankNTypes") = EnableExtension RankNTypes
toExtension (Ident _ "PolymorphicComponents") = EnableExtension PolymorphicComponents
toExtension (Ident _ "ExistentialQuantification") = EnableExtension ExistentialQuantification
toExtension (Ident _ "ScopedTypeVariables") = EnableExtension ScopedTypeVariables
toExtension (Ident _ "PatternSignatures") = EnableExtension PatternSignatures
toExtension (Ident _ "ImplicitParams") = EnableExtension ImplicitParams
toExtension (Ident _ "FlexibleContexts") = EnableExtension FlexibleContexts
toExtension (Ident _ "FlexibleInstances") = EnableExtension FlexibleInstances
toExtension (Ident _ "EmptyDataDecls") = EnableExtension EmptyDataDecls
toExtension (Ident _ "CPP") = EnableExtension CPP
toExtension (Ident _ "KindSignatures") = EnableExtension KindSignatures
toExtension (Ident _ "BangPatterns") = EnableExtension BangPatterns
toExtension (Ident _ "TypeSynonymInstances") = EnableExtension TypeSynonymInstances
toExtension (Ident _ "TemplateHaskell") = EnableExtension TemplateHaskell
toExtension (Ident _ "ForeignFunctionInterface") = EnableExtension ForeignFunctionInterface
toExtension (Ident _ "Arrows") = EnableExtension Arrows
toExtension (Ident _ "Generics") = EnableExtension Generics
toExtension (Ident _ "ImplicitPrelude") = EnableExtension ImplicitPrelude
toExtension (Ident _ "NamedFieldPuns") = EnableExtension NamedFieldPuns
toExtension (Ident _ "PatternGuards") = EnableExtension PatternGuards
toExtension (Ident _ "GeneralizedNewtypeDeriving") = EnableExtension GeneralizedNewtypeDeriving
toExtension (Ident _ "DeriveAnyClass") = EnableExtension DeriveAnyClass
toExtension (Ident _ "ExtensibleRecords") = EnableExtension ExtensibleRecords
toExtension (Ident _ "RestrictedTypeSynonyms") = EnableExtension RestrictedTypeSynonyms
toExtension (Ident _ "HereDocuments") = EnableExtension HereDocuments
toExtension (Ident _ "MagicHash") = EnableExtension MagicHash
toExtension (Ident _ "BinaryLiterals") = EnableExtension BinaryLiterals
toExtension (Ident _ "TypeFamilies") = EnableExtension TypeFamilies
toExtension (Ident _ "StandaloneDeriving") = EnableExtension StandaloneDeriving
toExtension (Ident _ "UnicodeSyntax") = EnableExtension UnicodeSyntax
toExtension (Ident _ "UnliftedFFITypes") = EnableExtension UnliftedFFITypes
toExtension (Ident _ "LiberalTypeSynonyms") = EnableExtension LiberalTypeSynonyms
toExtension (Ident _ "TypeOperators") = EnableExtension TypeOperators
toExtension (Ident _ "ParallelArrays") = EnableExtension ParallelArrays
toExtension (Ident _ "RecordWildCards") = EnableExtension RecordWildCards
toExtension (Ident _ "RecordPuns") = EnableExtension RecordPuns
toExtension (Ident _ "DisambiguateRecordFields") = EnableExtension DisambiguateRecordFields
toExtension (Ident _ "OverloadedStrings") = EnableExtension OverloadedStrings
toExtension (Ident _ "GADTs") = EnableExtension GADTs
toExtension (Ident _ "MonoPatBinds") = EnableExtension MonoPatBinds
toExtension (Ident _ "RelaxedPolyRec") = EnableExtension RelaxedPolyRec
toExtension (Ident _ "ExtendedDefaultRules") = EnableExtension ExtendedDefaultRules
toExtension (Ident _ "UnboxedTuples") = EnableExtension UnboxedTuples
toExtension (Ident _ "DeriveDataTypeable") = EnableExtension DeriveDataTypeable
toExtension (Ident _ "ConstrainedClassMethods") = EnableExtension ConstrainedClassMethods
toExtension (Ident _ "PackageImports") = EnableExtension PackageImports
toExtension (Ident _ "LambdaCase") = EnableExtension LambdaCase
toExtension (Ident _ "EmptyCase") = EnableExtension EmptyCase
toExtension (Ident _ "ImpredicativeTypes") = EnableExtension ImpredicativeTypes
toExtension (Ident _ "NewQualifiedOperators") = EnableExtension NewQualifiedOperators
toExtension (Ident _ "PostfixOperators") = EnableExtension PostfixOperators
toExtension (Ident _ "QuasiQuotes") = EnableExtension QuasiQuotes
toExtension (Ident _ "TransformListComp") = EnableExtension TransformListComp
toExtension (Ident _ "ViewPatterns") = EnableExtension ViewPatterns
toExtension (Ident _ "XmlSyntax") = EnableExtension XmlSyntax
toExtension (Ident _ "RegularPatterns") = EnableExtension RegularPatterns
toExtension (Ident _ "TupleSections") = EnableExtension TupleSections
toExtension (Ident _ "GHCForeignImportPrim") = EnableExtension GHCForeignImportPrim
toExtension (Ident _ "NPlusKPatterns") = EnableExtension NPlusKPatterns
toExtension (Ident _ "DoAndIfThenElse") = EnableExtension DoAndIfThenElse
toExtension (Ident _ "RebindableSyntax") = EnableExtension RebindableSyntax
toExtension (Ident _ "ExplicitForAll") = EnableExtension ExplicitForAll
toExtension (Ident _ "DatatypeContexts") = EnableExtension DatatypeContexts
toExtension (Ident _ "MonoLocalBinds") = EnableExtension MonoLocalBinds
toExtension (Ident _ "DeriveFunctor") = EnableExtension DeriveFunctor
toExtension (Ident _ "DeriveGeneric") = EnableExtension DeriveGeneric
toExtension (Ident _ "DeriveTraversable") = EnableExtension DeriveTraversable
toExtension (Ident _ "DeriveFoldable") = EnableExtension DeriveFoldable
toExtension (Ident _ "NondecreasingIndentation") = EnableExtension NondecreasingIndentation
toExtension (Ident _ "InterruptibleFFI") = EnableExtension InterruptibleFFI
toExtension (Ident _ "CApiFFI") = EnableExtension CApiFFI
toExtension (Ident _ "JavaScriptFFI") = EnableExtension JavaScriptFFI
toExtension (Ident _ "ExplicitNamespaces") = EnableExtension ExplicitNamespaces
toExtension (Ident _ "DataKinds") = EnableExtension DataKinds
toExtension (Ident _ "PolyKinds") = EnableExtension PolyKinds
toExtension (Ident _ "MultiWayIf") = EnableExtension MultiWayIf
toExtension (Ident _ "SafeImports") = EnableExtension SafeImports
toExtension (Ident _ "Safe") = EnableExtension Safe
toExtension (Ident _ "Trustworthy") = EnableExtension Trustworthy
toExtension (Ident _ "DefaultSignatures") = EnableExtension DefaultSignatures
toExtension (Ident _ "ConstraintKinds") = EnableExtension ConstraintKinds
toExtension (Ident _ "RoleAnnotations") = EnableExtension RoleAnnotations
toExtension (Ident _ "PatternSynonyms") = EnableExtension PatternSynonyms
toExtension (Ident _ "PartialTypeSignatures") = EnableExtension PartialTypeSignatures
toExtension (Ident _ "NamedWildCards") = EnableExtension NamedWildCards
toExtension (Ident _ "TypeApplications") = EnableExtension TypeApplications
toExtension (Ident _ "TypeFamilyDependencies") = EnableExtension TypeFamilyDependencies
toExtension (Ident _ "OverloadedLabels") = EnableExtension OverloadedLabels
toExtension (Ident _ "DerivingStrategies") = EnableExtension DerivingStrategies
toExtension (Ident _ "UnboxedSums") = EnableExtension UnboxedSums
toExtension (Ident _ "TypeInType") = EnableExtension TypeInType
toExtension (Ident _ "Strict") = EnableExtension Strict
toExtension (Ident _ "StrictData") = EnableExtension StrictData
toExtension (Ident _ "DerivingVia") = EnableExtension DerivingVia
toExtension (Ident _ "QuantifiedConstraints") = EnableExtension QuantifiedConstraints
toExtension (Ident _ "BlockArguments") = EnableExtension BlockArguments
toExtension name = error $ "Unknown extension: " ++ show name
getDependencies :: FilePath -> Module SrcSpanInfo -> [(ImportDecl SrcSpanInfo, FilePath)]
getDependencies sourceFile moduleSource = fmap (id &&& getLocation) importDecls
where
(Module _ (Just (ModuleHead _ (ModuleName _ moduleName) _ _)) exportSpec importDecls decls) =
moduleSource
srcDir = getSrcDir sourceFile moduleName
getLocation = locateImport srcDir . getModuleName . importModule
getSrcDir :: FilePath -> String -> FilePath
getSrcDir sourceFile moduleName = srcDir where
parents = moduleName
& fmap Text.unpack . Text.splitOn (Text.pack ".") . Text.pack
srcDir = iterate takeDirectory sourceFile !! length parents
locateImport :: FilePath -> String -> FilePath
locateImport srcDir importedModuleName = importedSourceFile where
(parents, child) = importedModuleName
& fmap Text.unpack . Text.splitOn (Text.pack ".") . Text.pack
& (init &&& last)
importedSourceFile = foldl (</>) srcDir parents </> child <.> ".hs"
mergePragmas :: [[ModulePragma SrcSpanInfo]] -> [ModulePragma SrcSpanInfo]
TODO Works , but not elaborated enough .
mergeImportDecls :: [[ImportDecl SrcSpanInfo]] -> [ImportDecl SrcSpanInfo]
mergeImportDecls decls =
TODO module modifiers ( hiding , qualified ) are not merged !
nubBy (\d1 d2 -> (EQ == ) $ comparing (getModuleName . importModule) d1 d2) (concat decls)
getModuleName :: ModuleName SrcSpanInfo -> String
getModuleName (ModuleName _ moduleName) = moduleName
patchRunMain :: Decl SrcSpanInfo -> Decl SrcSpanInfo
patchRunMain decl = case decl of
(TypeSig srcLoc names t) -> TypeSig srcLoc (fmap patchName names) t
(FunBind srcLoc matchs) -> FunBind srcLoc (fmap patchMatch matchs)
(PatBind srcLoc pat rhs binds) -> PatBind srcLoc (patchPat pat) rhs binds
_ -> decl
where
patchName (Ident srcLoc "runMain") = Ident srcLoc "main"
patchName name = name
patchMatch (Match srcLoc name pats rhs binds) =
Match srcLoc (patchName name) pats rhs binds
patchMatch (InfixMatch srcLoc pat name pats rhs binds) =
InfixMatch srcLoc pat (patchName name) pats rhs binds
patchPat (PVar srcLoc name) = PVar srcLoc (patchName name)
patchPat pat = pat
hppConfig :: HppState -> HppState
hppConfig = T.over T.config opts
where opts = T.setL C.inhibitLinemarkersL True
readAndPreProcessFile :: FilePath -> IO String
readAndPreProcessFile filePath =
case addDefinition "CG_ARENA" "1" (hppConfig emptyHppState) of
Just state -> readFile filePath >>= hpp (hppConfig state)
Nothing -> error "Preprocessor definition did not parse"
hpp :: HppState -> String -> IO String
hpp st src =
case runExcept (expand st (preprocess (map pack (lines src)))) of
Left e -> error ("Error running hpp: " ++ show e)
Right (HppOutput _ ls, _) -> return (unlines (map unpack ls))
| null | https://raw.githubusercontent.com/Chatanga/codingame-hs/2199b3f5fcb11ab2b89d1d106aa5382bd7915da9/src/Codingame/SourcePackager.hs | haskell | |
A small module to create monolithic sources from multiples files.
--------------------------------------------------------------------------------------------------
Reserve a slot for the module with an undefined value to avoid recursion.
TOREDO I really don’t like this. | # LANGUAGE OverloadedStrings , LambdaCase #
module Codingame.SourcePackager
( createMonolithicSource
, createMonolithicSourceWithMode
) where
import Control.Arrow ( Arrow((&&&)) )
import Control.Monad ( foldM )
import Control.Monad.Trans.Except ( runExcept )
import Control.Exception ( tryJust )
import Data.ByteString.Char8 ( pack, unpack )
import Data.Function ( (&) )
import Data.List ( nub, nubBy )
import Hpp
( addDefinition,
emptyHppState,
expand,
preprocess,
HppOutput(HppOutput),
HppState )
import qualified Hpp.Config as C
import qualified Hpp.Types as T
import qualified Data.Map.Lazy as Map
import Data.Ord ( comparing )
import qualified Data.Text as Text
import Language.Haskell.Exts
( defaultParseMode,
getTopPragmas,
parseModuleWithMode,
prettyPrint,
Extension(EnableExtension),
KnownExtension(..),
ParseMode(extensions),
ParseResult(ParseFailed, ParseOk),
SrcLoc(srcFilename, srcLine),
SrcSpanInfo,
Decl(PatBind, TypeSig, FunBind),
ImportDecl(importModule),
Match(InfixMatch, Match),
Module(Module),
ModuleHead(ModuleHead),
ModuleName(..),
ModulePragma(LanguagePragma),
Name(Ident),
Pat(PVar) )
import System.FilePath ( (<.>), (</>), takeDirectory )
import System.IO.Error ( isDoesNotExistError )
type ModuleSourceMap = Map.Map FilePath ([ModulePragma SrcSpanInfo], Module SrcSpanInfo)
| Create a monolithic source by concatenating a source file and all its local
dependencies .
The result is not just a string concatenation and source files are actually parsed and processed
such as the returned source forms a valid Haskell content . Only the local content is incorporated in
the resulting source , whereas the external modules are simply kept as imported modules ( eg . the
source code of \"System . IO\ " wo n’t be included ) . An internal module is a module whose source file
can be found in the same hierachical directory as the initial file provided . Per instance , when
creating a monolithic source from \"src\/Machin.hs\ " , the source of an imported module named
\"Truc . Bidule\ " will be searched in \"src\/Truc\ " . These transformations remains rather simple and
wo n't be able to solve any name clash between functions , nor handle incompatible qualified and/or
hidden import directives .
Since this source concatenation remains pretty basic , processing directives are now supported to
help keeping the generated source compatible with Codingame , mainly by prunning any unwanted
dependencies ( the CG_ARENA identifier is automatically defined ) . This way , it becomes possible to
better integrate a bot with a development environment .
Lastly , any function named \"runMain\ " will be renamed " . It allows you to generate a new
valid program by only selecting a subset of your code base which uses another main function .
dependencies.
The result is not just a string concatenation and source files are actually parsed and processed
such as the returned source forms a valid Haskell content. Only the local content is incorporated in
the resulting source, whereas the external modules are simply kept as imported modules (eg. the
source code of \"System.IO\" won’t be included). An internal module is a module whose source file
can be found in the same hierachical directory as the initial file provided. Per instance, when
creating a monolithic source from \"src\/Machin.hs\", the source of an imported module named
\"Truc.Bidule\" will be searched in \"src\/Truc\". These transformations remains rather simple and
won't be able to solve any name clash between functions, nor handle incompatible qualified and/or
hidden import directives.
Since this source concatenation remains pretty basic, processing directives are now supported to
help keeping the generated source compatible with Codingame, mainly by prunning any unwanted
dependencies (the CG_ARENA identifier is automatically defined). This way, it becomes possible to
better integrate a bot with a development environment.
Lastly, any function named \"runMain\" will be renamed \"main\". It allows you to generate a new
valid program by only selecting a subset of your code base which uses another main function.
-}
createMonolithicSource :: FilePath -> IO String
createMonolithicSource = createMonolithicSourceWithMode defaultParseMode
| Create a monolithic source by concatenating a source file and all its local
dependencies .
This function works the same way as createMonolithicSource but offer a way to customize the parse
mode in order to deal with some parsing limitations . Indeed files are only parsed separately , not
compiled as a whole and some things are beyond the parser capability , such as operator fixities .
If you are defining you own operators in a file and use then into another , you need to declare them
by overriding the parse mode :
@
let importedFixities = infixl _ 8 [ \"|>\ " ]
fixities ' = importedFixities + + fromMaybe [ ] ( )
parseMode = defaultParseMode { fixities = Just fixities ' }
source < - createMonolithicSourceWithMode parseMode \"src / Golgoth.hs\ "
@
dependencies.
This function works the same way as createMonolithicSource but offer a way to customize the parse
mode in order to deal with some parsing limitations. Indeed files are only parsed separately, not
compiled as a whole and some things are beyond the parser capability, such as operator fixities.
If you are defining you own operators in a file and use then into another, you need to declare them
by overriding the parse mode:
@
let importedFixities = infixl_ 8 [\"|>\"]
fixities' = importedFixities ++ fromMaybe [] (fixities defaultParseMode)
parseMode = defaultParseMode{ fixities = Just fixities' }
source <- createMonolithicSourceWithMode parseMode \"src/Golgoth.hs\"
@
-}
createMonolithicSourceWithMode :: ParseMode -> FilePath -> IO String
createMonolithicSourceWithMode parseMode sourceFile = do
moduleSourceMap <- processModule parseMode Map.empty sourceFile
let contributions = fmap (getContribution moduleSourceMap) (Map.assocs moduleSourceMap)
srcLoc = error "no srcLoc"
pragmas = mergePragmas (fmap fst contributions)
importDecls = mergeImportDecls (fmap (fst . snd) contributions)
decls = fmap patchRunMain (concatMap (snd . snd) contributions)
moduleHead = Nothing
mergedCode = Module srcLoc moduleHead pragmas importDecls decls
return (prettyPrint mergedCode)
getContribution :: ModuleSourceMap
-> (FilePath, ([ModulePragma SrcSpanInfo], Module SrcSpanInfo))
-> ([ModulePragma SrcSpanInfo], ([ImportDecl SrcSpanInfo], [Decl SrcSpanInfo]))
getContribution moduleSourceMap (sourceFile, moduleSource) =
(fst moduleSource, (getExternalImportDecls importDecls, decls))
where
(Module _ (Just (ModuleHead _ moduleName _ _)) _ importDecls decls) =
snd moduleSource
srcDir = getSrcDir sourceFile (getModuleName moduleName)
getExternalImportDecls importDecls = importDecls
& fmap (id &&& (locateImport srcDir . getModuleName . importModule))
& filter (not . flip Map.member moduleSourceMap . snd)
& fmap fst
processModule :: ParseMode -> ModuleSourceMap -> FilePath -> IO ModuleSourceMap
processModule parseMode moduleSourceMap sourceFile =
if Map.member sourceFile moduleSourceMap
then return moduleSourceMap
else readAndPreProcessFile sourceFile >>= parseModuleSource parseMode moduleSourceMap sourceFile
processInternalModule :: ParseMode -> ModuleSourceMap -> FilePath -> IO ModuleSourceMap
processInternalModule parseMode moduleSourceMap sourceFile = do
let selectDoesNotExistError e = if isDoesNotExistError e then Just e else Nothing
result <- tryJust selectDoesNotExistError (processModule parseMode moduleSourceMap sourceFile)
case result of
Left _ -> return moduleSourceMap
Right moduleSourceMap' -> return moduleSourceMap'
parseModuleSource :: ParseMode -> ModuleSourceMap -> FilePath -> String -> IO ModuleSourceMap
parseModuleSource parseMode moduleSourceMap sourceFile source = do
let pragmas = case getTopPragmas source of
ParseOk pragmas
-> pragmas
ParseFailed srcLoc message
-> error (message ++ "\nAt: " ++ show srcLoc{ srcFilename = sourceFile } ++ "\n" ++ dumpSource (srcLine srcLoc))
enabledLanguageExtensions = flip concatMap pragmas $ \case
LanguagePragma _ names -> map toExtension names
_ -> []
moduleSource = case parseModuleWithMode parseMode{ extensions = enabledLanguageExtensions } source of
ParseOk moduleSource
-> moduleSource
ParseFailed srcLoc message
-> error (message ++ "\nAt: " ++ show srcLoc{ srcFilename = sourceFile } ++ "\n" ++ dumpSource (srcLine srcLoc))
TOREDO To work around the fact that SrcLoc becomes useless once HPP has been run on the source .
dumpSource lineNumber =
let radius = 5
start = max 1 (lineNumber - radius)
in concat $ zipWith (\n line -> show n ++ "\t" ++ line ++ "\n") [start..] (take (radius * 2 + 1) . drop (start - 1) $ lines source)
dependencies = getDependencies sourceFile moduleSource
moduleSourceMap' = Map.insert sourceFile undefined moduleSourceMap
moduleSourceMap'' <-
foldM (processInternalModule parseMode) moduleSourceMap' (fmap snd dependencies)
return $ Map.insert sourceFile (pragmas, moduleSource) moduleSourceMap''
toExtension :: Name SrcSpanInfo -> Extension
toExtension (Ident _ "OverlappingInstances") = EnableExtension OverlappingInstances
toExtension (Ident _ "UndecidableInstances") = EnableExtension UndecidableInstances
toExtension (Ident _ "IncoherentInstances") = EnableExtension IncoherentInstances
toExtension (Ident _ "InstanceSigs") = EnableExtension InstanceSigs
toExtension (Ident _ "DoRec") = EnableExtension DoRec
toExtension (Ident _ "RecursiveDo") = EnableExtension RecursiveDo
toExtension (Ident _ "ParallelListComp") = EnableExtension ParallelListComp
toExtension (Ident _ "MultiParamTypeClasses") = EnableExtension MultiParamTypeClasses
toExtension (Ident _ "MonomorphismRestriction") = EnableExtension MonomorphismRestriction
toExtension (Ident _ "FunctionalDependencies") = EnableExtension FunctionalDependencies
toExtension (Ident _ "Rank2Types") = EnableExtension Rank2Types
toExtension (Ident _ "RankNTypes") = EnableExtension RankNTypes
toExtension (Ident _ "PolymorphicComponents") = EnableExtension PolymorphicComponents
toExtension (Ident _ "ExistentialQuantification") = EnableExtension ExistentialQuantification
toExtension (Ident _ "ScopedTypeVariables") = EnableExtension ScopedTypeVariables
toExtension (Ident _ "PatternSignatures") = EnableExtension PatternSignatures
toExtension (Ident _ "ImplicitParams") = EnableExtension ImplicitParams
toExtension (Ident _ "FlexibleContexts") = EnableExtension FlexibleContexts
toExtension (Ident _ "FlexibleInstances") = EnableExtension FlexibleInstances
toExtension (Ident _ "EmptyDataDecls") = EnableExtension EmptyDataDecls
toExtension (Ident _ "CPP") = EnableExtension CPP
toExtension (Ident _ "KindSignatures") = EnableExtension KindSignatures
toExtension (Ident _ "BangPatterns") = EnableExtension BangPatterns
toExtension (Ident _ "TypeSynonymInstances") = EnableExtension TypeSynonymInstances
toExtension (Ident _ "TemplateHaskell") = EnableExtension TemplateHaskell
toExtension (Ident _ "ForeignFunctionInterface") = EnableExtension ForeignFunctionInterface
toExtension (Ident _ "Arrows") = EnableExtension Arrows
toExtension (Ident _ "Generics") = EnableExtension Generics
toExtension (Ident _ "ImplicitPrelude") = EnableExtension ImplicitPrelude
toExtension (Ident _ "NamedFieldPuns") = EnableExtension NamedFieldPuns
toExtension (Ident _ "PatternGuards") = EnableExtension PatternGuards
toExtension (Ident _ "GeneralizedNewtypeDeriving") = EnableExtension GeneralizedNewtypeDeriving
toExtension (Ident _ "DeriveAnyClass") = EnableExtension DeriveAnyClass
toExtension (Ident _ "ExtensibleRecords") = EnableExtension ExtensibleRecords
toExtension (Ident _ "RestrictedTypeSynonyms") = EnableExtension RestrictedTypeSynonyms
toExtension (Ident _ "HereDocuments") = EnableExtension HereDocuments
toExtension (Ident _ "MagicHash") = EnableExtension MagicHash
toExtension (Ident _ "BinaryLiterals") = EnableExtension BinaryLiterals
toExtension (Ident _ "TypeFamilies") = EnableExtension TypeFamilies
toExtension (Ident _ "StandaloneDeriving") = EnableExtension StandaloneDeriving
toExtension (Ident _ "UnicodeSyntax") = EnableExtension UnicodeSyntax
toExtension (Ident _ "UnliftedFFITypes") = EnableExtension UnliftedFFITypes
toExtension (Ident _ "LiberalTypeSynonyms") = EnableExtension LiberalTypeSynonyms
toExtension (Ident _ "TypeOperators") = EnableExtension TypeOperators
toExtension (Ident _ "ParallelArrays") = EnableExtension ParallelArrays
toExtension (Ident _ "RecordWildCards") = EnableExtension RecordWildCards
toExtension (Ident _ "RecordPuns") = EnableExtension RecordPuns
toExtension (Ident _ "DisambiguateRecordFields") = EnableExtension DisambiguateRecordFields
toExtension (Ident _ "OverloadedStrings") = EnableExtension OverloadedStrings
toExtension (Ident _ "GADTs") = EnableExtension GADTs
toExtension (Ident _ "MonoPatBinds") = EnableExtension MonoPatBinds
toExtension (Ident _ "RelaxedPolyRec") = EnableExtension RelaxedPolyRec
toExtension (Ident _ "ExtendedDefaultRules") = EnableExtension ExtendedDefaultRules
toExtension (Ident _ "UnboxedTuples") = EnableExtension UnboxedTuples
toExtension (Ident _ "DeriveDataTypeable") = EnableExtension DeriveDataTypeable
toExtension (Ident _ "ConstrainedClassMethods") = EnableExtension ConstrainedClassMethods
toExtension (Ident _ "PackageImports") = EnableExtension PackageImports
toExtension (Ident _ "LambdaCase") = EnableExtension LambdaCase
toExtension (Ident _ "EmptyCase") = EnableExtension EmptyCase
toExtension (Ident _ "ImpredicativeTypes") = EnableExtension ImpredicativeTypes
toExtension (Ident _ "NewQualifiedOperators") = EnableExtension NewQualifiedOperators
toExtension (Ident _ "PostfixOperators") = EnableExtension PostfixOperators
toExtension (Ident _ "QuasiQuotes") = EnableExtension QuasiQuotes
toExtension (Ident _ "TransformListComp") = EnableExtension TransformListComp
toExtension (Ident _ "ViewPatterns") = EnableExtension ViewPatterns
toExtension (Ident _ "XmlSyntax") = EnableExtension XmlSyntax
toExtension (Ident _ "RegularPatterns") = EnableExtension RegularPatterns
toExtension (Ident _ "TupleSections") = EnableExtension TupleSections
toExtension (Ident _ "GHCForeignImportPrim") = EnableExtension GHCForeignImportPrim
toExtension (Ident _ "NPlusKPatterns") = EnableExtension NPlusKPatterns
toExtension (Ident _ "DoAndIfThenElse") = EnableExtension DoAndIfThenElse
toExtension (Ident _ "RebindableSyntax") = EnableExtension RebindableSyntax
toExtension (Ident _ "ExplicitForAll") = EnableExtension ExplicitForAll
toExtension (Ident _ "DatatypeContexts") = EnableExtension DatatypeContexts
toExtension (Ident _ "MonoLocalBinds") = EnableExtension MonoLocalBinds
toExtension (Ident _ "DeriveFunctor") = EnableExtension DeriveFunctor
toExtension (Ident _ "DeriveGeneric") = EnableExtension DeriveGeneric
toExtension (Ident _ "DeriveTraversable") = EnableExtension DeriveTraversable
toExtension (Ident _ "DeriveFoldable") = EnableExtension DeriveFoldable
toExtension (Ident _ "NondecreasingIndentation") = EnableExtension NondecreasingIndentation
toExtension (Ident _ "InterruptibleFFI") = EnableExtension InterruptibleFFI
toExtension (Ident _ "CApiFFI") = EnableExtension CApiFFI
toExtension (Ident _ "JavaScriptFFI") = EnableExtension JavaScriptFFI
toExtension (Ident _ "ExplicitNamespaces") = EnableExtension ExplicitNamespaces
toExtension (Ident _ "DataKinds") = EnableExtension DataKinds
toExtension (Ident _ "PolyKinds") = EnableExtension PolyKinds
toExtension (Ident _ "MultiWayIf") = EnableExtension MultiWayIf
toExtension (Ident _ "SafeImports") = EnableExtension SafeImports
toExtension (Ident _ "Safe") = EnableExtension Safe
toExtension (Ident _ "Trustworthy") = EnableExtension Trustworthy
toExtension (Ident _ "DefaultSignatures") = EnableExtension DefaultSignatures
toExtension (Ident _ "ConstraintKinds") = EnableExtension ConstraintKinds
toExtension (Ident _ "RoleAnnotations") = EnableExtension RoleAnnotations
toExtension (Ident _ "PatternSynonyms") = EnableExtension PatternSynonyms
toExtension (Ident _ "PartialTypeSignatures") = EnableExtension PartialTypeSignatures
toExtension (Ident _ "NamedWildCards") = EnableExtension NamedWildCards
toExtension (Ident _ "TypeApplications") = EnableExtension TypeApplications
toExtension (Ident _ "TypeFamilyDependencies") = EnableExtension TypeFamilyDependencies
toExtension (Ident _ "OverloadedLabels") = EnableExtension OverloadedLabels
toExtension (Ident _ "DerivingStrategies") = EnableExtension DerivingStrategies
toExtension (Ident _ "UnboxedSums") = EnableExtension UnboxedSums
toExtension (Ident _ "TypeInType") = EnableExtension TypeInType
toExtension (Ident _ "Strict") = EnableExtension Strict
toExtension (Ident _ "StrictData") = EnableExtension StrictData
toExtension (Ident _ "DerivingVia") = EnableExtension DerivingVia
toExtension (Ident _ "QuantifiedConstraints") = EnableExtension QuantifiedConstraints
toExtension (Ident _ "BlockArguments") = EnableExtension BlockArguments
toExtension name = error $ "Unknown extension: " ++ show name
getDependencies :: FilePath -> Module SrcSpanInfo -> [(ImportDecl SrcSpanInfo, FilePath)]
getDependencies sourceFile moduleSource = fmap (id &&& getLocation) importDecls
where
(Module _ (Just (ModuleHead _ (ModuleName _ moduleName) _ _)) exportSpec importDecls decls) =
moduleSource
srcDir = getSrcDir sourceFile moduleName
getLocation = locateImport srcDir . getModuleName . importModule
getSrcDir :: FilePath -> String -> FilePath
getSrcDir sourceFile moduleName = srcDir where
parents = moduleName
& fmap Text.unpack . Text.splitOn (Text.pack ".") . Text.pack
srcDir = iterate takeDirectory sourceFile !! length parents
locateImport :: FilePath -> String -> FilePath
locateImport srcDir importedModuleName = importedSourceFile where
(parents, child) = importedModuleName
& fmap Text.unpack . Text.splitOn (Text.pack ".") . Text.pack
& (init &&& last)
importedSourceFile = foldl (</>) srcDir parents </> child <.> ".hs"
mergePragmas :: [[ModulePragma SrcSpanInfo]] -> [ModulePragma SrcSpanInfo]
TODO Works , but not elaborated enough .
mergeImportDecls :: [[ImportDecl SrcSpanInfo]] -> [ImportDecl SrcSpanInfo]
mergeImportDecls decls =
TODO module modifiers ( hiding , qualified ) are not merged !
nubBy (\d1 d2 -> (EQ == ) $ comparing (getModuleName . importModule) d1 d2) (concat decls)
getModuleName :: ModuleName SrcSpanInfo -> String
getModuleName (ModuleName _ moduleName) = moduleName
patchRunMain :: Decl SrcSpanInfo -> Decl SrcSpanInfo
patchRunMain decl = case decl of
(TypeSig srcLoc names t) -> TypeSig srcLoc (fmap patchName names) t
(FunBind srcLoc matchs) -> FunBind srcLoc (fmap patchMatch matchs)
(PatBind srcLoc pat rhs binds) -> PatBind srcLoc (patchPat pat) rhs binds
_ -> decl
where
patchName (Ident srcLoc "runMain") = Ident srcLoc "main"
patchName name = name
patchMatch (Match srcLoc name pats rhs binds) =
Match srcLoc (patchName name) pats rhs binds
patchMatch (InfixMatch srcLoc pat name pats rhs binds) =
InfixMatch srcLoc pat (patchName name) pats rhs binds
patchPat (PVar srcLoc name) = PVar srcLoc (patchName name)
patchPat pat = pat
hppConfig :: HppState -> HppState
hppConfig = T.over T.config opts
where opts = T.setL C.inhibitLinemarkersL True
readAndPreProcessFile :: FilePath -> IO String
readAndPreProcessFile filePath =
case addDefinition "CG_ARENA" "1" (hppConfig emptyHppState) of
Just state -> readFile filePath >>= hpp (hppConfig state)
Nothing -> error "Preprocessor definition did not parse"
hpp :: HppState -> String -> IO String
hpp st src =
case runExcept (expand st (preprocess (map pack (lines src)))) of
Left e -> error ("Error running hpp: " ++ show e)
Right (HppOutput _ ls, _) -> return (unlines (map unpack ls))
|
302febe8318faa885a381839e85872231af8a08a3466e3e9713ae1c1cd9de197 | smallmelon/sdzmmo | mod_pet.erl | %%%------------------------------------
%%% @Module : mod_pet
@Author : shebiao
%%% @Email :
@Created : 2010.07.03
%%% @Description: 宠物处理
%%%------------------------------------
-module(mod_pet).
-behaviour(gen_server).
-include("common.hrl").
-include("record.hrl").
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-compile(export_all).
%%=========================================================================
%% 一些定义
%%=========================================================================
-record(state, {interval = 0}).
%%=========================================================================
%% 接口函数
%%=========================================================================
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
stop() ->
gen_server:call(?MODULE, stop).
%%=========================================================================
回调函数
%%=========================================================================
init([]) ->
process_flag(trap_exit, true),
Timeout = 60000,
State = #state{interval = Timeout},
?DEBUG("init: loading base_pet....", []),
lib_pet:load_base_pet(),
{ok, State}.
handle_call(_Request, _From, State) ->
{reply, State, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%=========================================================================
%% 业务处理函数
%%=========================================================================
%% -----------------------------------------------------------------
%% 宠物孵化
%% -----------------------------------------------------------------
incubate_pet(Status, [GoodsId, GoodsUseNum]) ->
?DEBUG("incubate_pet: GoodsId=[~p], GoodsUseNum=[~p]", [GoodsId, GoodsUseNum]),
Goods = lib_pet:get_goods(GoodsId),
if % 该物品不存在
Goods =:= [] -> [2, 0, <<>>];
true ->
[EggGoodsType, EggGoodsSubType] = data_pet:get_pet_config(egg_goods_type,[]),
[GoodsPlayerId, GoodsTypeId, GoodsType, GoodsSubtype, GoodsNum, _GoodsCell, GoodsLevel] =
[Goods#goods.player_id, Goods#goods.goods_id, Goods#goods.type, Goods#goods.subtype, Goods#goods.num, Goods#goods.cell, Goods#goods.level],
if % 物品不归你所有
GoodsPlayerId /= Status#player_status.id -> [3, 0, <<>>];
% 该物品不是宠物蛋
((GoodsType /= EggGoodsType) and (GoodsSubtype /= EggGoodsSubType)) -> [4, 0, <<>>];
GoodsNum < GoodsUseNum -> [5, 0, <<>>];
true ->
GoodsTypeInfo = lib_pet:get_goods_type(GoodsTypeId),
if % 该物品类型信息不存在
GoodsTypeInfo =:= [] ->
?ERR("incubate_pet: Goods type not in cache, type_id=[~p]", [GoodsTypeId]),
[0, 0, <<>>];
true ->
if % 你级别不够
Status#player_status.lv < GoodsLevel -> [6, 0, <<>>];
true ->
PetCount = lib_pet:get_pet_count(Status#player_status.id),
PetCapacity = data_pet:get_pet_config(capacity,[]),
if % 宠物数已满
PetCount >= PetCapacity -> [7, 0, <<>>];
true ->
case gen_server:call(Status#player_status.goods_pid, {'delete_one', GoodsId, GoodsUseNum}) of
[1, _GoodsNumNew] ->
case lib_pet:incubate_pet(Status#player_status.id, GoodsTypeInfo) of
[ok, PetId, PetName] ->
[1, PetId, PetName];
_ ->
[0, 0, <<>>]
end;
[GoodsModuleCode, 0] ->
?DEBUG("incubate_pet: Call goods module faild, result code=[~p]", [GoodsModuleCode]),
[0, 0, <<>>]
end
end
end
end
end
end.
%% -----------------------------------------------------------------
%% 宠物放生
%% -----------------------------------------------------------------
free_pet(Status, [PetId]) ->
?DEBUG("free_pet: PetId=[~p]", [PetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> 2;
true ->
[PlayerId, UpgradeFlag, FightFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.upgrade_flag, Pet#ets_pet.fight_flag],
该宠物不归你所有
PlayerId /= Status#player_status.id -> 3;
% 宠物正在升级
UpgradeFlag == 1 -> 4;
宠物正在出战
FightFlag == 1 -> 5;
true ->
case lib_pet:free_pet(PetId) of
ok -> 1;
_ -> 0
end
end
end.
%% -----------------------------------------------------------------
%% 宠物改名
%% -----------------------------------------------------------------
rename_pet(Status, [PetId, PetName]) ->
?DEBUG("rename_pet: PetId=[~p], PetName=[~s]", [PetId, PetName]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0];
true ->
[PlayerId, Name, RenameCount] = [Pet#ets_pet.player_id, Pet#ets_pet.name, Pet#ets_pet.rename_count],
NewName = lib_pet:make_sure_binary(PetName),
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0];
新旧名称相同
Name =:= NewName -> [4, 0, 0];
true ->
if % 修改次数大于0要收钱
RenameCount > 0 ->
RenameMoney = data_pet:get_rename_money(RenameCount),
if % 金币不够
Status#player_status.gold < RenameMoney -> [5, 0, 0];
true ->
case lib_pet:rename_pet(PetId, NewName, Status#player_status.id, RenameMoney) of
ok ->
% 更新缓存
PetNew = Pet#ets_pet{
rename_count = RenameCount+1,
name = NewName},
lib_pet:update_pet(PetNew),
[1, 1, Status#player_status.gold-RenameMoney];
_ -> [0, 0, 0]
end
end;
% 修改次数等于0不收钱
true ->
case lib_pet:rename_pet(PetId, PetName, Status#player_status.id, 0) of
ok ->
% 更新缓存
PetNew = Pet#ets_pet{
rename_count = RenameCount+1,
name = NewName},
lib_pet:update_pet(PetNew),
[1, 0, Status#player_status.gold];
_ ->
[0, 0, 0]
end
end
end
end.
%% -----------------------------------------------------------------
宠物出战
%% -----------------------------------------------------------------
fighting_pet(Status, [PetId, FightIconPos]) ->
?DEBUG("fighting_pet: PetId=[~p], FightIconPos=[~p]", [PetId, FightIconPos]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0];
true ->
[PlayerId, ForzaUse, WitUse, AgileUse, FightFlag, Strength] = [Pet#ets_pet.player_id, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.fight_flag, Pet#ets_pet.strength],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0];
% 宠物已经出战
FightFlag == 1 -> [4, 0, 0, 0, 0];
体力值为0
Strength == 0 -> [5, 0, 0, 0, 0];
true ->
MaxFighting = data_pet:get_pet_config(maxinum_fighting,[]),
FightingPet = lib_pet:get_fighting_pet(PlayerId),
if % 出战宠物数达到上限
length(FightingPet) >= MaxFighting -> [6, 0, 0, 0, 0];
true ->
case lib_pet:fighting_pet(PetId, FightingPet, FightIconPos) of
[ok, IconPos] ->
[IntervalSync, _StrengthSync] = data_pet:get_pet_config(strength_sync, []),
NowTime = util:unixtime(),
% 更新缓存
PetNew = Pet#ets_pet{fight_flag = 1,
fight_icon_pos = IconPos,
strength_nexttime = NowTime+IntervalSync},
lib_pet:update_pet(PetNew),
[1, IconPos, ForzaUse, WitUse, AgileUse];
_ ->
[0, 0, 0, 0, 0]
end
end
end
end.
%% -----------------------------------------------------------------
%% 宠物休息
%% -----------------------------------------------------------------
rest_pet(Status, [PetId]) ->
?DEBUG("rest_pet: PetId=[~p]", [PetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0];
true ->
[PlayerId, ForzaUse, WitUse, AgileUse, FightFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.fight_flag],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0];
宠物已经休息
FightFlag == 0 -> [4, 0, 0, 0];
true ->
case lib_pet:rest_pet(PetId) of
ok ->
% 更新缓存
PetNew = Pet#ets_pet{fight_flag = 0,
fight_icon_pos = 0,
strength_nexttime = 0},
lib_pet:update_pet(PetNew),
[1, ForzaUse, WitUse, AgileUse];
_ ->
[0, 0, 0, 0]
end
end
end.
%% -----------------------------------------------------------------
%% 属性洗练
%% -----------------------------------------------------------------
shuffle_attribute(Status, [PetId, PayType, GoodsId, GoodsUseNum]) ->
?DEBUG("shuffle_attribute: PetId=[~p], PayType=[~p], GoodsId=[~p], GoodsUseNum=[~p]", [PetId, PayType,GoodsId, GoodsUseNum]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0];
true ->
[PlayerId, ShuffleCount, FightFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.attribute_shuffle_count, Pet#ets_pet.fight_flag],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0];
宠物正在战斗
FightFlag == 1 -> [4, 0, 0, 0, 0];
true ->
case PayType of
% 银两支付
0 ->
ShuffleMoney = data_pet:get_pet_config(shuffle_money,[]),
if % 金币不够
Status#player_status.gold < ShuffleMoney -> [5, 0, 0, 0, 0];
true ->
case lib_pet:shuffle_attribute(Status#player_status.id, PetId, PayType, ShuffleCount, GoodsId, Status#player_status.gold, ShuffleMoney) of
[ok, BaseForzaNew, BaseWitNew, BaseAgileNew] ->
% 更新缓存
PetNew = Pet#ets_pet{
base_forza_new = BaseForzaNew,
base_wit_new = BaseWitNew,
base_agile_new = BaseAgileNew,
attribute_shuffle_count = ShuffleCount+1},
lib_pet:update_pet(PetNew),
[1, BaseForzaNew, BaseWitNew, BaseAgileNew, Status#player_status.gold-ShuffleMoney];
_ ->
[0, 0, 0, 0, 0]
end
end;
% 物品支付
1 ->
Goods = lib_pet:get_goods(GoodsId),
Goods =:= [] -> [6, 0, 0, 0, 0];
true ->
[GoodsPlayerId, _GoodsTypeId, GoodsType, GoodsSubtype, GoodsNum, _GoodsCell] =
[Goods#goods.player_id, Goods#goods.goods_id, Goods#goods.type, Goods#goods.subtype, Goods#goods.num, Goods#goods.cell],
[ShuffleGoodsType, ShuffleGoodsSubType] = data_pet:get_pet_config(attribute_shuffle_goods_type,[]),
if % 物品不归你所有
GoodsPlayerId /= Status#player_status.id -> [7, 0, 0, 0, 0];
该物品不是洗练药水
((GoodsType /= ShuffleGoodsType) and (GoodsSubtype /= ShuffleGoodsSubType)) -> [8, 0, 0, 0, 0];
GoodsNum < GoodsUseNum -> [9, 0, 0, 0, 0];
true ->
case gen_server:call(Status#player_status.goods_pid, {'delete_one', GoodsId, GoodsUseNum}) of
[1, _GoodsNumNew] ->
case lib_pet:shuffle_attribute(Status#player_status.id, PetId, PayType, ShuffleCount, GoodsId, GoodsNum, GoodsUseNum) of
[ok, BaseForzaNew, BaseWitNew, BaseAgileNew] ->
% 更新缓存
PetNew = Pet#ets_pet{base_forza_new = BaseForzaNew,
base_wit_new = BaseWitNew,
base_agile_new = BaseAgileNew,
attribute_shuffle_count = ShuffleCount+1},
lib_pet:update_pet(PetNew),
[1, BaseForzaNew, BaseWitNew, BaseAgileNew, Status#player_status.gold];
_ ->
[0, 0, 0, 0, 0]
end;
[GoodsModuleCode, 0] ->
?DEBUG("shuffle_attribute: Call goods module faild, result code=[~p]", [GoodsModuleCode]),
[0, 0, 0, 0, 0]
end
end
end;
支付类型未知
_ ->
?ERR("shuffle_attribute: Unknow pay type, type=[~p]", [PayType]),
[0, 0, 0, 0, 0]
end
end
end.
%% -----------------------------------------------------------------
洗练属性使用
%% -----------------------------------------------------------------
use_attribute(Status, [PetId, ActionType]) ->
?DEBUG("use_attribute: PetId=[~p], ActionType=[~p]", [PetId, ActionType]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0, 0, 0];
true ->
[PlayerId, Level, Strength, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, BaseForzaNew, BaseWitNew, BaseAgileNew, FightFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile, Pet#ets_pet.base_forza_new, Pet#ets_pet.base_wit_new, Pet#ets_pet.base_agile_new, Pet#ets_pet.fight_flag],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0, 0, 0];
宠物正在战斗
FightFlag == 1 -> [4, 0, 0, 0, 0, 0, 0];
% 宠物没有洗练过
((BaseForzaNew==0) and (BaseWitNew==0) and (BaseAgileNew==0)) -> [5, 0, 0, 0, 0, 0, 0];
true ->
case ActionType of
% 保留原有基础属性
0 ->
case lib_pet:use_attribute(PetId, BaseForza, BaseWit, BaseAgile, AptitudeForza, AptitudeWit, AptitudeAgile, Level, Strength) of
[ok, _NewForza, _NewWit, _NewAgile, _NewForzaUse, _NewWitUse, _NewAgileUse] ->
% 更新缓存
PetNew = Pet#ets_pet{base_forza_new = 0,
base_wit_new = 0,
base_agile_new = 0},
lib_pet:update_pet(PetNew),
[1, Forza, Wit, Agile, 0, 0, 0];
_ ->
[0, 0, 0, 0, 0, 0, 0]
end;
% 使用新基础属性
1 ->
case lib_pet:use_attribute(PetId, BaseForzaNew, BaseWitNew, BaseAgileNew, AptitudeForza, AptitudeWit, AptitudeAgile, Level, Strength) of
[ok, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] ->
% 更新缓存
PetNew = Pet#ets_pet{forza = NewForza,
wit = NewWit,
agile = NewAgile,
forza_use = NewForzaUse,
wit_use = NewWitUse,
agile_use = NewAgileUse,
base_forza = BaseForzaNew,
base_wit = BaseWitNew,
base_agile = BaseAgileNew,
base_forza_new = 0,
base_wit_new = 0,
base_agile_new = 0},
lib_pet:update_pet(PetNew),
[1, NewForza, NewWit, NewAgile, NewForzaUse-ForzaUse, NewWitUse-WitUse, NewAgileUse-AgileUse];
_ ->
[0, 0, 0, 0, 0, 0, 0]
end;
_ ->
?ERR("use_attribute: Unknow action type, type=[~p]", [ActionType]),
[0, 0, 0, 0, 0, 0, 0]
end
end
end.
%% -----------------------------------------------------------------
%% 宠物开始升级
%% -----------------------------------------------------------------
start_upgrade(Status, [PetId]) ->
?DEBUG("start_upgrade, PetId=[~p]", [PetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0];
true ->
[PlayerId, Level, Quality, UpgradeFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.quality, Pet#ets_pet.upgrade_flag],
MaxLevel = data_pet:get_pet_config(maxinum_level, []),
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0];
% 宠物已经在升级
UpgradeFlag == 1 -> [4, 0, 0];
% 宠物等级已经和玩家等级相等
Level == Status#player_status.lv -> [5, 0, 0];
% 宠物已升到最高级
Level >= MaxLevel -> [6, 0, 0];
true ->
QueNum = Status#player_status.pet_upgrade_que_num,
UpgradingPet = lib_pet:get_upgrading_pet(PlayerId),
if % 宠物升级队列已满
length(UpgradingPet) >= QueNum -> [7, 0, 0];
true ->
[UpgradeMoney, UpgradeTime] = data_pet:get_upgrade_info(Quality, Level),
铜币不够
Status#player_status.coin < UpgradeMoney -> [8, 0, 0];
true ->
NowTime = util:unixtime(),
UpgradeEndTime = NowTime+UpgradeTime,
case lib_pet:pet_start_upgrade(Status#player_status.id, PetId, UpgradeEndTime, UpgradeMoney) of
ok ->
% 更新缓存
PetNew = Pet#ets_pet{upgrade_flag = 1,
upgrade_endtime = UpgradeEndTime},
lib_pet:update_pet(PetNew),
[1, UpgradeTime, Status#player_status.coin-UpgradeMoney];
_ -> [0, 0, 0]
end
end
end
end
end.
%% -----------------------------------------------------------------
%% 宠物升级加速
%% -----------------------------------------------------------------
shorten_upgrade(Status, [PetId, ShortenTime]) ->
?DEBUG("shorten_upgrade, PetId=[~p], ShortenTime=[~p]", [PetId, ShortenTime]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0, 0, 0, 0, 0, 0];
true ->
[PlayerId, Level, Strength, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeFlag, UpgradeEndTime] =
[Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile, Pet#ets_pet.upgrade_flag, Pet#ets_pet.upgrade_endtime],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0, 0, 0, 0, 0, 0];
% 宠物不在升级
UpgradeFlag == 0 -> [4, 0, 0, 0, 0, 0, 0, 0, 0, 0];
true ->
ShortenMoney = lib_pet:calc_shorten_money(ShortenTime),
if % 金币不够
Status#player_status.gold < ShortenMoney -> [5, 0, 0, 0, 0, 0, 0, 0, 0, 0];
true ->
UpgradeEndTimeNew = UpgradeEndTime-ShortenTime,
MoneyLeft = Status#player_status.gold-ShortenMoney,
case lib_pet:check_upgrade_state(Status#player_status.id, PetId, Level, Strength, UpgradeFlag, UpgradeEndTimeNew, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, ShortenMoney) of
% 宠物不在升级
[0, _UpgradeLeftTime] ->
[4, 0, 0, 0, 0, 0, 0, 0, 0, 0];
% 宠物还在升级
[1, UpgradeLeftTime] ->
case lib_pet:shorten_upgrade(Status#player_status.id, PetId, UpgradeEndTimeNew, ShortenMoney) of
ok ->
% 更新缓存
PetNew = Pet#ets_pet{upgrade_flag = 1,
upgrade_endtime = UpgradeEndTimeNew},
lib_pet:update_pet(PetNew),
[1, Level, Forza, Wit, Agile, 0, 0, 0, UpgradeLeftTime, MoneyLeft];
_ ->
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
end;
% 宠物升完级
[2, UpgradeLeftTime, NewLevel, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] ->
% 更新缓存
PetNew = Pet#ets_pet{upgrade_flag = 0,
upgrade_endtime = 0,
level = NewLevel,
forza = NewForza,
wit = NewWit,
agile = NewAgile,
forza_use = NewForzaUse,
wit_use = NewWitUse,
agile_use = NewAgileUse
},
lib_pet:update_pet(PetNew),
[1, NewLevel, NewForza, NewWit, NewAgile, NewForzaUse-ForzaUse, NewWitUse-WitUse, NewAgileUse-AgileUse, UpgradeLeftTime, MoneyLeft];
% 其他情况
_ -> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
end
end
end
end.
%% -----------------------------------------------------------------
%% 宠物完成升级
%% -----------------------------------------------------------------
finish_upgrade(Status, [PetId]) ->
?DEBUG("finish_upgrade, PetId=[~p]", [PetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0, 0, 0, 0];
true ->
[PlayerId, Level, Strength, _Forza, _Wit, _Agile, ForzaUse, WitUse, AgileUse, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeFlag, UpgradeEndTime] =
[Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile, Pet#ets_pet.upgrade_flag, Pet#ets_pet.upgrade_endtime],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0, 0, 0, 0];
true ->
case lib_pet:check_upgrade_state(Status#player_status.id, PetId, Level, Strength, UpgradeFlag, UpgradeEndTime, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, 0) of
% 宠物不在升级
[0, _UpgradeLeftTime] -> [4, 0, 0, 0, 0, 0, 0, 0];
% 宠物还在升级
[1, _UpgradeLeftTime] -> [5, 0, 0, 0, 0, 0, 0, 0];
% 宠物升完级
[2, _UpgradeLeftTime, NewLevel, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] ->
?DEBUG("finish_upgrade: NewLevel=[~p], NewForza=[~p], NewWit=[~p], NewAgile=[~p], NewForzaUse=[~p], NewWitUse=[~p], NewAgileUse=[~p], ForzaUse=[~p], WitUse=[~p], AgileUse=[~p]", [NewLevel, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse, ForzaUse, WitUse, AgileUse]),
% 更新缓存
PetNew = Pet#ets_pet{upgrade_flag = 0,
upgrade_endtime = 0,
level = NewLevel,
forza = NewForza,
wit = NewWit,
agile = NewAgile,
forza_use = NewForzaUse,
wit_use = NewWitUse,
agile_use = NewAgileUse
},
lib_pet:update_pet(PetNew),
[1, NewLevel, NewForza, NewWit, NewAgile, NewForzaUse-ForzaUse, NewWitUse-WitUse, NewAgileUse-AgileUse];
_ -> [0, 0, 0, 0, 0, 0, 0, 0]
end
end
end.
%% -----------------------------------------------------------------
%% 扩展升级队列
%% -----------------------------------------------------------------
extent_upgrade_que(Status, []) ->
MaxQueNum = data_pet:get_pet_config(maxinum_que_num, []),
QueNum = Status#player_status.pet_upgrade_que_num,
?DEBUG("extent_upgrade_que: MaxQueNum=[~p], QueNum=[~p]", [MaxQueNum, QueNum]),
if % 已达到最大队列上限
QueNum >= MaxQueNum -> [2, 0, 0];
true ->
NewQueNum = QueNum+1,
ExtentQueMoney = data_pet:get_pet_config(extent_que_money, [NewQueNum]),
if % 金币不够
Status#player_status.gold < ExtentQueMoney -> [3, 0, 0];
true ->
case lib_pet:extent_upgrade_que(Status#player_status.id, NewQueNum, ExtentQueMoney) of
ok -> [1, NewQueNum, Status#player_status.gold-ExtentQueMoney];
_ -> [0, 0, 0]
end
end
end.
%% -----------------------------------------------------------------
%% -----------------------------------------------------------------
feed_pet(Status, [PetId, GoodsId, GoodsUseNum]) ->
?DEBUG("feed_pet, PetId=[~p], GoodsId=[~p], GoodsUseNum=[~p]", [PetId, GoodsId, GoodsUseNum]),
if % 你已经死亡
Status#player_status.hp =< 0 -> [2, 0, 0, 0, 0, 0, 0, 0];
true ->
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [3, 0, 0, 0, 0, 0, 0, 0];
true ->
[PlayerId, Level, PetStrength, PetStrengThreshold, PetQuality, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile] =
[Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.strength_threshold, Pet#ets_pet.quality, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile],
if % 宠物不归你所有
PlayerId /= Status#player_status.id -> [4, 0, 0, 0, 0, 0, 0, 0];
% 宠物体力值已满
PetStrength == PetStrengThreshold -> [5, 0, 0, 0, 0, 0, 0, 0];
true ->
Goods = lib_pet:get_goods(GoodsId),
Goods =:= [] -> [6, 0, 0, 0, 0, 0, 0, 0];
true ->
[FoodGoodsType, FoodGoodsSubType] = data_pet:get_pet_config(food_goods_type,[]),
[GoodsPlayerId, GoodsTypeId, GoodsType, GoodsSubtype, GoodsNum, _GoodsCell, GoodsColor] =
[Goods#goods.player_id, Goods#goods.goods_id, Goods#goods.type, Goods#goods.subtype, Goods#goods.num, Goods#goods.cell, Goods#goods.color],
if % 物品不归你所有
GoodsPlayerId /= Status#player_status.id -> [7, 0, 0, 0, 0, 0, 0, 0];
% 该物品不是食物
((GoodsType /= FoodGoodsType) and (GoodsSubtype /= FoodGoodsSubType)) -> [8, 0, 0, 0, 0, 0, 0, 0];
% 食物品阶不够
GoodsColor < PetQuality -> [10, 0, 0, 0, 0, 0, 0, 0];
true ->
单个物品数量不够
GoodsNum < GoodsUseNum ->
试图扣取多个格子物品
case gen_server:call(Status#player_status.goods_pid, {'delete_more', GoodsTypeId, GoodsUseNum}) of
1 ->
case lib_pet:feed_pet(PetId, PetQuality, GoodsColor, GoodsUseNum, PetStrength, PetStrengThreshold, Level, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile) of
% 体力值变化且影响了力智敏
[ok, NewStrength, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] ->
% 更新缓存
PetNew = Pet#ets_pet{strength = NewStrength,
forza = NewForza,
wit = NewWit,
agile = NewAgile,
forza_use = NewForzaUse,
wit_use = NewWitUse,
agile_use = NewAgileUse
},
lib_pet:update_pet(PetNew),
[1, NewStrength, NewForza, NewWit, NewAgile, NewForzaUse-ForzaUse, NewWitUse-WitUse, NewAgileUse-AgileUse];
% 体力值变化但不影响力智敏
[ok, NewStrength] ->
% 更新缓存
PetNew = Pet#ets_pet{strength = NewStrength
},
lib_pet:update_pet(PetNew),
[1, NewStrength, Forza, Wit, Agile, 0, 0, 0];
% 出错
_ -> [0, 0, 0, 0, 0, 0, 0, 0]
end;
% 扣取物品失败
0 ->
?DEBUG("feed_pet: Call goods module faild", []),
[0, 0, 0, 0, 0, 0, 0, 0];
_ ->
[9, 0, 0, 0, 0, 0, 0, 0]
end;
% 单个物品数量足够
true ->
% 扣取物品
case gen_server:call(Status#player_status.goods_pid, {'delete_one', GoodsId, GoodsUseNum}) of
扣取物品成功
[1, _GoodsNumNew] ->
case lib_pet:feed_pet(PetId, PetQuality, GoodsColor, GoodsUseNum, PetStrength, PetStrengThreshold, Level, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile) of
% 体力值变化且影响力智敏
[ok, NewStrength, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] ->
% 更新缓存
PetNew = Pet#ets_pet{strength = NewStrength,
forza = NewForza,
wit = NewWit,
agile = NewAgile,
forza_use = NewForzaUse,
wit_use = NewWitUse,
agile_use = NewAgileUse
},
lib_pet:update_pet(PetNew),
[1, NewStrength, NewForza, NewWit, NewAgile, NewForzaUse-ForzaUse, NewWitUse-WitUse, NewAgileUse-AgileUse];
% 体力值有变化但不影响力智敏
[ok, NewStrength] ->
% 更新缓存
PetNew = Pet#ets_pet{strength = NewStrength},
lib_pet:update_pet(PetNew),
[1, NewStrength, Forza, Wit, Agile, 0, 0, 0];
% 出错
_ -> [0, 0, 0, 0, 0, 0, 0, 0]
end;
% 扣取物品失败
[GoodsModuleCode, 0] ->
?DEBUG("feed_pet: Call goods module faild, result code=[~p]", [GoodsModuleCode]),
[0, 0, 0, 0, 0, 0, 0, 0]
end
end
end
end
end
end
end.
%% -----------------------------------------------------------------
%% 宠物驯养
%% -----------------------------------------------------------------
domesticate_pet(Status, [PetId, DomesticateType, GoodsId, GoodsUseNum]) ->
?DEBUG("domesticate_pet, PetId=[~p], DomesticateType=[~p], GoodsId=[~p], GoodsUseNum=[~p]", [PetId, DomesticateType, GoodsId, GoodsUseNum]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0, 0];
true ->
[PlayerId, Level, Strength, Quality, _Forza, _Wit, _Agile, ForzaUse, WitUse, AgileUse, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile] =
[Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.quality, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0, 0];
true ->
Goods = lib_pet:get_goods(GoodsId),
Goods =:= [] -> [4, 0, 0, 0, 0, 0];
true ->
[GoodsPlayerId, GoodsTypeId, GoodsType, GoodsSubtype, GoodsNum, _GoodsCell, GoodsForza, GoodsWit, GoodsAgile] =
[Goods#goods.player_id, Goods#goods.goods_id, Goods#goods.type, Goods#goods.subtype, Goods#goods.num, Goods#goods.cell, Goods#goods.forza, Goods#goods.wit, Goods#goods.agile],
[BookGoodsType, BookGoodsSubType] = data_pet:get_pet_config(attribute_book_goods_type,[]),
if % 物品不归你所有
GoodsPlayerId /= Status#player_status.id -> [5, 0, 0, 0, 0, 0];
% 该物品不是训练书
((GoodsType /= BookGoodsType) and (GoodsSubtype /= BookGoodsSubType)) -> [7, 0, 0, 0, 0, 0];
true ->
AptitudeThreshold = data_pet:get_pet_config(aptitude_threshold,[Quality]),
单个物品数量不够
GoodsNum < GoodsUseNum ->
试图扣取多个格子物品
case gen_server:call(Status#player_status.goods_pid, {'delete_more', GoodsTypeId, GoodsUseNum}) of
1 ->
case DomesticateType of
0 ->
资质已经满
AptitudeForza >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeForza+GoodsUseNum*GoodsForza, AptitudeThreshold, BaseForza) of
[ok, AptitudeForzaNew, ForzaNew, ForzaUseNew] ->
% 更新缓存
PetNew = Pet#ets_pet{aptitude_forza = AptitudeForzaNew,
forza = ForzaNew,
forza_use = ForzaUseNew
},
lib_pet:update_pet(PetNew),
[1, AptitudeForzaNew, ForzaNew, ForzaUseNew-ForzaUse, 0, 0];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
驯养智力
1 ->
资质已经满
AptitudeWit >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeWit+GoodsUseNum*GoodsWit, AptitudeThreshold, BaseWit) of
[ok, AptitudeWitNew, WitNew, WitUseNew] ->
% 更新缓存
PetNew = Pet#ets_pet{aptitude_wit = AptitudeWitNew,
wit = WitNew,
wit_use = WitUseNew
},
lib_pet:update_pet(PetNew),
[1, AptitudeWitNew, WitNew, 0, WitUseNew-WitUse, 0];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
% 驯养敏捷
2 ->
资质已经满
AptitudeAgile >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeAgile+GoodsUseNum*GoodsAgile, AptitudeThreshold, BaseAgile) of
[ok, AptitudeAgileNew, AgileNew, AgileUseNew] ->
% 更新缓存
PetNew = Pet#ets_pet{aptitude_agile = AptitudeAgileNew,
agile = AgileNew,
agile_use = AgileUseNew
},
lib_pet:update_pet(PetNew),
[1, AptitudeAgileNew, AgileNew, 0, 0, AgileUseNew-AgileUse];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
_ ->
?ERR("domesticate_pet: Unknow domesticate type, type=[~p]", [DomesticateType]),
[0, 0, 0, 0, 0, 0]
end;
% 扣取物品失败
0 ->
?DEBUG("domesticate_pet: Call goods module faild", []),
[0, 0, 0, 0, 0, 0];
_ ->
[6, 0, 0, 0, 0, 0]
end;
% 单个物品数量足够
true ->
% 扣取物品
case gen_server:call(Status#player_status.goods_pid, {'delete_one', GoodsId, GoodsUseNum}) of
扣取物品成功
[1, _GoodsNumNew] ->
case DomesticateType of
0 ->
资质已经满
AptitudeForza >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeForza+GoodsUseNum*GoodsForza, AptitudeThreshold, BaseForza) of
[ok, AptitudeForzaNew, ForzaNew, ForzaUseNew] ->
% 更新缓存
PetNew = Pet#ets_pet{aptitude_forza = AptitudeForzaNew,
forza = ForzaNew,
forza_use = ForzaUseNew},
lib_pet:update_pet(PetNew),
[1, AptitudeForzaNew, ForzaNew, ForzaUseNew-ForzaUse, 0, 0];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
驯养智力
1 ->
资质已经满
AptitudeWit >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeWit+GoodsUseNum*GoodsWit, AptitudeThreshold, BaseWit) of
[ok, AptitudeWitNew, WitNew, WitUseNew] ->
% 更新缓存
PetNew = Pet#ets_pet{aptitude_wit = AptitudeWitNew,
wit = WitNew,
wit_use = WitUseNew},
lib_pet:update_pet(PetNew),
[1, AptitudeWitNew, WitNew, 0, WitUseNew-WitUse, 0];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
% 驯养敏捷
2 ->
资质已经满
AptitudeAgile >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeAgile+GoodsUseNum*GoodsAgile, AptitudeThreshold, BaseAgile) of
[ok, AptitudeAgileNew, AgileNew, AgileUseNew] ->
% 更新缓存
PetNew = Pet#ets_pet{aptitude_agile = AptitudeAgileNew,
agile = AgileNew,
agile_use = AgileUseNew},
lib_pet:update_pet(PetNew),
[1, AptitudeAgileNew, AgileNew, 0, 0, AgileUseNew-AgileUse];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
_ ->
?ERR("domesticate_pet: Unknow domesticate type, type=[~p]", [DomesticateType]),
[0, 0, 0, 0, 0, 0]
end;
% 扣取物品失败
[GoodsModuleCode, 0] ->
?DEBUG("domesticate_pet: Call goods module faild, result code=[~p]", [GoodsModuleCode]),
[0, 0, 0, 0, 0, 0]
end
end
end
end
end
end.
%% -----------------------------------------------------------------
宠物进阶
%% -----------------------------------------------------------------
enhance_quality(Status, [PetId, GoodsId, GoodsUseNum]) ->
?DEBUG("enhance_quality: PetId=[~p], GoodsId=[~p], GoodsUseNum=[~p]", [PetId, GoodsId, GoodsUseNum]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0];
true ->
[PlayerId, Level, Quality, UpgradeFlag, FightFlag] =
[Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.quality, Pet#ets_pet.upgrade_flag, Pet#ets_pet.fight_flag],
MaxQuality = data_pet:get_pet_config(maxinum_quality,[]),
if % 宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0];
% 宠物已经是最高品
Quality >= MaxQuality -> [4, 0, 0, 0];
% 宠物正在升级
UpgradeFlag == 1 -> [5, 0, 0, 0];
宠物正在出战
FightFlag == 1 -> [6, 0, 0, 0];
true ->
%SuccessProbability = data_pet:get_pet_config(enhance_quality_probability,[Quality]),
BasePet = lib_pet:get_base_pet(GoodsId),
SuccessProbability = case BasePet of
[] -> ?ERR("enhance_quality: Not find the base_pet, goods_id=[~p]", [GoodsId]),
100;
_ -> BasePet#ets_base_pet.probability
end,
Goods = lib_pet:get_goods(GoodsId),
Goods =:= [] -> [8, 0, 0, 0];
true ->
[GoodsPlayerId, _GoodsTypeId, GoodsType, GoodsSubtype, GoodsNum, _GoodsCell, GoodsColor, GoodsLevel] =
[Goods#goods.player_id, Goods#goods.goods_id, Goods#goods.type, Goods#goods.subtype, Goods#goods.num, Goods#goods.cell, Goods#goods.color, Goods#goods.level],
[StoneGoodsType, StoneGoodsSubType] = data_pet:get_pet_config(quality_stone_goods_type, []),
if % 物品不归你所有
GoodsPlayerId /= Status#player_status.id -> [9, 0, 0, 0];
GoodsNum < GoodsUseNum -> [10, 0, 0, 0];
% 级别不够
Level < GoodsLevel -> [7, 0, 0, 0];
% 物品不是进化石
((GoodsType /=StoneGoodsType) and (GoodsSubtype /=StoneGoodsSubType)) -> [11, 0, 0, 0];
true ->
品阶不对
Quality > GoodsColor -> [12, 0, 0, 0];
true ->
case gen_server:call(Status#player_status.goods_pid, {'delete_one', GoodsId, GoodsUseNum}) of
[1, _GoodsNumNew] ->
case lib_pet:enhance_quality(PetId, Quality, SuccessProbability) of
[ok, EvolutionResult, QualityNew, AptitudeThresholdNew] ->
% 更新缓存
PetNew = Pet#ets_pet{level = 1,
quality = QualityNew,
aptitude_threshold = AptitudeThresholdNew},
lib_pet:update_pet(PetNew),
[1, EvolutionResult, QualityNew, AptitudeThresholdNew];
_ ->
[0, 0, 0, 0]
end;
[GoodsModuleCode, 0] ->
?DEBUG("enhance_quality: Call goods module faild, result code=[~p]", [GoodsModuleCode]),
[0, 0, 0, 0]
end
end
end
end
end
end.
%% -----------------------------------------------------------------
%% 获取宠物信息
%% -----------------------------------------------------------------
get_pet_info(_Status, [PetId]) ->
?DEBUG("get_pet_info, PetId=[~p]", [PetId]),
lib_pet:get_pet_info(PetId).
%% -----------------------------------------------------------------
%% 获取宠物列表
%% -----------------------------------------------------------------
get_pet_list(_Status, [PlayerId]) ->
?DEBUG("get_pet_list, PlayerId=[~p]", [PlayerId]),
lib_pet:get_pet_list(PlayerId).
%% -----------------------------------------------------------------
%% 宠物出战替换
%% -----------------------------------------------------------------
fighting_replace(Status, [PetId, ReplacedPetId]) ->
?DEBUG("fighting_pet: PetId=[~p], ReplacedPet=[~p]", [PetId, ReplacedPetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0];
true ->
[PlayerId, ForzaUse, WitUse, AgileUse, FightFlag, Strength] = [Pet#ets_pet.player_id, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.fight_flag, Pet#ets_pet.strength],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0];
% 宠物已经出战
FightFlag == 1 -> [4, 0, 0, 0, 0];
体力值为0
Strength == 0 -> [5, 0, 0, 0, 0];
true ->
Pet1 = lib_pet:get_pet(ReplacedPetId),
if % 被替换宠物不存在
Pet1 =:= [] -> [6, 0, 0, 0, 0];
true ->
[PlayerId1, ForzaUse1, WitUse1, AgileUse1, FightFlag1, IconPos1] = [Pet1#ets_pet.player_id, Pet1#ets_pet.forza_use, Pet1#ets_pet.wit_use, Pet1#ets_pet.agile_use, Pet1#ets_pet.fight_flag, Pet1#ets_pet.fight_icon_pos],
if % 被替换宠物不归你所有
PlayerId1 /= Status#player_status.id -> [7, 0, 0, 0, 0];
FightFlag1 == 0 -> [8, 0, 0, 0, 0];
true ->
case lib_pet:fighting_replace(PetId, ReplacedPetId, IconPos1) of
ok ->
[IntervalSync, _StrengthSync] = data_pet:get_pet_config(strength_sync, []),
NowTime = util:unixtime(),
% 更新缓存
PetNew = Pet#ets_pet{fight_flag = 1,
fight_icon_pos = IconPos1,
strength_nexttime = NowTime+IntervalSync},
lib_pet:update_pet(PetNew),
PetNew1 = Pet1#ets_pet{fight_flag = 0,
fight_icon_pos = 0,
strength_nexttime = 0},
lib_pet:update_pet(PetNew1),
[1, IconPos1, ForzaUse-ForzaUse1, WitUse-WitUse1, AgileUse-AgileUse1];
_ ->
[0, 0, 0, 0, 0]
end
end
end
end
end.
%% -----------------------------------------------------------------
%% 取消升级
%% -----------------------------------------------------------------
cancel_upgrade(Status, [PetId]) ->
?DEBUG("cancel_upgrade: PetId=[~p]", [PetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> 2;
true ->
[PlayerId, UpgradeFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.upgrade_flag],
该宠物不归你所有
PlayerId /= Status#player_status.id -> 3;
% 宠物不在升级
UpgradeFlag == 0 -> 4;
true ->
case lib_pet:cancel_upgrade(PetId) of
ok ->
% 更新缓存
PetNew = Pet#ets_pet{upgrade_flag = 0,
upgrade_endtime = 0},
lib_pet:update_pet(PetNew),
1;
_ -> 0
end
end
end.
%% -----------------------------------------------------------------
%% 体力值同步
%% -----------------------------------------------------------------
strength_sync(Status, []) ->
? DEBUG("strength_sync : PlayerId=[~p ] " , [ Status#player_status.id ] ) ,
FightingPet = lib_pet:get_fighting_pet(Status#player_status.id),
NowTime = util:unixtime(),
[RecordsNum, RecordsData, TotalForzaUse, TotalWitUse, TotalAgileUse] = lib_pet:strength_sync(FightingPet, NowTime, 0, <<>>, 0, 0, 0),
%?DEBUG("strength_sync: RecordsNum=[~p]", [RecordsNum]),
[1, RecordsNum, RecordsData, TotalForzaUse, TotalWitUse, TotalAgileUse]. | null | https://raw.githubusercontent.com/smallmelon/sdzmmo/254ff430481de474527c0e96202c63fb0d2c29d2/src/mod/mod_pet.erl | erlang | ------------------------------------
@Module : mod_pet
@Email :
@Description: 宠物处理
------------------------------------
=========================================================================
一些定义
=========================================================================
=========================================================================
接口函数
=========================================================================
=========================================================================
=========================================================================
=========================================================================
业务处理函数
=========================================================================
-----------------------------------------------------------------
宠物孵化
-----------------------------------------------------------------
该物品不存在
物品不归你所有
该物品不是宠物蛋
该物品类型信息不存在
你级别不够
宠物数已满
-----------------------------------------------------------------
宠物放生
-----------------------------------------------------------------
宠物正在升级
-----------------------------------------------------------------
宠物改名
-----------------------------------------------------------------
修改次数大于0要收钱
金币不够
更新缓存
修改次数等于0不收钱
更新缓存
-----------------------------------------------------------------
-----------------------------------------------------------------
宠物已经出战
出战宠物数达到上限
更新缓存
-----------------------------------------------------------------
宠物休息
-----------------------------------------------------------------
更新缓存
-----------------------------------------------------------------
属性洗练
-----------------------------------------------------------------
银两支付
金币不够
更新缓存
物品支付
物品不归你所有
更新缓存
-----------------------------------------------------------------
-----------------------------------------------------------------
宠物没有洗练过
保留原有基础属性
更新缓存
使用新基础属性
更新缓存
-----------------------------------------------------------------
宠物开始升级
-----------------------------------------------------------------
宠物已经在升级
宠物等级已经和玩家等级相等
宠物已升到最高级
宠物升级队列已满
更新缓存
-----------------------------------------------------------------
宠物升级加速
-----------------------------------------------------------------
宠物不在升级
金币不够
宠物不在升级
宠物还在升级
更新缓存
宠物升完级
更新缓存
其他情况
-----------------------------------------------------------------
宠物完成升级
-----------------------------------------------------------------
宠物不在升级
宠物还在升级
宠物升完级
更新缓存
-----------------------------------------------------------------
扩展升级队列
-----------------------------------------------------------------
已达到最大队列上限
金币不够
-----------------------------------------------------------------
-----------------------------------------------------------------
你已经死亡
宠物不归你所有
宠物体力值已满
物品不归你所有
该物品不是食物
食物品阶不够
体力值变化且影响了力智敏
更新缓存
体力值变化但不影响力智敏
更新缓存
出错
扣取物品失败
单个物品数量足够
扣取物品
体力值变化且影响力智敏
更新缓存
体力值有变化但不影响力智敏
更新缓存
出错
扣取物品失败
-----------------------------------------------------------------
宠物驯养
-----------------------------------------------------------------
物品不归你所有
该物品不是训练书
更新缓存
更新缓存
驯养敏捷
更新缓存
扣取物品失败
单个物品数量足够
扣取物品
更新缓存
更新缓存
驯养敏捷
更新缓存
扣取物品失败
-----------------------------------------------------------------
-----------------------------------------------------------------
宠物不归你所有
宠物已经是最高品
宠物正在升级
SuccessProbability = data_pet:get_pet_config(enhance_quality_probability,[Quality]),
物品不归你所有
级别不够
物品不是进化石
更新缓存
-----------------------------------------------------------------
获取宠物信息
-----------------------------------------------------------------
-----------------------------------------------------------------
获取宠物列表
-----------------------------------------------------------------
-----------------------------------------------------------------
宠物出战替换
-----------------------------------------------------------------
宠物已经出战
被替换宠物不存在
被替换宠物不归你所有
更新缓存
-----------------------------------------------------------------
取消升级
-----------------------------------------------------------------
宠物不在升级
更新缓存
-----------------------------------------------------------------
体力值同步
-----------------------------------------------------------------
?DEBUG("strength_sync: RecordsNum=[~p]", [RecordsNum]),
| @Author : shebiao
@Created : 2010.07.03
-module(mod_pet).
-behaviour(gen_server).
-include("common.hrl").
-include("record.hrl").
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-compile(export_all).
-record(state, {interval = 0}).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
stop() ->
gen_server:call(?MODULE, stop).
回调函数
init([]) ->
process_flag(trap_exit, true),
Timeout = 60000,
State = #state{interval = Timeout},
?DEBUG("init: loading base_pet....", []),
lib_pet:load_base_pet(),
{ok, State}.
handle_call(_Request, _From, State) ->
{reply, State, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
incubate_pet(Status, [GoodsId, GoodsUseNum]) ->
?DEBUG("incubate_pet: GoodsId=[~p], GoodsUseNum=[~p]", [GoodsId, GoodsUseNum]),
Goods = lib_pet:get_goods(GoodsId),
Goods =:= [] -> [2, 0, <<>>];
true ->
[EggGoodsType, EggGoodsSubType] = data_pet:get_pet_config(egg_goods_type,[]),
[GoodsPlayerId, GoodsTypeId, GoodsType, GoodsSubtype, GoodsNum, _GoodsCell, GoodsLevel] =
[Goods#goods.player_id, Goods#goods.goods_id, Goods#goods.type, Goods#goods.subtype, Goods#goods.num, Goods#goods.cell, Goods#goods.level],
GoodsPlayerId /= Status#player_status.id -> [3, 0, <<>>];
((GoodsType /= EggGoodsType) and (GoodsSubtype /= EggGoodsSubType)) -> [4, 0, <<>>];
GoodsNum < GoodsUseNum -> [5, 0, <<>>];
true ->
GoodsTypeInfo = lib_pet:get_goods_type(GoodsTypeId),
GoodsTypeInfo =:= [] ->
?ERR("incubate_pet: Goods type not in cache, type_id=[~p]", [GoodsTypeId]),
[0, 0, <<>>];
true ->
Status#player_status.lv < GoodsLevel -> [6, 0, <<>>];
true ->
PetCount = lib_pet:get_pet_count(Status#player_status.id),
PetCapacity = data_pet:get_pet_config(capacity,[]),
PetCount >= PetCapacity -> [7, 0, <<>>];
true ->
case gen_server:call(Status#player_status.goods_pid, {'delete_one', GoodsId, GoodsUseNum}) of
[1, _GoodsNumNew] ->
case lib_pet:incubate_pet(Status#player_status.id, GoodsTypeInfo) of
[ok, PetId, PetName] ->
[1, PetId, PetName];
_ ->
[0, 0, <<>>]
end;
[GoodsModuleCode, 0] ->
?DEBUG("incubate_pet: Call goods module faild, result code=[~p]", [GoodsModuleCode]),
[0, 0, <<>>]
end
end
end
end
end
end.
free_pet(Status, [PetId]) ->
?DEBUG("free_pet: PetId=[~p]", [PetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> 2;
true ->
[PlayerId, UpgradeFlag, FightFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.upgrade_flag, Pet#ets_pet.fight_flag],
该宠物不归你所有
PlayerId /= Status#player_status.id -> 3;
UpgradeFlag == 1 -> 4;
宠物正在出战
FightFlag == 1 -> 5;
true ->
case lib_pet:free_pet(PetId) of
ok -> 1;
_ -> 0
end
end
end.
rename_pet(Status, [PetId, PetName]) ->
?DEBUG("rename_pet: PetId=[~p], PetName=[~s]", [PetId, PetName]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0];
true ->
[PlayerId, Name, RenameCount] = [Pet#ets_pet.player_id, Pet#ets_pet.name, Pet#ets_pet.rename_count],
NewName = lib_pet:make_sure_binary(PetName),
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0];
新旧名称相同
Name =:= NewName -> [4, 0, 0];
true ->
RenameCount > 0 ->
RenameMoney = data_pet:get_rename_money(RenameCount),
Status#player_status.gold < RenameMoney -> [5, 0, 0];
true ->
case lib_pet:rename_pet(PetId, NewName, Status#player_status.id, RenameMoney) of
ok ->
PetNew = Pet#ets_pet{
rename_count = RenameCount+1,
name = NewName},
lib_pet:update_pet(PetNew),
[1, 1, Status#player_status.gold-RenameMoney];
_ -> [0, 0, 0]
end
end;
true ->
case lib_pet:rename_pet(PetId, PetName, Status#player_status.id, 0) of
ok ->
PetNew = Pet#ets_pet{
rename_count = RenameCount+1,
name = NewName},
lib_pet:update_pet(PetNew),
[1, 0, Status#player_status.gold];
_ ->
[0, 0, 0]
end
end
end
end.
宠物出战
fighting_pet(Status, [PetId, FightIconPos]) ->
?DEBUG("fighting_pet: PetId=[~p], FightIconPos=[~p]", [PetId, FightIconPos]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0];
true ->
[PlayerId, ForzaUse, WitUse, AgileUse, FightFlag, Strength] = [Pet#ets_pet.player_id, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.fight_flag, Pet#ets_pet.strength],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0];
FightFlag == 1 -> [4, 0, 0, 0, 0];
体力值为0
Strength == 0 -> [5, 0, 0, 0, 0];
true ->
MaxFighting = data_pet:get_pet_config(maxinum_fighting,[]),
FightingPet = lib_pet:get_fighting_pet(PlayerId),
length(FightingPet) >= MaxFighting -> [6, 0, 0, 0, 0];
true ->
case lib_pet:fighting_pet(PetId, FightingPet, FightIconPos) of
[ok, IconPos] ->
[IntervalSync, _StrengthSync] = data_pet:get_pet_config(strength_sync, []),
NowTime = util:unixtime(),
PetNew = Pet#ets_pet{fight_flag = 1,
fight_icon_pos = IconPos,
strength_nexttime = NowTime+IntervalSync},
lib_pet:update_pet(PetNew),
[1, IconPos, ForzaUse, WitUse, AgileUse];
_ ->
[0, 0, 0, 0, 0]
end
end
end
end.
rest_pet(Status, [PetId]) ->
?DEBUG("rest_pet: PetId=[~p]", [PetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0];
true ->
[PlayerId, ForzaUse, WitUse, AgileUse, FightFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.fight_flag],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0];
宠物已经休息
FightFlag == 0 -> [4, 0, 0, 0];
true ->
case lib_pet:rest_pet(PetId) of
ok ->
PetNew = Pet#ets_pet{fight_flag = 0,
fight_icon_pos = 0,
strength_nexttime = 0},
lib_pet:update_pet(PetNew),
[1, ForzaUse, WitUse, AgileUse];
_ ->
[0, 0, 0, 0]
end
end
end.
shuffle_attribute(Status, [PetId, PayType, GoodsId, GoodsUseNum]) ->
?DEBUG("shuffle_attribute: PetId=[~p], PayType=[~p], GoodsId=[~p], GoodsUseNum=[~p]", [PetId, PayType,GoodsId, GoodsUseNum]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0];
true ->
[PlayerId, ShuffleCount, FightFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.attribute_shuffle_count, Pet#ets_pet.fight_flag],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0];
宠物正在战斗
FightFlag == 1 -> [4, 0, 0, 0, 0];
true ->
case PayType of
0 ->
ShuffleMoney = data_pet:get_pet_config(shuffle_money,[]),
Status#player_status.gold < ShuffleMoney -> [5, 0, 0, 0, 0];
true ->
case lib_pet:shuffle_attribute(Status#player_status.id, PetId, PayType, ShuffleCount, GoodsId, Status#player_status.gold, ShuffleMoney) of
[ok, BaseForzaNew, BaseWitNew, BaseAgileNew] ->
PetNew = Pet#ets_pet{
base_forza_new = BaseForzaNew,
base_wit_new = BaseWitNew,
base_agile_new = BaseAgileNew,
attribute_shuffle_count = ShuffleCount+1},
lib_pet:update_pet(PetNew),
[1, BaseForzaNew, BaseWitNew, BaseAgileNew, Status#player_status.gold-ShuffleMoney];
_ ->
[0, 0, 0, 0, 0]
end
end;
1 ->
Goods = lib_pet:get_goods(GoodsId),
Goods =:= [] -> [6, 0, 0, 0, 0];
true ->
[GoodsPlayerId, _GoodsTypeId, GoodsType, GoodsSubtype, GoodsNum, _GoodsCell] =
[Goods#goods.player_id, Goods#goods.goods_id, Goods#goods.type, Goods#goods.subtype, Goods#goods.num, Goods#goods.cell],
[ShuffleGoodsType, ShuffleGoodsSubType] = data_pet:get_pet_config(attribute_shuffle_goods_type,[]),
GoodsPlayerId /= Status#player_status.id -> [7, 0, 0, 0, 0];
该物品不是洗练药水
((GoodsType /= ShuffleGoodsType) and (GoodsSubtype /= ShuffleGoodsSubType)) -> [8, 0, 0, 0, 0];
GoodsNum < GoodsUseNum -> [9, 0, 0, 0, 0];
true ->
case gen_server:call(Status#player_status.goods_pid, {'delete_one', GoodsId, GoodsUseNum}) of
[1, _GoodsNumNew] ->
case lib_pet:shuffle_attribute(Status#player_status.id, PetId, PayType, ShuffleCount, GoodsId, GoodsNum, GoodsUseNum) of
[ok, BaseForzaNew, BaseWitNew, BaseAgileNew] ->
PetNew = Pet#ets_pet{base_forza_new = BaseForzaNew,
base_wit_new = BaseWitNew,
base_agile_new = BaseAgileNew,
attribute_shuffle_count = ShuffleCount+1},
lib_pet:update_pet(PetNew),
[1, BaseForzaNew, BaseWitNew, BaseAgileNew, Status#player_status.gold];
_ ->
[0, 0, 0, 0, 0]
end;
[GoodsModuleCode, 0] ->
?DEBUG("shuffle_attribute: Call goods module faild, result code=[~p]", [GoodsModuleCode]),
[0, 0, 0, 0, 0]
end
end
end;
支付类型未知
_ ->
?ERR("shuffle_attribute: Unknow pay type, type=[~p]", [PayType]),
[0, 0, 0, 0, 0]
end
end
end.
洗练属性使用
use_attribute(Status, [PetId, ActionType]) ->
?DEBUG("use_attribute: PetId=[~p], ActionType=[~p]", [PetId, ActionType]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0, 0, 0];
true ->
[PlayerId, Level, Strength, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, BaseForzaNew, BaseWitNew, BaseAgileNew, FightFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile, Pet#ets_pet.base_forza_new, Pet#ets_pet.base_wit_new, Pet#ets_pet.base_agile_new, Pet#ets_pet.fight_flag],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0, 0, 0];
宠物正在战斗
FightFlag == 1 -> [4, 0, 0, 0, 0, 0, 0];
((BaseForzaNew==0) and (BaseWitNew==0) and (BaseAgileNew==0)) -> [5, 0, 0, 0, 0, 0, 0];
true ->
case ActionType of
0 ->
case lib_pet:use_attribute(PetId, BaseForza, BaseWit, BaseAgile, AptitudeForza, AptitudeWit, AptitudeAgile, Level, Strength) of
[ok, _NewForza, _NewWit, _NewAgile, _NewForzaUse, _NewWitUse, _NewAgileUse] ->
PetNew = Pet#ets_pet{base_forza_new = 0,
base_wit_new = 0,
base_agile_new = 0},
lib_pet:update_pet(PetNew),
[1, Forza, Wit, Agile, 0, 0, 0];
_ ->
[0, 0, 0, 0, 0, 0, 0]
end;
1 ->
case lib_pet:use_attribute(PetId, BaseForzaNew, BaseWitNew, BaseAgileNew, AptitudeForza, AptitudeWit, AptitudeAgile, Level, Strength) of
[ok, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] ->
PetNew = Pet#ets_pet{forza = NewForza,
wit = NewWit,
agile = NewAgile,
forza_use = NewForzaUse,
wit_use = NewWitUse,
agile_use = NewAgileUse,
base_forza = BaseForzaNew,
base_wit = BaseWitNew,
base_agile = BaseAgileNew,
base_forza_new = 0,
base_wit_new = 0,
base_agile_new = 0},
lib_pet:update_pet(PetNew),
[1, NewForza, NewWit, NewAgile, NewForzaUse-ForzaUse, NewWitUse-WitUse, NewAgileUse-AgileUse];
_ ->
[0, 0, 0, 0, 0, 0, 0]
end;
_ ->
?ERR("use_attribute: Unknow action type, type=[~p]", [ActionType]),
[0, 0, 0, 0, 0, 0, 0]
end
end
end.
start_upgrade(Status, [PetId]) ->
?DEBUG("start_upgrade, PetId=[~p]", [PetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0];
true ->
[PlayerId, Level, Quality, UpgradeFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.quality, Pet#ets_pet.upgrade_flag],
MaxLevel = data_pet:get_pet_config(maxinum_level, []),
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0];
UpgradeFlag == 1 -> [4, 0, 0];
Level == Status#player_status.lv -> [5, 0, 0];
Level >= MaxLevel -> [6, 0, 0];
true ->
QueNum = Status#player_status.pet_upgrade_que_num,
UpgradingPet = lib_pet:get_upgrading_pet(PlayerId),
length(UpgradingPet) >= QueNum -> [7, 0, 0];
true ->
[UpgradeMoney, UpgradeTime] = data_pet:get_upgrade_info(Quality, Level),
铜币不够
Status#player_status.coin < UpgradeMoney -> [8, 0, 0];
true ->
NowTime = util:unixtime(),
UpgradeEndTime = NowTime+UpgradeTime,
case lib_pet:pet_start_upgrade(Status#player_status.id, PetId, UpgradeEndTime, UpgradeMoney) of
ok ->
PetNew = Pet#ets_pet{upgrade_flag = 1,
upgrade_endtime = UpgradeEndTime},
lib_pet:update_pet(PetNew),
[1, UpgradeTime, Status#player_status.coin-UpgradeMoney];
_ -> [0, 0, 0]
end
end
end
end
end.
shorten_upgrade(Status, [PetId, ShortenTime]) ->
?DEBUG("shorten_upgrade, PetId=[~p], ShortenTime=[~p]", [PetId, ShortenTime]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0, 0, 0, 0, 0, 0];
true ->
[PlayerId, Level, Strength, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeFlag, UpgradeEndTime] =
[Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile, Pet#ets_pet.upgrade_flag, Pet#ets_pet.upgrade_endtime],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0, 0, 0, 0, 0, 0];
UpgradeFlag == 0 -> [4, 0, 0, 0, 0, 0, 0, 0, 0, 0];
true ->
ShortenMoney = lib_pet:calc_shorten_money(ShortenTime),
Status#player_status.gold < ShortenMoney -> [5, 0, 0, 0, 0, 0, 0, 0, 0, 0];
true ->
UpgradeEndTimeNew = UpgradeEndTime-ShortenTime,
MoneyLeft = Status#player_status.gold-ShortenMoney,
case lib_pet:check_upgrade_state(Status#player_status.id, PetId, Level, Strength, UpgradeFlag, UpgradeEndTimeNew, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, ShortenMoney) of
[0, _UpgradeLeftTime] ->
[4, 0, 0, 0, 0, 0, 0, 0, 0, 0];
[1, UpgradeLeftTime] ->
case lib_pet:shorten_upgrade(Status#player_status.id, PetId, UpgradeEndTimeNew, ShortenMoney) of
ok ->
PetNew = Pet#ets_pet{upgrade_flag = 1,
upgrade_endtime = UpgradeEndTimeNew},
lib_pet:update_pet(PetNew),
[1, Level, Forza, Wit, Agile, 0, 0, 0, UpgradeLeftTime, MoneyLeft];
_ ->
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
end;
[2, UpgradeLeftTime, NewLevel, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] ->
PetNew = Pet#ets_pet{upgrade_flag = 0,
upgrade_endtime = 0,
level = NewLevel,
forza = NewForza,
wit = NewWit,
agile = NewAgile,
forza_use = NewForzaUse,
wit_use = NewWitUse,
agile_use = NewAgileUse
},
lib_pet:update_pet(PetNew),
[1, NewLevel, NewForza, NewWit, NewAgile, NewForzaUse-ForzaUse, NewWitUse-WitUse, NewAgileUse-AgileUse, UpgradeLeftTime, MoneyLeft];
_ -> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
end
end
end
end.
finish_upgrade(Status, [PetId]) ->
?DEBUG("finish_upgrade, PetId=[~p]", [PetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0, 0, 0, 0];
true ->
[PlayerId, Level, Strength, _Forza, _Wit, _Agile, ForzaUse, WitUse, AgileUse, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, UpgradeFlag, UpgradeEndTime] =
[Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile, Pet#ets_pet.upgrade_flag, Pet#ets_pet.upgrade_endtime],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0, 0, 0, 0];
true ->
case lib_pet:check_upgrade_state(Status#player_status.id, PetId, Level, Strength, UpgradeFlag, UpgradeEndTime, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile, 0) of
[0, _UpgradeLeftTime] -> [4, 0, 0, 0, 0, 0, 0, 0];
[1, _UpgradeLeftTime] -> [5, 0, 0, 0, 0, 0, 0, 0];
[2, _UpgradeLeftTime, NewLevel, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] ->
?DEBUG("finish_upgrade: NewLevel=[~p], NewForza=[~p], NewWit=[~p], NewAgile=[~p], NewForzaUse=[~p], NewWitUse=[~p], NewAgileUse=[~p], ForzaUse=[~p], WitUse=[~p], AgileUse=[~p]", [NewLevel, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse, ForzaUse, WitUse, AgileUse]),
PetNew = Pet#ets_pet{upgrade_flag = 0,
upgrade_endtime = 0,
level = NewLevel,
forza = NewForza,
wit = NewWit,
agile = NewAgile,
forza_use = NewForzaUse,
wit_use = NewWitUse,
agile_use = NewAgileUse
},
lib_pet:update_pet(PetNew),
[1, NewLevel, NewForza, NewWit, NewAgile, NewForzaUse-ForzaUse, NewWitUse-WitUse, NewAgileUse-AgileUse];
_ -> [0, 0, 0, 0, 0, 0, 0, 0]
end
end
end.
extent_upgrade_que(Status, []) ->
MaxQueNum = data_pet:get_pet_config(maxinum_que_num, []),
QueNum = Status#player_status.pet_upgrade_que_num,
?DEBUG("extent_upgrade_que: MaxQueNum=[~p], QueNum=[~p]", [MaxQueNum, QueNum]),
QueNum >= MaxQueNum -> [2, 0, 0];
true ->
NewQueNum = QueNum+1,
ExtentQueMoney = data_pet:get_pet_config(extent_que_money, [NewQueNum]),
Status#player_status.gold < ExtentQueMoney -> [3, 0, 0];
true ->
case lib_pet:extent_upgrade_que(Status#player_status.id, NewQueNum, ExtentQueMoney) of
ok -> [1, NewQueNum, Status#player_status.gold-ExtentQueMoney];
_ -> [0, 0, 0]
end
end
end.
feed_pet(Status, [PetId, GoodsId, GoodsUseNum]) ->
?DEBUG("feed_pet, PetId=[~p], GoodsId=[~p], GoodsUseNum=[~p]", [PetId, GoodsId, GoodsUseNum]),
Status#player_status.hp =< 0 -> [2, 0, 0, 0, 0, 0, 0, 0];
true ->
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [3, 0, 0, 0, 0, 0, 0, 0];
true ->
[PlayerId, Level, PetStrength, PetStrengThreshold, PetQuality, Forza, Wit, Agile, ForzaUse, WitUse, AgileUse, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile] =
[Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.strength_threshold, Pet#ets_pet.quality, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile],
PlayerId /= Status#player_status.id -> [4, 0, 0, 0, 0, 0, 0, 0];
PetStrength == PetStrengThreshold -> [5, 0, 0, 0, 0, 0, 0, 0];
true ->
Goods = lib_pet:get_goods(GoodsId),
Goods =:= [] -> [6, 0, 0, 0, 0, 0, 0, 0];
true ->
[FoodGoodsType, FoodGoodsSubType] = data_pet:get_pet_config(food_goods_type,[]),
[GoodsPlayerId, GoodsTypeId, GoodsType, GoodsSubtype, GoodsNum, _GoodsCell, GoodsColor] =
[Goods#goods.player_id, Goods#goods.goods_id, Goods#goods.type, Goods#goods.subtype, Goods#goods.num, Goods#goods.cell, Goods#goods.color],
GoodsPlayerId /= Status#player_status.id -> [7, 0, 0, 0, 0, 0, 0, 0];
((GoodsType /= FoodGoodsType) and (GoodsSubtype /= FoodGoodsSubType)) -> [8, 0, 0, 0, 0, 0, 0, 0];
GoodsColor < PetQuality -> [10, 0, 0, 0, 0, 0, 0, 0];
true ->
单个物品数量不够
GoodsNum < GoodsUseNum ->
试图扣取多个格子物品
case gen_server:call(Status#player_status.goods_pid, {'delete_more', GoodsTypeId, GoodsUseNum}) of
1 ->
case lib_pet:feed_pet(PetId, PetQuality, GoodsColor, GoodsUseNum, PetStrength, PetStrengThreshold, Level, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile) of
[ok, NewStrength, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] ->
PetNew = Pet#ets_pet{strength = NewStrength,
forza = NewForza,
wit = NewWit,
agile = NewAgile,
forza_use = NewForzaUse,
wit_use = NewWitUse,
agile_use = NewAgileUse
},
lib_pet:update_pet(PetNew),
[1, NewStrength, NewForza, NewWit, NewAgile, NewForzaUse-ForzaUse, NewWitUse-WitUse, NewAgileUse-AgileUse];
[ok, NewStrength] ->
PetNew = Pet#ets_pet{strength = NewStrength
},
lib_pet:update_pet(PetNew),
[1, NewStrength, Forza, Wit, Agile, 0, 0, 0];
_ -> [0, 0, 0, 0, 0, 0, 0, 0]
end;
0 ->
?DEBUG("feed_pet: Call goods module faild", []),
[0, 0, 0, 0, 0, 0, 0, 0];
_ ->
[9, 0, 0, 0, 0, 0, 0, 0]
end;
true ->
case gen_server:call(Status#player_status.goods_pid, {'delete_one', GoodsId, GoodsUseNum}) of
扣取物品成功
[1, _GoodsNumNew] ->
case lib_pet:feed_pet(PetId, PetQuality, GoodsColor, GoodsUseNum, PetStrength, PetStrengThreshold, Level, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile) of
[ok, NewStrength, NewForza, NewWit, NewAgile, NewForzaUse, NewWitUse, NewAgileUse] ->
PetNew = Pet#ets_pet{strength = NewStrength,
forza = NewForza,
wit = NewWit,
agile = NewAgile,
forza_use = NewForzaUse,
wit_use = NewWitUse,
agile_use = NewAgileUse
},
lib_pet:update_pet(PetNew),
[1, NewStrength, NewForza, NewWit, NewAgile, NewForzaUse-ForzaUse, NewWitUse-WitUse, NewAgileUse-AgileUse];
[ok, NewStrength] ->
PetNew = Pet#ets_pet{strength = NewStrength},
lib_pet:update_pet(PetNew),
[1, NewStrength, Forza, Wit, Agile, 0, 0, 0];
_ -> [0, 0, 0, 0, 0, 0, 0, 0]
end;
[GoodsModuleCode, 0] ->
?DEBUG("feed_pet: Call goods module faild, result code=[~p]", [GoodsModuleCode]),
[0, 0, 0, 0, 0, 0, 0, 0]
end
end
end
end
end
end
end.
domesticate_pet(Status, [PetId, DomesticateType, GoodsId, GoodsUseNum]) ->
?DEBUG("domesticate_pet, PetId=[~p], DomesticateType=[~p], GoodsId=[~p], GoodsUseNum=[~p]", [PetId, DomesticateType, GoodsId, GoodsUseNum]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0, 0];
true ->
[PlayerId, Level, Strength, Quality, _Forza, _Wit, _Agile, ForzaUse, WitUse, AgileUse, AptitudeForza, AptitudeWit, AptitudeAgile, BaseForza, BaseWit, BaseAgile] =
[Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.strength, Pet#ets_pet.quality, Pet#ets_pet.forza, Pet#ets_pet.wit, Pet#ets_pet.agile, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.aptitude_forza, Pet#ets_pet.aptitude_wit, Pet#ets_pet.aptitude_agile, Pet#ets_pet.base_forza, Pet#ets_pet.base_wit, Pet#ets_pet.base_agile],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0, 0];
true ->
Goods = lib_pet:get_goods(GoodsId),
Goods =:= [] -> [4, 0, 0, 0, 0, 0];
true ->
[GoodsPlayerId, GoodsTypeId, GoodsType, GoodsSubtype, GoodsNum, _GoodsCell, GoodsForza, GoodsWit, GoodsAgile] =
[Goods#goods.player_id, Goods#goods.goods_id, Goods#goods.type, Goods#goods.subtype, Goods#goods.num, Goods#goods.cell, Goods#goods.forza, Goods#goods.wit, Goods#goods.agile],
[BookGoodsType, BookGoodsSubType] = data_pet:get_pet_config(attribute_book_goods_type,[]),
GoodsPlayerId /= Status#player_status.id -> [5, 0, 0, 0, 0, 0];
((GoodsType /= BookGoodsType) and (GoodsSubtype /= BookGoodsSubType)) -> [7, 0, 0, 0, 0, 0];
true ->
AptitudeThreshold = data_pet:get_pet_config(aptitude_threshold,[Quality]),
单个物品数量不够
GoodsNum < GoodsUseNum ->
试图扣取多个格子物品
case gen_server:call(Status#player_status.goods_pid, {'delete_more', GoodsTypeId, GoodsUseNum}) of
1 ->
case DomesticateType of
0 ->
资质已经满
AptitudeForza >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeForza+GoodsUseNum*GoodsForza, AptitudeThreshold, BaseForza) of
[ok, AptitudeForzaNew, ForzaNew, ForzaUseNew] ->
PetNew = Pet#ets_pet{aptitude_forza = AptitudeForzaNew,
forza = ForzaNew,
forza_use = ForzaUseNew
},
lib_pet:update_pet(PetNew),
[1, AptitudeForzaNew, ForzaNew, ForzaUseNew-ForzaUse, 0, 0];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
驯养智力
1 ->
资质已经满
AptitudeWit >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeWit+GoodsUseNum*GoodsWit, AptitudeThreshold, BaseWit) of
[ok, AptitudeWitNew, WitNew, WitUseNew] ->
PetNew = Pet#ets_pet{aptitude_wit = AptitudeWitNew,
wit = WitNew,
wit_use = WitUseNew
},
lib_pet:update_pet(PetNew),
[1, AptitudeWitNew, WitNew, 0, WitUseNew-WitUse, 0];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
2 ->
资质已经满
AptitudeAgile >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeAgile+GoodsUseNum*GoodsAgile, AptitudeThreshold, BaseAgile) of
[ok, AptitudeAgileNew, AgileNew, AgileUseNew] ->
PetNew = Pet#ets_pet{aptitude_agile = AptitudeAgileNew,
agile = AgileNew,
agile_use = AgileUseNew
},
lib_pet:update_pet(PetNew),
[1, AptitudeAgileNew, AgileNew, 0, 0, AgileUseNew-AgileUse];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
_ ->
?ERR("domesticate_pet: Unknow domesticate type, type=[~p]", [DomesticateType]),
[0, 0, 0, 0, 0, 0]
end;
0 ->
?DEBUG("domesticate_pet: Call goods module faild", []),
[0, 0, 0, 0, 0, 0];
_ ->
[6, 0, 0, 0, 0, 0]
end;
true ->
case gen_server:call(Status#player_status.goods_pid, {'delete_one', GoodsId, GoodsUseNum}) of
扣取物品成功
[1, _GoodsNumNew] ->
case DomesticateType of
0 ->
资质已经满
AptitudeForza >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeForza+GoodsUseNum*GoodsForza, AptitudeThreshold, BaseForza) of
[ok, AptitudeForzaNew, ForzaNew, ForzaUseNew] ->
PetNew = Pet#ets_pet{aptitude_forza = AptitudeForzaNew,
forza = ForzaNew,
forza_use = ForzaUseNew},
lib_pet:update_pet(PetNew),
[1, AptitudeForzaNew, ForzaNew, ForzaUseNew-ForzaUse, 0, 0];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
驯养智力
1 ->
资质已经满
AptitudeWit >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeWit+GoodsUseNum*GoodsWit, AptitudeThreshold, BaseWit) of
[ok, AptitudeWitNew, WitNew, WitUseNew] ->
PetNew = Pet#ets_pet{aptitude_wit = AptitudeWitNew,
wit = WitNew,
wit_use = WitUseNew},
lib_pet:update_pet(PetNew),
[1, AptitudeWitNew, WitNew, 0, WitUseNew-WitUse, 0];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
2 ->
资质已经满
AptitudeAgile >= AptitudeThreshold -> [8, 0, 0, 0, 0, 0];
true ->
case lib_pet:domesticate_pet(PetId, DomesticateType, Level, Strength, AptitudeAgile+GoodsUseNum*GoodsAgile, AptitudeThreshold, BaseAgile) of
[ok, AptitudeAgileNew, AgileNew, AgileUseNew] ->
PetNew = Pet#ets_pet{aptitude_agile = AptitudeAgileNew,
agile = AgileNew,
agile_use = AgileUseNew},
lib_pet:update_pet(PetNew),
[1, AptitudeAgileNew, AgileNew, 0, 0, AgileUseNew-AgileUse];
_ -> [0, 0, 0, 0, 0, 0]
end
end;
_ ->
?ERR("domesticate_pet: Unknow domesticate type, type=[~p]", [DomesticateType]),
[0, 0, 0, 0, 0, 0]
end;
[GoodsModuleCode, 0] ->
?DEBUG("domesticate_pet: Call goods module faild, result code=[~p]", [GoodsModuleCode]),
[0, 0, 0, 0, 0, 0]
end
end
end
end
end
end.
宠物进阶
enhance_quality(Status, [PetId, GoodsId, GoodsUseNum]) ->
?DEBUG("enhance_quality: PetId=[~p], GoodsId=[~p], GoodsUseNum=[~p]", [PetId, GoodsId, GoodsUseNum]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0];
true ->
[PlayerId, Level, Quality, UpgradeFlag, FightFlag] =
[Pet#ets_pet.player_id, Pet#ets_pet.level, Pet#ets_pet.quality, Pet#ets_pet.upgrade_flag, Pet#ets_pet.fight_flag],
MaxQuality = data_pet:get_pet_config(maxinum_quality,[]),
PlayerId /= Status#player_status.id -> [3, 0, 0, 0];
Quality >= MaxQuality -> [4, 0, 0, 0];
UpgradeFlag == 1 -> [5, 0, 0, 0];
宠物正在出战
FightFlag == 1 -> [6, 0, 0, 0];
true ->
BasePet = lib_pet:get_base_pet(GoodsId),
SuccessProbability = case BasePet of
[] -> ?ERR("enhance_quality: Not find the base_pet, goods_id=[~p]", [GoodsId]),
100;
_ -> BasePet#ets_base_pet.probability
end,
Goods = lib_pet:get_goods(GoodsId),
Goods =:= [] -> [8, 0, 0, 0];
true ->
[GoodsPlayerId, _GoodsTypeId, GoodsType, GoodsSubtype, GoodsNum, _GoodsCell, GoodsColor, GoodsLevel] =
[Goods#goods.player_id, Goods#goods.goods_id, Goods#goods.type, Goods#goods.subtype, Goods#goods.num, Goods#goods.cell, Goods#goods.color, Goods#goods.level],
[StoneGoodsType, StoneGoodsSubType] = data_pet:get_pet_config(quality_stone_goods_type, []),
GoodsPlayerId /= Status#player_status.id -> [9, 0, 0, 0];
GoodsNum < GoodsUseNum -> [10, 0, 0, 0];
Level < GoodsLevel -> [7, 0, 0, 0];
((GoodsType /=StoneGoodsType) and (GoodsSubtype /=StoneGoodsSubType)) -> [11, 0, 0, 0];
true ->
品阶不对
Quality > GoodsColor -> [12, 0, 0, 0];
true ->
case gen_server:call(Status#player_status.goods_pid, {'delete_one', GoodsId, GoodsUseNum}) of
[1, _GoodsNumNew] ->
case lib_pet:enhance_quality(PetId, Quality, SuccessProbability) of
[ok, EvolutionResult, QualityNew, AptitudeThresholdNew] ->
PetNew = Pet#ets_pet{level = 1,
quality = QualityNew,
aptitude_threshold = AptitudeThresholdNew},
lib_pet:update_pet(PetNew),
[1, EvolutionResult, QualityNew, AptitudeThresholdNew];
_ ->
[0, 0, 0, 0]
end;
[GoodsModuleCode, 0] ->
?DEBUG("enhance_quality: Call goods module faild, result code=[~p]", [GoodsModuleCode]),
[0, 0, 0, 0]
end
end
end
end
end
end.
get_pet_info(_Status, [PetId]) ->
?DEBUG("get_pet_info, PetId=[~p]", [PetId]),
lib_pet:get_pet_info(PetId).
get_pet_list(_Status, [PlayerId]) ->
?DEBUG("get_pet_list, PlayerId=[~p]", [PlayerId]),
lib_pet:get_pet_list(PlayerId).
fighting_replace(Status, [PetId, ReplacedPetId]) ->
?DEBUG("fighting_pet: PetId=[~p], ReplacedPet=[~p]", [PetId, ReplacedPetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> [2, 0, 0, 0, 0];
true ->
[PlayerId, ForzaUse, WitUse, AgileUse, FightFlag, Strength] = [Pet#ets_pet.player_id, Pet#ets_pet.forza_use, Pet#ets_pet.wit_use, Pet#ets_pet.agile_use, Pet#ets_pet.fight_flag, Pet#ets_pet.strength],
该宠物不归你所有
PlayerId /= Status#player_status.id -> [3, 0, 0, 0, 0];
FightFlag == 1 -> [4, 0, 0, 0, 0];
体力值为0
Strength == 0 -> [5, 0, 0, 0, 0];
true ->
Pet1 = lib_pet:get_pet(ReplacedPetId),
Pet1 =:= [] -> [6, 0, 0, 0, 0];
true ->
[PlayerId1, ForzaUse1, WitUse1, AgileUse1, FightFlag1, IconPos1] = [Pet1#ets_pet.player_id, Pet1#ets_pet.forza_use, Pet1#ets_pet.wit_use, Pet1#ets_pet.agile_use, Pet1#ets_pet.fight_flag, Pet1#ets_pet.fight_icon_pos],
PlayerId1 /= Status#player_status.id -> [7, 0, 0, 0, 0];
FightFlag1 == 0 -> [8, 0, 0, 0, 0];
true ->
case lib_pet:fighting_replace(PetId, ReplacedPetId, IconPos1) of
ok ->
[IntervalSync, _StrengthSync] = data_pet:get_pet_config(strength_sync, []),
NowTime = util:unixtime(),
PetNew = Pet#ets_pet{fight_flag = 1,
fight_icon_pos = IconPos1,
strength_nexttime = NowTime+IntervalSync},
lib_pet:update_pet(PetNew),
PetNew1 = Pet1#ets_pet{fight_flag = 0,
fight_icon_pos = 0,
strength_nexttime = 0},
lib_pet:update_pet(PetNew1),
[1, IconPos1, ForzaUse-ForzaUse1, WitUse-WitUse1, AgileUse-AgileUse1];
_ ->
[0, 0, 0, 0, 0]
end
end
end
end
end.
cancel_upgrade(Status, [PetId]) ->
?DEBUG("cancel_upgrade: PetId=[~p]", [PetId]),
Pet = lib_pet:get_pet(PetId),
宠物不存在
Pet =:= [] -> 2;
true ->
[PlayerId, UpgradeFlag] = [Pet#ets_pet.player_id, Pet#ets_pet.upgrade_flag],
该宠物不归你所有
PlayerId /= Status#player_status.id -> 3;
UpgradeFlag == 0 -> 4;
true ->
case lib_pet:cancel_upgrade(PetId) of
ok ->
PetNew = Pet#ets_pet{upgrade_flag = 0,
upgrade_endtime = 0},
lib_pet:update_pet(PetNew),
1;
_ -> 0
end
end
end.
strength_sync(Status, []) ->
? DEBUG("strength_sync : PlayerId=[~p ] " , [ Status#player_status.id ] ) ,
FightingPet = lib_pet:get_fighting_pet(Status#player_status.id),
NowTime = util:unixtime(),
[RecordsNum, RecordsData, TotalForzaUse, TotalWitUse, TotalAgileUse] = lib_pet:strength_sync(FightingPet, NowTime, 0, <<>>, 0, 0, 0),
[1, RecordsNum, RecordsData, TotalForzaUse, TotalWitUse, TotalAgileUse]. |
72f0070bfcca229598f200139cbe955592ab3582fa92e6616e9212f0b28b4e6b | elastic/eui-cljs | icon_trash.cljs | (ns eui.icon-trash
(:require ["@elastic/eui/lib/components/icon/assets/trash.js" :as eui]))
(def trash eui/icon)
| null | https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/icon_trash.cljs | clojure | (ns eui.icon-trash
(:require ["@elastic/eui/lib/components/icon/assets/trash.js" :as eui]))
(def trash eui/icon)
|
|
e86f2f0aeed8db398237df50c9266f0465521c58770678a5d1f2af5e3b9cf6ff | lehitoskin/ivy | main.rkt | #!/usr/bin/env racket
#lang racket/base
; main.rkt
; main file for ivy, the taggable image viewer
(require racket/class
racket/cmdline
racket/gui/base
racket/list
racket/path
riff
txexpr
xml
"base.rkt"
"config.rkt"
"db.rkt"
"embed.rkt"
"error-log.rkt"
(only-in "files.rkt" ivy-version)
"frame.rkt"
"meta-editor.rkt"
"thumbnails.rkt")
(define show-frame? (make-parameter #t))
(define tags-to-search (make-parameter empty))
(define search-type (make-parameter #f))
(define tags-to-exclude (make-parameter empty))
(define excluding? (make-parameter #f))
(define null-flag (make-parameter #f))
(define verbose? (make-parameter #f))
(define list-tags? (make-parameter #f))
(define add-tags? (make-parameter #f))
(define tags-to-add (make-parameter empty))
(define delete-tags? (make-parameter #f))
(define tags-to-delete (make-parameter empty))
(define set-tags? (make-parameter #f))
(define tags-to-set (make-parameter empty))
(define moving? (make-parameter #f))
(define purging? (make-parameter #f))
(define show-xmp? (make-parameter #f))
(define set-xmp? (make-parameter #f))
(define xmp-to-set (make-parameter ""))
(define show-rating? (make-parameter #f))
(define set-rating? (make-parameter #f))
(define rating-to-set (make-parameter "0"))
(define show-tagged? (make-parameter #f))
(define show-untagged? (make-parameter #f))
; make sure the path provided is a proper absolute path
(define relative->absolute (compose1 simple-form-path expand-user-path))
; resize ivy-frame based on the dimensions of the image
(define (resize-ivy-frame bmp)
; determine the monitor dimensions
(define-values (monitor-width monitor-height) (get-display-size))
; approximate canvas offset
(define canvas-offset 84)
(define max-width (- monitor-width 100))
(define max-height (- monitor-height 100))
(define bmp-width (send bmp get-width))
(define bmp-height (send bmp get-height))
(cond
; all good, let's shrink the frame
[(and (< bmp-width max-width)
(< bmp-height max-height))
(send ivy-frame resize
(inexact->exact (floor bmp-width))
(+ (inexact->exact (floor bmp-height)) canvas-offset))]
; image is the same size as the monitor
[(and (= bmp-width max-width)
(= bmp-height max-height))
(define resized
(let ([scale (/ (- max-height canvas-offset) bmp-height)])
(* bmp-height scale)))
(send ivy-frame resize resized max-height)]
; wide image
[(and (>= bmp-width max-width)
(<= bmp-height max-height))
(define y
(cond [(> bmp-height (- max-height canvas-offset))
max-height]
[(<= bmp-height (- max-height canvas-offset))
(+ bmp-height canvas-offset)]
[else bmp-height]))
(define scale
(let ([scale-w (/ max-width bmp-width)]
[scale-y (/ max-height y)])
(if (<= scale-w scale-y) scale-w scale-y)))
(define resized-height (* y scale))
(send ivy-frame resize
max-width
(+ (inexact->exact (floor resized-height)) canvas-offset))]
; tall image
[(and (<= bmp-width max-width)
(>= bmp-height max-height))
(define resized
(let ([scale (/ (- max-height canvas-offset) bmp-height)])
(* bmp-width scale)))
(send ivy-frame resize (inexact->exact (floor resized)) max-height)]
; both wide and tall
[(and (> bmp-width max-width)
(> bmp-height max-height))
(define scale
(let ([scale-x (/ max-width bmp-width)]
[scale-y (/ (- max-height canvas-offset) bmp-height)])
(if (<= scale-x scale-y) scale-x scale-y)))
(define resized-width (* bmp-width scale))
(send ivy-frame resize (inexact->exact (floor resized-width)) max-height)]))
(define (set-image-paths! paths)
; if there are directories as paths, scan them
(define absolute-paths
(remove-duplicates
(for/fold ([imgs empty])
([ap (map relative->absolute paths)])
; directory?
(if (directory-exists? ap)
(append imgs (dir-files ap))
(append imgs (list ap))))))
(cond [(> (length absolute-paths) 1)
; we want to load a collection
(pfs absolute-paths)]
[else
; we want to load the image from the directory
(define base (path-only (first absolute-paths)))
(image-dir base)
; (path-files dir) filters only supported images
(pfs (path-files base))])
(image-path (first absolute-paths)))
; application handler stuff
(application-file-handler
(λ (path)
(when (supported-file? path)
(cond [(equal? (image-path) +root-path+)
; prep work
(set-image-paths! (list path))
; actually load the file
(load-image path)
; only bother resizing ivy-frame if we're starting fresh
(resize-ivy-frame image-bmp-master)
; center the frame
(send ivy-frame center 'both)]
[else
; append image to the collection
(send (ivy-canvas) on-drop-file path)]))))
; accept command-line path to load image
(command-line
#:program "Ivy"
#:usage-help
"Calling Ivy without a path will simply open the GUI."
"Supplying a path will tell Ivy to load the provided image."
"Supplying multiple paths will tell Ivy to load them as a collection."
#:once-any
[("-V" "--version")
"Display Ivy version."
(printf "Ivy ~a~n" ivy-version)
(exit:exit)]
[("-o" "--search-or")
taglist
"Search the tags database inclusively with a comma-separated string."
(show-frame? #f)
(search-type 'or)
(tags-to-search (string->taglist taglist))]
[("-a" "--search-and")
taglist
"Search the tags database exclusively with a comma-separated string."
(show-frame? #f)
(search-type 'and)
(tags-to-search (string->taglist taglist))]
[("-L" "--list-tags")
"Lists the tags for the image(s)."
(show-frame? #f)
(list-tags? #t)]
[("-A" "--add-tags")
taglist
"Add tags to an image. ex: ivy -A \"tag0, tag1, ...\" /path/to/image ..."
(show-frame? #f)
(add-tags? #t)
(tags-to-add (string->taglist taglist))]
[("-D" "--delete-tags")
taglist
"Delete tags from image. ex: ivy -D \"tag0, tag1, ...\" /path/to/image ..."
(show-frame? #f)
(delete-tags? #t)
(tags-to-delete (string->taglist taglist))]
[("-P" "--purge")
"Remove all tags from the images and purge from the database. ex: ivy -P /path/to/image ..."
(show-frame? #f)
(purging? #t)]
[("-T" "--set-tags")
taglist
"Sets the taglist of the image. ex: ivy -T \"tag0, tag1, ...\" /path/to/image ..."
(show-frame? #f)
(set-tags? #t)
(tags-to-set (string->taglist taglist))]
[("-M" "--move-image")
"Moves the source file(s) to the destination, updating the database."
(show-frame? #f)
(moving? #t)]
[("--show-xmp")
"Extract the embedded XMP in supported images."
(show-frame? #f)
(show-xmp? #t)]
[("--set-xmp")
xmp-str
"Set the embedded XMP in supported images."
(show-frame? #f)
(set-xmp? #t)
(xmp-to-set xmp-str)]
[("--show-rating")
"Show the stored rating from the database."
(show-frame? #f)
(show-rating? #t)]
[("--set-rating")
rating
"Set the xmp:Rating for the image."
(show-frame? #f)
(set-rating? #t)
(rating-to-set rating)]
[("-t" "--tagged")
"List tagged images in a given directory."
(show-frame? #f)
(show-tagged? #t)]
[("-u" "--untagged")
"List untagged images in a given directory."
(show-frame? #f)
(show-untagged? #t)]
#:once-each
[("-e" "--exact-search")
"Search the tags database for exact matches."
(show-frame? #f)
(exact-search? #t)]
[("-x" "--exclude")
exclude
"Search the tags database with -o/-a, but exclude images with the specified tags."
(show-frame? #f)
(excluding? #t)
(tags-to-exclude (string->taglist exclude))]
[("-n" "--null")
"Search result items are terminated by a null character instead of by whitespace."
(show-frame? #f)
(null-flag #t)]
[("-v" "--verbose")
"Display verbose information for certain operations."
(show-frame? #f)
(verbose? #t)]
#:args args
; hijack requested-images for -M
(unless (or (not (show-frame?)) (empty? args))
; if there are directories as paths, scan them
(set-image-paths! args))
(unless (show-frame?)
(uncaught-exception-handler (λ (err)
(printf "ivy: error: ~a~n" (exn-message err))
(exit 1))))
(cond
; we aren't search for tags on the cmdline, open frame
[(show-frame?)
; only change the error port if we're opening the GUI
(current-error-port err-port)
(send (ivy-canvas) focus)
; center the frame
(send ivy-frame center 'both)
(send ivy-frame show #t)
; canvas won't resize until the frame is shown.
(when (supported-file? (image-path))
(load-image (image-path))
(resize-ivy-frame image-bmp-master)
(send ivy-frame center 'both))]
; only searching for tags
[(and (search-type)
(not (excluding?))
(not (empty? (tags-to-search)))
(empty? (tags-to-exclude)))
(define search-results
(if (exact-search?)
(search-db-exact (search-type) (tags-to-search))
(search-db-inexact (search-type) (tags-to-search))))
(define search-sorted (sort (map path->string search-results) string<?))
(define len (length search-sorted))
(unless (zero? len)
(for ([sr (in-list search-sorted)])
(if (null-flag)
(printf "~a" (bytes-append (string->bytes/utf-8 sr) (bytes 0)))
(printf "~a~n" sr)))
(when (verbose?)
(printf "Found ~a results for tags ~v~n" len (tags-to-search))))]
; only excluding tags (resulting output may be very long!)
[(and (excluding?)
(not (search-type))
(not (empty? (tags-to-exclude))))
(define imgs (table-column 'images 'Path))
(define excluded
(if (exact-search?)
(exclude-search-exact imgs (tags-to-exclude))
(exclude-search-inexact imgs (tags-to-exclude))))
(define final-sorted (sort (map path->string excluded) string<?))
(define len (length final-sorted))
(unless (zero? len)
(for ([sr (in-list final-sorted)])
(if (null-flag)
(printf "~a" (bytes-append (string->bytes/utf-8 sr) (bytes 0)))
(printf "~a~n" sr)))
(when (verbose?)
(printf "Found ~a results without tags ~v~n" len (tags-to-exclude))))]
; searching for tags and excluding tags
[(and (search-type)
(excluding?)
(not (empty? (tags-to-search)))
(not (empty? (tags-to-exclude))))
(define search-results
(if (exact-search?)
(search-db-exact (search-type) (tags-to-search))
(search-db-inexact (search-type) (tags-to-search))))
(cond [(zero? (length search-results))
(when (verbose?)
(printf "Found 0 results for tags ~v~n" (tags-to-search)))]
[else
(define exclude
(if (exact-search?)
(exclude-search-exact search-results (tags-to-exclude))
(exclude-search-inexact search-results (tags-to-exclude))))
(define exclude-sorted (sort (map path->string exclude) string<?))
(for ([ex (in-list exclude-sorted)])
(if (null-flag)
(printf "~a" (bytes-append (string->bytes/utf-8 ex) (bytes 0)))
(printf "~a~n" ex)))
(when (verbose?)
(printf "Found ~a results for tags ~v, excluding tags ~v~n"
(length exclude-sorted) (tags-to-search) (tags-to-exclude)))])]
[(list-tags?)
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(when (db-has-key? 'images absolute-path)
(when (verbose?)
(printf "~a:~n" absolute-path))
(define taglist (image-taglist absolute-path))
(for ([tag (in-list taglist)])
(if (null-flag)
(printf "~a" (bytes-append (string->bytes/utf-8 tag) (bytes 0)))
(printf "~a~n" tag)))))]
[(show-xmp?)
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(when (embed-support? absolute-path)
(when (verbose?)
(printf "~a:~n" absolute-path))
(define xmp (get-embed-xmp absolute-path))
(for ([str (in-list xmp)])
(if (null-flag)
(printf "~a" (bytes-append (string->bytes/utf-8 str) (bytes 0)))
(printf "~a~n" str)))))]
default to 0 if there is no recorded : Rating
[(show-rating?)
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(when (embed-support? absolute-path)
(when (verbose?)
(printf "~a: " absolute-path))
(cond [(db-has-key? 'ratings absolute-path)
(displayln (image-rating absolute-path))]
[else (displayln 0)])))]
[(add-tags?)
(cond
[(empty? args)
(raise-argument-error 'add-tags "1 or more image arguments" (length args))
(exit:exit)]
[else
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(unless (empty? (tags-to-add))
(define img-obj
(if (db-has-key? 'images absolute-path)
(make-data-object sqlc image% absolute-path)
(new image% [path absolute-path])))
(when (verbose?)
(printf "Adding tags ~v to ~v~n" (tags-to-add) absolute-path))
(when (embed-support? img)
(add-embed-tags! img (tags-to-add)))
(add-tags! img-obj (tags-to-add))))])]
[(delete-tags?)
(cond
[(empty? args)
(raise-argument-error 'delete-tags "1 or more image arguments" (length args))
(exit:exit)]
[else
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(when (and (not (empty? (tags-to-delete)))
(db-has-key? 'images absolute-path))
(define img-obj (make-data-object sqlc image% absolute-path))
(when (verbose?)
(printf "Removing tags ~v from ~v~n" (tags-to-delete) absolute-path))
(when (embed-support? img)
(del-embed-tags! img (tags-to-delete)))
(del-tags! img-obj (tags-to-delete))))])]
[(purging?)
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
; clean up the thumbnail cache a little
(define thumb-name (path->md5 absolute-path))
(when (verbose?)
(printf "Purging ~v from the database.~n" absolute-path))
(db-purge! absolute-path)
; remove the old thumbnail
(when (file-exists? thumb-name)
(delete-file thumb-name)))]
[(set-tags?)
(cond
[(empty? args)
(raise-argument-error 'set-tags "1 or more image arguments" (length args))
(exit:exit)]
[else
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(unless (empty? (tags-to-set))
(when (verbose?)
(printf "Setting tags of ~v to ~v~n" absolute-path (tags-to-set)))
(reconcile-tags! absolute-path (tags-to-set))
(when (embed-support? absolute-path)
(set-embed-tags! absolute-path (tags-to-set)))))])]
set the XMP metadata for a file
[(set-xmp?)
(cond
[(empty? args)
(raise-argument-error 'set-xmp "1 or more image arguments" (length args))
(exit:exit)]
[else
; make sure the paths are absolute
(define absolutes (map relative->absolute args))
(for ([path (in-list absolutes)])
(when (embed-support? path)
set the XMP data
(set-embed-xmp! path (xmp-to-set))
; grab the tag list and update the database
(define xexpr (string->xexpr (xmp-to-set)))
; find the dc:subject info
(define dc:sub-lst (findf*-txexpr xexpr is-dc:subject?))
(define tags
(if dc:sub-lst
; grab the embedded tags
(flatten (map dc:subject->list dc:sub-lst))
empty))
(when (verbose?)
(printf "Setting the XMP of ~a...~n" path))
(reconcile-tags! (path->string path) (sort tags string<?))))])]
set the : Rating in both the database and the XMP
[(set-rating?)
(cond
[(empty? args)
(raise-argument-error 'add-tags "1 or more image arguments" (length args))
(exit:exit)]
[else
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(when (verbose?)
(printf "Setting the rating for ~a...~n" absolute-path))
; set the rating in the database
(set-image-rating! absolute-path (string->number (rating-to-set)))
set the rating in the embedded XMP
(when (embed-support? absolute-path)
(define xmp (get-embed-xmp absolute-path))
(define xexpr (if (empty? xmp)
(make-xmp-xexpr empty)
(string->xexpr (first xmp))))
(define tag (findf-txexpr xexpr (is-tag? 'xmp:Rating)))
(define setted
((set-xmp-tag (if tag 'xmp:Rating 'rdf:Description))
xexpr
(create-dc-meta "xmp:Rating"
(rating-to-set)
""
(box (list (xexpr->string xexpr))))))
(set-embed-xmp! absolute-path (xexpr->string setted))))])]
; moving an image in the database to another location
[(moving?)
(define len (length args))
(cond
[(< len 2)
(raise-argument-error 'move-image "2 or more arguments" len)
(exit:exit)]
[else
; make sure the paths are absolute
(define absolute-str
(for/list ([ri (in-list args)])
(path->string (relative->absolute ri))))
(define dest-or-dir (last absolute-str))
(define-values (dest-base dest-name must-be-dir?) (split-path dest-or-dir))
(for ([old-path (in-list (take absolute-str (- len 1)))])
(define new-path
(let ([file-name (file-name-from-path old-path)])
(cond
; dest is a directory ending in /
[must-be-dir? (path->string (build-path dest-base dest-name file-name))]
; dest is a directory that does not end in /
[(directory-exists? (build-path dest-base dest-name))
(path->string (build-path dest-base dest-name file-name))]
; dest is a file path
[else
(cond
[(> len 2)
(raise-argument-error 'move-image
"destination needs to be a directory"
dest-or-dir)
#f]
[else dest-or-dir])])))
; do the actual moving
(when new-path
; if new-path exists or old-path doesn't exist, error out
(cond [(file-exists? new-path)
(raise-user-error '--move-image "Destination path ~v already exists." new-path)]
[(not (file-exists? old-path))
(raise-user-error '--move-image "Source path ~v does not exist." old-path)]
[else
(cond
; reassociate the tags to the new destination
[(db-has-key? 'images old-path)
; clean up the thumbnail cache a little
(define old-thumb-name (path->md5 old-path))
(define new-thumb-name (path->md5 new-path))
(define old-img-obj (make-data-object sqlc image% old-path))
(define tags (send old-img-obj get-tags))
; remove the old thumbnails
(when (file-exists? old-thumb-name)
(delete-file old-thumb-name))
(when (file-exists? new-thumb-name)
(delete-file new-thumb-name))
; move the tags
(reconcile-tags! new-path tags)
; preserve the old rating, if we can
(define old-rating
(if (db-has-key? 'ratings old-path)
(image-rating old-path)
0))
(set-image-rating! new-path old-rating)
(db-purge! old-path)]
[else
; spit out an error message, but move anyway
(eprintf "Database does not contain ~v~n" old-path)])
; copy the file over, do not overwrite dest if exists
(when (verbose?)
(printf "Moving ~v to ~v~n" old-path new-path))
(rename-file-or-directory old-path new-path #f)])))])]
[(show-tagged?)
(cond [(empty? args)
(raise-argument-error 'show-tagged "at least one directory" 0)
(exit:exit)]
[else
(for ([dir (in-list args)])
(define files (for/list ([f (in-directory dir)]) f))
(define absolute-paths (map (compose1 path->string relative->absolute) files))
(for ([path (in-list absolute-paths)])
(when (db-has-key? 'images path)
(printf "~a~n" path))))])]
[(show-untagged?)
(cond [(empty? args)
(raise-argument-error 'show-tagged "at least one directory" 0)
(exit:exit)]
[else
(for ([dir (in-list args)])
(define files (for/list ([f (in-directory dir)]) f))
(define absolute-paths (map (compose1 path->string relative->absolute) files))
(for ([path (in-list absolute-paths)])
(unless (db-has-key? 'images path)
(printf "~a~n" path))))])])
; exit explicitly
(unless (show-frame?)
(exit:exit)))
| null | https://raw.githubusercontent.com/lehitoskin/ivy/e32cac3fe65ee21f3db7d117aca1f53c407f86db/main.rkt | racket | main.rkt
main file for ivy, the taggable image viewer
make sure the path provided is a proper absolute path
resize ivy-frame based on the dimensions of the image
determine the monitor dimensions
approximate canvas offset
all good, let's shrink the frame
image is the same size as the monitor
wide image
tall image
both wide and tall
if there are directories as paths, scan them
directory?
we want to load a collection
we want to load the image from the directory
(path-files dir) filters only supported images
application handler stuff
prep work
actually load the file
only bother resizing ivy-frame if we're starting fresh
center the frame
append image to the collection
accept command-line path to load image
hijack requested-images for -M
if there are directories as paths, scan them
we aren't search for tags on the cmdline, open frame
only change the error port if we're opening the GUI
center the frame
canvas won't resize until the frame is shown.
only searching for tags
only excluding tags (resulting output may be very long!)
searching for tags and excluding tags
clean up the thumbnail cache a little
remove the old thumbnail
make sure the paths are absolute
grab the tag list and update the database
find the dc:subject info
grab the embedded tags
set the rating in the database
moving an image in the database to another location
make sure the paths are absolute
dest is a directory ending in /
dest is a directory that does not end in /
dest is a file path
do the actual moving
if new-path exists or old-path doesn't exist, error out
reassociate the tags to the new destination
clean up the thumbnail cache a little
remove the old thumbnails
move the tags
preserve the old rating, if we can
spit out an error message, but move anyway
copy the file over, do not overwrite dest if exists
exit explicitly | #!/usr/bin/env racket
#lang racket/base
(require racket/class
racket/cmdline
racket/gui/base
racket/list
racket/path
riff
txexpr
xml
"base.rkt"
"config.rkt"
"db.rkt"
"embed.rkt"
"error-log.rkt"
(only-in "files.rkt" ivy-version)
"frame.rkt"
"meta-editor.rkt"
"thumbnails.rkt")
(define show-frame? (make-parameter #t))
(define tags-to-search (make-parameter empty))
(define search-type (make-parameter #f))
(define tags-to-exclude (make-parameter empty))
(define excluding? (make-parameter #f))
(define null-flag (make-parameter #f))
(define verbose? (make-parameter #f))
(define list-tags? (make-parameter #f))
(define add-tags? (make-parameter #f))
(define tags-to-add (make-parameter empty))
(define delete-tags? (make-parameter #f))
(define tags-to-delete (make-parameter empty))
(define set-tags? (make-parameter #f))
(define tags-to-set (make-parameter empty))
(define moving? (make-parameter #f))
(define purging? (make-parameter #f))
(define show-xmp? (make-parameter #f))
(define set-xmp? (make-parameter #f))
(define xmp-to-set (make-parameter ""))
(define show-rating? (make-parameter #f))
(define set-rating? (make-parameter #f))
(define rating-to-set (make-parameter "0"))
(define show-tagged? (make-parameter #f))
(define show-untagged? (make-parameter #f))
(define relative->absolute (compose1 simple-form-path expand-user-path))
(define (resize-ivy-frame bmp)
(define-values (monitor-width monitor-height) (get-display-size))
(define canvas-offset 84)
(define max-width (- monitor-width 100))
(define max-height (- monitor-height 100))
(define bmp-width (send bmp get-width))
(define bmp-height (send bmp get-height))
(cond
[(and (< bmp-width max-width)
(< bmp-height max-height))
(send ivy-frame resize
(inexact->exact (floor bmp-width))
(+ (inexact->exact (floor bmp-height)) canvas-offset))]
[(and (= bmp-width max-width)
(= bmp-height max-height))
(define resized
(let ([scale (/ (- max-height canvas-offset) bmp-height)])
(* bmp-height scale)))
(send ivy-frame resize resized max-height)]
[(and (>= bmp-width max-width)
(<= bmp-height max-height))
(define y
(cond [(> bmp-height (- max-height canvas-offset))
max-height]
[(<= bmp-height (- max-height canvas-offset))
(+ bmp-height canvas-offset)]
[else bmp-height]))
(define scale
(let ([scale-w (/ max-width bmp-width)]
[scale-y (/ max-height y)])
(if (<= scale-w scale-y) scale-w scale-y)))
(define resized-height (* y scale))
(send ivy-frame resize
max-width
(+ (inexact->exact (floor resized-height)) canvas-offset))]
[(and (<= bmp-width max-width)
(>= bmp-height max-height))
(define resized
(let ([scale (/ (- max-height canvas-offset) bmp-height)])
(* bmp-width scale)))
(send ivy-frame resize (inexact->exact (floor resized)) max-height)]
[(and (> bmp-width max-width)
(> bmp-height max-height))
(define scale
(let ([scale-x (/ max-width bmp-width)]
[scale-y (/ (- max-height canvas-offset) bmp-height)])
(if (<= scale-x scale-y) scale-x scale-y)))
(define resized-width (* bmp-width scale))
(send ivy-frame resize (inexact->exact (floor resized-width)) max-height)]))
(define (set-image-paths! paths)
(define absolute-paths
(remove-duplicates
(for/fold ([imgs empty])
([ap (map relative->absolute paths)])
(if (directory-exists? ap)
(append imgs (dir-files ap))
(append imgs (list ap))))))
(cond [(> (length absolute-paths) 1)
(pfs absolute-paths)]
[else
(define base (path-only (first absolute-paths)))
(image-dir base)
(pfs (path-files base))])
(image-path (first absolute-paths)))
(application-file-handler
(λ (path)
(when (supported-file? path)
(cond [(equal? (image-path) +root-path+)
(set-image-paths! (list path))
(load-image path)
(resize-ivy-frame image-bmp-master)
(send ivy-frame center 'both)]
[else
(send (ivy-canvas) on-drop-file path)]))))
(command-line
#:program "Ivy"
#:usage-help
"Calling Ivy without a path will simply open the GUI."
"Supplying a path will tell Ivy to load the provided image."
"Supplying multiple paths will tell Ivy to load them as a collection."
#:once-any
[("-V" "--version")
"Display Ivy version."
(printf "Ivy ~a~n" ivy-version)
(exit:exit)]
[("-o" "--search-or")
taglist
"Search the tags database inclusively with a comma-separated string."
(show-frame? #f)
(search-type 'or)
(tags-to-search (string->taglist taglist))]
[("-a" "--search-and")
taglist
"Search the tags database exclusively with a comma-separated string."
(show-frame? #f)
(search-type 'and)
(tags-to-search (string->taglist taglist))]
[("-L" "--list-tags")
"Lists the tags for the image(s)."
(show-frame? #f)
(list-tags? #t)]
[("-A" "--add-tags")
taglist
"Add tags to an image. ex: ivy -A \"tag0, tag1, ...\" /path/to/image ..."
(show-frame? #f)
(add-tags? #t)
(tags-to-add (string->taglist taglist))]
[("-D" "--delete-tags")
taglist
"Delete tags from image. ex: ivy -D \"tag0, tag1, ...\" /path/to/image ..."
(show-frame? #f)
(delete-tags? #t)
(tags-to-delete (string->taglist taglist))]
[("-P" "--purge")
"Remove all tags from the images and purge from the database. ex: ivy -P /path/to/image ..."
(show-frame? #f)
(purging? #t)]
[("-T" "--set-tags")
taglist
"Sets the taglist of the image. ex: ivy -T \"tag0, tag1, ...\" /path/to/image ..."
(show-frame? #f)
(set-tags? #t)
(tags-to-set (string->taglist taglist))]
[("-M" "--move-image")
"Moves the source file(s) to the destination, updating the database."
(show-frame? #f)
(moving? #t)]
[("--show-xmp")
"Extract the embedded XMP in supported images."
(show-frame? #f)
(show-xmp? #t)]
[("--set-xmp")
xmp-str
"Set the embedded XMP in supported images."
(show-frame? #f)
(set-xmp? #t)
(xmp-to-set xmp-str)]
[("--show-rating")
"Show the stored rating from the database."
(show-frame? #f)
(show-rating? #t)]
[("--set-rating")
rating
"Set the xmp:Rating for the image."
(show-frame? #f)
(set-rating? #t)
(rating-to-set rating)]
[("-t" "--tagged")
"List tagged images in a given directory."
(show-frame? #f)
(show-tagged? #t)]
[("-u" "--untagged")
"List untagged images in a given directory."
(show-frame? #f)
(show-untagged? #t)]
#:once-each
[("-e" "--exact-search")
"Search the tags database for exact matches."
(show-frame? #f)
(exact-search? #t)]
[("-x" "--exclude")
exclude
"Search the tags database with -o/-a, but exclude images with the specified tags."
(show-frame? #f)
(excluding? #t)
(tags-to-exclude (string->taglist exclude))]
[("-n" "--null")
"Search result items are terminated by a null character instead of by whitespace."
(show-frame? #f)
(null-flag #t)]
[("-v" "--verbose")
"Display verbose information for certain operations."
(show-frame? #f)
(verbose? #t)]
#:args args
(unless (or (not (show-frame?)) (empty? args))
(set-image-paths! args))
(unless (show-frame?)
(uncaught-exception-handler (λ (err)
(printf "ivy: error: ~a~n" (exn-message err))
(exit 1))))
(cond
[(show-frame?)
(current-error-port err-port)
(send (ivy-canvas) focus)
(send ivy-frame center 'both)
(send ivy-frame show #t)
(when (supported-file? (image-path))
(load-image (image-path))
(resize-ivy-frame image-bmp-master)
(send ivy-frame center 'both))]
[(and (search-type)
(not (excluding?))
(not (empty? (tags-to-search)))
(empty? (tags-to-exclude)))
(define search-results
(if (exact-search?)
(search-db-exact (search-type) (tags-to-search))
(search-db-inexact (search-type) (tags-to-search))))
(define search-sorted (sort (map path->string search-results) string<?))
(define len (length search-sorted))
(unless (zero? len)
(for ([sr (in-list search-sorted)])
(if (null-flag)
(printf "~a" (bytes-append (string->bytes/utf-8 sr) (bytes 0)))
(printf "~a~n" sr)))
(when (verbose?)
(printf "Found ~a results for tags ~v~n" len (tags-to-search))))]
[(and (excluding?)
(not (search-type))
(not (empty? (tags-to-exclude))))
(define imgs (table-column 'images 'Path))
(define excluded
(if (exact-search?)
(exclude-search-exact imgs (tags-to-exclude))
(exclude-search-inexact imgs (tags-to-exclude))))
(define final-sorted (sort (map path->string excluded) string<?))
(define len (length final-sorted))
(unless (zero? len)
(for ([sr (in-list final-sorted)])
(if (null-flag)
(printf "~a" (bytes-append (string->bytes/utf-8 sr) (bytes 0)))
(printf "~a~n" sr)))
(when (verbose?)
(printf "Found ~a results without tags ~v~n" len (tags-to-exclude))))]
[(and (search-type)
(excluding?)
(not (empty? (tags-to-search)))
(not (empty? (tags-to-exclude))))
(define search-results
(if (exact-search?)
(search-db-exact (search-type) (tags-to-search))
(search-db-inexact (search-type) (tags-to-search))))
(cond [(zero? (length search-results))
(when (verbose?)
(printf "Found 0 results for tags ~v~n" (tags-to-search)))]
[else
(define exclude
(if (exact-search?)
(exclude-search-exact search-results (tags-to-exclude))
(exclude-search-inexact search-results (tags-to-exclude))))
(define exclude-sorted (sort (map path->string exclude) string<?))
(for ([ex (in-list exclude-sorted)])
(if (null-flag)
(printf "~a" (bytes-append (string->bytes/utf-8 ex) (bytes 0)))
(printf "~a~n" ex)))
(when (verbose?)
(printf "Found ~a results for tags ~v, excluding tags ~v~n"
(length exclude-sorted) (tags-to-search) (tags-to-exclude)))])]
[(list-tags?)
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(when (db-has-key? 'images absolute-path)
(when (verbose?)
(printf "~a:~n" absolute-path))
(define taglist (image-taglist absolute-path))
(for ([tag (in-list taglist)])
(if (null-flag)
(printf "~a" (bytes-append (string->bytes/utf-8 tag) (bytes 0)))
(printf "~a~n" tag)))))]
[(show-xmp?)
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(when (embed-support? absolute-path)
(when (verbose?)
(printf "~a:~n" absolute-path))
(define xmp (get-embed-xmp absolute-path))
(for ([str (in-list xmp)])
(if (null-flag)
(printf "~a" (bytes-append (string->bytes/utf-8 str) (bytes 0)))
(printf "~a~n" str)))))]
default to 0 if there is no recorded : Rating
[(show-rating?)
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(when (embed-support? absolute-path)
(when (verbose?)
(printf "~a: " absolute-path))
(cond [(db-has-key? 'ratings absolute-path)
(displayln (image-rating absolute-path))]
[else (displayln 0)])))]
[(add-tags?)
(cond
[(empty? args)
(raise-argument-error 'add-tags "1 or more image arguments" (length args))
(exit:exit)]
[else
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(unless (empty? (tags-to-add))
(define img-obj
(if (db-has-key? 'images absolute-path)
(make-data-object sqlc image% absolute-path)
(new image% [path absolute-path])))
(when (verbose?)
(printf "Adding tags ~v to ~v~n" (tags-to-add) absolute-path))
(when (embed-support? img)
(add-embed-tags! img (tags-to-add)))
(add-tags! img-obj (tags-to-add))))])]
[(delete-tags?)
(cond
[(empty? args)
(raise-argument-error 'delete-tags "1 or more image arguments" (length args))
(exit:exit)]
[else
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(when (and (not (empty? (tags-to-delete)))
(db-has-key? 'images absolute-path))
(define img-obj (make-data-object sqlc image% absolute-path))
(when (verbose?)
(printf "Removing tags ~v from ~v~n" (tags-to-delete) absolute-path))
(when (embed-support? img)
(del-embed-tags! img (tags-to-delete)))
(del-tags! img-obj (tags-to-delete))))])]
[(purging?)
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(define thumb-name (path->md5 absolute-path))
(when (verbose?)
(printf "Purging ~v from the database.~n" absolute-path))
(db-purge! absolute-path)
(when (file-exists? thumb-name)
(delete-file thumb-name)))]
[(set-tags?)
(cond
[(empty? args)
(raise-argument-error 'set-tags "1 or more image arguments" (length args))
(exit:exit)]
[else
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(unless (empty? (tags-to-set))
(when (verbose?)
(printf "Setting tags of ~v to ~v~n" absolute-path (tags-to-set)))
(reconcile-tags! absolute-path (tags-to-set))
(when (embed-support? absolute-path)
(set-embed-tags! absolute-path (tags-to-set)))))])]
set the XMP metadata for a file
[(set-xmp?)
(cond
[(empty? args)
(raise-argument-error 'set-xmp "1 or more image arguments" (length args))
(exit:exit)]
[else
(define absolutes (map relative->absolute args))
(for ([path (in-list absolutes)])
(when (embed-support? path)
set the XMP data
(set-embed-xmp! path (xmp-to-set))
(define xexpr (string->xexpr (xmp-to-set)))
(define dc:sub-lst (findf*-txexpr xexpr is-dc:subject?))
(define tags
(if dc:sub-lst
(flatten (map dc:subject->list dc:sub-lst))
empty))
(when (verbose?)
(printf "Setting the XMP of ~a...~n" path))
(reconcile-tags! (path->string path) (sort tags string<?))))])]
set the : Rating in both the database and the XMP
[(set-rating?)
(cond
[(empty? args)
(raise-argument-error 'add-tags "1 or more image arguments" (length args))
(exit:exit)]
[else
(for ([img (in-list args)])
(define absolute-path (path->string (relative->absolute img)))
(when (verbose?)
(printf "Setting the rating for ~a...~n" absolute-path))
(set-image-rating! absolute-path (string->number (rating-to-set)))
set the rating in the embedded XMP
(when (embed-support? absolute-path)
(define xmp (get-embed-xmp absolute-path))
(define xexpr (if (empty? xmp)
(make-xmp-xexpr empty)
(string->xexpr (first xmp))))
(define tag (findf-txexpr xexpr (is-tag? 'xmp:Rating)))
(define setted
((set-xmp-tag (if tag 'xmp:Rating 'rdf:Description))
xexpr
(create-dc-meta "xmp:Rating"
(rating-to-set)
""
(box (list (xexpr->string xexpr))))))
(set-embed-xmp! absolute-path (xexpr->string setted))))])]
[(moving?)
(define len (length args))
(cond
[(< len 2)
(raise-argument-error 'move-image "2 or more arguments" len)
(exit:exit)]
[else
(define absolute-str
(for/list ([ri (in-list args)])
(path->string (relative->absolute ri))))
(define dest-or-dir (last absolute-str))
(define-values (dest-base dest-name must-be-dir?) (split-path dest-or-dir))
(for ([old-path (in-list (take absolute-str (- len 1)))])
(define new-path
(let ([file-name (file-name-from-path old-path)])
(cond
[must-be-dir? (path->string (build-path dest-base dest-name file-name))]
[(directory-exists? (build-path dest-base dest-name))
(path->string (build-path dest-base dest-name file-name))]
[else
(cond
[(> len 2)
(raise-argument-error 'move-image
"destination needs to be a directory"
dest-or-dir)
#f]
[else dest-or-dir])])))
(when new-path
(cond [(file-exists? new-path)
(raise-user-error '--move-image "Destination path ~v already exists." new-path)]
[(not (file-exists? old-path))
(raise-user-error '--move-image "Source path ~v does not exist." old-path)]
[else
(cond
[(db-has-key? 'images old-path)
(define old-thumb-name (path->md5 old-path))
(define new-thumb-name (path->md5 new-path))
(define old-img-obj (make-data-object sqlc image% old-path))
(define tags (send old-img-obj get-tags))
(when (file-exists? old-thumb-name)
(delete-file old-thumb-name))
(when (file-exists? new-thumb-name)
(delete-file new-thumb-name))
(reconcile-tags! new-path tags)
(define old-rating
(if (db-has-key? 'ratings old-path)
(image-rating old-path)
0))
(set-image-rating! new-path old-rating)
(db-purge! old-path)]
[else
(eprintf "Database does not contain ~v~n" old-path)])
(when (verbose?)
(printf "Moving ~v to ~v~n" old-path new-path))
(rename-file-or-directory old-path new-path #f)])))])]
[(show-tagged?)
(cond [(empty? args)
(raise-argument-error 'show-tagged "at least one directory" 0)
(exit:exit)]
[else
(for ([dir (in-list args)])
(define files (for/list ([f (in-directory dir)]) f))
(define absolute-paths (map (compose1 path->string relative->absolute) files))
(for ([path (in-list absolute-paths)])
(when (db-has-key? 'images path)
(printf "~a~n" path))))])]
[(show-untagged?)
(cond [(empty? args)
(raise-argument-error 'show-tagged "at least one directory" 0)
(exit:exit)]
[else
(for ([dir (in-list args)])
(define files (for/list ([f (in-directory dir)]) f))
(define absolute-paths (map (compose1 path->string relative->absolute) files))
(for ([path (in-list absolute-paths)])
(unless (db-has-key? 'images path)
(printf "~a~n" path))))])])
(unless (show-frame?)
(exit:exit)))
|
f8aec4cdb9ad66ebc705bd8934245bfb9678d08a2f62171a7c621d1fe8aca8aa | samee/netlist | Gcil-old.hs | module Test.Gcil where
import Control.Monad.State.Strict
import Circuit.Gcil.Compiler as GC
import Data.List
import Debug.Trace
import System.IO
-- Fragile tests. Disabled for now
testAplusb = result > > = return.fst
where
expected = " .input t1 1 8\n.input t2 2 8\nt3 add t1 t2\n.output t3\n "
result = compile [ 8,8 ] [ 1,2 ] ( \[a , b ] - > addWithCarryU a b > > = return . (: [ ] ) )
testConcat = result > > = return.fst
where
expected = " .input t1 1 8\n.input t2 2 16\nt3 concat t1 t2\n "
+ + " select t3 0 16\nt5 select t3 16 24\n.output t5\n.output "
result = compile [ 8,16 ] [ 1,2 ] ( \[a , b ] - > do
c < - GC.concat [ a , b ]
[ a',b ' ] < - unconcat [ gblWidth a , gblWidth b ] c
return [ a',b ' ] )
runTests = do show testAplusb + + " Test . Garbled.testAplusb "
putStrLn $ show testConcat + + " Test . "
testAplusb = result >>= return.fst
where
expected = ".input t1 1 8\n.input t2 2 8\nt3 add t1 t2\n.output t3\n"
result = compile [8,8] [1,2] (\[a,b] -> addWithCarryU a b >>= return.(:[]))
testConcat = result >>= return.fst
where
expected = ".input t1 1 8\n.input t2 2 16\nt3 concat t1 t2\n"
++ "t4 select t3 0 16\nt5 select t3 16 24\n.output t5\n.output t4\n"
result = compile [8,16] [1,2] (\[a,b] -> do
c <- GC.concat [a,b]
[a',b'] <- unconcat [gblWidth a, gblWidth b] c
return [a',b'])
runTests = do putStrLn $ show testAplusb ++ " Test.Garbled.testAplusb"
putStrLn $ show testConcat ++ " Test.Garbled.testConcat"
-}
writeTestCase :: String -> GcilMonad a ->
(a -> [(String,Int)]) -> (a -> [(String,Int)]) -> IO ()
writeTestCase testName ckt serverInputs clientInputs = do
(ins,cost) <- withFile ("gcilouts/"++testName++".cir") WriteMode
(evalStateT ckt' . GC.initState)
writeFile ("gcilouts/"++testName++"-server.in") $ showpair $ serverInputs ins
writeFile ("gcilouts/"++testName++"-client.in") $ showpair $ clientInputs ins
putStrLn $ testName ++ " uses "++ show cost ++ " non-free gates"
where
ckt' = do ins <- ckt
cost <- gets totalAndGates
return (ins,cost)
showpair l = Prelude.concat $ intersperse "\n" $ map vline l
vline (n,v) = n ++ " " ++ show v
runTests :: IO ()
runTests = return ()
| null | https://raw.githubusercontent.com/samee/netlist/9fc20829f29724dc1148e54bd64fefd7e70af5ba/Test/Gcil-old.hs | haskell | Fragile tests. Disabled for now | module Test.Gcil where
import Control.Monad.State.Strict
import Circuit.Gcil.Compiler as GC
import Data.List
import Debug.Trace
import System.IO
testAplusb = result > > = return.fst
where
expected = " .input t1 1 8\n.input t2 2 8\nt3 add t1 t2\n.output t3\n "
result = compile [ 8,8 ] [ 1,2 ] ( \[a , b ] - > addWithCarryU a b > > = return . (: [ ] ) )
testConcat = result > > = return.fst
where
expected = " .input t1 1 8\n.input t2 2 16\nt3 concat t1 t2\n "
+ + " select t3 0 16\nt5 select t3 16 24\n.output t5\n.output "
result = compile [ 8,16 ] [ 1,2 ] ( \[a , b ] - > do
c < - GC.concat [ a , b ]
[ a',b ' ] < - unconcat [ gblWidth a , gblWidth b ] c
return [ a',b ' ] )
runTests = do show testAplusb + + " Test . Garbled.testAplusb "
putStrLn $ show testConcat + + " Test . "
testAplusb = result >>= return.fst
where
expected = ".input t1 1 8\n.input t2 2 8\nt3 add t1 t2\n.output t3\n"
result = compile [8,8] [1,2] (\[a,b] -> addWithCarryU a b >>= return.(:[]))
testConcat = result >>= return.fst
where
expected = ".input t1 1 8\n.input t2 2 16\nt3 concat t1 t2\n"
++ "t4 select t3 0 16\nt5 select t3 16 24\n.output t5\n.output t4\n"
result = compile [8,16] [1,2] (\[a,b] -> do
c <- GC.concat [a,b]
[a',b'] <- unconcat [gblWidth a, gblWidth b] c
return [a',b'])
runTests = do putStrLn $ show testAplusb ++ " Test.Garbled.testAplusb"
putStrLn $ show testConcat ++ " Test.Garbled.testConcat"
-}
writeTestCase :: String -> GcilMonad a ->
(a -> [(String,Int)]) -> (a -> [(String,Int)]) -> IO ()
writeTestCase testName ckt serverInputs clientInputs = do
(ins,cost) <- withFile ("gcilouts/"++testName++".cir") WriteMode
(evalStateT ckt' . GC.initState)
writeFile ("gcilouts/"++testName++"-server.in") $ showpair $ serverInputs ins
writeFile ("gcilouts/"++testName++"-client.in") $ showpair $ clientInputs ins
putStrLn $ testName ++ " uses "++ show cost ++ " non-free gates"
where
ckt' = do ins <- ckt
cost <- gets totalAndGates
return (ins,cost)
showpair l = Prelude.concat $ intersperse "\n" $ map vline l
vline (n,v) = n ++ " " ++ show v
runTests :: IO ()
runTests = return ()
|
d77393489bae4380d1ea6d5bddd7fc4a65825327fa2f22d1740d61995b45f7d8 | ros/roslisp_common | screws.lisp | Copyright ( c ) 2014 , < >
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
* Neither the name of the Institute for Artificial Intelligence/
Universitaet Bremen nor the names of its contributors may be used to
;;; endorse or promote products derived from this software without specific
;;; prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;;; POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-transforms)
;;;
;;; TWIST REPRESENTATION
;;;
(defclass twist ()
((translation :initarg :translation :reader translation :type point)
(rotation :initarg :rotation :reader rotation :type point)))
(defun make-twist (translation rotation)
(make-instance 'twist :translation translation :rotation rotation))
(defun make-identity-twist ()
(make-twist (make-identity-vector) (make-identity-vector)))
(defun copy-twist (twist &key translation rotation)
(with-slots ((old-translation translation)
(old-rotation rotation))
twist
(make-twist
(or translation old-translation)
(or rotation old-rotation))))
(defmethod print-object ((obj twist) strm)
(print-unreadable-object (obj strm :type t)
(with-slots (translation rotation) obj
(format strm "~{~<~% ~{ ~a~}~>~}"
`(("TRANSLATION" ,translation) ("ROTATION" ,rotation))))))
;;;
;;; WRENCH REPRESENTATION
;;;
(defclass wrench ()
((translation :initarg :translation :initform (make-identity-vector)
:reader translation :type point)
(rotation :initarg :rotation :initform (make-identity-vector)
:reader rotation :type point)))
(defun make-wrench (translation rotation)
(make-instance 'wrench :translation translation :rotation rotation))
(defun make-identity-wrench ()
(make-wrench (make-identity-vector) (make-identity-vector)))
(defun copy-wrench (wrench &key translation rotation)
(with-slots ((old-translation translation)
(old-rotation rotation))
wrench
(make-wrench
(or translation old-translation)
(or rotation old-rotation))))
(defmethod print-object ((obj wrench) strm)
(print-unreadable-object (obj strm :type t)
(with-slots (translation rotation) obj
(format strm "~{~<~% ~{ ~a~}~>~}"
`(("TRANSLATION" ,translation) ("ROTATION" ,rotation))))))
| null | https://raw.githubusercontent.com/ros/roslisp_common/4db311da26497d84a147f190200e50c7a5b4106e/cl_transforms/src/screws.lisp | lisp | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
endorse or promote products derived from this software without specific
prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
TWIST REPRESENTATION
WRENCH REPRESENTATION
| Copyright ( c ) 2014 , < >
* Neither the name of the Institute for Artificial Intelligence/
Universitaet Bremen nor the names of its contributors may be used to
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package :cl-transforms)
(defclass twist ()
((translation :initarg :translation :reader translation :type point)
(rotation :initarg :rotation :reader rotation :type point)))
(defun make-twist (translation rotation)
(make-instance 'twist :translation translation :rotation rotation))
(defun make-identity-twist ()
(make-twist (make-identity-vector) (make-identity-vector)))
(defun copy-twist (twist &key translation rotation)
(with-slots ((old-translation translation)
(old-rotation rotation))
twist
(make-twist
(or translation old-translation)
(or rotation old-rotation))))
(defmethod print-object ((obj twist) strm)
(print-unreadable-object (obj strm :type t)
(with-slots (translation rotation) obj
(format strm "~{~<~% ~{ ~a~}~>~}"
`(("TRANSLATION" ,translation) ("ROTATION" ,rotation))))))
(defclass wrench ()
((translation :initarg :translation :initform (make-identity-vector)
:reader translation :type point)
(rotation :initarg :rotation :initform (make-identity-vector)
:reader rotation :type point)))
(defun make-wrench (translation rotation)
(make-instance 'wrench :translation translation :rotation rotation))
(defun make-identity-wrench ()
(make-wrench (make-identity-vector) (make-identity-vector)))
(defun copy-wrench (wrench &key translation rotation)
(with-slots ((old-translation translation)
(old-rotation rotation))
wrench
(make-wrench
(or translation old-translation)
(or rotation old-rotation))))
(defmethod print-object ((obj wrench) strm)
(print-unreadable-object (obj strm :type t)
(with-slots (translation rotation) obj
(format strm "~{~<~% ~{ ~a~}~>~}"
`(("TRANSLATION" ,translation) ("ROTATION" ,rotation))))))
|
ff1fbeb7093e3646f6a06bfc14b24673839f41224c8ddd97b165005e9a7e3cbd | biocaml/phylogenetics | sequence_simulator.ml | open Core
module type Alphabet = sig
type t
val card : int
val of_int_exn : int -> t
val to_char : t -> char
end
module Make(A : Alphabet) = struct
type profile = Profile of {
probs : float array ;
dist : Gsl.Randist.discrete ;
}
let of_array_exn probs =
if Array.length probs <> A.card then failwith "Array has incorrect size" ;
let dist = Gsl.Randist.discrete_preproc probs in
Profile { probs ; dist }
let random_profile ~alpha rng =
let alpha = Array.create ~len:A.card alpha in
let theta = Array.create ~len:A.card 0. in
Gsl.Randist.dirichlet rng ~alpha ~theta ;
of_array_exn theta
let draw_from_profile (Profile p) rng =
Gsl.Randist.discrete rng p.dist
|> A.of_int_exn
type pwm = profile array
let random_pwm ~alpha n rng =
Array.init n ~f:(fun _ -> random_profile ~alpha rng)
let draw_from_pwm pwm rng =
let n = Array.length pwm in
String.init n ~f:(fun i ->
draw_from_profile pwm.(i) rng
|> A.to_char
)
end
| null | https://raw.githubusercontent.com/biocaml/phylogenetics/e225616a700b03c429c16f760dbe8c363fb4c79d/lib/sequence_simulator.ml | ocaml | open Core
module type Alphabet = sig
type t
val card : int
val of_int_exn : int -> t
val to_char : t -> char
end
module Make(A : Alphabet) = struct
type profile = Profile of {
probs : float array ;
dist : Gsl.Randist.discrete ;
}
let of_array_exn probs =
if Array.length probs <> A.card then failwith "Array has incorrect size" ;
let dist = Gsl.Randist.discrete_preproc probs in
Profile { probs ; dist }
let random_profile ~alpha rng =
let alpha = Array.create ~len:A.card alpha in
let theta = Array.create ~len:A.card 0. in
Gsl.Randist.dirichlet rng ~alpha ~theta ;
of_array_exn theta
let draw_from_profile (Profile p) rng =
Gsl.Randist.discrete rng p.dist
|> A.of_int_exn
type pwm = profile array
let random_pwm ~alpha n rng =
Array.init n ~f:(fun _ -> random_profile ~alpha rng)
let draw_from_pwm pwm rng =
let n = Array.length pwm in
String.init n ~f:(fun i ->
draw_from_profile pwm.(i) rng
|> A.to_char
)
end
|
|
0931360e950e46b47ef8e695d97299af4ea2962ef1b93e5933bf96811e8af432 | Clojure2D/clojure2d-examples | quad.clj | (ns rt4.the-next-week.ch07a.quad
(:require [fastmath.core :as m]
[rt4.the-next-week.ch07a.hittable :as hittable]
[rt4.the-next-week.ch07a.aabb :as aabb]
[fastmath.vector :as v]
[rt4.the-next-week.ch07a.interval :as interval]
[rt4.the-next-week.ch07a.ray :as ray]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defrecord Quad [Q u v mat bbox normal ^double D w]
hittable/HittableProto
(hit [_ r ray-t]
(let [denom (v/dot normal (:direction r))]
(when (>= (m/abs denom) 1.0e-8)
(let [t (/ (- D (v/dot normal (:origin r))) denom)]
(when (interval/contains- ray-t t)
(let [intersection (ray/at r t)
planar-hitp-vector (v/sub intersection Q)
alpha (v/dot w (v/cross planar-hitp-vector v))
beta (v/dot w (v/cross u planar-hitp-vector))]
(when-not (or (neg? alpha) (< 1.0 alpha)
(neg? beta) (< 1.0 beta))
(hittable/hit-data r intersection normal mat t alpha beta)))))))))
(defn quad
[Q u v mat]
(let [box (aabb/pad (aabb/aabb Q (v/add (v/add Q u) v)))
n (v/cross u v)
normal (v/normalize n)]
(->Quad Q u v mat box normal (v/dot normal Q) (v/div n (v/dot n n)))))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/the_next_week/ch07a/quad.clj | clojure | (ns rt4.the-next-week.ch07a.quad
(:require [fastmath.core :as m]
[rt4.the-next-week.ch07a.hittable :as hittable]
[rt4.the-next-week.ch07a.aabb :as aabb]
[fastmath.vector :as v]
[rt4.the-next-week.ch07a.interval :as interval]
[rt4.the-next-week.ch07a.ray :as ray]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defrecord Quad [Q u v mat bbox normal ^double D w]
hittable/HittableProto
(hit [_ r ray-t]
(let [denom (v/dot normal (:direction r))]
(when (>= (m/abs denom) 1.0e-8)
(let [t (/ (- D (v/dot normal (:origin r))) denom)]
(when (interval/contains- ray-t t)
(let [intersection (ray/at r t)
planar-hitp-vector (v/sub intersection Q)
alpha (v/dot w (v/cross planar-hitp-vector v))
beta (v/dot w (v/cross u planar-hitp-vector))]
(when-not (or (neg? alpha) (< 1.0 alpha)
(neg? beta) (< 1.0 beta))
(hittable/hit-data r intersection normal mat t alpha beta)))))))))
(defn quad
[Q u v mat]
(let [box (aabb/pad (aabb/aabb Q (v/add (v/add Q u) v)))
n (v/cross u v)
normal (v/normalize n)]
(->Quad Q u v mat box normal (v/dot normal Q) (v/div n (v/dot n n)))))
|
|
d31947449f6d99175822d50c97502e617987720007640aa7a904e7d2ae0145b4 | dakk/yallo-lang | yallo.ml | open Core
open Yallo
open Helpers.Errors
let run action filename opt =
(match action with
| "compile" -> Compiler.compile filename opt
(* | "build-storage" -> *)
(* | "build-parameter" -> *)
(* | "interface-of-michelson" -> Interface_of_michelson.extract filename opt *)
| "extract-interface" -> Compiler.extract_interface filename opt
| _ -> raise @@ CompilerError ("Invalid compiler action: " ^ action)
)
let summary = ""
^ "=== actions ===\n\n"
^ " compile file.yallo [-dcontract ContractName] [-target ligo|tz|coq]\n"
^ " compiles a contract ContractName to target language\n\n"
^ " extract-interface file.yallo -dcontract ContractName\n"
^ " extracts the yallo interface for the given contract\n\n"
^ " interface-of-michelson file.tz\n"
^ " produce a yallo interface from michelson contract\n"
let command =
Command.basic
~summary:"Yallo-lang compiler"
~readme:(fun () -> summary)
(let open Command.Let_syntax in
let open Command.Param in
let%map
action = anon ("action" %: string)
and filename = anon ("filename" %: string)
and contract = flag "-contract" (optional string) ~doc:" selected contract"
and past = flag "-print-ast" no_arg ~doc:" print ast"
and ppt = flag "-print-pt" no_arg ~doc:" print parse-tree"
and pligo = flag "-print-ligo" no_arg ~doc:" print ligo code"
and verbose = flag "-verbose" no_arg ~doc:" enable verbosity"
and noremoveunused = flag "-no-remove-unused" no_arg ~doc:" disable removing unused symbols"
and target = flag "-target" (optional string) ~doc:" target language (ligo, tz, coq)"
in fun () ->
let opt = Compiler.{
target = if is_none target then Some("tz") else target;
contract = contract;
print_pt = ppt;
print_ast = past;
print_ligo = pligo;
verbose = verbose;
no_remove_unused = noremoveunused;
} in (
let pp_err p cc m = pp_message p cc m true in
try run action filename opt with
| CompilerError (m) -> print_endline @@ pp_err None "CompilerError" m
| SyntaxError (p,m) -> print_endline @@ pp_err p "SyntaxError" m
| ParsingError (p,m) -> print_endline @@ pp_err p "ParsingError" m
| TypeError (p,m) -> print_endline @@ pp_err p "TypeError" m
| SymbolNotFound (p,m) -> print_endline @@ pp_err p "SymbolNotFound" m
| DuplicateSymbolError (p,m) -> print_endline @@ pp_err p "DuplicateSymbolError" m
| DeclarationError (p,m) -> print_endline @@ pp_err p "DeclarationError" m
| InvalidExpression (p,m) -> print_endline @@ pp_err p "InvalidExpression" m
| ContractError (p,m) -> print_endline @@ pp_err p "ContractError" m
| APIError (p,m) -> print_endline @@ pp_err p "APIError" m
| GenerateLigoError (p,m) -> print_endline @@ pp_err p "GenerateLigoError" m
)
)
let () = Command.run ~version:"0.1" ~build_info:"git" command | null | https://raw.githubusercontent.com/dakk/yallo-lang/55a1b379306c9f113bd707e78b6e0c1be81bb7be/src/yallo.ml | ocaml | | "build-storage" ->
| "build-parameter" ->
| "interface-of-michelson" -> Interface_of_michelson.extract filename opt | open Core
open Yallo
open Helpers.Errors
let run action filename opt =
(match action with
| "compile" -> Compiler.compile filename opt
| "extract-interface" -> Compiler.extract_interface filename opt
| _ -> raise @@ CompilerError ("Invalid compiler action: " ^ action)
)
let summary = ""
^ "=== actions ===\n\n"
^ " compile file.yallo [-dcontract ContractName] [-target ligo|tz|coq]\n"
^ " compiles a contract ContractName to target language\n\n"
^ " extract-interface file.yallo -dcontract ContractName\n"
^ " extracts the yallo interface for the given contract\n\n"
^ " interface-of-michelson file.tz\n"
^ " produce a yallo interface from michelson contract\n"
let command =
Command.basic
~summary:"Yallo-lang compiler"
~readme:(fun () -> summary)
(let open Command.Let_syntax in
let open Command.Param in
let%map
action = anon ("action" %: string)
and filename = anon ("filename" %: string)
and contract = flag "-contract" (optional string) ~doc:" selected contract"
and past = flag "-print-ast" no_arg ~doc:" print ast"
and ppt = flag "-print-pt" no_arg ~doc:" print parse-tree"
and pligo = flag "-print-ligo" no_arg ~doc:" print ligo code"
and verbose = flag "-verbose" no_arg ~doc:" enable verbosity"
and noremoveunused = flag "-no-remove-unused" no_arg ~doc:" disable removing unused symbols"
and target = flag "-target" (optional string) ~doc:" target language (ligo, tz, coq)"
in fun () ->
let opt = Compiler.{
target = if is_none target then Some("tz") else target;
contract = contract;
print_pt = ppt;
print_ast = past;
print_ligo = pligo;
verbose = verbose;
no_remove_unused = noremoveunused;
} in (
let pp_err p cc m = pp_message p cc m true in
try run action filename opt with
| CompilerError (m) -> print_endline @@ pp_err None "CompilerError" m
| SyntaxError (p,m) -> print_endline @@ pp_err p "SyntaxError" m
| ParsingError (p,m) -> print_endline @@ pp_err p "ParsingError" m
| TypeError (p,m) -> print_endline @@ pp_err p "TypeError" m
| SymbolNotFound (p,m) -> print_endline @@ pp_err p "SymbolNotFound" m
| DuplicateSymbolError (p,m) -> print_endline @@ pp_err p "DuplicateSymbolError" m
| DeclarationError (p,m) -> print_endline @@ pp_err p "DeclarationError" m
| InvalidExpression (p,m) -> print_endline @@ pp_err p "InvalidExpression" m
| ContractError (p,m) -> print_endline @@ pp_err p "ContractError" m
| APIError (p,m) -> print_endline @@ pp_err p "APIError" m
| GenerateLigoError (p,m) -> print_endline @@ pp_err p "GenerateLigoError" m
)
)
let () = Command.run ~version:"0.1" ~build_info:"git" command |
bd68c1a4f28dccce3a0ab861ad9ef2fe13920feab9dfc0a278fd2e9c8ce66e60 | mvaldesdeleon/aoc18 | Day21.hs | # LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
module Day21
( day21
) where
import Control.Lens
import Data.Bits ((.&.), (.|.))
import Data.List (find, genericLength)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
import Paths_aoc18 (getDataFileName)
import Text.Parsec (Parsec, digit, many, many1, newline, parse,
sepBy1, space, string, try, (<?>), (<|>))
data CPU = CPU
{ _registries :: [Integer]
, _ipIx :: Integer
, _program :: [Instruction]
} deriving (Show, Eq)
data OpCode
= ADDR
| ADDI
| MULR
| MULI
| BANR
| BANI
| BORR
| BORI
| SETR
| SETI
| GTIR
| GTRI
| GTRR
| EQRI
| EQIR
| EQRR
deriving (Show, Eq, Ord)
data Instruction = Instruction
{ _opcode :: OpCode
, _a :: Integer
, _b :: Integer
, _c :: Integer
} deriving (Show, Eq)
makeLenses ''CPU
makeLenses ''Instruction
loadInput :: IO String
loadInput = getDataFileName "inputs/day-21.txt" >>= readFile
fI :: (Integral a, Num b) => a -> b
fI = fromIntegral
number :: Parsec String () Integer
number = read <$> (many space *> many1 digit)
parseDecaration :: Parsec String () Integer
parseDecaration = string "#ip " *> number
parseOpCode :: Parsec String () OpCode
parseOpCode =
pADDR <|> pADDI <|> pMULR <|> pMULI <|> pBANR <|> pBANI <|> pBORR <|> pBORI <|>
pSETR <|>
pSETI <|>
pGTIR <|>
pGTRI <|>
pGTRR <|>
pEQRI <|>
pEQIR <|>
pEQRR <?>
"opcode"
where
pADDR = try (ADDR <$ string "addr")
pADDI = try (ADDI <$ string "addi")
pMULR = try (MULR <$ string "mulr")
pMULI = try (MULI <$ string "muli")
pBANR = try (BANR <$ string "banr")
pBANI = try (BANI <$ string "bani")
pBORR = try (BORR <$ string "borr")
pBORI = try (BORI <$ string "bori")
pSETR = try (SETR <$ string "setr")
pSETI = try (SETI <$ string "seti")
pGTIR = try (GTIR <$ string "gtir")
pGTRI = try (GTRI <$ string "gtri")
pGTRR = try (GTRR <$ string "gtrr")
pEQRI = try (EQRI <$ string "eqri")
pEQIR = try (EQIR <$ string "eqir")
pEQRR = try (EQRR <$ string "eqrr")
parseInstruction :: Parsec String () Instruction
parseInstruction =
Instruction <$> parseOpCode <*> (many1 space *> number) <*>
(many1 space *> number) <*>
(many1 space *> number)
parseCPU :: Parsec String () CPU
parseCPU =
CPU <$> pure [0, 0, 0, 0, 0, 0] <*> (parseDecaration <* newline) <*>
parseInstruction `sepBy1`
newline
parseInput :: String -> CPU
parseInput input =
case result of
Left e -> error $ show e
Right r -> r
where
result = parse parseCPU "" input
operations :: M.Map OpCode (Integer -> Integer -> Integer -> CPU -> CPU)
operations =
M.fromList $
zip [ ADDR
, ADDI
, MULR
, MULI
, BANR
, BANI
, BORR
, BORI
, SETR
, SETI
, GTIR
, GTRI
, GTRR
, EQIR
, EQRI
, EQRR
]
[ addr
, addi
, mulr
, muli
, banr
, bani
, borr
, bori
, setr
, seti
, gtir
, gtri
, gtrr
, eqir
, eqri
, eqrr
]
addr :: Integer -> Integer -> Integer -> CPU -> CPU
addr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~ (ra + rb)
addi :: Integer -> Integer -> Integer -> CPU -> CPU
addi a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~ (ra + b)
mulr :: Integer -> Integer -> Integer -> CPU -> CPU
mulr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~ (ra * rb)
muli :: Integer -> Integer -> Integer -> CPU -> CPU
muli a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~ (ra * b)
banr :: Integer -> Integer -> Integer -> CPU -> CPU
banr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~ (ra .&. rb)
bani :: Integer -> Integer -> Integer -> CPU -> CPU
bani a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~ (ra .&. b)
borr :: Integer -> Integer -> Integer -> CPU -> CPU
borr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~ (ra .|. rb)
bori :: Integer -> Integer -> Integer -> CPU -> CPU
bori a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~ (ra .|. b)
setr :: Integer -> Integer -> Integer -> CPU -> CPU
setr a _ c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~ ra
seti :: Integer -> Integer -> Integer -> CPU -> CPU
seti a _ c cpu = cpu & (registries . ix (fI c)) .~ a
gtir :: Integer -> Integer -> Integer -> CPU -> CPU
gtir a b c cpu =
let rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~
(if a > rb
then 1
else 0)
gtri :: Integer -> Integer -> Integer -> CPU -> CPU
gtri a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~
(if ra > b
then 1
else 0)
gtrr :: Integer -> Integer -> Integer -> CPU -> CPU
gtrr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~
(if ra > rb
then 1
else 0)
eqir :: Integer -> Integer -> Integer -> CPU -> CPU
eqir a b c cpu =
let rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~
(if a == rb
then 1
else 0)
eqri :: Integer -> Integer -> Integer -> CPU -> CPU
eqri a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~
(if ra == b
then 1
else 0)
eqrr :: Integer -> Integer -> Integer -> CPU -> CPU
eqrr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~
(if ra == rb
then 1
else 0)
halted :: CPU -> Bool
halted cpu =
let ip = fromMaybe 0 $ cpu ^? registries . ix (fI $ cpu ^. ipIx)
in ip >= genericLength (cpu ^. program)
execute :: CPU -> CPU
execute cpu =
let ip = fromMaybe 0 $ cpu ^? registries . ix (fI $ cpu ^. ipIx)
Just ins = cpu ^? (program . ix (fI ip))
in ((registries . ix (fI $ cpu ^. ipIx)) %~ succ) . executeInstruction ins $
cpu
executeInstruction :: Instruction -> CPU -> CPU
executeInstruction Instruction {..} = (operations M.! _opcode) _a _b _c
run :: CPU -> CPU
run cpu =
if halted cpu
then cpu
else run $ execute cpu
ips :: CPU -> [Integer]
ips cpu =
if halted cpu
then []
else fromMaybe 0 (cpu ^? registries . ix (fI $ cpu ^. ipIx)) :
ips (execute cpu)
findCycle :: Ord a => [a] -> (Integer, Integer)
findCycle vs = go vs 0 M.empty
where
go :: Ord a => [a] -> Integer -> M.Map a Integer -> (Integer, Integer)
go (v:vs) i vals =
case v `M.lookup` vals of
Just iv -> (iv, i - iv)
Nothing -> go vs (i + 1) (M.insert v i vals)
day21 :: IO ()
day21 = do
input <- parseInput <$> loadInput
let haltVals =
map (fromMaybe 0 . (^? registries . ix 3)) $ filter at28 $
iterate execute input
print $ head haltVals
print $ head $ drop ( 5382 + 5069 - 1 ) $ haltVals
let (lambda, mu) = findCycle haltVals
print $ head . drop (fI lambda + fI mu - 1) $ haltVals
where
at28 cpu = fromMaybe 0 (cpu ^? registries . ix (fI $ cpu ^. ipIx)) == 28
| null | https://raw.githubusercontent.com/mvaldesdeleon/aoc18/1a6f6de7c482e5de264360e36f97a3c7487e2457/src/Day21.hs | haskell | # LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
module Day21
( day21
) where
import Control.Lens
import Data.Bits ((.&.), (.|.))
import Data.List (find, genericLength)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
import Paths_aoc18 (getDataFileName)
import Text.Parsec (Parsec, digit, many, many1, newline, parse,
sepBy1, space, string, try, (<?>), (<|>))
data CPU = CPU
{ _registries :: [Integer]
, _ipIx :: Integer
, _program :: [Instruction]
} deriving (Show, Eq)
data OpCode
= ADDR
| ADDI
| MULR
| MULI
| BANR
| BANI
| BORR
| BORI
| SETR
| SETI
| GTIR
| GTRI
| GTRR
| EQRI
| EQIR
| EQRR
deriving (Show, Eq, Ord)
data Instruction = Instruction
{ _opcode :: OpCode
, _a :: Integer
, _b :: Integer
, _c :: Integer
} deriving (Show, Eq)
makeLenses ''CPU
makeLenses ''Instruction
loadInput :: IO String
loadInput = getDataFileName "inputs/day-21.txt" >>= readFile
fI :: (Integral a, Num b) => a -> b
fI = fromIntegral
number :: Parsec String () Integer
number = read <$> (many space *> many1 digit)
parseDecaration :: Parsec String () Integer
parseDecaration = string "#ip " *> number
parseOpCode :: Parsec String () OpCode
parseOpCode =
pADDR <|> pADDI <|> pMULR <|> pMULI <|> pBANR <|> pBANI <|> pBORR <|> pBORI <|>
pSETR <|>
pSETI <|>
pGTIR <|>
pGTRI <|>
pGTRR <|>
pEQRI <|>
pEQIR <|>
pEQRR <?>
"opcode"
where
pADDR = try (ADDR <$ string "addr")
pADDI = try (ADDI <$ string "addi")
pMULR = try (MULR <$ string "mulr")
pMULI = try (MULI <$ string "muli")
pBANR = try (BANR <$ string "banr")
pBANI = try (BANI <$ string "bani")
pBORR = try (BORR <$ string "borr")
pBORI = try (BORI <$ string "bori")
pSETR = try (SETR <$ string "setr")
pSETI = try (SETI <$ string "seti")
pGTIR = try (GTIR <$ string "gtir")
pGTRI = try (GTRI <$ string "gtri")
pGTRR = try (GTRR <$ string "gtrr")
pEQRI = try (EQRI <$ string "eqri")
pEQIR = try (EQIR <$ string "eqir")
pEQRR = try (EQRR <$ string "eqrr")
parseInstruction :: Parsec String () Instruction
parseInstruction =
Instruction <$> parseOpCode <*> (many1 space *> number) <*>
(many1 space *> number) <*>
(many1 space *> number)
parseCPU :: Parsec String () CPU
parseCPU =
CPU <$> pure [0, 0, 0, 0, 0, 0] <*> (parseDecaration <* newline) <*>
parseInstruction `sepBy1`
newline
parseInput :: String -> CPU
parseInput input =
case result of
Left e -> error $ show e
Right r -> r
where
result = parse parseCPU "" input
operations :: M.Map OpCode (Integer -> Integer -> Integer -> CPU -> CPU)
operations =
M.fromList $
zip [ ADDR
, ADDI
, MULR
, MULI
, BANR
, BANI
, BORR
, BORI
, SETR
, SETI
, GTIR
, GTRI
, GTRR
, EQIR
, EQRI
, EQRR
]
[ addr
, addi
, mulr
, muli
, banr
, bani
, borr
, bori
, setr
, seti
, gtir
, gtri
, gtrr
, eqir
, eqri
, eqrr
]
addr :: Integer -> Integer -> Integer -> CPU -> CPU
addr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~ (ra + rb)
addi :: Integer -> Integer -> Integer -> CPU -> CPU
addi a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~ (ra + b)
mulr :: Integer -> Integer -> Integer -> CPU -> CPU
mulr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~ (ra * rb)
muli :: Integer -> Integer -> Integer -> CPU -> CPU
muli a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~ (ra * b)
banr :: Integer -> Integer -> Integer -> CPU -> CPU
banr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~ (ra .&. rb)
bani :: Integer -> Integer -> Integer -> CPU -> CPU
bani a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~ (ra .&. b)
borr :: Integer -> Integer -> Integer -> CPU -> CPU
borr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~ (ra .|. rb)
bori :: Integer -> Integer -> Integer -> CPU -> CPU
bori a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~ (ra .|. b)
setr :: Integer -> Integer -> Integer -> CPU -> CPU
setr a _ c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~ ra
seti :: Integer -> Integer -> Integer -> CPU -> CPU
seti a _ c cpu = cpu & (registries . ix (fI c)) .~ a
gtir :: Integer -> Integer -> Integer -> CPU -> CPU
gtir a b c cpu =
let rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~
(if a > rb
then 1
else 0)
gtri :: Integer -> Integer -> Integer -> CPU -> CPU
gtri a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~
(if ra > b
then 1
else 0)
gtrr :: Integer -> Integer -> Integer -> CPU -> CPU
gtrr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~
(if ra > rb
then 1
else 0)
eqir :: Integer -> Integer -> Integer -> CPU -> CPU
eqir a b c cpu =
let rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~
(if a == rb
then 1
else 0)
eqri :: Integer -> Integer -> Integer -> CPU -> CPU
eqri a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
in cpu & (registries . ix (fI c)) .~
(if ra == b
then 1
else 0)
eqrr :: Integer -> Integer -> Integer -> CPU -> CPU
eqrr a b c cpu =
let ra = fromMaybe 0 $ cpu ^? registries . ix (fI a)
rb = fromMaybe 0 $ cpu ^? registries . ix (fI b)
in cpu & (registries . ix (fI c)) .~
(if ra == rb
then 1
else 0)
halted :: CPU -> Bool
halted cpu =
let ip = fromMaybe 0 $ cpu ^? registries . ix (fI $ cpu ^. ipIx)
in ip >= genericLength (cpu ^. program)
execute :: CPU -> CPU
execute cpu =
let ip = fromMaybe 0 $ cpu ^? registries . ix (fI $ cpu ^. ipIx)
Just ins = cpu ^? (program . ix (fI ip))
in ((registries . ix (fI $ cpu ^. ipIx)) %~ succ) . executeInstruction ins $
cpu
executeInstruction :: Instruction -> CPU -> CPU
executeInstruction Instruction {..} = (operations M.! _opcode) _a _b _c
run :: CPU -> CPU
run cpu =
if halted cpu
then cpu
else run $ execute cpu
ips :: CPU -> [Integer]
ips cpu =
if halted cpu
then []
else fromMaybe 0 (cpu ^? registries . ix (fI $ cpu ^. ipIx)) :
ips (execute cpu)
findCycle :: Ord a => [a] -> (Integer, Integer)
findCycle vs = go vs 0 M.empty
where
go :: Ord a => [a] -> Integer -> M.Map a Integer -> (Integer, Integer)
go (v:vs) i vals =
case v `M.lookup` vals of
Just iv -> (iv, i - iv)
Nothing -> go vs (i + 1) (M.insert v i vals)
day21 :: IO ()
day21 = do
input <- parseInput <$> loadInput
let haltVals =
map (fromMaybe 0 . (^? registries . ix 3)) $ filter at28 $
iterate execute input
print $ head haltVals
print $ head $ drop ( 5382 + 5069 - 1 ) $ haltVals
let (lambda, mu) = findCycle haltVals
print $ head . drop (fI lambda + fI mu - 1) $ haltVals
where
at28 cpu = fromMaybe 0 (cpu ^? registries . ix (fI $ cpu ^. ipIx)) == 28
|
|
656b2e094807dc977d3379cfa575dd134bba32b832e6649dce22764907b105b2 | jeromesimeon/Galax | print_xquery_algebra.ml | (***********************************************************************)
(* *)
(* GALAX *)
(* XQuery Engine *)
(* *)
Copyright 2001 - 2007 .
(* Distributed only by permission. *)
(* *)
(***********************************************************************)
$ I d : print_xquery_algebra.ml , v 1.75 2007/10/16 01:25:34
(* Module: Print_xquery_algebra
Description:
This module implements pretty-printing for the XQuery Algebra
AST.
*)
open Error
open Gmisc
open Occurrence
open Namespace_names
open Namespace_symbols
open Datatypes
open Xquery_common_ast
open Xquery_algebra_ast
open Xquery_algebra_ast_util
open Xquery_algebra_ast_annotation_util
open Print_common
open Format
(*************)
(* Node kind *)
(*************)
let print_aelement_test ff aet =
match aet with
| ASchemaElementTest elem_sym ->
let cename = relem_name elem_sym in
fprintf ff "schema-element(%a)" print_rqname cename
| AElementTest None ->
fprintf ff "element()"
| AElementTest (Some (elem_sym, None)) ->
let cename = relem_name elem_sym in
fprintf ff "element(%a)" print_rqname cename
| AElementTest (Some (elem_sym, Some type_sym)) ->
let cename = relem_name elem_sym in
let ctname = rtype_name type_sym in
fprintf ff "element(%a,%a)" print_rqname cename print_rqname ctname
let print_aattribute_test ff aat =
match aat with
| ASchemaAttributeTest attr_sym ->
let caname = rattr_name attr_sym in
fprintf ff "schema-attribute(%a)" print_rqname caname
| AAttributeTest None ->
fprintf ff "attribute()"
| AAttributeTest (Some (attr_sym, None)) ->
let caname = rattr_name attr_sym in
fprintf ff "attribute(%a)" print_rqname caname
| AAttributeTest (Some (attr_sym, Some type_sym)) ->
let caname = rattr_name attr_sym in
let ctname = rtype_name type_sym in
fprintf ff "attribute(%a,%a)" print_rqname caname print_rqname ctname
let print_akind_test ff akt =
match akt with
| ADocumentKind None ->
fprintf ff "document-node()"
| ADocumentKind (Some aet) ->
fprintf ff "document-node(%a)" print_aelement_test aet
| AElementKind aet ->
fprintf ff "%a" print_aelement_test aet
| AAttributeKind aat ->
fprintf ff "%a" print_aattribute_test aat
| APIKind None ->
fprintf ff "processing-instruction()"
| APIKind (Some s) ->
fprintf ff "processing-instruction(\"%s\")" s
| ACommentKind ->
fprintf ff "comment()"
| ATextKind ->
fprintf ff "text()"
| AAnyKind ->
fprintf ff "node()"
(******************)
(* Sequence types *)
(******************)
let print_aitemtype ff adtk =
match adtk with
| AITKindTest akt ->
fprintf ff "%a" print_akind_test akt
| AITTypeRef type_sym ->
let ctname = rtype_name type_sym in
fprintf ff "type(%a)" print_rqname ctname
| AITItem ->
fprintf ff "item()"
| AITNumeric ->
fprintf ff "numeric()"
| AITAnyString ->
fprintf ff "anystring()"
| AITEmpty ->
fprintf ff "empty()"
| AITAtomic type_sym ->
let ctname = rtype_name type_sym in
fprintf ff "%a" print_rqname ctname
let print_asequencetype ff adt =
match adt.pasequencetype_desc with
| (adtk,occ) ->
fprintf ff "%a%a" print_aitemtype adtk print_occurence occ
(* Replicated code should make a print core util *)
let print_anode_test ff nt =
match nt with
| APNameTest qn ->
fprintf ff "%s" (Namespace_symbols.relem_prefix_string qn)
| APNodeKindTest nk ->
fprintf ff "%a" print_akind_test nk
let print_optasequencetype ff t =
match t with
| None -> ()
| Some dt ->
fprintf ff " as %a" print_asequencetype dt
(***************************)
(* Core XQuery expressions *)
(***************************)
let print_algop_insert_loc ff loc =
match loc with
| AOUAsLastInto -> fprintf ff "as last into"
| AOUAsFirstInto -> fprintf ff "as first into"
| AOUInto -> fprintf ff "into"
| AOUAfter -> fprintf ff "after"
| AOUBefore -> fprintf ff "before"
let print_algop_value_of_flag ff vf =
match vf with
| Normal_Replace -> ()
| Value_Of_Replace -> fprintf ff "value of@;"
let rec print_var_list ff tfl =
match tfl with
| [] -> ()
| x :: [] ->
fprintf ff "%a" print_rqname x
| x :: rest ->
fprintf ff "%a,%a" print_rqname x print_var_list rest
let print_free_vars ff fv =
if fv = []
then ()
else fprintf ff "free : %a;@;" print_var_list fv
let string_of_variable_usage u =
match u with
| Never -> "Never"
| Once -> "Once"
| Many -> "Many"
| Redefined -> "Redefined"
let print_use_count ff (var,(count,usage)) =
fprintf ff "(%a,%i,%s),"
print_rqname var
count
(string_of_variable_usage usage)
let print_use_counts ff uc_list =
List.iter (fprintf ff "%a" print_use_count) uc_list
let print_bound_vars ff bv =
if bv = []
then ()
else fprintf ff "bound : %a;@;" print_use_counts bv
let print_accessed_fields ff tf =
if tf = []
then ()
else fprintf ff "accessed : %a;@;" print_var_list tf
let string_of_cardinality c =
match c with
| NoTable -> "NoTable"
| Table COne -> "Table COne"
| Table CMany -> "Table CMany"
let print_cardinality ff c =
fprintf ff "cardinality: %s;@;" (string_of_cardinality c)
let print_candidate_fields ff tf =
if tf = []
then ()
else fprintf ff "candidate fields : %a;@;" print_var_list tf
let print_tuple_field_use_counts ff tf =
if tf = [] then
()
else
fprintf ff "tuple field use counts : %a;@;" print_use_counts tf
let print_returned_fields ff tf =
if tf = []
then ()
else fprintf ff "returned : %a;@;" print_var_list tf
let check_lists cur f l_of_l =
let apply b cur_list = b || (not ((f cur_list) = cur)) in
List.fold_left apply false l_of_l
let free_var_changed cur i_list d_list =
(* check that cur is the same as each of the lists *)
check_lists cur algop_get_free_variables (i_list @ d_list)
let tuple_fields_changed cur i_list d_list =
check_lists cur algop_get_accessed_fields (i_list @ d_list)
let print_free_variable_desc ff algop =
let has_changed algop =
let fv_list = algop_get_free_variables algop in
let tf_list = algop_get_accessed_fields algop in
let i_list = subexpr_to_list algop.psub_expression in
let d_list = subexpr_to_list algop.pdep_sub_expression in
(free_var_changed fv_list i_list d_list)
|| (tuple_fields_changed tf_list i_list d_list)
in
let empty_fvd op =
((algop_get_free_variables op) = []) &&
((algop_get_accessed_fields op) = []) &&
((algop_get_returned_fields op) = []) &&
((algop_get_bound_use_counts op) = [])
in
if ((not (empty_fvd algop)) &&
(has_changed algop)) || true then
begin
let (tuple_field_use_counts, candidate_fields, cardinality) = algop_get_tuple_field_use_counts algop in
fprintf ff "@[|%a%a%a%a%a%a%a|@]@;"
print_free_vars (algop_get_free_variables algop)
print_bound_vars (algop_get_bound_use_counts algop)
print_accessed_fields (algop_get_accessed_fields algop)
print_returned_fields (algop_get_returned_fields algop)
print_tuple_field_use_counts tuple_field_use_counts
print_candidate_fields candidate_fields
print_cardinality cardinality
end
let print_group_desc ff gd =
match (get_aggregate_type gd) with
| None ->
fprintf ff "[%a][%a][%a]"
print_var_list (Xquery_algebra_ast_util.get_group_names gd)
print_var_list (Xquery_algebra_ast_util.get_valid_names gd)
print_rqname (Xquery_algebra_ast_util.get_aggregate_name gd)
| Some dt ->
fprintf ff "[%a][%a][%a(%a)]"
print_var_list (Xquery_algebra_ast_util.get_group_names gd)
print_var_list (Xquery_algebra_ast_util.get_valid_names gd)
print_rqname (Xquery_algebra_ast_util.get_aggregate_name gd)
print_asequencetype dt
let print_http_method ff hm =
match hm with
| Galax_url.File str ->
fprintf ff "%s" ("\"" ^ str ^ "\"")
| Galax_url.Http (str1, i, str2) ->
fprintf ff "%s" ("\"" ^ str1 ^ (string_of_int i) ^ str2 ^ "\"")
| Galax_url.ExternalSource (str1, str2, opt_str, str4) ->
begin
let str3 = match opt_str with
| None -> ""
| Some str -> str
in
fprintf ff "%s" ("\"" ^ str1 ^ str2 ^ str3 ^ str4 ^ "\"")
end
let print_ordered idname print_algop ff deps =
let apply v = fprintf ff "%a" (print_algop idname 0) v in
Array.iter apply deps
let print_tuple_create idname print_algop ff (rnames,exprs) =
begin
if ((Array.length rnames) != (Array.length exprs))
then
raise (Query
(Malformed_Tuple
("Number of tuple slots does not equal number of expressions")))
end;
begin
for i = 0 to (Array.length rnames) - 1 do
let printsemi ff i =
if (i == (Array.length rnames -1))
then
fprintf ff "%a"
(print_algop idname 0) exprs.(i)
else
fprintf ff "%a;@ "
(print_algop idname 0) exprs.(i)
in
if (fst rnames.(i)) = None
then
fprintf ff "@[<hv 2>%a :@;%a@]"
print_rqname (snd rnames.(i))
printsemi i
else
fprintf ff "@[<hv 2>%a%a :@;%a@]"
print_rqname (snd rnames.(i))
print_optasequencetype (fst rnames.(i))
printsemi i
done
end
let rec print_params idname print_algop ff es =
match es with
| e :: [] ->
fprintf ff "%a" (print_algop idname 0) e
| e :: es ->
fprintf ff "%a,@ %a" (print_algop idname 0) e (print_params idname print_algop) es
| [] ->
()
let print_coptvariable_as ff ovn =
match ovn with
| None -> ()
| Some vn -> fprintf ff "$%a as " print_rqname vn
let print_coptvariable ff ovn =
match ovn with
| None -> ()
| Some vn -> fprintf ff "$%a " print_rqname vn
let print_cpattern ff (p, ovn) =
match p.papattern_desc with
| ACase m ->
fprintf ff "case %a%a" print_coptvariable_as ovn print_asequencetype m
| ADefault ->
fprintf ff "default %a" print_coptvariable ovn
let print_cases print_algop idname ff (pattern,exprs) =
if ((Array.length pattern) != (Array.length exprs)) then
raise (Query
(Malformed_Expr
("Number of cases does not match the number of expressions")));
for i = 0 to (Array.length pattern)-1 do
fprintf ff "%a return@;<1 2>%a@;"
print_cpattern pattern.(i)
(print_algop idname 0) exprs.(i)
done
let print_aoeelem_contents idname print_algop ff ecs =
for i = 0 to (Array.length ecs) - 1 do
fprintf ff "%a" (print_algop idname 0) ecs.(i)
done
let print_group_by ff gds =
List.iter (fun gd ->
fprintf ff "%a"
print_group_desc gd) gds
let print_dep idname print_algop ff algop =
fprintf ff "{%a}@," (print_algop idname 0) algop
let print_many_deps idname print_algop ff algops =
Array.iter (print_dep idname print_algop ff) algops
let rec print_pred_desc idname p ops print_algop ff (pred_desc:predicate_desc) =
match pred_desc with
| SimpleConjunct (start_i,end_i) ->
begin
fprintf ff "@[<hov 1>";
for i = start_i to end_i - 1 do
fprintf ff "%a@;<1 0>and@;<1 0>" (print_algop idname 3) ops.(i)
done;
fprintf ff "%a" (print_algop idname 3) ops.(end_i);
fprintf ff "@]"
end
| ComplexConjunct (l,r) ->
if p > 3
then
fprintf ff "@[<hv 1>(@[<hov 1>%a@;<1 0>and@;<1 0>%a@])@]"
(print_pred_desc idname 3 ops print_algop) l
(print_pred_desc idname 3 ops print_algop) r
else
fprintf ff "@[<hov 1>%a@;<1 0>and@;<1 0>%a@]"
(print_pred_desc idname 3 ops print_algop) l
(print_pred_desc idname 3 ops print_algop) r
| Disjunct (l,r) ->
if p > 2
then
fprintf ff "@[<hv 1>(@[<hov 1>%a@;<1 0>or@;<1 0>%a@])@]"
(print_pred_desc idname 2 ops print_algop) l
(print_pred_desc idname 2 ops print_algop) r
else
fprintf ff "@[<hov 1>%a@;<1 0>or@;<1 0>%a@]"
(print_pred_desc idname 2 ops print_algop) l
(print_pred_desc idname 2 ops print_algop) r
let print_twig_node_test ff ont =
match ont with
| Some nt -> fprintf ff "%a" print_anode_test nt
| None -> fprintf ff "."
let print_out_field ff twignode =
match twignode.out with
| Some f ->
begin
if twignode.restore_out
then fprintf ff "{%a*}" print_rqname f
else fprintf ff "{%a}" print_rqname f
end
| None ->
fprintf ff ""
let print_sbdo ff twignode =
(* if Debug.default_debug() then *)
begin
let (sigma,delta) = twignode.requires_sbdo in
let msg = (
"(" ^
(if sigma && delta then "s,d"
else if delta then "d"
else if sigma then "s"
else "") ^ ")"
)
in
(* Debug.print_default_debug msg *)
fprintf ff "%s" msg
end
let rec print_child_node pattern ff child_twig =
match child_twig with
| Some (typ, ind) ->
fprintf ff "/%a::%a"
print_axis typ
(print_twig_node_aux pattern) ind
| None -> fprintf ff ""
and print_predicates pattern ff predlist =
match predlist with
| hd::tl ->
let (typ, ind) = hd in
fprintf ff "[./%a::%a]%a"
print_axis typ
(print_twig_node_aux pattern) ind
(print_predicates pattern) tl
| [] ->
fprintf ff ""
and print_twig_node_aux pattern ff index =
fprintf ff "%a%a%a%a%a"
print_twig_node_test pattern.(index).node_test
print_out_field pattern.(index)
print_sbdo pattern.(index)
(print_predicates pattern) pattern.(index).pred_twigs
(print_child_node pattern) pattern.(index).child_twig
let print_twig_node ff pattern =
print_twig_node_aux pattern ff 0
let print_physical_signature ff algop_sig =
match algop_sig with
| None -> ()
| Some x ->
fprintf ff "(: %s :)@\n" (Print_xquery_physical_type.string_of_eval_sig x)
let print_algop_main idname physical p print_algop ff algop =
begin
if !Conf.bPrinting_comp_annotations
then print_free_variable_desc ff algop
end;
begin
if physical
then
print_physical_signature ff algop.palgop_expr_eval_sig
end;
match algop.palgop_expr_name with
| AOELetvar (odt,vn) ->
let indep = access_onesub algop.psub_expression in
let dep = access_onesub algop.pdep_sub_expression in
if p > 1
then
fprintf ff
"@[<hv 1>(@[<hv 2>letvar $%a%a :=@ %a@]@;<1 0>@[<hv 2>return@;<1 0>%a@])@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 1) indep
(print_algop idname 1) dep
else
fprintf ff
"@[<hv 0>@[<hv 2>letvar $%a%a :=@ %a@]@;<1 0>@[<hv 2>return@;<1 0>%a@]@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 1) indep
(print_algop idname 1) dep
| AOEIf ->
let e1 = access_onesub algop.psub_expression in
let e2,e3 = access_twosub algop.pdep_sub_expression in
if p > 1
then
fprintf ff
"@[<hv 1>(if (%a)@;<1 0>@[<hv 2>then@;<1 0>%a@]@;<1 0>@[<hv 2>else@;<1 0>%a@])@]"
(print_algop idname 0) e1
(print_algop idname 1) e2
(print_algop idname 1) e3
else
fprintf ff
"@[<hv 0>if (%a)@;<1 0>@[<hv 2>then@;<1 0>%a@]@;<1 0>@[<hv 2>else@;<1 0>%a@]@]"
(print_algop idname 0) e1
(print_algop idname 1) e2
(print_algop idname 1) e3
| AOEWhile ->
let e1,e2 = access_twosub algop.pdep_sub_expression in
if p > 1
then
fprintf ff
"@[<hv 1>(while (%a)@;<1 0>@[<hv 2>return@;<1 0>%a@])@]"
(print_algop idname 0) e1
(print_algop idname 1) e2
else
fprintf ff
"@[<hv 0>while (%a)@;<1 0>@[<hv 2>return@;<1 0>%a@]@]"
(print_algop idname 0) e1
(print_algop idname 1) e2
| AOETypeswitch pattern ->
let e' = access_onesub algop.psub_expression in
let cases = access_manysub algop.pdep_sub_expression in
if p > 1
then
fprintf ff "@[<hv 1>(@[<hv 2>@[<hv 2>typeswitch (@,%a@;<0 -2>)@]@;<1 0>%a@])@]"
(print_algop idname 0) e'
(print_cases print_algop idname) (pattern,cases)
else
fprintf ff "@[<hv 2>@[<hv 2>typeswitch (@,%a@;<0 -2>)@]@;<1 0>%a@]"
(print_algop idname 0) e'
(print_cases print_algop idname) (pattern,cases)
| AOEVar v ->
if Namespace_names.rqname_equal v idname then
fprintf ff "ID"
else
fprintf ff "$%a" print_rqname v
| AOEScalar bv ->
fprintf ff "%a" print_literal bv
| AOEText t ->
fprintf ff "text { \"%s\" }" t
| AOECharRef i ->
fprintf ff "@[<hv 2>text {@,\"&#%i;\"@;<0 -2>}@]" i
| AOETextComputed ->
let e = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>text {@,\"%a\"@;<0 -2>}@]"
(print_algop idname 0) e
| AOEPI (target,pi_content) ->
fprintf ff "<?%s %s?>" target pi_content
| AOEPIComputed ->
let e1,e2 = access_twosub algop.psub_expression in
fprintf ff "@[<hv 2>processing-instruction {@,%a@;<0 -2>} {@,%a@;<0 -2>}@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
| AOEComment c ->
fprintf ff "<!--%s-->" c
| AOECommentComputed ->
let e = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>comment {@,%a@;<0 -2>}@]"
(print_algop idname 0) e
| AOEDocument ->
let e = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>document {@,%a@;<0 -2>}@]"
(print_algop idname 0) e
| AOECallUserDefined ((name,arity), optintypes, opttypes, _, _)
| AOECallBuiltIn ((name,arity), optintypes, opttypes, _) ->
let params = Array.to_list (access_manysub algop.psub_expression) in
(* let is_upd = updating_flag_to_string upd in *)
fprintf ff "@[<hv 2>%a(@,%a@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
| AOECallOverloaded ((name, arity),table) ->
let params = Array.to_list (access_manysub algop.psub_expression) in
fprintf ff "@[<hv 2>%a(@,%a@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
| AOEConvertSimple atomic_type ->
let name = Namespace_builtin.fs_convert_simple_operand in
let param1 = access_onesub algop.psub_expression in
let s = string_of_proto_value atomic_type in
let params = [param1] in
fprintf ff "@[<hv 2>%a(@,%a,@ %s@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
s
| AOEPromoteNumeric atomic_type ->
let name = Namespace_builtin.fs_promote_to_numeric in
let param1 = access_onesub algop.psub_expression in
let s = string_of_proto_value atomic_type in
let params = [param1] in
fprintf ff "@[<hv 2>%a(@,%a,@ %s@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
s
| AOEPromoteAnyString ->
let name = Namespace_builtin.fs_promote_to_anystring in
let param1 = access_onesub algop.psub_expression in
let params = [param1] in
fprintf ff "@[<hv 2>%a(@,%a@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
| AOEUnsafePromoteNumeric atomic_type ->
let name = Namespace_builtin.fs_unsafe_promote_to_numeric in
let param1 = access_onesub algop.psub_expression in
let s = string_of_proto_value atomic_type in
let params = [param1] in
fprintf ff "@[<hv 2>%a(@,%a,@ %s@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
s
| AOESeq ->
let e1,e2 = access_twosub algop.psub_expression in
if p > 0 then
fprintf ff "@[<hov 1>(%a,@ %a)@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
else
fprintf ff "@[<hov 0>%a,@ %a@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
| AOEImperativeSeq ->
let e1,e2 = access_twosub algop.psub_expression in
if p > 0 then
fprintf ff "@[<hov 1>@,%a;@ %a@,@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
else
fprintf ff "@[<hov 0>%a;@ %a@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
| AOEEmpty ->
fprintf ff "()"
| AOEElem (l,nsenv) ->
let el = access_manysub algop.psub_expression in
begin
match (Array.length el) with
| 0 ->
fprintf ff "@[<hv 2>element %a {}@]"
print_symbol l
| _ ->
fprintf ff "@[<hv 2>element %a {@,%a@;<0 -2>}@]"
print_symbol l
(print_aoeelem_contents idname print_algop) el
end
| AOEAnyElem (nsenv1,nsenv2) ->
let e1, e2 = access_twosub algop.psub_expression in
begin
match e2.palgop_expr_name with
| AOEEmpty ->
fprintf ff "@[<hv 2>element {@,%a@;<0 -2>} {}@]"
(print_algop idname 0) e1
| _ ->
fprintf ff "@[<hv 2>element {@,%a@;<0 -2>} {@,%a@;<0 -2>}@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
end
| AOEAttr (l,nsenv) ->
let el = access_manysub algop.psub_expression in
begin
match (Array.length el) with
| 0 ->
fprintf ff "@[<hv 2>attribute %a {}@]"
print_symbol l
| _ ->
fprintf ff "@[<hv 2>attribute %a {@,%a@;<0 -2>}@]"
print_symbol l
(print_aoeelem_contents idname print_algop) el
end
| AOEAnyAttr nsenv ->
let e1, e2 = access_twosub algop.psub_expression in
begin
match e2.palgop_expr_name with
| AOEEmpty ->
fprintf ff "@[<hv 2>attribute {@,%a@;<0 -2>} {}@]"
(print_algop idname 0) e1
| _ ->
fprintf ff "@[<hv 2>attribute {@,%a@;<0 -2>} {@,%a@;<0 -2>}@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
end
| AOEError ->
let params = Array.to_list (access_manysub algop.psub_expression) in
fprintf ff "@[<hv 2>%a(@,%a@;<0 -2>)@]"
print_rqname Namespace_builtin.fn_error
(print_params idname print_algop) params
| AOETreat cdt ->
let e' = access_onesub algop.psub_expression in
if p > 11
then
fprintf ff "@[<hv 1>(@[<hv 2>%a treat as %a@])@]"
(print_algop idname 11) e'
print_asequencetype cdt
else
fprintf ff "@[<hv 2>%a treat as %a@]"
(print_algop idname 11) e'
print_asequencetype cdt
| AOEValidate vmode ->
let e' = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>validate %a@ {@,%a@;<0 -2>}@]"
print_validation_mode vmode
(print_algop idname 0) e'
| AOECast (nsenv, cdt) ->
let e' = access_onesub algop.psub_expression in
if p > 13
then
fprintf ff "@[<hv 1>(@[<hv 2>%a@ cast as %a@])@]"
(print_algop idname 13) e'
print_asequencetype cdt
else
fprintf ff "@[<hv 2>%a@ cast as %a@]"
(print_algop idname 13) e'
print_asequencetype cdt
| AOECastable (nsenv, cdt) ->
let e' = access_onesub algop.psub_expression in
if p > 12
then
fprintf ff "@[<hv 1>(@[<hv 2>%a@ castable as %a@])@]"
(print_algop idname 12) e'
print_asequencetype cdt
else
fprintf ff "@[<hv 2>%a@ castable as %a@]"
(print_algop idname 12) e'
print_asequencetype cdt
| AOESome (odt,vn) ->
let ae1 = access_onesub algop.psub_expression in
let ae2 = access_onesub algop.pdep_sub_expression in
if p > 1
then
fprintf ff "@[<hv 1>(@[<hv 0>@[<hv 5>some $%a%a@ in %a@]@ @[<hv 2>satisfies@ %a@]@])@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 0) ae1
(print_algop idname 1) ae2
else
fprintf ff "@[<hv 0>@[<hv 5>some $%a%a@ in %a@]@ @[<hv 2>satisfies@ %a@]@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 0) ae1
(print_algop idname 1) ae2
| AOEEvery (odt,vn) ->
let ae1 = access_onesub algop.psub_expression in
let ae2 = access_onesub algop.pdep_sub_expression in
if p > 1
then
fprintf ff "@[<hv 1>(@[<hv 0>@[<hv 5>every $%a%a@ in %a@]@ @[<hv 2>satisfies@ %a@]@])@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 0) ae1
(print_algop idname 1) ae2
else
fprintf ff "@[<hv 0>@[<hv 5>every $%a%a@ in %a@]@ @[<hv 2>satisfies@ %a@]@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 0) ae1
(print_algop idname 1) ae2
DXQ
| AOEServerImplements (ncname,uri) ->
let e1 = access_onesub algop.psub_expression in
let e2 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 0>let server@ %s@ implement@ %s@ @[<hv 2>at@ %a@] @[<hv 2>return@;<1 0>{%a}@]@]" ncname uri (print_algop idname 0) (e1) (print_algop idname 0) (e2)
| AOEForServerClose (ncname,uri) ->
Handle two cases here : before code selection there is 1
subexpressions , afterwards there is none , so do a match here :
subexpressions, afterwards there is none, so do a match here :
*)
begin
match algop.psub_expression with
| NoSub ->
fprintf ff "@[<hv 0>for server@ %s@ @[<hv 2>closed@;@]@]" ncname
| OneSub (e1) ->
fprintf ff "@[<hv 0>for server@ %s@ @[<hv 2>close@;<1 0>{%a}@]@]" ncname (print_algop idname 0) (e1)
| _ -> raise (Query(Internal_Error("Invalid number of arguments to for-server-close")))
end
| AOEEvalClosure ->
Debug.print_dxq_debug ("print_xquery_alg : Before eval-box access_onesub\n");
begin
match algop.psub_expression with
| NoSub ->
fprintf ff "@[<hv 0>eval box@ no_indep"
| OneSub (e1) ->
fprintf ff "@[<hv 0>eval box@ @[<hv 2>{%a}@]@]" (print_algop idname 0) (e1)
| _ -> raise (Query(Internal_Error("Invalid number of indep arguments to eval-closure")))
end;
begin
match algop.pdep_sub_expression with
| NoSub ->
fprintf ff "no_dep"
| OneSub (e1) ->
fprintf ff "@[<hv 0>@[<hv 2>{%a}@]@]" (print_algop idname 0) (e1)
| _ -> raise (Query(Internal_Error("Invalid number of dep arguments to eval-closure")))
end;
Debug.print_dxq_debug ("print_xquery_alg : After eval-box access_onesub\n");
let e1 = access_onesub algop.psub_expression in
ff " @[<hv 0 > eval closure@ { % a}@ ] " ( 0 ) ( e1 )
let e1 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 0>eval closure@ {%a}@]" (print_algop idname 0) (e1) *)
| AOEExecute (ncname, uri) ->
Handle two cases here : before code selection there are 2
subexpressions , afterwards there is one , so do a match here :
subexpressions, afterwards there is one, so do a match here :
*)
begin
match algop.psub_expression with
| OneSub (e1) ->
fprintf ff "from server@ %s@ at@,{%a}" ncname (print_algop idname 0) (e1)
| TwoSub (e1,e2) ->
let (expr1, expr2) = access_twosub algop.psub_expression in
fprintf ff "from server@ %s@ at@,{%a} return@,{%a}" ncname (print_algop idname 0) (expr1) (print_algop idname 0) (expr2)
| _ -> raise (Query(Internal_Error("Invalid number of arguments to Execute")))
end
| AOEASyncExecute (ncname, uri) ->
Handle two cases here : before code selection there are 2
subexpressions , afterwards there is one , so do a match here :
subexpressions, afterwards there is one, so do a match here :
*)
begin
match algop.psub_expression with
| OneSub (e1) ->
fprintf ff "at server@ %s@ at@,{%a}" ncname (print_algop idname 0) (e1)
| TwoSub (e1,e2) ->
let (expr1, expr2) = access_twosub algop.psub_expression in
fprintf ff "at server@ %s@ at@,{%a} do@,{%a}" ncname (print_algop idname 0) (expr1) (print_algop idname 0) (expr2)
| _ -> raise (Query(Internal_Error("Invalid number of arguments to Execute")))
end
(*******************)
(* Tuple Operators *)
(*******************)
| AOECreateTuple rname_array ->
let aes = access_manysub algop.psub_expression in
fprintf ff "@[<h 2>[@,%a@;<0 -2>]@]"
(print_tuple_create idname print_algop)
(rname_array, aes)
| AOEAccessTuple (rname) ->
fprintf ff "#%a" print_rqname rname
| AOEProject rname_array ->
let print_rqname_list ff l =
let rname_string = String.concat ", "
(List.map prefixed_string_of_rqname (Array.to_list l)) in
fprintf ff "%s" rname_string
in
let op3 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>Project[(%a)](@,%a@;<0 -2>)@]"
print_rqname_list rname_array
(print_algop idname 0) op3
| AOEMapToItem ->
let op3 = access_onesub algop.psub_expression in
let op1 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Map@,{%a}@,(%a)@]"
(print_algop idname 0) op1
(print_algop idname 0) op3
| AOEMap ->
let op3 = access_onesub algop.psub_expression in
let op1 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Map@,{%a}@,(%a)@]"
(print_algop idname 0) op1
(print_algop idname 0) op3
| AOEMapIndex index_name ->
let op3 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>MapIndex[(%a)](@,%a@;<0 -2>)@]"
print_rqname index_name
(print_algop idname 0) op3
| AOEMapIndexStep index_name ->
let op3 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>MapIndexStep[(%a)](%a)@]"
print_rqname index_name
(print_algop idname 0) op3
| AOENullMap vn ->
let op3 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 1>NullMap[(%a)](%a)@]"
print_rqname vn
(print_algop idname 0) op3
| AOEProduct ->
let l, r = access_twosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 1>Product(%a,@,%a)@]"
(print_algop idname 0) l
(print_algop idname 0) r
| AOESelect pred_desc ->
let input = access_onesub algop.psub_expression in
let pred = access_manysub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Select@,{%a}@,@[<hv 1>(%a)@]@]"
(print_pred_desc idname 0 pred print_algop) pred_desc
(print_algop idname 0) input
| AOEOrderBy(stable, sort_kind_empty_list,_) ->
let op3 = access_onesub algop.psub_expression in
let deps = access_manysub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>OrderBy@,{%a}@,@[<hv 1>(%a)@]@]"
(print_ordered idname print_algop) deps
(print_algop idname 0) op3
| AOEConcatTuples ->
let t1, t2 = access_twosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
if p > 9
then
fprintf ff "@[<hv 1>(@[<hov 1>%a@;<1 0>@[<hov 1>++@;<1 0>%a@]@])@]"
(print_algop idname 9) t1
(print_algop idname 9) t2
else
fprintf ff "@[<hov 1>%a@;<1 0>@[<hov 1>++@;<1 0>%a@]@]"
(print_algop idname 9) t1
(print_algop idname 9) t2
| AOEMapFromItem vname ->
let op3 = access_onesub algop.psub_expression in
let op1 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Map@,@[<hv 1>{%a}@]@,@[<hv 1>(%a)@]@]"
(print_algop vname 0) op1
(print_algop idname 0) op3
| AOEInputTuple ->
let _ = access_nosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "ID"
| AOEMapConcat ->
let op3 = access_onesub algop.psub_expression in
let op1 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>MapConcat@,@[<hv 1>{%a}@]@,@[<hv 1>(%a)@]@]"
(print_algop idname 0) op1
(print_algop idname 0) op3
| AOEOuterMapConcat vn ->
let op3 = access_onesub algop.psub_expression in
let op1 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>OMapConcat[(%a)]@,@[<hv 1>{%a}@]@,@[<hv 1>(%a)@]@]"
print_rqname vn
(print_algop idname 0) op1
(print_algop idname 0) op3
| AOEJoin pred_desc ->
let l,r = access_twosub algop.psub_expression in
let pred = access_manysub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Join@,@[<hv 1>{%a}@]@,@[<hv 1>(%a,@,%a)@]@]"
(print_pred_desc idname 0 pred print_algop) pred_desc
(print_algop idname 0) l
(print_algop idname 0) r
| AOELeftOuterJoin (v,pred_desc) ->
let l,r = access_twosub algop.psub_expression in
let pred = access_manysub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>LeftOuterJoin[(%a)]@,@[<hv 1>{%a}@]@,@[<hv 1>(%a,@,%a)@]@]"
print_rqname v
(print_pred_desc idname 0 pred print_algop) pred_desc
(print_algop idname 0) l
(print_algop idname 0) r
| AOEGroupBy gd_list ->
let input = access_onesub algop.psub_expression in
let many = access_manysub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>GroupBy%a@,%a@[<hv 1>(%a)@]@]"
print_group_by gd_list
(print_many_deps idname print_algop) many
(print_algop idname 0) input
(********************)
(* Update Operators *)
(********************)
| AOECopy ->
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Copy@[<hv 1>(%a)@]@]"
(print_algop idname 0) a1
| AOEDelete ->
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Delete@[<hv 1>(%a)@]@]"
(print_algop idname 0) a1
| AOEInsert loc ->
let a1,a2 = access_twosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Insert[%a]@[<hv 1>(%a,@,%a)@]@]"
print_algop_insert_loc loc
(print_algop idname 0) a1
(print_algop idname 0) a2
| AOERename nsenv ->
let a1, a2 = access_twosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Rename@[<hv 1>(%a,@,%a)@]@]"
(print_algop idname 0) a1
(print_algop idname 0) a2
| AOEReplace valueflag ->
let a1, a2 = access_twosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Replace[%a]@[<hv 1>(%a,@,%a)@]@]"
print_algop_value_of_flag valueflag
(print_algop idname 0) a1
(print_algop idname 0) a2
| AOESnap sm ->
let a1 = access_onesub algop.pdep_sub_expression in
let _ = access_nosub algop.psub_expression in
fprintf ff "@[<hv 2>Snap[%a]@[<hv 1>(%a)@]@]"
print_snap_modifier sm
(print_algop idname 0) a1
| AOESet vn ->
let a1 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>Set[$%a]@[<hv 1>(%a)@]@]"
print_rqname vn
(print_algop idname 0) a1
(********************)
XPath evaluation
(********************)
| AOEParse uri ->
fprintf ff "Parse(%s)" uri
| AOETreeJoin (a, nt) ->
let ae = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>TreeJoin[%a::%a]@,@[<hv 1>(%a)@]@]"
print_axis a
print_anode_test nt
(print_algop idname 0) ae
| AOETupleTreePattern (input, pattern) ->
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>TupleTreePattern[(%a),(%a)]@,@[<hv 1>(%a)@]@]"
print_rqname input
print_twig_node pattern
(print_algop idname 0) a1
| AOEPrune ( name , a ) - >
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
ff " @[<hv 2 > Prune[%a,%a]@,@[<hv 1>(%a)@]@ ] "
print_rqname name
print_axis a
( 0 ) a1
| AOEDistinct name - >
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
ff " @[<hv 2 > Distinct[%a]@,@[<hv 1>(%a)@]@ ] "
print_rqname name
( 0 ) a1
| AOEPrune (name, a) ->
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Prune[%a,%a]@,@[<hv 1>(%a)@]@]"
print_rqname name
print_axis a
(print_algop idname 0) a1
| AOEDistinct name ->
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Distinct[%a]@,@[<hv 1>(%a)@]@]"
print_rqname name
(print_algop idname 0) a1
*)
(* check_signatures *)
let msg_constructor msg x =
if x = ""
then []
else [msg ^ x]
let print_physical_algop ff algop =
let rec print_physical_algop_prec idname p ff algop =
(* This can only be called if the signatures are filled in *)
let _ =
check_signatures msg_constructor algop.palgop_expr_eval_sig algop.psub_expression
in
(print_algop_main idname true) p print_physical_algop_prec ff algop
in
print_physical_algop_prec Xquery_common_ast_util.bogus_cvname 0 ff algop
let rec print_logical_algop ff (algop: ('a,'b) Xquery_algebra_ast.aalgop_expr) =
let rec print_logical_algop idname p ff algop =
(print_algop_main idname false) p print_logical_algop ff algop
in
print_logical_algop Xquery_common_ast_util.bogus_cvname 0 ff algop
(*******************)
(* Core Statements *)
(*******************)
(* Statements *)
let print_algstatement print_algop ff s =
fprintf ff "@[%a@]" print_algop s
let rec print_algstatements print_algop ff ss =
let print_algstatement' ff s = print_algstatement print_algop ff s in
let print_algstatements' ff s = print_algstatements print_algop ff s in
match ss with
| s :: [] ->
fprintf ff "%a;@\n" print_algstatement' s
| s :: ss' ->
fprintf ff "%a;@\n%a" print_algstatement' s print_algstatements' ss'
| [] ->
()
(***************)
Core Module
(***************)
(* Function definitions *)
let print_algprolog print_algop ff qm =
let rec print_cfunction_def ff fd =
let print_fn_body ff body =
match !(body.palgop_func_optimized_logical_plan) with
| AOEFunctionImported -> ()
(* What do we print here? The optimized logical plan or the physical plan? *)
| AOEFunctionUser userbody ->
print_algop ff userbody
in
let rec print_intypes ff t =
match t with
| [] -> ()
| t' :: [] ->
fprintf ff "%a" print_asequencetype t'
| t' :: rest ->
fprintf ff "%a,%a" print_asequencetype t' print_intypes rest
in
let ((fn,arity), (dts,odt), fbody, upd) = fd.palgop_function_decl_desc in
let upd_flag = updating_flag_to_string upd in
fprintf ff
"@[<hv 2>@[<hv 2>declare %sfunction@ %a(@,%a@;<0 -2>)@] as %a {@,%a@;<0 -2>};@]"
upd_flag
print_rqname fn
print_intypes dts
print_asequencetype odt
print_fn_body fbody
(* MF: pretty printing is very finicky. The @, below is essential to
getting good line breaks between function definitions *)
and print_cfunction_defs ff fds =
match fds with
| [] ->
()
| fd :: fds' ->
fprintf ff "@[%a@,@]@\n%a" print_cfunction_def fd print_cfunction_defs fds'
(* Variable declaration *)
and print_decl ff vd =
match vd.alg_decl_name with
| AOEVarDecl (odt, vn) ->
let sub = access_onesub vd.alg_decl_indep in
let _ = access_nosub vd.alg_decl_dep in
fprintf ff "declare variable@ $%a%a { @[%a@]@ };"
print_rqname vn
print_optasequencetype odt
print_algop sub
| AOEVarDeclImported (odt, vn)
| AOEVarDeclExternal (odt, vn) ->
let _ = access_nosub vd.alg_decl_indep in
let _ = access_nosub vd.alg_decl_dep in
fprintf ff "declare variable@ $%a%a external;"
print_rqname vn
print_optasequencetype odt
| AOEValueIndexDecl kn ->
let a1 = access_onesub vd.alg_decl_indep in
let a2 = access_onesub vd.alg_decl_dep in
fprintf ff "@[<hv 2>declare value index %s {@,%a@;<0 -2>} {@,%a@;<0 -2>};@]"
kn
print_algop a1
print_algop a2
| AOENameIndexDecl l ->
let _ = access_nosub vd.alg_decl_indep in
let _ = access_nosub vd.alg_decl_dep in
fprintf ff "@[<hv 2>declare name index %a;@]"
print_symbol l
and print_decls ff vds =
match vds with
| [] ->
()
| vd :: vds' ->
fprintf ff "@[%a@]@\n%a"
print_decl vd
print_decls vds'
(* The module itself *)
in
let print_algprolog' ff prolog =
print_decls ff prolog.palgop_prolog_vars;
print_cfunction_defs ff prolog.palgop_prolog_functions;
print_decls ff prolog.palgop_prolog_indices;
in
if !Conf.print_prolog
then print_algprolog' ff qm
else ()
let print_algmodule print_annot ff qm =
print_algprolog print_annot ff qm.palgop_module_prolog;
print_algstatements print_annot ff qm.palgop_module_statements
2006 - 2 - 15 CAR - I added flushes to each of these functions as
the pretty printer in ocaml 3.09.1 does not do it
when the formatter is closed .
the pretty printer in ocaml 3.09.1 does not do it
when the formatter is closed.
*)
let print_logical_algstatement ff s =
(print_algstatement print_logical_algop) ff s;
fprintf ff "@?"
let print_physical_algstatement ff s =
print_algstatement print_physical_algop ff s;
fprintf ff "@?"
let print_logical_algprolog ff s =
print_algprolog print_logical_algop ff s;
fprintf ff "@?"
let print_physical_algprolog ff s =
print_algprolog print_physical_algop ff s;
fprintf ff "@?"
let print_logical_algmodule ff s =
print_algmodule print_logical_algop ff s;
fprintf ff "@?"
let print_physical_algmodule ff s =
print_algmodule print_physical_algop ff s;
fprintf ff "@?"
(* Exported *)
(* Logical Statements *)
let fprintf_logical_algstatement f s st =
fprintf_stub f s print_logical_algstatement st
let printf_logical_algstatement s st = printf_stub s print_logical_algstatement st
let bprintf_logical_algstatement s st = bprintf_stub s print_logical_algstatement st
(* Logical prolog *)
let fprintf_logical_algprolog f s st = fprintf_stub f s print_logical_algprolog st
let printf_logical_algprolog s qms = printf_stub s print_logical_algprolog qms
let bprintf_logical_algprolog s qms = bprintf_stub s print_logical_algprolog qms
(* Logical modules *)
let fprintf_logical_algmodule f s st = fprintf_stub f s print_logical_algmodule st
let printf_logical_algmodule s qms = printf_stub s print_logical_algmodule qms
let bprintf_logical_algmodule s qms = bprintf_stub s print_logical_algmodule qms
(* Optimized - still logical *)
(* Optimized Logical Statements *)
let fprintf_optimized_algstatement f s st =
fprintf_stub f s print_logical_algstatement st
let printf_optimized_algstatement s st = printf_stub s print_logical_algstatement st
let bprintf_optimized_algstatement s st = bprintf_stub s print_logical_algstatement st
(* Optimized Logical prolog *)
let fprintf_optimized_algprolog f s st = fprintf_stub f s print_logical_algprolog st
let printf_optimized_algprolog s qms = printf_stub s print_logical_algprolog qms
let bprintf_optimized_algprolog s qms = bprintf_stub s print_logical_algprolog qms
(* Optimized Logical modules *)
let fprintf_optimized_algmodule f s st = fprintf_stub f s print_logical_algmodule st
let printf_optimized_algmodule s qms = printf_stub s print_logical_algmodule qms
let bprintf_optimized_algmodule s qms = bprintf_stub s print_logical_algmodule qms
(* Physical Statements *)
let fprintf_physical_algstatement f s st =
fprintf_stub f s print_physical_algstatement st
let printf_physical_algstatement s st = printf_stub s print_physical_algstatement st
let bprintf_physical_algstatement s st = bprintf_stub s print_physical_algstatement st
(* Physical prolog *)
let fprintf_physical_algprolog f s st = fprintf_stub f s print_physical_algprolog st
let printf_physical_algprolog s qms = printf_stub s print_physical_algprolog qms
let bprintf_physical_algprolog s qms = bprintf_stub s print_physical_algprolog qms
(* Physical modules *)
let fprintf_physical_algmodule f s st = fprintf_stub f s print_physical_algmodule st
let printf_physical_algmodule s qms = printf_stub s print_physical_algmodule qms
let bprintf_physical_algmodule s qms = bprintf_stub s print_physical_algmodule qms
(* Node node *)
let printf_anode_test s akt = printf_stub s print_anode_test akt
let bprintf_anode_test s akt = bprintf_stub s print_anode_test akt
| null | https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/ast_printer/print_xquery_algebra.ml | ocaml | *********************************************************************
GALAX
XQuery Engine
Distributed only by permission.
*********************************************************************
Module: Print_xquery_algebra
Description:
This module implements pretty-printing for the XQuery Algebra
AST.
***********
Node kind
***********
****************
Sequence types
****************
Replicated code should make a print core util
*************************
Core XQuery expressions
*************************
check that cur is the same as each of the lists
if Debug.default_debug() then
Debug.print_default_debug msg
let is_upd = updating_flag_to_string upd in
*****************
Tuple Operators
*****************
******************
Update Operators
******************
******************
******************
check_signatures
This can only be called if the signatures are filled in
*****************
Core Statements
*****************
Statements
*************
*************
Function definitions
What do we print here? The optimized logical plan or the physical plan?
MF: pretty printing is very finicky. The @, below is essential to
getting good line breaks between function definitions
Variable declaration
The module itself
Exported
Logical Statements
Logical prolog
Logical modules
Optimized - still logical
Optimized Logical Statements
Optimized Logical prolog
Optimized Logical modules
Physical Statements
Physical prolog
Physical modules
Node node | Copyright 2001 - 2007 .
$ I d : print_xquery_algebra.ml , v 1.75 2007/10/16 01:25:34
open Error
open Gmisc
open Occurrence
open Namespace_names
open Namespace_symbols
open Datatypes
open Xquery_common_ast
open Xquery_algebra_ast
open Xquery_algebra_ast_util
open Xquery_algebra_ast_annotation_util
open Print_common
open Format
let print_aelement_test ff aet =
match aet with
| ASchemaElementTest elem_sym ->
let cename = relem_name elem_sym in
fprintf ff "schema-element(%a)" print_rqname cename
| AElementTest None ->
fprintf ff "element()"
| AElementTest (Some (elem_sym, None)) ->
let cename = relem_name elem_sym in
fprintf ff "element(%a)" print_rqname cename
| AElementTest (Some (elem_sym, Some type_sym)) ->
let cename = relem_name elem_sym in
let ctname = rtype_name type_sym in
fprintf ff "element(%a,%a)" print_rqname cename print_rqname ctname
let print_aattribute_test ff aat =
match aat with
| ASchemaAttributeTest attr_sym ->
let caname = rattr_name attr_sym in
fprintf ff "schema-attribute(%a)" print_rqname caname
| AAttributeTest None ->
fprintf ff "attribute()"
| AAttributeTest (Some (attr_sym, None)) ->
let caname = rattr_name attr_sym in
fprintf ff "attribute(%a)" print_rqname caname
| AAttributeTest (Some (attr_sym, Some type_sym)) ->
let caname = rattr_name attr_sym in
let ctname = rtype_name type_sym in
fprintf ff "attribute(%a,%a)" print_rqname caname print_rqname ctname
let print_akind_test ff akt =
match akt with
| ADocumentKind None ->
fprintf ff "document-node()"
| ADocumentKind (Some aet) ->
fprintf ff "document-node(%a)" print_aelement_test aet
| AElementKind aet ->
fprintf ff "%a" print_aelement_test aet
| AAttributeKind aat ->
fprintf ff "%a" print_aattribute_test aat
| APIKind None ->
fprintf ff "processing-instruction()"
| APIKind (Some s) ->
fprintf ff "processing-instruction(\"%s\")" s
| ACommentKind ->
fprintf ff "comment()"
| ATextKind ->
fprintf ff "text()"
| AAnyKind ->
fprintf ff "node()"
let print_aitemtype ff adtk =
match adtk with
| AITKindTest akt ->
fprintf ff "%a" print_akind_test akt
| AITTypeRef type_sym ->
let ctname = rtype_name type_sym in
fprintf ff "type(%a)" print_rqname ctname
| AITItem ->
fprintf ff "item()"
| AITNumeric ->
fprintf ff "numeric()"
| AITAnyString ->
fprintf ff "anystring()"
| AITEmpty ->
fprintf ff "empty()"
| AITAtomic type_sym ->
let ctname = rtype_name type_sym in
fprintf ff "%a" print_rqname ctname
let print_asequencetype ff adt =
match adt.pasequencetype_desc with
| (adtk,occ) ->
fprintf ff "%a%a" print_aitemtype adtk print_occurence occ
let print_anode_test ff nt =
match nt with
| APNameTest qn ->
fprintf ff "%s" (Namespace_symbols.relem_prefix_string qn)
| APNodeKindTest nk ->
fprintf ff "%a" print_akind_test nk
let print_optasequencetype ff t =
match t with
| None -> ()
| Some dt ->
fprintf ff " as %a" print_asequencetype dt
let print_algop_insert_loc ff loc =
match loc with
| AOUAsLastInto -> fprintf ff "as last into"
| AOUAsFirstInto -> fprintf ff "as first into"
| AOUInto -> fprintf ff "into"
| AOUAfter -> fprintf ff "after"
| AOUBefore -> fprintf ff "before"
let print_algop_value_of_flag ff vf =
match vf with
| Normal_Replace -> ()
| Value_Of_Replace -> fprintf ff "value of@;"
let rec print_var_list ff tfl =
match tfl with
| [] -> ()
| x :: [] ->
fprintf ff "%a" print_rqname x
| x :: rest ->
fprintf ff "%a,%a" print_rqname x print_var_list rest
let print_free_vars ff fv =
if fv = []
then ()
else fprintf ff "free : %a;@;" print_var_list fv
let string_of_variable_usage u =
match u with
| Never -> "Never"
| Once -> "Once"
| Many -> "Many"
| Redefined -> "Redefined"
let print_use_count ff (var,(count,usage)) =
fprintf ff "(%a,%i,%s),"
print_rqname var
count
(string_of_variable_usage usage)
let print_use_counts ff uc_list =
List.iter (fprintf ff "%a" print_use_count) uc_list
let print_bound_vars ff bv =
if bv = []
then ()
else fprintf ff "bound : %a;@;" print_use_counts bv
let print_accessed_fields ff tf =
if tf = []
then ()
else fprintf ff "accessed : %a;@;" print_var_list tf
let string_of_cardinality c =
match c with
| NoTable -> "NoTable"
| Table COne -> "Table COne"
| Table CMany -> "Table CMany"
let print_cardinality ff c =
fprintf ff "cardinality: %s;@;" (string_of_cardinality c)
let print_candidate_fields ff tf =
if tf = []
then ()
else fprintf ff "candidate fields : %a;@;" print_var_list tf
let print_tuple_field_use_counts ff tf =
if tf = [] then
()
else
fprintf ff "tuple field use counts : %a;@;" print_use_counts tf
let print_returned_fields ff tf =
if tf = []
then ()
else fprintf ff "returned : %a;@;" print_var_list tf
let check_lists cur f l_of_l =
let apply b cur_list = b || (not ((f cur_list) = cur)) in
List.fold_left apply false l_of_l
let free_var_changed cur i_list d_list =
check_lists cur algop_get_free_variables (i_list @ d_list)
let tuple_fields_changed cur i_list d_list =
check_lists cur algop_get_accessed_fields (i_list @ d_list)
let print_free_variable_desc ff algop =
let has_changed algop =
let fv_list = algop_get_free_variables algop in
let tf_list = algop_get_accessed_fields algop in
let i_list = subexpr_to_list algop.psub_expression in
let d_list = subexpr_to_list algop.pdep_sub_expression in
(free_var_changed fv_list i_list d_list)
|| (tuple_fields_changed tf_list i_list d_list)
in
let empty_fvd op =
((algop_get_free_variables op) = []) &&
((algop_get_accessed_fields op) = []) &&
((algop_get_returned_fields op) = []) &&
((algop_get_bound_use_counts op) = [])
in
if ((not (empty_fvd algop)) &&
(has_changed algop)) || true then
begin
let (tuple_field_use_counts, candidate_fields, cardinality) = algop_get_tuple_field_use_counts algop in
fprintf ff "@[|%a%a%a%a%a%a%a|@]@;"
print_free_vars (algop_get_free_variables algop)
print_bound_vars (algop_get_bound_use_counts algop)
print_accessed_fields (algop_get_accessed_fields algop)
print_returned_fields (algop_get_returned_fields algop)
print_tuple_field_use_counts tuple_field_use_counts
print_candidate_fields candidate_fields
print_cardinality cardinality
end
let print_group_desc ff gd =
match (get_aggregate_type gd) with
| None ->
fprintf ff "[%a][%a][%a]"
print_var_list (Xquery_algebra_ast_util.get_group_names gd)
print_var_list (Xquery_algebra_ast_util.get_valid_names gd)
print_rqname (Xquery_algebra_ast_util.get_aggregate_name gd)
| Some dt ->
fprintf ff "[%a][%a][%a(%a)]"
print_var_list (Xquery_algebra_ast_util.get_group_names gd)
print_var_list (Xquery_algebra_ast_util.get_valid_names gd)
print_rqname (Xquery_algebra_ast_util.get_aggregate_name gd)
print_asequencetype dt
let print_http_method ff hm =
match hm with
| Galax_url.File str ->
fprintf ff "%s" ("\"" ^ str ^ "\"")
| Galax_url.Http (str1, i, str2) ->
fprintf ff "%s" ("\"" ^ str1 ^ (string_of_int i) ^ str2 ^ "\"")
| Galax_url.ExternalSource (str1, str2, opt_str, str4) ->
begin
let str3 = match opt_str with
| None -> ""
| Some str -> str
in
fprintf ff "%s" ("\"" ^ str1 ^ str2 ^ str3 ^ str4 ^ "\"")
end
let print_ordered idname print_algop ff deps =
let apply v = fprintf ff "%a" (print_algop idname 0) v in
Array.iter apply deps
let print_tuple_create idname print_algop ff (rnames,exprs) =
begin
if ((Array.length rnames) != (Array.length exprs))
then
raise (Query
(Malformed_Tuple
("Number of tuple slots does not equal number of expressions")))
end;
begin
for i = 0 to (Array.length rnames) - 1 do
let printsemi ff i =
if (i == (Array.length rnames -1))
then
fprintf ff "%a"
(print_algop idname 0) exprs.(i)
else
fprintf ff "%a;@ "
(print_algop idname 0) exprs.(i)
in
if (fst rnames.(i)) = None
then
fprintf ff "@[<hv 2>%a :@;%a@]"
print_rqname (snd rnames.(i))
printsemi i
else
fprintf ff "@[<hv 2>%a%a :@;%a@]"
print_rqname (snd rnames.(i))
print_optasequencetype (fst rnames.(i))
printsemi i
done
end
let rec print_params idname print_algop ff es =
match es with
| e :: [] ->
fprintf ff "%a" (print_algop idname 0) e
| e :: es ->
fprintf ff "%a,@ %a" (print_algop idname 0) e (print_params idname print_algop) es
| [] ->
()
let print_coptvariable_as ff ovn =
match ovn with
| None -> ()
| Some vn -> fprintf ff "$%a as " print_rqname vn
let print_coptvariable ff ovn =
match ovn with
| None -> ()
| Some vn -> fprintf ff "$%a " print_rqname vn
let print_cpattern ff (p, ovn) =
match p.papattern_desc with
| ACase m ->
fprintf ff "case %a%a" print_coptvariable_as ovn print_asequencetype m
| ADefault ->
fprintf ff "default %a" print_coptvariable ovn
let print_cases print_algop idname ff (pattern,exprs) =
if ((Array.length pattern) != (Array.length exprs)) then
raise (Query
(Malformed_Expr
("Number of cases does not match the number of expressions")));
for i = 0 to (Array.length pattern)-1 do
fprintf ff "%a return@;<1 2>%a@;"
print_cpattern pattern.(i)
(print_algop idname 0) exprs.(i)
done
let print_aoeelem_contents idname print_algop ff ecs =
for i = 0 to (Array.length ecs) - 1 do
fprintf ff "%a" (print_algop idname 0) ecs.(i)
done
let print_group_by ff gds =
List.iter (fun gd ->
fprintf ff "%a"
print_group_desc gd) gds
let print_dep idname print_algop ff algop =
fprintf ff "{%a}@," (print_algop idname 0) algop
let print_many_deps idname print_algop ff algops =
Array.iter (print_dep idname print_algop ff) algops
let rec print_pred_desc idname p ops print_algop ff (pred_desc:predicate_desc) =
match pred_desc with
| SimpleConjunct (start_i,end_i) ->
begin
fprintf ff "@[<hov 1>";
for i = start_i to end_i - 1 do
fprintf ff "%a@;<1 0>and@;<1 0>" (print_algop idname 3) ops.(i)
done;
fprintf ff "%a" (print_algop idname 3) ops.(end_i);
fprintf ff "@]"
end
| ComplexConjunct (l,r) ->
if p > 3
then
fprintf ff "@[<hv 1>(@[<hov 1>%a@;<1 0>and@;<1 0>%a@])@]"
(print_pred_desc idname 3 ops print_algop) l
(print_pred_desc idname 3 ops print_algop) r
else
fprintf ff "@[<hov 1>%a@;<1 0>and@;<1 0>%a@]"
(print_pred_desc idname 3 ops print_algop) l
(print_pred_desc idname 3 ops print_algop) r
| Disjunct (l,r) ->
if p > 2
then
fprintf ff "@[<hv 1>(@[<hov 1>%a@;<1 0>or@;<1 0>%a@])@]"
(print_pred_desc idname 2 ops print_algop) l
(print_pred_desc idname 2 ops print_algop) r
else
fprintf ff "@[<hov 1>%a@;<1 0>or@;<1 0>%a@]"
(print_pred_desc idname 2 ops print_algop) l
(print_pred_desc idname 2 ops print_algop) r
let print_twig_node_test ff ont =
match ont with
| Some nt -> fprintf ff "%a" print_anode_test nt
| None -> fprintf ff "."
let print_out_field ff twignode =
match twignode.out with
| Some f ->
begin
if twignode.restore_out
then fprintf ff "{%a*}" print_rqname f
else fprintf ff "{%a}" print_rqname f
end
| None ->
fprintf ff ""
let print_sbdo ff twignode =
begin
let (sigma,delta) = twignode.requires_sbdo in
let msg = (
"(" ^
(if sigma && delta then "s,d"
else if delta then "d"
else if sigma then "s"
else "") ^ ")"
)
in
fprintf ff "%s" msg
end
let rec print_child_node pattern ff child_twig =
match child_twig with
| Some (typ, ind) ->
fprintf ff "/%a::%a"
print_axis typ
(print_twig_node_aux pattern) ind
| None -> fprintf ff ""
and print_predicates pattern ff predlist =
match predlist with
| hd::tl ->
let (typ, ind) = hd in
fprintf ff "[./%a::%a]%a"
print_axis typ
(print_twig_node_aux pattern) ind
(print_predicates pattern) tl
| [] ->
fprintf ff ""
and print_twig_node_aux pattern ff index =
fprintf ff "%a%a%a%a%a"
print_twig_node_test pattern.(index).node_test
print_out_field pattern.(index)
print_sbdo pattern.(index)
(print_predicates pattern) pattern.(index).pred_twigs
(print_child_node pattern) pattern.(index).child_twig
let print_twig_node ff pattern =
print_twig_node_aux pattern ff 0
let print_physical_signature ff algop_sig =
match algop_sig with
| None -> ()
| Some x ->
fprintf ff "(: %s :)@\n" (Print_xquery_physical_type.string_of_eval_sig x)
let print_algop_main idname physical p print_algop ff algop =
begin
if !Conf.bPrinting_comp_annotations
then print_free_variable_desc ff algop
end;
begin
if physical
then
print_physical_signature ff algop.palgop_expr_eval_sig
end;
match algop.palgop_expr_name with
| AOELetvar (odt,vn) ->
let indep = access_onesub algop.psub_expression in
let dep = access_onesub algop.pdep_sub_expression in
if p > 1
then
fprintf ff
"@[<hv 1>(@[<hv 2>letvar $%a%a :=@ %a@]@;<1 0>@[<hv 2>return@;<1 0>%a@])@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 1) indep
(print_algop idname 1) dep
else
fprintf ff
"@[<hv 0>@[<hv 2>letvar $%a%a :=@ %a@]@;<1 0>@[<hv 2>return@;<1 0>%a@]@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 1) indep
(print_algop idname 1) dep
| AOEIf ->
let e1 = access_onesub algop.psub_expression in
let e2,e3 = access_twosub algop.pdep_sub_expression in
if p > 1
then
fprintf ff
"@[<hv 1>(if (%a)@;<1 0>@[<hv 2>then@;<1 0>%a@]@;<1 0>@[<hv 2>else@;<1 0>%a@])@]"
(print_algop idname 0) e1
(print_algop idname 1) e2
(print_algop idname 1) e3
else
fprintf ff
"@[<hv 0>if (%a)@;<1 0>@[<hv 2>then@;<1 0>%a@]@;<1 0>@[<hv 2>else@;<1 0>%a@]@]"
(print_algop idname 0) e1
(print_algop idname 1) e2
(print_algop idname 1) e3
| AOEWhile ->
let e1,e2 = access_twosub algop.pdep_sub_expression in
if p > 1
then
fprintf ff
"@[<hv 1>(while (%a)@;<1 0>@[<hv 2>return@;<1 0>%a@])@]"
(print_algop idname 0) e1
(print_algop idname 1) e2
else
fprintf ff
"@[<hv 0>while (%a)@;<1 0>@[<hv 2>return@;<1 0>%a@]@]"
(print_algop idname 0) e1
(print_algop idname 1) e2
| AOETypeswitch pattern ->
let e' = access_onesub algop.psub_expression in
let cases = access_manysub algop.pdep_sub_expression in
if p > 1
then
fprintf ff "@[<hv 1>(@[<hv 2>@[<hv 2>typeswitch (@,%a@;<0 -2>)@]@;<1 0>%a@])@]"
(print_algop idname 0) e'
(print_cases print_algop idname) (pattern,cases)
else
fprintf ff "@[<hv 2>@[<hv 2>typeswitch (@,%a@;<0 -2>)@]@;<1 0>%a@]"
(print_algop idname 0) e'
(print_cases print_algop idname) (pattern,cases)
| AOEVar v ->
if Namespace_names.rqname_equal v idname then
fprintf ff "ID"
else
fprintf ff "$%a" print_rqname v
| AOEScalar bv ->
fprintf ff "%a" print_literal bv
| AOEText t ->
fprintf ff "text { \"%s\" }" t
| AOECharRef i ->
fprintf ff "@[<hv 2>text {@,\"&#%i;\"@;<0 -2>}@]" i
| AOETextComputed ->
let e = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>text {@,\"%a\"@;<0 -2>}@]"
(print_algop idname 0) e
| AOEPI (target,pi_content) ->
fprintf ff "<?%s %s?>" target pi_content
| AOEPIComputed ->
let e1,e2 = access_twosub algop.psub_expression in
fprintf ff "@[<hv 2>processing-instruction {@,%a@;<0 -2>} {@,%a@;<0 -2>}@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
| AOEComment c ->
fprintf ff "<!--%s-->" c
| AOECommentComputed ->
let e = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>comment {@,%a@;<0 -2>}@]"
(print_algop idname 0) e
| AOEDocument ->
let e = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>document {@,%a@;<0 -2>}@]"
(print_algop idname 0) e
| AOECallUserDefined ((name,arity), optintypes, opttypes, _, _)
| AOECallBuiltIn ((name,arity), optintypes, opttypes, _) ->
let params = Array.to_list (access_manysub algop.psub_expression) in
fprintf ff "@[<hv 2>%a(@,%a@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
| AOECallOverloaded ((name, arity),table) ->
let params = Array.to_list (access_manysub algop.psub_expression) in
fprintf ff "@[<hv 2>%a(@,%a@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
| AOEConvertSimple atomic_type ->
let name = Namespace_builtin.fs_convert_simple_operand in
let param1 = access_onesub algop.psub_expression in
let s = string_of_proto_value atomic_type in
let params = [param1] in
fprintf ff "@[<hv 2>%a(@,%a,@ %s@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
s
| AOEPromoteNumeric atomic_type ->
let name = Namespace_builtin.fs_promote_to_numeric in
let param1 = access_onesub algop.psub_expression in
let s = string_of_proto_value atomic_type in
let params = [param1] in
fprintf ff "@[<hv 2>%a(@,%a,@ %s@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
s
| AOEPromoteAnyString ->
let name = Namespace_builtin.fs_promote_to_anystring in
let param1 = access_onesub algop.psub_expression in
let params = [param1] in
fprintf ff "@[<hv 2>%a(@,%a@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
| AOEUnsafePromoteNumeric atomic_type ->
let name = Namespace_builtin.fs_unsafe_promote_to_numeric in
let param1 = access_onesub algop.psub_expression in
let s = string_of_proto_value atomic_type in
let params = [param1] in
fprintf ff "@[<hv 2>%a(@,%a,@ %s@;<0 -2>)@]"
print_rqname name
(print_params idname print_algop) params
s
| AOESeq ->
let e1,e2 = access_twosub algop.psub_expression in
if p > 0 then
fprintf ff "@[<hov 1>(%a,@ %a)@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
else
fprintf ff "@[<hov 0>%a,@ %a@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
| AOEImperativeSeq ->
let e1,e2 = access_twosub algop.psub_expression in
if p > 0 then
fprintf ff "@[<hov 1>@,%a;@ %a@,@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
else
fprintf ff "@[<hov 0>%a;@ %a@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
| AOEEmpty ->
fprintf ff "()"
| AOEElem (l,nsenv) ->
let el = access_manysub algop.psub_expression in
begin
match (Array.length el) with
| 0 ->
fprintf ff "@[<hv 2>element %a {}@]"
print_symbol l
| _ ->
fprintf ff "@[<hv 2>element %a {@,%a@;<0 -2>}@]"
print_symbol l
(print_aoeelem_contents idname print_algop) el
end
| AOEAnyElem (nsenv1,nsenv2) ->
let e1, e2 = access_twosub algop.psub_expression in
begin
match e2.palgop_expr_name with
| AOEEmpty ->
fprintf ff "@[<hv 2>element {@,%a@;<0 -2>} {}@]"
(print_algop idname 0) e1
| _ ->
fprintf ff "@[<hv 2>element {@,%a@;<0 -2>} {@,%a@;<0 -2>}@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
end
| AOEAttr (l,nsenv) ->
let el = access_manysub algop.psub_expression in
begin
match (Array.length el) with
| 0 ->
fprintf ff "@[<hv 2>attribute %a {}@]"
print_symbol l
| _ ->
fprintf ff "@[<hv 2>attribute %a {@,%a@;<0 -2>}@]"
print_symbol l
(print_aoeelem_contents idname print_algop) el
end
| AOEAnyAttr nsenv ->
let e1, e2 = access_twosub algop.psub_expression in
begin
match e2.palgop_expr_name with
| AOEEmpty ->
fprintf ff "@[<hv 2>attribute {@,%a@;<0 -2>} {}@]"
(print_algop idname 0) e1
| _ ->
fprintf ff "@[<hv 2>attribute {@,%a@;<0 -2>} {@,%a@;<0 -2>}@]"
(print_algop idname 0) e1
(print_algop idname 0) e2
end
| AOEError ->
let params = Array.to_list (access_manysub algop.psub_expression) in
fprintf ff "@[<hv 2>%a(@,%a@;<0 -2>)@]"
print_rqname Namespace_builtin.fn_error
(print_params idname print_algop) params
| AOETreat cdt ->
let e' = access_onesub algop.psub_expression in
if p > 11
then
fprintf ff "@[<hv 1>(@[<hv 2>%a treat as %a@])@]"
(print_algop idname 11) e'
print_asequencetype cdt
else
fprintf ff "@[<hv 2>%a treat as %a@]"
(print_algop idname 11) e'
print_asequencetype cdt
| AOEValidate vmode ->
let e' = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>validate %a@ {@,%a@;<0 -2>}@]"
print_validation_mode vmode
(print_algop idname 0) e'
| AOECast (nsenv, cdt) ->
let e' = access_onesub algop.psub_expression in
if p > 13
then
fprintf ff "@[<hv 1>(@[<hv 2>%a@ cast as %a@])@]"
(print_algop idname 13) e'
print_asequencetype cdt
else
fprintf ff "@[<hv 2>%a@ cast as %a@]"
(print_algop idname 13) e'
print_asequencetype cdt
| AOECastable (nsenv, cdt) ->
let e' = access_onesub algop.psub_expression in
if p > 12
then
fprintf ff "@[<hv 1>(@[<hv 2>%a@ castable as %a@])@]"
(print_algop idname 12) e'
print_asequencetype cdt
else
fprintf ff "@[<hv 2>%a@ castable as %a@]"
(print_algop idname 12) e'
print_asequencetype cdt
| AOESome (odt,vn) ->
let ae1 = access_onesub algop.psub_expression in
let ae2 = access_onesub algop.pdep_sub_expression in
if p > 1
then
fprintf ff "@[<hv 1>(@[<hv 0>@[<hv 5>some $%a%a@ in %a@]@ @[<hv 2>satisfies@ %a@]@])@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 0) ae1
(print_algop idname 1) ae2
else
fprintf ff "@[<hv 0>@[<hv 5>some $%a%a@ in %a@]@ @[<hv 2>satisfies@ %a@]@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 0) ae1
(print_algop idname 1) ae2
| AOEEvery (odt,vn) ->
let ae1 = access_onesub algop.psub_expression in
let ae2 = access_onesub algop.pdep_sub_expression in
if p > 1
then
fprintf ff "@[<hv 1>(@[<hv 0>@[<hv 5>every $%a%a@ in %a@]@ @[<hv 2>satisfies@ %a@]@])@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 0) ae1
(print_algop idname 1) ae2
else
fprintf ff "@[<hv 0>@[<hv 5>every $%a%a@ in %a@]@ @[<hv 2>satisfies@ %a@]@]"
print_rqname vn
print_optasequencetype odt
(print_algop idname 0) ae1
(print_algop idname 1) ae2
DXQ
| AOEServerImplements (ncname,uri) ->
let e1 = access_onesub algop.psub_expression in
let e2 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 0>let server@ %s@ implement@ %s@ @[<hv 2>at@ %a@] @[<hv 2>return@;<1 0>{%a}@]@]" ncname uri (print_algop idname 0) (e1) (print_algop idname 0) (e2)
| AOEForServerClose (ncname,uri) ->
Handle two cases here : before code selection there is 1
subexpressions , afterwards there is none , so do a match here :
subexpressions, afterwards there is none, so do a match here :
*)
begin
match algop.psub_expression with
| NoSub ->
fprintf ff "@[<hv 0>for server@ %s@ @[<hv 2>closed@;@]@]" ncname
| OneSub (e1) ->
fprintf ff "@[<hv 0>for server@ %s@ @[<hv 2>close@;<1 0>{%a}@]@]" ncname (print_algop idname 0) (e1)
| _ -> raise (Query(Internal_Error("Invalid number of arguments to for-server-close")))
end
| AOEEvalClosure ->
Debug.print_dxq_debug ("print_xquery_alg : Before eval-box access_onesub\n");
begin
match algop.psub_expression with
| NoSub ->
fprintf ff "@[<hv 0>eval box@ no_indep"
| OneSub (e1) ->
fprintf ff "@[<hv 0>eval box@ @[<hv 2>{%a}@]@]" (print_algop idname 0) (e1)
| _ -> raise (Query(Internal_Error("Invalid number of indep arguments to eval-closure")))
end;
begin
match algop.pdep_sub_expression with
| NoSub ->
fprintf ff "no_dep"
| OneSub (e1) ->
fprintf ff "@[<hv 0>@[<hv 2>{%a}@]@]" (print_algop idname 0) (e1)
| _ -> raise (Query(Internal_Error("Invalid number of dep arguments to eval-closure")))
end;
Debug.print_dxq_debug ("print_xquery_alg : After eval-box access_onesub\n");
let e1 = access_onesub algop.psub_expression in
ff " @[<hv 0 > eval closure@ { % a}@ ] " ( 0 ) ( e1 )
let e1 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 0>eval closure@ {%a}@]" (print_algop idname 0) (e1) *)
| AOEExecute (ncname, uri) ->
Handle two cases here : before code selection there are 2
subexpressions , afterwards there is one , so do a match here :
subexpressions, afterwards there is one, so do a match here :
*)
begin
match algop.psub_expression with
| OneSub (e1) ->
fprintf ff "from server@ %s@ at@,{%a}" ncname (print_algop idname 0) (e1)
| TwoSub (e1,e2) ->
let (expr1, expr2) = access_twosub algop.psub_expression in
fprintf ff "from server@ %s@ at@,{%a} return@,{%a}" ncname (print_algop idname 0) (expr1) (print_algop idname 0) (expr2)
| _ -> raise (Query(Internal_Error("Invalid number of arguments to Execute")))
end
| AOEASyncExecute (ncname, uri) ->
Handle two cases here : before code selection there are 2
subexpressions , afterwards there is one , so do a match here :
subexpressions, afterwards there is one, so do a match here :
*)
begin
match algop.psub_expression with
| OneSub (e1) ->
fprintf ff "at server@ %s@ at@,{%a}" ncname (print_algop idname 0) (e1)
| TwoSub (e1,e2) ->
let (expr1, expr2) = access_twosub algop.psub_expression in
fprintf ff "at server@ %s@ at@,{%a} do@,{%a}" ncname (print_algop idname 0) (expr1) (print_algop idname 0) (expr2)
| _ -> raise (Query(Internal_Error("Invalid number of arguments to Execute")))
end
| AOECreateTuple rname_array ->
let aes = access_manysub algop.psub_expression in
fprintf ff "@[<h 2>[@,%a@;<0 -2>]@]"
(print_tuple_create idname print_algop)
(rname_array, aes)
| AOEAccessTuple (rname) ->
fprintf ff "#%a" print_rqname rname
| AOEProject rname_array ->
let print_rqname_list ff l =
let rname_string = String.concat ", "
(List.map prefixed_string_of_rqname (Array.to_list l)) in
fprintf ff "%s" rname_string
in
let op3 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>Project[(%a)](@,%a@;<0 -2>)@]"
print_rqname_list rname_array
(print_algop idname 0) op3
| AOEMapToItem ->
let op3 = access_onesub algop.psub_expression in
let op1 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Map@,{%a}@,(%a)@]"
(print_algop idname 0) op1
(print_algop idname 0) op3
| AOEMap ->
let op3 = access_onesub algop.psub_expression in
let op1 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Map@,{%a}@,(%a)@]"
(print_algop idname 0) op1
(print_algop idname 0) op3
| AOEMapIndex index_name ->
let op3 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>MapIndex[(%a)](@,%a@;<0 -2>)@]"
print_rqname index_name
(print_algop idname 0) op3
| AOEMapIndexStep index_name ->
let op3 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>MapIndexStep[(%a)](%a)@]"
print_rqname index_name
(print_algop idname 0) op3
| AOENullMap vn ->
let op3 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 1>NullMap[(%a)](%a)@]"
print_rqname vn
(print_algop idname 0) op3
| AOEProduct ->
let l, r = access_twosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 1>Product(%a,@,%a)@]"
(print_algop idname 0) l
(print_algop idname 0) r
| AOESelect pred_desc ->
let input = access_onesub algop.psub_expression in
let pred = access_manysub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Select@,{%a}@,@[<hv 1>(%a)@]@]"
(print_pred_desc idname 0 pred print_algop) pred_desc
(print_algop idname 0) input
| AOEOrderBy(stable, sort_kind_empty_list,_) ->
let op3 = access_onesub algop.psub_expression in
let deps = access_manysub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>OrderBy@,{%a}@,@[<hv 1>(%a)@]@]"
(print_ordered idname print_algop) deps
(print_algop idname 0) op3
| AOEConcatTuples ->
let t1, t2 = access_twosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
if p > 9
then
fprintf ff "@[<hv 1>(@[<hov 1>%a@;<1 0>@[<hov 1>++@;<1 0>%a@]@])@]"
(print_algop idname 9) t1
(print_algop idname 9) t2
else
fprintf ff "@[<hov 1>%a@;<1 0>@[<hov 1>++@;<1 0>%a@]@]"
(print_algop idname 9) t1
(print_algop idname 9) t2
| AOEMapFromItem vname ->
let op3 = access_onesub algop.psub_expression in
let op1 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Map@,@[<hv 1>{%a}@]@,@[<hv 1>(%a)@]@]"
(print_algop vname 0) op1
(print_algop idname 0) op3
| AOEInputTuple ->
let _ = access_nosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "ID"
| AOEMapConcat ->
let op3 = access_onesub algop.psub_expression in
let op1 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>MapConcat@,@[<hv 1>{%a}@]@,@[<hv 1>(%a)@]@]"
(print_algop idname 0) op1
(print_algop idname 0) op3
| AOEOuterMapConcat vn ->
let op3 = access_onesub algop.psub_expression in
let op1 = access_onesub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>OMapConcat[(%a)]@,@[<hv 1>{%a}@]@,@[<hv 1>(%a)@]@]"
print_rqname vn
(print_algop idname 0) op1
(print_algop idname 0) op3
| AOEJoin pred_desc ->
let l,r = access_twosub algop.psub_expression in
let pred = access_manysub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Join@,@[<hv 1>{%a}@]@,@[<hv 1>(%a,@,%a)@]@]"
(print_pred_desc idname 0 pred print_algop) pred_desc
(print_algop idname 0) l
(print_algop idname 0) r
| AOELeftOuterJoin (v,pred_desc) ->
let l,r = access_twosub algop.psub_expression in
let pred = access_manysub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>LeftOuterJoin[(%a)]@,@[<hv 1>{%a}@]@,@[<hv 1>(%a,@,%a)@]@]"
print_rqname v
(print_pred_desc idname 0 pred print_algop) pred_desc
(print_algop idname 0) l
(print_algop idname 0) r
| AOEGroupBy gd_list ->
let input = access_onesub algop.psub_expression in
let many = access_manysub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>GroupBy%a@,%a@[<hv 1>(%a)@]@]"
print_group_by gd_list
(print_many_deps idname print_algop) many
(print_algop idname 0) input
| AOECopy ->
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Copy@[<hv 1>(%a)@]@]"
(print_algop idname 0) a1
| AOEDelete ->
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Delete@[<hv 1>(%a)@]@]"
(print_algop idname 0) a1
| AOEInsert loc ->
let a1,a2 = access_twosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Insert[%a]@[<hv 1>(%a,@,%a)@]@]"
print_algop_insert_loc loc
(print_algop idname 0) a1
(print_algop idname 0) a2
| AOERename nsenv ->
let a1, a2 = access_twosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Rename@[<hv 1>(%a,@,%a)@]@]"
(print_algop idname 0) a1
(print_algop idname 0) a2
| AOEReplace valueflag ->
let a1, a2 = access_twosub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Replace[%a]@[<hv 1>(%a,@,%a)@]@]"
print_algop_value_of_flag valueflag
(print_algop idname 0) a1
(print_algop idname 0) a2
| AOESnap sm ->
let a1 = access_onesub algop.pdep_sub_expression in
let _ = access_nosub algop.psub_expression in
fprintf ff "@[<hv 2>Snap[%a]@[<hv 1>(%a)@]@]"
print_snap_modifier sm
(print_algop idname 0) a1
| AOESet vn ->
let a1 = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>Set[$%a]@[<hv 1>(%a)@]@]"
print_rqname vn
(print_algop idname 0) a1
XPath evaluation
| AOEParse uri ->
fprintf ff "Parse(%s)" uri
| AOETreeJoin (a, nt) ->
let ae = access_onesub algop.psub_expression in
fprintf ff "@[<hv 2>TreeJoin[%a::%a]@,@[<hv 1>(%a)@]@]"
print_axis a
print_anode_test nt
(print_algop idname 0) ae
| AOETupleTreePattern (input, pattern) ->
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>TupleTreePattern[(%a),(%a)]@,@[<hv 1>(%a)@]@]"
print_rqname input
print_twig_node pattern
(print_algop idname 0) a1
| AOEPrune ( name , a ) - >
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
ff " @[<hv 2 > Prune[%a,%a]@,@[<hv 1>(%a)@]@ ] "
print_rqname name
print_axis a
( 0 ) a1
| AOEDistinct name - >
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
ff " @[<hv 2 > Distinct[%a]@,@[<hv 1>(%a)@]@ ] "
print_rqname name
( 0 ) a1
| AOEPrune (name, a) ->
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Prune[%a,%a]@,@[<hv 1>(%a)@]@]"
print_rqname name
print_axis a
(print_algop idname 0) a1
| AOEDistinct name ->
let a1 = access_onesub algop.psub_expression in
let _ = access_nosub algop.pdep_sub_expression in
fprintf ff "@[<hv 2>Distinct[%a]@,@[<hv 1>(%a)@]@]"
print_rqname name
(print_algop idname 0) a1
*)
let msg_constructor msg x =
if x = ""
then []
else [msg ^ x]
let print_physical_algop ff algop =
let rec print_physical_algop_prec idname p ff algop =
let _ =
check_signatures msg_constructor algop.palgop_expr_eval_sig algop.psub_expression
in
(print_algop_main idname true) p print_physical_algop_prec ff algop
in
print_physical_algop_prec Xquery_common_ast_util.bogus_cvname 0 ff algop
let rec print_logical_algop ff (algop: ('a,'b) Xquery_algebra_ast.aalgop_expr) =
let rec print_logical_algop idname p ff algop =
(print_algop_main idname false) p print_logical_algop ff algop
in
print_logical_algop Xquery_common_ast_util.bogus_cvname 0 ff algop
let print_algstatement print_algop ff s =
fprintf ff "@[%a@]" print_algop s
let rec print_algstatements print_algop ff ss =
let print_algstatement' ff s = print_algstatement print_algop ff s in
let print_algstatements' ff s = print_algstatements print_algop ff s in
match ss with
| s :: [] ->
fprintf ff "%a;@\n" print_algstatement' s
| s :: ss' ->
fprintf ff "%a;@\n%a" print_algstatement' s print_algstatements' ss'
| [] ->
()
Core Module
let print_algprolog print_algop ff qm =
let rec print_cfunction_def ff fd =
let print_fn_body ff body =
match !(body.palgop_func_optimized_logical_plan) with
| AOEFunctionImported -> ()
| AOEFunctionUser userbody ->
print_algop ff userbody
in
let rec print_intypes ff t =
match t with
| [] -> ()
| t' :: [] ->
fprintf ff "%a" print_asequencetype t'
| t' :: rest ->
fprintf ff "%a,%a" print_asequencetype t' print_intypes rest
in
let ((fn,arity), (dts,odt), fbody, upd) = fd.palgop_function_decl_desc in
let upd_flag = updating_flag_to_string upd in
fprintf ff
"@[<hv 2>@[<hv 2>declare %sfunction@ %a(@,%a@;<0 -2>)@] as %a {@,%a@;<0 -2>};@]"
upd_flag
print_rqname fn
print_intypes dts
print_asequencetype odt
print_fn_body fbody
and print_cfunction_defs ff fds =
match fds with
| [] ->
()
| fd :: fds' ->
fprintf ff "@[%a@,@]@\n%a" print_cfunction_def fd print_cfunction_defs fds'
and print_decl ff vd =
match vd.alg_decl_name with
| AOEVarDecl (odt, vn) ->
let sub = access_onesub vd.alg_decl_indep in
let _ = access_nosub vd.alg_decl_dep in
fprintf ff "declare variable@ $%a%a { @[%a@]@ };"
print_rqname vn
print_optasequencetype odt
print_algop sub
| AOEVarDeclImported (odt, vn)
| AOEVarDeclExternal (odt, vn) ->
let _ = access_nosub vd.alg_decl_indep in
let _ = access_nosub vd.alg_decl_dep in
fprintf ff "declare variable@ $%a%a external;"
print_rqname vn
print_optasequencetype odt
| AOEValueIndexDecl kn ->
let a1 = access_onesub vd.alg_decl_indep in
let a2 = access_onesub vd.alg_decl_dep in
fprintf ff "@[<hv 2>declare value index %s {@,%a@;<0 -2>} {@,%a@;<0 -2>};@]"
kn
print_algop a1
print_algop a2
| AOENameIndexDecl l ->
let _ = access_nosub vd.alg_decl_indep in
let _ = access_nosub vd.alg_decl_dep in
fprintf ff "@[<hv 2>declare name index %a;@]"
print_symbol l
and print_decls ff vds =
match vds with
| [] ->
()
| vd :: vds' ->
fprintf ff "@[%a@]@\n%a"
print_decl vd
print_decls vds'
in
let print_algprolog' ff prolog =
print_decls ff prolog.palgop_prolog_vars;
print_cfunction_defs ff prolog.palgop_prolog_functions;
print_decls ff prolog.palgop_prolog_indices;
in
if !Conf.print_prolog
then print_algprolog' ff qm
else ()
let print_algmodule print_annot ff qm =
print_algprolog print_annot ff qm.palgop_module_prolog;
print_algstatements print_annot ff qm.palgop_module_statements
2006 - 2 - 15 CAR - I added flushes to each of these functions as
the pretty printer in ocaml 3.09.1 does not do it
when the formatter is closed .
the pretty printer in ocaml 3.09.1 does not do it
when the formatter is closed.
*)
let print_logical_algstatement ff s =
(print_algstatement print_logical_algop) ff s;
fprintf ff "@?"
let print_physical_algstatement ff s =
print_algstatement print_physical_algop ff s;
fprintf ff "@?"
let print_logical_algprolog ff s =
print_algprolog print_logical_algop ff s;
fprintf ff "@?"
let print_physical_algprolog ff s =
print_algprolog print_physical_algop ff s;
fprintf ff "@?"
let print_logical_algmodule ff s =
print_algmodule print_logical_algop ff s;
fprintf ff "@?"
let print_physical_algmodule ff s =
print_algmodule print_physical_algop ff s;
fprintf ff "@?"
let fprintf_logical_algstatement f s st =
fprintf_stub f s print_logical_algstatement st
let printf_logical_algstatement s st = printf_stub s print_logical_algstatement st
let bprintf_logical_algstatement s st = bprintf_stub s print_logical_algstatement st
let fprintf_logical_algprolog f s st = fprintf_stub f s print_logical_algprolog st
let printf_logical_algprolog s qms = printf_stub s print_logical_algprolog qms
let bprintf_logical_algprolog s qms = bprintf_stub s print_logical_algprolog qms
let fprintf_logical_algmodule f s st = fprintf_stub f s print_logical_algmodule st
let printf_logical_algmodule s qms = printf_stub s print_logical_algmodule qms
let bprintf_logical_algmodule s qms = bprintf_stub s print_logical_algmodule qms
let fprintf_optimized_algstatement f s st =
fprintf_stub f s print_logical_algstatement st
let printf_optimized_algstatement s st = printf_stub s print_logical_algstatement st
let bprintf_optimized_algstatement s st = bprintf_stub s print_logical_algstatement st
let fprintf_optimized_algprolog f s st = fprintf_stub f s print_logical_algprolog st
let printf_optimized_algprolog s qms = printf_stub s print_logical_algprolog qms
let bprintf_optimized_algprolog s qms = bprintf_stub s print_logical_algprolog qms
let fprintf_optimized_algmodule f s st = fprintf_stub f s print_logical_algmodule st
let printf_optimized_algmodule s qms = printf_stub s print_logical_algmodule qms
let bprintf_optimized_algmodule s qms = bprintf_stub s print_logical_algmodule qms
let fprintf_physical_algstatement f s st =
fprintf_stub f s print_physical_algstatement st
let printf_physical_algstatement s st = printf_stub s print_physical_algstatement st
let bprintf_physical_algstatement s st = bprintf_stub s print_physical_algstatement st
let fprintf_physical_algprolog f s st = fprintf_stub f s print_physical_algprolog st
let printf_physical_algprolog s qms = printf_stub s print_physical_algprolog qms
let bprintf_physical_algprolog s qms = bprintf_stub s print_physical_algprolog qms
let fprintf_physical_algmodule f s st = fprintf_stub f s print_physical_algmodule st
let printf_physical_algmodule s qms = printf_stub s print_physical_algmodule qms
let bprintf_physical_algmodule s qms = bprintf_stub s print_physical_algmodule qms
let printf_anode_test s akt = printf_stub s print_anode_test akt
let bprintf_anode_test s akt = bprintf_stub s print_anode_test akt
|
cc77285d331463dfaec592801dfcc9b86414b47991c1a05e6a06cab2a4db9eba | CGenie/ray-tracer | tracing.ml | (* tracing.ml *)
open Gg.V3
open Formatters
open Algorithms
open Tracing_types
open Initials
let rec intersect ({origin=ro; direction=rd} as r:ray) wo =
(* TODO: ray direction should be normalized, add an assertion *)
let rd2 = norm2 rd in
match wo.shape with
| Ball{origin=bo; radius=br} ->
let ro_bo = ro - bo in
let a = rd2
and b = 2.*.(dot ro_bo rd)
and c = (norm2 ro_bo) -. br*.br in
let zeros = q_zeros a b c in (
match zeros with
[] -> []
| z::_ -> [{normal=unit (ro_bo); point=(ro + z*rd); ray=r; w_object=wo}]
)
| Affine{m=_; inv_m=inv_m; shape=s} ->
let inv_ray = {origin=Gg.P3.tr inv_m ro; direction=Gg.V3.tr inv_m rd} in
let intersections = intersect inv_ray {wo with shape=s} in
List.map (fun i -> {i with w_object=wo}) intersections
let image_plane_of_camera c =
let mid_p = c.eye + (smul c.distance c.direction) in (* middle point of image plane *)
find 2 vetors perpendicular to c.direction : one going " right " , one going " up "
let x, y, z = to_tuple c.direction in
let vec_r = unit @@ if z < 0.0 then
Gg.V3.v (-.z) 0.0 x
else
Gg.V3.v z 0.0 (-.x)
in
let vec_u = unit @@ if z < 0.0 then
Gg.V3.v 0.0 (-.z) y
else
Gg.V3.v 0.0 z (-.y)
in
(* lower-left point of image plane *)
let ll = mid_p - (smul (0.5 *. c.width) vec_r) - (smul (0.5 *. c.height) vec_u) in
(* upper-right point of image plane *)
let ur = mid_p + (smul (0.5 *. c.width) vec_r) + (smul (0.5 *. c.height) vec_u) in
{ll=ll; ur=ur}
(* [image_plane_of_camera] tests *)
let%test_module _ = (module struct
let%test _ =
let c: camera = {
eye=Gg.P3.v 0.0 0.0 (-2.0);
direction=Gg.V3.unit @@ Gg.V3.v 0.0 0.0 1.0;
distance=1.0;
width=4.0;
height=4.0;
} in
let ip = image_plane_of_camera c in
let expected_ll = Gg.P3.v (-2.) (-2.) (-1.) in
let expected_ur = Gg.P3.v 2. 2. (-1.) in
let err = (Gg.V3.norm (ip.ll - expected_ll)) +. (Gg.V3.norm (ip.ur - expected_ur)) in
Printf.printf "ll: %s; expected_ll: %s\n" (format_p3 ip.ll) (format_p3 expected_ll);
Printf.printf "ur: %s; expected_ur: %s\n" (format_p3 ip.ur) (format_p3 expected_ur);
err < 0.001
end)
let phong_color (material_color: Gg.color) (material_phong: phong_t) (light_: lighting) (point: Gg.p3) (eyev: Gg.v3) (normalv: Gg.v3) =
match light_ with
PointLight light -> Gg.Color.with_a (
let effective_color = Gg.V4.mul light.intensity material_color in
let ambient = Gg.V4.smul material_phong.ambient effective_color in
let lightv = unit @@ light.position - point in
let light_dot_normal = dot lightv normalv in
if light_dot_normal < 0.0 then
ambient (* Not illuminated -- light behind the surface -- diffuse = specular = Color.black *)
else (
let diffuse = Gg.V4.smul (material_phong.diffuse *. light_dot_normal) effective_color in
let reflectv = reflect (neg lightv) normalv in
let reflect_dot_eye = (dot reflectv eyev) ** material_phong.shininess in
let specular = if reflect_dot_eye <= 0.0 then
Gg.Color.black
else
Gg.V4.smul (material_phong.specular *. reflect_dot_eye) light.intensity
in
Gg.V4.add ambient @@ Gg.V4.add diffuse specular
)
) 1.0
(* [phong_color] tests *)
let%test_module _ = (module struct
let m_phong: phong_t = {
ambient=0.1;
diffuse=0.9;
specular=0.9;
shininess=200.0
}
let m_color = Gg.Color.v 1.0 1.0 1.0 1.0
let position = Gg.P3.v 0.0 0.0 0.0
(* light behind the eye *)
let%test _ = let eyev = v 0.0 0.0 (-1.0) in
let normalv = v 0.0 0.0 (-1.0) in
let light = PointLight {position=Gg.P3.v 0.0 0.0 (-10.0); intensity=Gg.Color.v 1.0 1.0 1.0 1.0} in
let ph_light = phong_color m_color m_phong light position eyev normalv in
let expected = Gg.Color.v 1.9 1.9 1.9 1.0 in
let err = Gg.V4.norm @@ Gg.V4.sub ph_light expected in
err < 0.00001
45 deg angle
let%test _ = let eyev = v 0.0 (0.5 *. (sqrt 2.0)) (-0.5 *. (sqrt 2.0)) in
let normalv = v 0.0 0.0 (-1.0) in
let light = PointLight {position=Gg.P3.v 0.0 0.0 (-10.0); intensity=Gg.Color.v 1.0 1.0 1.0 1.0} in
let ph_light = phong_color m_color m_phong light position eyev normalv in
let expected = Gg.Color.v 1.0 1.0 1.0 1.0 in
let err = Gg.V4.norm @@ Gg.V4.sub ph_light expected in
err < 0.00001
45 deg angle again
let%test _ = let eyev = v 0.0 0.0 (-1.0) in
let normalv = v 0.0 0.0 (-1.0) in
let light = PointLight {position=Gg.P3.v 0.0 10.0 (-10.0); intensity=Gg.Color.v 1.0 1.0 1.0 1.0} in
let ph_light = phong_color m_color m_phong light position eyev normalv in
let expected = Gg.Color.v 0.7364 0.7364 0.7364 1.0 in
let err = Gg.V4.norm @@ Gg.V4.sub ph_light expected in
err < 0.00001
45 deg angle again
let%test _ = let eyev = v 0.0 (-0.5 *. (sqrt 2.0)) (-0.5 *. (sqrt 2.0)) in
let normalv = v 0.0 0.0 (-1.0) in
let light = PointLight {position=Gg.P3.v 0.0 10.0 (-10.0); intensity=Gg.Color.v 1.0 1.0 1.0 1.0} in
let ph_light = phong_color m_color m_phong light position eyev normalv in
let expected = Gg.Color.v 1.6364 1.6364 1.6364 1.0 in
let err = Gg.V4.norm @@ Gg.V4.sub ph_light expected in
err < 0.00001
(* light behind the surface *)
let%test _ = let eyev = v 0.0 0.0 (-1.0) in
let normalv = v 0.0 0.0 (-1.0) in
let light = PointLight {position=Gg.P3.v 0.0 0.0 10.0; intensity=Gg.Color.v 1.0 1.0 1.0 1.0} in
let ph_light = phong_color m_color m_phong light position eyev normalv in
let expected = Gg.Color.v 0.1 0.1 0.1 1.0 in
let err = Gg.V4.norm @@ Gg.V4.sub ph_light expected in
err < 0.00001
end)
let colorize_point (w: world) (r: ray) =
let intersections_mapped = List.rev_map (intersect r) w.objects
and comparator (a: intersection) (b: intersection) =
let d = (norm2 @@ r.origin - a.point) -. (norm2 @@ r.origin - b.point) in
if d < 0. then (-1)
else if d > 0. then 1
else 0 in
let intersections = List.fold_left List.append [] intersections_mapped in
let intersections_sorted = List.sort comparator intersections in
let c =
match intersections_sorted with
[] -> w.background_color
| (i::_) ->
let vv = (unit @@ neg i.ray.direction) in
i.w_object.color -- for chapter 5 solution with only a red ball , no Phong
List.fold_left (fun acc l -> Gg.V4.add acc (phong_color i.w_object.color i.w_object.phong l i.point vv i.normal))
Gg.Color.black
w.lights
in
{point=r.origin; color=Gg.Color.with_a c 1.0}
let colorize (ip: image_plane) (w: world) (e: eye) =
let rays = get_rays e ip x_initial_rays y_initial_rays in
Printf.printf " num rays : % d\n " ( rays ) ;
(* List.iter (fun r -> Printf.printf "%s\n" (format_ray r)) rays; *)
List.rev_map ( colorize_point w ) rays
Seq.map (colorize_point w) rays
let simple_scene () =
let w = initial_world in
let c = initial_camera in
let ip = image_plane_of_camera c in
Printf.printf "Colorizing...\n";
(* let pts = colorize_parallel ip w e in *)
let pts = colorize ip w c.eye in
Printf.printf "Colorize done\n";
Drawing.render_points pts ~output:"./output/simple-scene.png"
(* external float_compare_noalloc : float -> float -> int = *)
(* "float_compare_noalloc_stub" "mystubs" *)
let run () =
simple_scene ();
Dumb.scene ()
Printf.printf " Float compare : % d\n " ( float_compare_noalloc 1.0 2.0 )
| null | https://raw.githubusercontent.com/CGenie/ray-tracer/37a7918c38497fe5d9b52ba0795f209c1c06fa9b/02-tracing/lib/tracing.ml | ocaml | tracing.ml
TODO: ray direction should be normalized, add an assertion
middle point of image plane
lower-left point of image plane
upper-right point of image plane
[image_plane_of_camera] tests
Not illuminated -- light behind the surface -- diffuse = specular = Color.black
[phong_color] tests
light behind the eye
light behind the surface
List.iter (fun r -> Printf.printf "%s\n" (format_ray r)) rays;
let pts = colorize_parallel ip w e in
external float_compare_noalloc : float -> float -> int =
"float_compare_noalloc_stub" "mystubs" |
open Gg.V3
open Formatters
open Algorithms
open Tracing_types
open Initials
let rec intersect ({origin=ro; direction=rd} as r:ray) wo =
let rd2 = norm2 rd in
match wo.shape with
| Ball{origin=bo; radius=br} ->
let ro_bo = ro - bo in
let a = rd2
and b = 2.*.(dot ro_bo rd)
and c = (norm2 ro_bo) -. br*.br in
let zeros = q_zeros a b c in (
match zeros with
[] -> []
| z::_ -> [{normal=unit (ro_bo); point=(ro + z*rd); ray=r; w_object=wo}]
)
| Affine{m=_; inv_m=inv_m; shape=s} ->
let inv_ray = {origin=Gg.P3.tr inv_m ro; direction=Gg.V3.tr inv_m rd} in
let intersections = intersect inv_ray {wo with shape=s} in
List.map (fun i -> {i with w_object=wo}) intersections
let image_plane_of_camera c =
find 2 vetors perpendicular to c.direction : one going " right " , one going " up "
let x, y, z = to_tuple c.direction in
let vec_r = unit @@ if z < 0.0 then
Gg.V3.v (-.z) 0.0 x
else
Gg.V3.v z 0.0 (-.x)
in
let vec_u = unit @@ if z < 0.0 then
Gg.V3.v 0.0 (-.z) y
else
Gg.V3.v 0.0 z (-.y)
in
let ll = mid_p - (smul (0.5 *. c.width) vec_r) - (smul (0.5 *. c.height) vec_u) in
let ur = mid_p + (smul (0.5 *. c.width) vec_r) + (smul (0.5 *. c.height) vec_u) in
{ll=ll; ur=ur}
let%test_module _ = (module struct
let%test _ =
let c: camera = {
eye=Gg.P3.v 0.0 0.0 (-2.0);
direction=Gg.V3.unit @@ Gg.V3.v 0.0 0.0 1.0;
distance=1.0;
width=4.0;
height=4.0;
} in
let ip = image_plane_of_camera c in
let expected_ll = Gg.P3.v (-2.) (-2.) (-1.) in
let expected_ur = Gg.P3.v 2. 2. (-1.) in
let err = (Gg.V3.norm (ip.ll - expected_ll)) +. (Gg.V3.norm (ip.ur - expected_ur)) in
Printf.printf "ll: %s; expected_ll: %s\n" (format_p3 ip.ll) (format_p3 expected_ll);
Printf.printf "ur: %s; expected_ur: %s\n" (format_p3 ip.ur) (format_p3 expected_ur);
err < 0.001
end)
let phong_color (material_color: Gg.color) (material_phong: phong_t) (light_: lighting) (point: Gg.p3) (eyev: Gg.v3) (normalv: Gg.v3) =
match light_ with
PointLight light -> Gg.Color.with_a (
let effective_color = Gg.V4.mul light.intensity material_color in
let ambient = Gg.V4.smul material_phong.ambient effective_color in
let lightv = unit @@ light.position - point in
let light_dot_normal = dot lightv normalv in
if light_dot_normal < 0.0 then
else (
let diffuse = Gg.V4.smul (material_phong.diffuse *. light_dot_normal) effective_color in
let reflectv = reflect (neg lightv) normalv in
let reflect_dot_eye = (dot reflectv eyev) ** material_phong.shininess in
let specular = if reflect_dot_eye <= 0.0 then
Gg.Color.black
else
Gg.V4.smul (material_phong.specular *. reflect_dot_eye) light.intensity
in
Gg.V4.add ambient @@ Gg.V4.add diffuse specular
)
) 1.0
let%test_module _ = (module struct
let m_phong: phong_t = {
ambient=0.1;
diffuse=0.9;
specular=0.9;
shininess=200.0
}
let m_color = Gg.Color.v 1.0 1.0 1.0 1.0
let position = Gg.P3.v 0.0 0.0 0.0
let%test _ = let eyev = v 0.0 0.0 (-1.0) in
let normalv = v 0.0 0.0 (-1.0) in
let light = PointLight {position=Gg.P3.v 0.0 0.0 (-10.0); intensity=Gg.Color.v 1.0 1.0 1.0 1.0} in
let ph_light = phong_color m_color m_phong light position eyev normalv in
let expected = Gg.Color.v 1.9 1.9 1.9 1.0 in
let err = Gg.V4.norm @@ Gg.V4.sub ph_light expected in
err < 0.00001
45 deg angle
let%test _ = let eyev = v 0.0 (0.5 *. (sqrt 2.0)) (-0.5 *. (sqrt 2.0)) in
let normalv = v 0.0 0.0 (-1.0) in
let light = PointLight {position=Gg.P3.v 0.0 0.0 (-10.0); intensity=Gg.Color.v 1.0 1.0 1.0 1.0} in
let ph_light = phong_color m_color m_phong light position eyev normalv in
let expected = Gg.Color.v 1.0 1.0 1.0 1.0 in
let err = Gg.V4.norm @@ Gg.V4.sub ph_light expected in
err < 0.00001
45 deg angle again
let%test _ = let eyev = v 0.0 0.0 (-1.0) in
let normalv = v 0.0 0.0 (-1.0) in
let light = PointLight {position=Gg.P3.v 0.0 10.0 (-10.0); intensity=Gg.Color.v 1.0 1.0 1.0 1.0} in
let ph_light = phong_color m_color m_phong light position eyev normalv in
let expected = Gg.Color.v 0.7364 0.7364 0.7364 1.0 in
let err = Gg.V4.norm @@ Gg.V4.sub ph_light expected in
err < 0.00001
45 deg angle again
let%test _ = let eyev = v 0.0 (-0.5 *. (sqrt 2.0)) (-0.5 *. (sqrt 2.0)) in
let normalv = v 0.0 0.0 (-1.0) in
let light = PointLight {position=Gg.P3.v 0.0 10.0 (-10.0); intensity=Gg.Color.v 1.0 1.0 1.0 1.0} in
let ph_light = phong_color m_color m_phong light position eyev normalv in
let expected = Gg.Color.v 1.6364 1.6364 1.6364 1.0 in
let err = Gg.V4.norm @@ Gg.V4.sub ph_light expected in
err < 0.00001
let%test _ = let eyev = v 0.0 0.0 (-1.0) in
let normalv = v 0.0 0.0 (-1.0) in
let light = PointLight {position=Gg.P3.v 0.0 0.0 10.0; intensity=Gg.Color.v 1.0 1.0 1.0 1.0} in
let ph_light = phong_color m_color m_phong light position eyev normalv in
let expected = Gg.Color.v 0.1 0.1 0.1 1.0 in
let err = Gg.V4.norm @@ Gg.V4.sub ph_light expected in
err < 0.00001
end)
let colorize_point (w: world) (r: ray) =
let intersections_mapped = List.rev_map (intersect r) w.objects
and comparator (a: intersection) (b: intersection) =
let d = (norm2 @@ r.origin - a.point) -. (norm2 @@ r.origin - b.point) in
if d < 0. then (-1)
else if d > 0. then 1
else 0 in
let intersections = List.fold_left List.append [] intersections_mapped in
let intersections_sorted = List.sort comparator intersections in
let c =
match intersections_sorted with
[] -> w.background_color
| (i::_) ->
let vv = (unit @@ neg i.ray.direction) in
i.w_object.color -- for chapter 5 solution with only a red ball , no Phong
List.fold_left (fun acc l -> Gg.V4.add acc (phong_color i.w_object.color i.w_object.phong l i.point vv i.normal))
Gg.Color.black
w.lights
in
{point=r.origin; color=Gg.Color.with_a c 1.0}
let colorize (ip: image_plane) (w: world) (e: eye) =
let rays = get_rays e ip x_initial_rays y_initial_rays in
Printf.printf " num rays : % d\n " ( rays ) ;
List.rev_map ( colorize_point w ) rays
Seq.map (colorize_point w) rays
let simple_scene () =
let w = initial_world in
let c = initial_camera in
let ip = image_plane_of_camera c in
Printf.printf "Colorizing...\n";
let pts = colorize ip w c.eye in
Printf.printf "Colorize done\n";
Drawing.render_points pts ~output:"./output/simple-scene.png"
let run () =
simple_scene ();
Dumb.scene ()
Printf.printf " Float compare : % d\n " ( float_compare_noalloc 1.0 2.0 )
|
1fe70cb04b34a9a3a489e367cff1cc68551571bd8ea5de6d9f325bdee2e73cc1 | MyDataFlow/ttalk-server | ejabberd_helper.erl | -module(ejabberd_helper).
-export([start_ejabberd/1,
stop_ejabberd/0,
use_config_file/2]).
-spec start_ejabberd(any()) -> 'ok' | {error, any()}.
start_ejabberd(_Config) ->
{ok, _} = ejabberd:start().
-spec stop_ejabberd() -> 'ok' | {error, any()}.
stop_ejabberd() ->
application:stop(ejabberd).
-spec use_config_file(any(), file:name_all()) -> ok.
use_config_file(Config, ConfigFile) ->
application:load(ejabberd),
DataDir = proplists:get_value(data_dir, Config),
ConfigPath = filename:join([DataDir, ConfigFile]),
application:set_env(ejabberd, config, ConfigPath).
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/apps/ejabberd/test/ejabberd_helper.erl | erlang | -module(ejabberd_helper).
-export([start_ejabberd/1,
stop_ejabberd/0,
use_config_file/2]).
-spec start_ejabberd(any()) -> 'ok' | {error, any()}.
start_ejabberd(_Config) ->
{ok, _} = ejabberd:start().
-spec stop_ejabberd() -> 'ok' | {error, any()}.
stop_ejabberd() ->
application:stop(ejabberd).
-spec use_config_file(any(), file:name_all()) -> ok.
use_config_file(Config, ConfigFile) ->
application:load(ejabberd),
DataDir = proplists:get_value(data_dir, Config),
ConfigPath = filename:join([DataDir, ConfigFile]),
application:set_env(ejabberd, config, ConfigPath).
|
|
05cccc23f6d397db4fc1e951191cb4ea1833e6435e3c6f0c872ccbcdc4a6aecb | composewell/streamly-dom | AcidRain.hs | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
This example is adapted from pipes - concurrency package .
-- -concurrency-2.0.8/docs/Pipes-Concurrent-Tutorial.html
module Main
( main
) where
import Streamly
import Streamly.Prelude as S
import Control.Monad (void)
import Control.Monad.State (MonadState, get, modify, runStateT)
#if __GHCJS__
import AcidRain.JSIO
#else
import AcidRain.StdIO
#endif
-------------------------------------------------------------------------------
-- Streams
-------------------------------------------------------------------------------
data GEvent = Quit | Harm Int | Heal Int | Unknown deriving (Show)
parseCommand :: String -> GEvent
parseCommand command =
case command of
"potion" -> Heal 10
"harm" -> Harm 10
"quit" -> Quit
_ -> Unknown
acidRain :: MonadAsync m => SerialT m GEvent
acidRain = asyncly $ constRate 1 $ S.repeatM $ return $ Harm 1
data Result = Check | Done | Error
runEvents :: (MonadState Int m, MonadAsync m) => SerialT m Result
runEvents = do
event <- fmap parseCommand userStream `parallel` acidRain
case event of
Harm n -> modify (\h -> h - n) >> return Check
Heal n -> modify (\h -> h + n) >> return Check
Unknown -> return Error
Quit -> return Done
data Status = Alive | GameOver deriving Eq
getStatus :: (MonadState Int m, MonadAsync m) => Result -> m Status
getStatus result = do
case result of
Done -> printHealth "You quit!" >> return GameOver
Error -> printError "Type potion or harm or quit" >> return Alive
Check -> do
health <- get
if (health <= 0)
then printHealth "You die!" >> return GameOver
else printHealth ("Health = " <> show health) >>
return Alive
-------------------------------------------------------------------------------
-- Game
-------------------------------------------------------------------------------
letItRain :: IO ()
letItRain = do
initConsole
let runGame =
S.drainWhile (== Alive) $ S.mapM getStatus runEvents
void $ runStateT runGame 60
main :: IO ()
main = letItRain
| null | https://raw.githubusercontent.com/composewell/streamly-dom/42c330424bd2785684390985e3c4478de74b3908/examples/AcidRain.hs | haskell | -concurrency-2.0.8/docs/Pipes-Concurrent-Tutorial.html
-----------------------------------------------------------------------------
Streams
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Game
----------------------------------------------------------------------------- | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
This example is adapted from pipes - concurrency package .
module Main
( main
) where
import Streamly
import Streamly.Prelude as S
import Control.Monad (void)
import Control.Monad.State (MonadState, get, modify, runStateT)
#if __GHCJS__
import AcidRain.JSIO
#else
import AcidRain.StdIO
#endif
data GEvent = Quit | Harm Int | Heal Int | Unknown deriving (Show)
parseCommand :: String -> GEvent
parseCommand command =
case command of
"potion" -> Heal 10
"harm" -> Harm 10
"quit" -> Quit
_ -> Unknown
acidRain :: MonadAsync m => SerialT m GEvent
acidRain = asyncly $ constRate 1 $ S.repeatM $ return $ Harm 1
data Result = Check | Done | Error
runEvents :: (MonadState Int m, MonadAsync m) => SerialT m Result
runEvents = do
event <- fmap parseCommand userStream `parallel` acidRain
case event of
Harm n -> modify (\h -> h - n) >> return Check
Heal n -> modify (\h -> h + n) >> return Check
Unknown -> return Error
Quit -> return Done
data Status = Alive | GameOver deriving Eq
getStatus :: (MonadState Int m, MonadAsync m) => Result -> m Status
getStatus result = do
case result of
Done -> printHealth "You quit!" >> return GameOver
Error -> printError "Type potion or harm or quit" >> return Alive
Check -> do
health <- get
if (health <= 0)
then printHealth "You die!" >> return GameOver
else printHealth ("Health = " <> show health) >>
return Alive
letItRain :: IO ()
letItRain = do
initConsole
let runGame =
S.drainWhile (== Alive) $ S.mapM getStatus runEvents
void $ runStateT runGame 60
main :: IO ()
main = letItRain
|
508a9a07d01559373218fc6df7915e4b90e19e152fb6e98820ed4995634f0739 | EveryTian/Haskell-Codewars | categorize-new-member.hs | -- -new-member
module Codewars.Kata.Categorize where
import Codewars.Kata.Categorize.Types
data Membership = Open | Senior deriving ( Eq , Show )
openOrSenior :: [(Int, Int)] -> [Membership]
openOrSenior = map (\x -> if fst x >= 55 && snd x > 7 then Senior else Open)
| null | https://raw.githubusercontent.com/EveryTian/Haskell-Codewars/dc48d95c676ce1a59f697d07672acb6d4722893b/7kyu/categorize-new-member.hs | haskell | -new-member |
module Codewars.Kata.Categorize where
import Codewars.Kata.Categorize.Types
data Membership = Open | Senior deriving ( Eq , Show )
openOrSenior :: [(Int, Int)] -> [Membership]
openOrSenior = map (\x -> if fst x >= 55 && snd x > 7 then Senior else Open)
|
4420212c8a8f7917acb6d4a377b090cb54ed3abfb9f9b9646ef23d93caf36939 | wardle/deprivare | build.clj | (ns build
(:require [clojure.tools.build.api :as b]
[deps-deploy.deps-deploy :as dd]))
(def lib 'com.eldrix/deprivare)
(def version (format "1.0.%s" (b/git-count-revs nil)))
(def class-dir "target/classes")
(def basis (b/create-basis {:project "deps.edn"}))
(def jar-file (format "target/%s-%s.jar" (name lib) version))
(defn clean [_]
(b/delete {:path "target"}))
(defn jar
"Create a library jar file."
[_]
(clean nil)
(println "Building" lib version)
(b/write-pom {:class-dir class-dir
:lib lib
:version version
:basis basis
:src-dirs ["src"]
:scm {:url ""
:tag (str "v" version)
:connection "scm:git:git"
:developerConnection "scm:git:ssh"}})
(b/copy-dir {:src-dirs ["src" "resources"]
:target-dir class-dir})
(b/jar {:class-dir class-dir
:jar-file jar-file}))
(defn install
"Install library to local maven repository."
[_]
(jar nil)
(println "Installing" lib version)
(b/install {:basis basis
:lib lib
:version version
:jar-file jar-file
:class-dir class-dir}))
(defn deploy
"Deploy library to clojars.
Environment variables CLOJARS_USERNAME and CLOJARS_PASSWORD must be set."
[_]
(jar nil)
(dd/deploy {:installer :remote
:artifact jar-file
:pom-file (b/pom-path {:lib lib
:class-dir class-dir})})) | null | https://raw.githubusercontent.com/wardle/deprivare/16f2ffa88590744bd5db843500a135e01664a812/build.clj | clojure | (ns build
(:require [clojure.tools.build.api :as b]
[deps-deploy.deps-deploy :as dd]))
(def lib 'com.eldrix/deprivare)
(def version (format "1.0.%s" (b/git-count-revs nil)))
(def class-dir "target/classes")
(def basis (b/create-basis {:project "deps.edn"}))
(def jar-file (format "target/%s-%s.jar" (name lib) version))
(defn clean [_]
(b/delete {:path "target"}))
(defn jar
"Create a library jar file."
[_]
(clean nil)
(println "Building" lib version)
(b/write-pom {:class-dir class-dir
:lib lib
:version version
:basis basis
:src-dirs ["src"]
:scm {:url ""
:tag (str "v" version)
:connection "scm:git:git"
:developerConnection "scm:git:ssh"}})
(b/copy-dir {:src-dirs ["src" "resources"]
:target-dir class-dir})
(b/jar {:class-dir class-dir
:jar-file jar-file}))
(defn install
"Install library to local maven repository."
[_]
(jar nil)
(println "Installing" lib version)
(b/install {:basis basis
:lib lib
:version version
:jar-file jar-file
:class-dir class-dir}))
(defn deploy
"Deploy library to clojars.
Environment variables CLOJARS_USERNAME and CLOJARS_PASSWORD must be set."
[_]
(jar nil)
(dd/deploy {:installer :remote
:artifact jar-file
:pom-file (b/pom-path {:lib lib
:class-dir class-dir})})) |
|
cfe4122c8542dfdc235b3b54851e2a2f060be35fa82ffe92c6a83022120b7581 | leptonyu/guiguzi | Main.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
module Main where
import API.Captcha
import Boots
import Boots.Web
import Control.Monad.IO.Class
import Data.Captcha
import Data.Text.Encoding
import Paths_captcha_server
import Servant
import Server.Captcha ()
main :: IO ()
main = bootWebEnv "captcha-server" Paths_captcha_server.version (return ()) $ do
tryServeWithSwagger True Proxy (Proxy @CaptchaAPI) captchaServer
| null | https://raw.githubusercontent.com/leptonyu/guiguzi/9b3cb22f1b0c5387964c0097ef9a789125d2daee/captcha-server/src/Main.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
module Main where
import API.Captcha
import Boots
import Boots.Web
import Control.Monad.IO.Class
import Data.Captcha
import Data.Text.Encoding
import Paths_captcha_server
import Servant
import Server.Captcha ()
main :: IO ()
main = bootWebEnv "captcha-server" Paths_captcha_server.version (return ()) $ do
tryServeWithSwagger True Proxy (Proxy @CaptchaAPI) captchaServer
|
da8f2034d6204cf5ff7ea3498cf3181774cb6ef7e4fc53b130257b5a075d6ddc | llvm-hs/llvm-hs-typed | CallingConvention.hs | -- | This module provides a type-safe variant of "LLVM.AST.CallingConvention".
-- It is currently a stub
module LLVM.AST.Tagged.CallingConvention (module LLVM.AST.CallingConvention) where
import LLVM.AST.CallingConvention
| null | https://raw.githubusercontent.com/llvm-hs/llvm-hs-typed/efe052cf2a7ac8e6fb8dba1879d75d036f6fcc80/src/LLVM/AST/Tagged/CallingConvention.hs | haskell | | This module provides a type-safe variant of "LLVM.AST.CallingConvention".
It is currently a stub | module LLVM.AST.Tagged.CallingConvention (module LLVM.AST.CallingConvention) where
import LLVM.AST.CallingConvention
|
99a93f8e9166145eb1ef9e85d821985f7e682fc3f3db97c05d31d24039a292bb | ocamllabs/ocaml-modular-implicits | t000.ml | (* empty file *)
*
0 ATOM0
1 SETGLOBAL T000
3 STOP
*
0 ATOM0
1 SETGLOBAL T000
3 STOP
**)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/tool-ocaml/t000.ml | ocaml | empty file |
*
0 ATOM0
1 SETGLOBAL T000
3 STOP
*
0 ATOM0
1 SETGLOBAL T000
3 STOP
**)
|
2652e7cdc24f732291164487ed2a77e481142ebbcc2528c0477338bb886ae1e0 | v-kolesnikov/sicp | 2_22.clj | (ns sicp.chapter02.2-22
(:require [sicp.common :as sicp]))
(defn square-list-v1
[coll]
(loop [things coll
answer nil]
(if (empty? things)
(reverse answer)
(recur (rest things)
(cons (sicp/square (first things))
answer)))))
(defn square-list-v2
[coll]
(loop [things coll
answer nil]
(if (empty? things)
answer
(recur (rest things)
(concat answer
(list (sicp/square (first things))))))))
| null | https://raw.githubusercontent.com/v-kolesnikov/sicp/4298de6083440a75898e97aad658025a8cecb631/src/sicp/chapter02/2_22.clj | clojure | (ns sicp.chapter02.2-22
(:require [sicp.common :as sicp]))
(defn square-list-v1
[coll]
(loop [things coll
answer nil]
(if (empty? things)
(reverse answer)
(recur (rest things)
(cons (sicp/square (first things))
answer)))))
(defn square-list-v2
[coll]
(loop [things coll
answer nil]
(if (empty? things)
answer
(recur (rest things)
(concat answer
(list (sicp/square (first things))))))))
|
|
748c92570a6e11ee2003198293d56ab2602684747480bedbd8da9941df0016ec | facebook/flow | jsdoc.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module Sedlexing = Flow_sedlexing
module Param = struct
type optionality =
| NotOptional
| Optional
| OptionalWithDefault of string
[@@deriving show, eq]
type info = {
description: string option;
optional: optionality;
}
[@@deriving show, eq]
type path =
| Name
| Element of path
| Member of path * string
[@@deriving show, eq]
type t = (path * info) list [@@deriving show, eq]
end
module Params = struct
type t = (string * Param.t) list [@@deriving show, eq]
end
module Unrecognized_tags = struct
type t = (string * string option) list [@@deriving show, eq]
end
type t = {
description: string option;
params: Params.t;
deprecated: string option;
unrecognized_tags: Unrecognized_tags.t;
}
(*************)
(* accessors *)
(*************)
let description { description; _ } = description
let params { params; _ } = params
let deprecated { deprecated; _ } = deprecated
let unrecognized_tags { unrecognized_tags; _ } = unrecognized_tags
(***********)
(* parsing *)
(***********)
module Parser = struct
regexps copied from Flow_lexer since sedlex does n't let us import them
let whitespace =
[%sedlex.regexp?
( 0x0009 | 0x000B | 0x000C | 0x0020 | 0x00A0 | 0xfeff | 0x1680
| 0x2000 .. 0x200a
| 0x202f | 0x205f | 0x3000 )]
let line_terminator_sequence = [%sedlex.regexp? '\n' | '\r' | "\r\n" | 0x2028 | 0x2029]
let identifier = [%sedlex.regexp? Plus (Compl (white_space | '[' | '.' | ']' | '=' | '{'))]
(* Helpers *)
let empty = { description = None; params = []; deprecated = None; unrecognized_tags = [] }
let trimmed_string_of_buffer buffer = buffer |> Buffer.contents |> String.trim
let description_of_desc_buf desc_buf =
match trimmed_string_of_buffer desc_buf with
| "" -> None
| s -> Some s
(* like Base.List.Assoc.add, but maintains ordering differently:
* - if k is already in the list, keeps it in that position and updates the value
* - if k isn't in the list, adds it to the end *)
let rec add_assoc ~equal k v = function
| [] -> [(k, v)]
| (k', v') :: xs ->
if equal k' k then
(k, v) :: xs
else
(k', v') :: add_assoc ~equal k v xs
let add_param jsdoc name path description optional =
let old_param_infos =
match Base.List.Assoc.find ~equal:String.equal jsdoc.params name with
| None -> []
| Some param_infos -> param_infos
in
let new_param_infos =
add_assoc ~equal:Param.equal_path path { Param.description; optional } old_param_infos
in
{ jsdoc with params = add_assoc ~equal:String.equal name new_param_infos jsdoc.params }
let add_unrecognized_tag jsdoc name description =
let { unrecognized_tags; _ } = jsdoc in
{ jsdoc with unrecognized_tags = unrecognized_tags @ [(name, description)] }
(* Parsing functions *)
` description ` , ` description_or_tag ` , and ` description_startline ` are
helpers for parsing descriptions : a description is a possibly - multiline
string terminated by EOF or a new tag . The beginning of each line could
contain whitespace and asterisks , which are stripped out when parsing .
`description`, `description_or_tag`, and `description_startline` are
helpers for parsing descriptions: a description is a possibly-multiline
string terminated by EOF or a new tag. The beginning of each line could
contain whitespace and asterisks, which are stripped out when parsing.
*)
let rec description desc_buf lexbuf =
match%sedlex lexbuf with
| line_terminator_sequence ->
Buffer.add_string desc_buf (Sedlexing.Utf8.lexeme lexbuf);
description_startline desc_buf lexbuf
| any ->
Buffer.add_string desc_buf (Sedlexing.Utf8.lexeme lexbuf);
description desc_buf lexbuf
eof
and description_or_tag desc_buf lexbuf =
match%sedlex lexbuf with
| '@' -> description_of_desc_buf desc_buf
| _ -> description desc_buf lexbuf
and description_startline desc_buf lexbuf =
match%sedlex lexbuf with
| '*'
| whitespace ->
description_startline desc_buf lexbuf
| _ -> description_or_tag desc_buf lexbuf
let rec param_path ?(path = Param.Name) lexbuf =
match%sedlex lexbuf with
| "[]" -> param_path ~path:(Param.Element path) lexbuf
| ('.', identifier) ->
let member = Sedlexing.Utf8.sub_lexeme lexbuf 1 (Sedlexing.lexeme_length lexbuf - 1) in
param_path ~path:(Param.Member (path, member)) lexbuf
| _ -> path
let rec skip_tag jsdoc lexbuf =
match%sedlex lexbuf with
| Plus (Compl '@') -> skip_tag jsdoc lexbuf
| '@' -> tag jsdoc lexbuf
eof
and param_tag_description jsdoc name path optional lexbuf =
let desc_buf = Buffer.create 127 in
let description = description desc_buf lexbuf in
let jsdoc = add_param jsdoc name path description optional in
tag jsdoc lexbuf
and param_tag_pre_description jsdoc name path optional lexbuf =
match%sedlex lexbuf with
| ' ' -> param_tag_pre_description jsdoc name path optional lexbuf
| '-' -> param_tag_description jsdoc name path optional lexbuf
| _ -> param_tag_description jsdoc name path optional lexbuf
and param_tag_optional_default jsdoc name path def_buf lexbuf =
match%sedlex lexbuf with
| ']' ->
let default = Buffer.contents def_buf in
param_tag_pre_description jsdoc name path (Param.OptionalWithDefault default) lexbuf
| Plus (Compl ']') ->
Buffer.add_string def_buf (Sedlexing.Utf8.lexeme lexbuf);
param_tag_optional_default jsdoc name path def_buf lexbuf
| _ ->
let default = Buffer.contents def_buf in
param_tag_pre_description jsdoc name path (Param.OptionalWithDefault default) lexbuf
and param_tag_optional jsdoc lexbuf =
match%sedlex lexbuf with
| identifier ->
let name = Sedlexing.Utf8.lexeme lexbuf in
let path = param_path lexbuf in
(match%sedlex lexbuf with
| ']' -> param_tag_pre_description jsdoc name path Param.Optional lexbuf
| '=' ->
let def_buf = Buffer.create 127 in
param_tag_optional_default jsdoc name path def_buf lexbuf
| _ -> param_tag_pre_description jsdoc name path Param.Optional lexbuf)
| _ -> skip_tag jsdoc lexbuf
(* ignore jsdoc type annotation *)
and param_tag_type jsdoc lexbuf =
match%sedlex lexbuf with
| '}' -> param_tag jsdoc lexbuf
| Plus (Compl '}') -> param_tag_type jsdoc lexbuf
eof
and param_tag jsdoc lexbuf =
match%sedlex lexbuf with
| ' ' -> param_tag jsdoc lexbuf
| '{' -> param_tag_type jsdoc lexbuf
| '[' -> param_tag_optional jsdoc lexbuf
| identifier ->
let name = Sedlexing.Utf8.lexeme lexbuf in
let path = param_path lexbuf in
param_tag_pre_description jsdoc name path Param.NotOptional lexbuf
| _ -> skip_tag jsdoc lexbuf
and description_tag jsdoc lexbuf =
let desc_buf = Buffer.create 127 in
let description = description desc_buf lexbuf in
let jsdoc = { jsdoc with description } in
tag jsdoc lexbuf
and deprecated_tag jsdoc lexbuf =
let deprecated_tag_buf = Buffer.create 127 in
let deprecated = Some (Base.Option.value ~default:"" (description deprecated_tag_buf lexbuf)) in
{ jsdoc with deprecated }
and unrecognized_tag jsdoc name lexbuf =
let desc_buf = Buffer.create 127 in
let description = description desc_buf lexbuf in
let jsdoc = add_unrecognized_tag jsdoc name description in
tag jsdoc lexbuf
and tag jsdoc lexbuf =
match%sedlex lexbuf with
| "param"
| "arg"
| "argument" ->
param_tag jsdoc lexbuf
| "description"
| "desc" ->
description_tag jsdoc lexbuf
| "deprecated" -> deprecated_tag jsdoc lexbuf
| identifier ->
let name = Sedlexing.Utf8.lexeme lexbuf in
unrecognized_tag jsdoc name lexbuf
| _ -> skip_tag jsdoc lexbuf
let initial lexbuf =
match%sedlex lexbuf with
| ('*', Compl '*') ->
Sedlexing.rollback lexbuf;
let desc_buf = Buffer.create 127 in
let description = description_startline desc_buf lexbuf in
let jsdoc = { empty with description } in
Some (tag jsdoc lexbuf)
| _ -> None
end
let parse str =
let lexbuf = Sedlexing.Utf8.from_string str in
Parser.initial lexbuf
(* find and parse the last jsdoc-containing comment in the list if exists *)
let of_comments =
let open Flow_ast in
let of_comment = function
| (_, Comment.{ kind = Block; text; _ }) -> parse text
| (_, Comment.{ kind = Line; _ }) -> None
in
let rec of_comment_list = function
| [] -> None
| c :: cs ->
(match of_comment_list cs with
| Some _ as j -> j
| None -> of_comment c)
in
let of_syntax Syntax.{ leading; _ } = of_comment_list leading in
Base.Option.bind ~f:of_syntax
| null | https://raw.githubusercontent.com/facebook/flow/cb708a0b1328441991c4ae1319a031196ce6ae1a/src/parser/jsdoc.ml | ocaml | ***********
accessors
***********
*********
parsing
*********
Helpers
like Base.List.Assoc.add, but maintains ordering differently:
* - if k is already in the list, keeps it in that position and updates the value
* - if k isn't in the list, adds it to the end
Parsing functions
ignore jsdoc type annotation
find and parse the last jsdoc-containing comment in the list if exists |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module Sedlexing = Flow_sedlexing
module Param = struct
type optionality =
| NotOptional
| Optional
| OptionalWithDefault of string
[@@deriving show, eq]
type info = {
description: string option;
optional: optionality;
}
[@@deriving show, eq]
type path =
| Name
| Element of path
| Member of path * string
[@@deriving show, eq]
type t = (path * info) list [@@deriving show, eq]
end
module Params = struct
type t = (string * Param.t) list [@@deriving show, eq]
end
module Unrecognized_tags = struct
type t = (string * string option) list [@@deriving show, eq]
end
type t = {
description: string option;
params: Params.t;
deprecated: string option;
unrecognized_tags: Unrecognized_tags.t;
}
let description { description; _ } = description
let params { params; _ } = params
let deprecated { deprecated; _ } = deprecated
let unrecognized_tags { unrecognized_tags; _ } = unrecognized_tags
module Parser = struct
regexps copied from Flow_lexer since sedlex does n't let us import them
let whitespace =
[%sedlex.regexp?
( 0x0009 | 0x000B | 0x000C | 0x0020 | 0x00A0 | 0xfeff | 0x1680
| 0x2000 .. 0x200a
| 0x202f | 0x205f | 0x3000 )]
let line_terminator_sequence = [%sedlex.regexp? '\n' | '\r' | "\r\n" | 0x2028 | 0x2029]
let identifier = [%sedlex.regexp? Plus (Compl (white_space | '[' | '.' | ']' | '=' | '{'))]
let empty = { description = None; params = []; deprecated = None; unrecognized_tags = [] }
let trimmed_string_of_buffer buffer = buffer |> Buffer.contents |> String.trim
let description_of_desc_buf desc_buf =
match trimmed_string_of_buffer desc_buf with
| "" -> None
| s -> Some s
let rec add_assoc ~equal k v = function
| [] -> [(k, v)]
| (k', v') :: xs ->
if equal k' k then
(k, v) :: xs
else
(k', v') :: add_assoc ~equal k v xs
let add_param jsdoc name path description optional =
let old_param_infos =
match Base.List.Assoc.find ~equal:String.equal jsdoc.params name with
| None -> []
| Some param_infos -> param_infos
in
let new_param_infos =
add_assoc ~equal:Param.equal_path path { Param.description; optional } old_param_infos
in
{ jsdoc with params = add_assoc ~equal:String.equal name new_param_infos jsdoc.params }
let add_unrecognized_tag jsdoc name description =
let { unrecognized_tags; _ } = jsdoc in
{ jsdoc with unrecognized_tags = unrecognized_tags @ [(name, description)] }
` description ` , ` description_or_tag ` , and ` description_startline ` are
helpers for parsing descriptions : a description is a possibly - multiline
string terminated by EOF or a new tag . The beginning of each line could
contain whitespace and asterisks , which are stripped out when parsing .
`description`, `description_or_tag`, and `description_startline` are
helpers for parsing descriptions: a description is a possibly-multiline
string terminated by EOF or a new tag. The beginning of each line could
contain whitespace and asterisks, which are stripped out when parsing.
*)
let rec description desc_buf lexbuf =
match%sedlex lexbuf with
| line_terminator_sequence ->
Buffer.add_string desc_buf (Sedlexing.Utf8.lexeme lexbuf);
description_startline desc_buf lexbuf
| any ->
Buffer.add_string desc_buf (Sedlexing.Utf8.lexeme lexbuf);
description desc_buf lexbuf
eof
and description_or_tag desc_buf lexbuf =
match%sedlex lexbuf with
| '@' -> description_of_desc_buf desc_buf
| _ -> description desc_buf lexbuf
and description_startline desc_buf lexbuf =
match%sedlex lexbuf with
| '*'
| whitespace ->
description_startline desc_buf lexbuf
| _ -> description_or_tag desc_buf lexbuf
let rec param_path ?(path = Param.Name) lexbuf =
match%sedlex lexbuf with
| "[]" -> param_path ~path:(Param.Element path) lexbuf
| ('.', identifier) ->
let member = Sedlexing.Utf8.sub_lexeme lexbuf 1 (Sedlexing.lexeme_length lexbuf - 1) in
param_path ~path:(Param.Member (path, member)) lexbuf
| _ -> path
let rec skip_tag jsdoc lexbuf =
match%sedlex lexbuf with
| Plus (Compl '@') -> skip_tag jsdoc lexbuf
| '@' -> tag jsdoc lexbuf
eof
and param_tag_description jsdoc name path optional lexbuf =
let desc_buf = Buffer.create 127 in
let description = description desc_buf lexbuf in
let jsdoc = add_param jsdoc name path description optional in
tag jsdoc lexbuf
and param_tag_pre_description jsdoc name path optional lexbuf =
match%sedlex lexbuf with
| ' ' -> param_tag_pre_description jsdoc name path optional lexbuf
| '-' -> param_tag_description jsdoc name path optional lexbuf
| _ -> param_tag_description jsdoc name path optional lexbuf
and param_tag_optional_default jsdoc name path def_buf lexbuf =
match%sedlex lexbuf with
| ']' ->
let default = Buffer.contents def_buf in
param_tag_pre_description jsdoc name path (Param.OptionalWithDefault default) lexbuf
| Plus (Compl ']') ->
Buffer.add_string def_buf (Sedlexing.Utf8.lexeme lexbuf);
param_tag_optional_default jsdoc name path def_buf lexbuf
| _ ->
let default = Buffer.contents def_buf in
param_tag_pre_description jsdoc name path (Param.OptionalWithDefault default) lexbuf
and param_tag_optional jsdoc lexbuf =
match%sedlex lexbuf with
| identifier ->
let name = Sedlexing.Utf8.lexeme lexbuf in
let path = param_path lexbuf in
(match%sedlex lexbuf with
| ']' -> param_tag_pre_description jsdoc name path Param.Optional lexbuf
| '=' ->
let def_buf = Buffer.create 127 in
param_tag_optional_default jsdoc name path def_buf lexbuf
| _ -> param_tag_pre_description jsdoc name path Param.Optional lexbuf)
| _ -> skip_tag jsdoc lexbuf
and param_tag_type jsdoc lexbuf =
match%sedlex lexbuf with
| '}' -> param_tag jsdoc lexbuf
| Plus (Compl '}') -> param_tag_type jsdoc lexbuf
eof
and param_tag jsdoc lexbuf =
match%sedlex lexbuf with
| ' ' -> param_tag jsdoc lexbuf
| '{' -> param_tag_type jsdoc lexbuf
| '[' -> param_tag_optional jsdoc lexbuf
| identifier ->
let name = Sedlexing.Utf8.lexeme lexbuf in
let path = param_path lexbuf in
param_tag_pre_description jsdoc name path Param.NotOptional lexbuf
| _ -> skip_tag jsdoc lexbuf
and description_tag jsdoc lexbuf =
let desc_buf = Buffer.create 127 in
let description = description desc_buf lexbuf in
let jsdoc = { jsdoc with description } in
tag jsdoc lexbuf
and deprecated_tag jsdoc lexbuf =
let deprecated_tag_buf = Buffer.create 127 in
let deprecated = Some (Base.Option.value ~default:"" (description deprecated_tag_buf lexbuf)) in
{ jsdoc with deprecated }
and unrecognized_tag jsdoc name lexbuf =
let desc_buf = Buffer.create 127 in
let description = description desc_buf lexbuf in
let jsdoc = add_unrecognized_tag jsdoc name description in
tag jsdoc lexbuf
and tag jsdoc lexbuf =
match%sedlex lexbuf with
| "param"
| "arg"
| "argument" ->
param_tag jsdoc lexbuf
| "description"
| "desc" ->
description_tag jsdoc lexbuf
| "deprecated" -> deprecated_tag jsdoc lexbuf
| identifier ->
let name = Sedlexing.Utf8.lexeme lexbuf in
unrecognized_tag jsdoc name lexbuf
| _ -> skip_tag jsdoc lexbuf
let initial lexbuf =
match%sedlex lexbuf with
| ('*', Compl '*') ->
Sedlexing.rollback lexbuf;
let desc_buf = Buffer.create 127 in
let description = description_startline desc_buf lexbuf in
let jsdoc = { empty with description } in
Some (tag jsdoc lexbuf)
| _ -> None
end
let parse str =
let lexbuf = Sedlexing.Utf8.from_string str in
Parser.initial lexbuf
let of_comments =
let open Flow_ast in
let of_comment = function
| (_, Comment.{ kind = Block; text; _ }) -> parse text
| (_, Comment.{ kind = Line; _ }) -> None
in
let rec of_comment_list = function
| [] -> None
| c :: cs ->
(match of_comment_list cs with
| Some _ as j -> j
| None -> of_comment c)
in
let of_syntax Syntax.{ leading; _ } = of_comment_list leading in
Base.Option.bind ~f:of_syntax
|
a834bb0b27f1172bb9a0a45d508b56df1bb01177cac8e14cc12bf275dfdce5dc | Feldspar/feldspar-language | UntypedRepresentation.hs | {-# LANGUAGE DeriveLift #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TypeFamilies #
# LANGUAGE RecordWildCards #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE StandaloneDeriving #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -Wall #
-- Names shadow in this module, not a big deal.
{-# OPTIONS_GHC -Wno-name-shadowing #-}
-- FIXME: Partial functions.
# OPTIONS_GHC -Wno - incomplete - patterns #
-- Unknown severity.
# OPTIONS_GHC -Wno - type - defaults #
--
Copyright ( c ) 2019 , ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
* Neither the name of the ERICSSON AB nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY ,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
module Feldspar.Core.UntypedRepresentation (
VarId (..)
, Term(..)
, UntypedFeld
, UntypedFeldF(..)
, Op(..)
, ScalarType(..)
, Type(..)
, Lit(..)
, Var(..)
, AddressSpace(..)
, Size(..)
, Signedness(..)
, Fork(..)
, HasType(..)
, getAnnotation
, dropAnnotation
, sizeWidth
, fv
, collectLetBinders
, collectBinders
, mkLets
, mkLam
, mkApp
, mkTup
, subst
, stringTree
, stringTreeExp
, indexType
, sharable
, legalToShare
, goodToShare
, legalToInline
, Rename
, rename
, newVar
)
where
import Control.Monad.State hiding (join)
import qualified Data.Map.Strict as M
import qualified Data.ByteString.Char8 as B
import Data.Function (on)
import Data.List (nubBy, intercalate)
import Data.Tree
import Language.Haskell.TH.Syntax (Lift(..))
import Feldspar.Compiler.Options (Pretty(..))
import Feldspar.Core.Representation (VarId(..))
import Feldspar.Range (Range(..), singletonRange)
import Feldspar.Core.Types (Length)
This file contains the UntypedFeld format and associated
-- helper-formats and -functions that work on those formats, for
example fv and .
--
The format resembles the structure of the typed Syntactic format ,
-- but it does not reflect into the host language type system.
-- | Types representing an annotated term
type UntypedFeld a = Term a UntypedFeldF
data Term a f = In a (f (Term a f))
deriving instance (Eq a, Eq (f (Term a f))) => Eq (Term a f)
instance (Show (f (Term a f))) => Show (Term a f) where
show (In _ f) = show f
instance Pretty a => Pretty (UntypedFeld a) where
pretty = prettyExp pretty
| Extract the annotation part of an UntypedFeld
getAnnotation :: UntypedFeld a -> a
getAnnotation (In r _) = r
| Drop the annotation part of an UntypedFeld
dropAnnotation :: UntypedFeld a -> UntypedFeldF (UntypedFeld a)
dropAnnotation (In _ e) = e
-- | Indication of where an object is sored
data AddressSpace = Local | Global
deriving (Eq,Show,Enum,Lift)
data Size = S8 | S16 | S32 | S40 | S64
Used by SICS .
deriving (Eq,Show,Enum,Ord,Lift)
| Returns the number of bits in a
sizeWidth :: Size -> Int
sizeWidth S8 = 8
sizeWidth S16 = 16
sizeWidth S32 = 32
sizeWidth S40 = 40
sizeWidth S64 = 64
sizeWidth S128 = 128
data Signedness = Signed | Unsigned
deriving (Eq,Show,Enum,Lift)
data Fork = None | Future | Par | Loop
deriving (Eq,Show)
data ScalarType =
BoolType
| IntType Signedness Size
| FloatType
| DoubleType
| ComplexType Type
deriving (Eq,Show)
data Type =
Length :# ScalarType
| StringType
| TupType [Type]
| MutType Type
| RefType Type
| ArrayType (Range Length) Type
| MArrType (Range Length) Type
| ParType Type
| ElementsType Type
| IVarType Type
| FunType Type Type
| FValType Type
deriving (Eq,Show)
data Var = Var { varNum :: VarId
, varType :: Type
, varName :: B.ByteString
}
-- Variables are equal if they have the same varNum.
instance Eq Var where
v1 == v2 = varNum v1 == varNum v2
instance Ord Var where
compare v1 v2 = compare (varNum v1) (varNum v2)
instance Show Var where
show (Var n _t name) = (if name == B.empty
then "v"
else B.unpack name) ++ show n
data Lit =
LBool Bool
| LInt Signedness Size Integer
| LFloat Float
| LDouble Double
| LComplex Lit Lit
| LString String -- String value including quotes if required.
| LArray Type [Lit] -- Type necessary for empty array literals.
| LTup [Lit]
deriving (Eq)
-- | The Type used to represent indexes, to which Index is mapped.
indexType :: Type
indexType = 1 :# IntType Unsigned S32
-- | Human readable show instance.
instance Show Lit where
show (LBool b) = show b
show (LInt _ _ i) = show i
show (LFloat f) = show f
show (LDouble d) = show d
show (LComplex r c) = "(" ++ show r ++ ", " ++ show c ++ "i)"
show (LString s) = s
show (LArray _ ls) = "[" ++ sls ++ "]"
where sls = intercalate "," $ map show ls
show (LTup ls) = "(" ++ intercalate ", " (map show ls) ++ ")"
-- | Application heads.
data Op =
-- Array
GetLength
| Parallel
| Append
| GetIx
| SetLength
| Sequential
| SetIx
-- Binding
| Let
-- Bits
| Bit
| Complement
| ReverseBits
| BitScan
| BitCount
| BAnd
| BOr
| BXor
| SetBit
| ClearBit
| ComplementBit
| TestBit
| ShiftLU
| ShiftRU
| ShiftL
| ShiftR
| RotateLU
| RotateRU
| RotateL
| RotateR
Complex
| RealPart
| ImagPart
| Conjugate
| Magnitude
| Phase
| Cis
| MkComplex
| MkPolar
-- Condition
| Condition
| ConditionM
-- Conversion
| F2I
| I2N
| B2I
| Round
| Ceiling
| Floor
-- Elements
| ESkip
| EMaterialize
| EWrite
| EPar
| EparFor
-- Eq
| Equal
| NotEqual
-- Error
| Undefined
| Assert String
FFI
| ForeignImport String
-- Floating
| Exp
| Sqrt
| Log
| Sin
| Tan
| Cos
| Asin
| Atan
| Acos
| Sinh
| Tanh
| Cosh
| Asinh
| Atanh
| Acosh
| Pow
| LogBase
-- Floating
| Pi
-- Fractional
| DivFrac
-- Future
| MkFuture
| Await
-- Integral
| Quot
| Rem
| Div
| Mod
| IExp
Logic
| Not
Logic
| And
| Or
-- Loop
| ForLoop
| WhileLoop
LoopM
| While
| For
-- Mutable
| Run
| Return
| Bind
| Then
| When
MutableArray
| NewArr_
| ArrLength
| NewArr
| GetArr
| SetArr
MutableToPure
| RunMutableArray
| WithArray
MutableReference
| NewRef
| GetRef
| SetRef
| ModRef
Noinline
| NoInline
-- Num
| Abs
| Sign
| Add
| Sub
| Mul
Par
| ParRun
| ParGet
| ParFork
| ParNew
| ParYield
| ParPut
-- Ord
| LTH
| GTH
| LTE
| GTE
| Min
| Max
RealFloat
| Atan2
-- Save
| Save
SizeProp
| PropSize
SourceInfo
| SourceInfo String
Switch
| Switch
Tuples
| Tup
These are zero indexed .
| Drop Int
-- Common nodes
| Call Fork String
deriving (Eq, Show)
-- | The main type: Variables, Bindings, Literals and Applications.
data UntypedFeldF e =
-- Binding
Variable Var
| Lambda Var e
| LetFun (String, Fork, e) e -- Note [Function bindings]
-- Literal
| Literal Lit
-- Common nodes
| App Op Type [e]
deriving (Eq)
Function bindings
-----------------
The LetFun constructor is different from the ordinary let - bindings ,
and therefore has its own node type . In an ordinary language the
constructor would be called LetRec , but we do not have any
recursion . Functions are created by the createTasks pass , and they can
be run sequentially or concurrently depending on the " Fork " .
Function bindings
-----------------
The LetFun constructor is different from the ordinary let-bindings,
and therefore has its own node type. In an ordinary language the
constructor would be called LetRec, but we do not have any
recursion. Functions are created by the createTasks pass, and they can
be run sequentially or concurrently depending on the "Fork".
-}
instance (Show e) => Show (UntypedFeldF e) where
show (Variable v) = show v
show (Lambda v e) = "(\\" ++ show v ++ " -> " ++ show e ++ ")"
show (LetFun (s, k, e1) e2) = "letFun " ++ show k ++ " " ++ s ++" = "++ show e1 ++ " in " ++ show e2
show (Literal l) = show l
show (App p@RunMutableArray _ [e]) = show p ++ " (" ++ show e ++ ")"
show (App GetIx _ [e1,e2]) = "(" ++ show e1 ++ " ! " ++ show e2 ++ ")"
show (App Add _ [e1,e2]) = "(" ++ show e1 ++ " + " ++ show e2 ++ ")"
show (App Sub _ [e1,e2]) = "(" ++ show e1 ++ " - " ++ show e2 ++ ")"
show (App Mul _ [e1,e2]) = "(" ++ show e1 ++ " * " ++ show e2 ++ ")"
show (App Div _ [e1,e2]) = "(" ++ show e1 ++ " / " ++ show e2 ++ ")"
show (App p@Then _ [e1, e2]) = show p ++ " (" ++ show e1 ++ ") (" ++
show e2 ++ ")"
show (App p _ [e1, e2])
| p `elem` [Bind, Let, EPar] = show p ++ " (" ++ show e1 ++ ") " ++ show e2
show (App (ForeignImport s) _ es)= s ++ " " ++ unwords (map show es)
show (App Tup _ es) = "(" ++ intercalate ", " (map show es) ++ ")"
show (App p@Parallel _ [e1,e2]) = show p ++ " (" ++ show e1 ++ ") " ++ show e2
show (App p@Sequential _ [e1,e2,e3]) = show p ++ " (" ++ show e1 ++ ") (" ++ show e2 ++ ") " ++ show e3
show (App p t es)
| p `elem` [F2I, I2N, B2I, Round, Ceiling, Floor]
= show p ++ "{" ++ show t ++ "} " ++ unwords (map show es)
show (App p _ es) = show p ++ " " ++ unwords (map show es)
-- | Compute a compact text representation of a scalar type
prTypeST :: ScalarType -> String
prTypeST BoolType = "bool"
prTypeST (IntType s sz) = prS s ++ prSz sz
where prS Signed = "i"
prS Unsigned = "u"
prSz s = drop 1 $ show s
prTypeST FloatType = "f32"
prTypeST DoubleType = "f64"
prTypeST (ComplexType t) = "c" ++ prType t
-- | Compute a compact text representation of a type
prType :: Type -> String
prType (n :# t) = show n ++ 'x':prTypeST t
prType (TupType ts) = "(" ++ intercalate "," (map prType ts) ++ ")"
prType (MutType t) = "M" ++ prType t
prType (RefType t) = "R" ++ prType t
prType (ArrayType r t) = "a" ++ prASize r ++ prType t
prType (MArrType _ t) = "A" ++ prType t
prType (ParType t) = "P" ++ prType t
prType (ElementsType t) = "e" ++ prType t
prType (IVarType t) = "V" ++ prType t
prType (FunType t1 t2) = "(" ++ prType t1 ++ "->" ++ prType t2 ++ ")"
prType (FValType t) = "F" ++ prType t
-- | Print an array size
prASize :: Range Length -> String
prASize r = "[" ++ go r ++ "]"
where go (Range l h) = show l ++ ":" ++ show h
| Convert an untyped unannotated syntax tree into a @Tree@ of @String@s
stringTree :: UntypedFeld a -> Tree String
stringTree = stringTreeExp (const "")
| Convert an untyped annotated syntax tree into a @Tree@ of @String@s
stringTreeExp :: (a -> String) -> UntypedFeld a -> Tree String
stringTreeExp prA = go
where
go (In r (Variable v)) = Node (show v ++ prC (typeof v) ++ prA r) []
go (In _ (Lambda v e)) = Node ("Lambda "++show v ++ prC (typeof v)) [go e]
go (In _ (LetFun (s,k,e1) e2)) = Node (unwords ["LetFun", show k, s]) [go e1, go e2]
go (In _ (Literal l)) = Node (show l ++ prC (typeof l)) []
go (In r (App Let t es)) = Node "Let" $ goLet $ In r (App Let t es)
go (In r (App p t es)) = Node (show p ++ prP t r) (map go es)
goLet (In _ (App Let _ [eRhs, In _ (Lambda v e)]))
= Node ("Var " ++ show v ++ prC (typeof v) ++ " = ") [go eRhs]
: goLet e
goLet e = [Node "In" [go e]]
prP t r = " {" ++ prType t ++ prA r ++ "}"
prC t = " : " ++ prType t
prettyExp :: (a -> String) -> UntypedFeld a -> String
prettyExp prA e = render (pr 0 0 e)
where pr p i (In r e) = pe p i r e
pe _ i _ (Variable v) = line i $ show v
pe _ i _ (Literal l) = line i $ show l
pe p i _ (Lambda v e) = par p 0 $ join $ line i ("\\ " ++ pv Nothing v ++ " ->") ++ pr 0 (i+2) e
pe p i r (App Let t es) = par p 0 $ line i "let" ++ pLet i (In r $ App Let t es)
pe p i r (App f t es) = par p 10 $ join $ line i (show f ++ prP t r) ++ pArgs p (i+2) es
pe _ i _ (LetFun (s,k,body) e) = line i ("letfun " ++ show k ++ " " ++ s)
++ pr 0 (i+2) body
++ line i "in"
++ pr 0 (i+2) e
pArgs _ _ [] = []
pArgs p i [e@(In _ (Lambda _ _))] = pr p i e
pArgs p i (e:es) = pr 11 i e ++ pArgs p i es
pLet i (In _ (App Let _ [eRhs, In _ (Lambda v e)]))
= join (line (i+2) (pv Nothing v ++ " =") ++ pr 0 (i+4) eRhs) ++ pLet i e
pLet i e = line i "in" ++ pr 0 (i+2) e
pv mr v = show v ++ prC (typeof v) ++ maybe "" ((++) " | " . prA) mr
prP t r = " {" ++ prType t ++ " | " ++ prA r ++ "}"
prC t = " : " ++ prType t
par _ _ [] = error "UntypedRepresentation.prettyExp: parethesisizing empty text"
par p i ls = if p <= i then ls else prepend "(" $ append ")" ls
prepend s ((i,n,v) : ls) = (i, n + length s, s ++ v) : ls
append s [(i,n,v)] = [(i, n + length s, v ++ s)]
append s (l:ls) = l : append s ls
join (x:y:xs)
| indent x <= indent y &&
all ((==) (indent y) . indent) xs &&
l <= 60
= [(indent x, l, unwords $ map val $ x:y:xs)]
where l = sum (map len $ x:y:xs) + length xs + 1
join xs = xs
render = foldr (\ (i,_,cs) str -> replicate i ' ' ++ cs ++ "\n" ++ str) ""
line i cs = [(i, length cs, cs)]
indent (i,_,_) = i
len (_,l,_) = l
val (_,_,v) = v
-- In the precedence argument, 0 means that no expressions need parentesis,
wheras 10 accepts applications and 11 only accepts atoms ( variables and literals )
class HasType a where
type TypeOf a
typeof :: a -> TypeOf a
instance HasType Var where
type TypeOf Var = Type
typeof Var{..} = varType
instance HasType Lit where
type TypeOf Lit = Type
typeof (LInt s n _) = 1 :# IntType s n
typeof LDouble{} = 1 :# DoubleType
typeof LFloat{} = 1 :# FloatType
typeof LBool{} = 1 :# BoolType
typeof LString{} = StringType
typeof (LArray t es) = ArrayType (singletonRange $ fromIntegral $ length es) t
typeof (LComplex r _) = 1 :# ComplexType (typeof r)
typeof (LTup ls) = TupType $ map typeof ls
instance HasType (UntypedFeld a) where
type TypeOf (UntypedFeld a) = Type
-- Binding
typeof (In _ (Variable v)) = typeof v
typeof (In _ (Lambda v e)) = FunType (typeof v) (typeof e)
typeof (In _ (LetFun _ e)) = typeof e
-- Literal
typeof (In _ (Literal l)) = typeof l
typeof (In _ (App _ t _)) = t
-- | Get free variables and their annotations for an UntypedFeld expression
fv :: UntypedFeld a -> [(a, Var)]
fv = nubBy ((==) `on` snd) . fvA' []
-- | Internal helper function for fv
fvA' :: [Var] -> UntypedFeld a -> [(a, Var)]
-- Binding
fvA' vs (In r (Variable v)) | v `elem` vs = []
| otherwise = [(r, v)]
fvA' vs (In _ (Lambda v e)) = fvA' (v:vs) e
fvA' vs (In _ (LetFun (_, _, e1) e2)) = fvA' vs e1 ++ fvA' vs e2
-- Literal
fvA' _ (In _ Literal{}) = []
-- Common nodes.
fvA' vs (In _ (App _ _ es)) = concatMap (fvA' vs) es
-- | Collect nested let binders into the binders and the body.
collectLetBinders :: UntypedFeld a -> ([(Var, UntypedFeld a)], UntypedFeld a)
collectLetBinders = go []
where go acc (In _ (App Let _ [e, In _ (Lambda v b)])) = go ((v, e):acc) b
go acc e = (reverse acc, e)
-- | Collect binders from nested lambda expressions.
collectBinders :: UntypedFeld a -> ([(a, Var)], UntypedFeld a)
collectBinders = go []
where go acc (In a (Lambda v e)) = go ((a,v):acc) e
go acc e = (reverse acc, e)
-- | Inverse of collectLetBinders, put the term back together.
mkLets :: ([(Var, UntypedFeld a)], UntypedFeld a) -> UntypedFeld a
mkLets ([], body) = body
mkLets ((v, e):t, body) = In r (App Let t' [e, body'])
where body' = In r (Lambda v (mkLets (t, body))) -- Value info of result
FunType _ t' = typeof body'
r = getAnnotation body
-- | Inverse of collectBinders, make a lambda abstraction.
mkLam :: [(a, Var)] -> UntypedFeld a -> UntypedFeld a
mkLam [] e = e
mkLam ((a, h):t) e = In a (Lambda h (mkLam t e))
-- | Make an application.
mkApp :: a -> Type -> Op -> [UntypedFeld a] -> UntypedFeld a
mkApp a t p es = In a (App p t es)
-- | Make a tuple; constructs the type from the types of the components
mkTup :: a -> [UntypedFeld a] -> UntypedFeld a
mkTup a es = In a $ App Tup (TupType $ map typeof es) es
| Substitute new for dst in e. Assumes no shadowing .
subst :: UntypedFeld a -> Var -> UntypedFeld a -> UntypedFeld a
subst new dst = go
where go v@(In _ (Variable v')) | dst == v' = new -- Replace.
| otherwise = v -- Stop.
go l@(In r (Lambda v e')) | v == dst = l -- Stop.
| otherwise = In r (Lambda v (go e'))
go (In r (LetFun (s, k, e1) e2))
Recurse .
go l@(In _ Literal{}) = l -- Stop.
Recurse .
-- | Expressions that can and should be shared
sharable :: UntypedFeld a -> Bool
sharable e = legalToShare e && goodToShare e
-- | Expressions that can be shared without breaking fromCore
legalToShare :: UntypedFeld a -> Bool
legalToShare (In _ (App op _ _)) = op `notElem` [ESkip, EWrite, EPar, EparFor,
Return, Bind, Then, When,
NewArr, NewArr_, GetArr, SetArr, ArrLength,
For, While,
NewRef, GetRef, SetRef, ModRef]
legalToShare (In _ (Lambda _ _)) = False
legalToShare _ = True
-- | Expressions that are expensive enough to be worth sharing
goodToShare :: UntypedFeld a -> Bool
goodToShare (In _ (Literal l))
| LArray _ (_:_) <- l = True
| LTup (_:_) <- l = True
goodToShare (In _ App{}) = True
goodToShare _ = False
legalToInline :: UntypedFeld a -> Bool
legalToInline _ = True
type Rename a = State VarId a
rename :: UntypedFeld a -> Rename (UntypedFeld a)
rename = renameA M.empty
type RRExp a = UntypedFeldF (UntypedFeld a)
renameA :: M.Map VarId (RRExp a) -> UntypedFeld a -> Rename (UntypedFeld a)
renameA env (In a r) = do r1 <- renameR env r
return $ In a r1
renameR :: M.Map VarId (RRExp a) -> RRExp a -> Rename (RRExp a)
renameR env (Variable v) = return $ env M.! varNum v
renameR env (App f t es) = do es1 <- mapM (renameA env) es
return $ App f t es1
renameR env (Lambda v e) = do v1 <- newVar v
e1 <- renameA (M.insert (varNum v) (Variable v1) env) e
return $ Lambda v1 e1
renameR _ (Literal l) = return $ Literal l
renameR _ e = error $ "FromTyped.renameR: unexpected expression " ++ show e
newVar :: MonadState VarId m => Var -> m Var
newVar v = do j <- get
put (j+1)
return $ v{varNum = j}
| null | https://raw.githubusercontent.com/Feldspar/feldspar-language/499e4e42d462f436a5267ddf0c2f73d5741a8248/src/Feldspar/Core/UntypedRepresentation.hs | haskell | # LANGUAGE DeriveLift #
# LANGUAGE RankNTypes #
Names shadow in this module, not a big deal.
# OPTIONS_GHC -Wno-name-shadowing #
FIXME: Partial functions.
Unknown severity.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
helper-formats and -functions that work on those formats, for
but it does not reflect into the host language type system.
| Types representing an annotated term
| Indication of where an object is sored
Variables are equal if they have the same varNum.
String value including quotes if required.
Type necessary for empty array literals.
| The Type used to represent indexes, to which Index is mapped.
| Human readable show instance.
| Application heads.
Array
Binding
Bits
Condition
Conversion
Elements
Eq
Error
Floating
Floating
Fractional
Future
Integral
Loop
Mutable
Num
Ord
Save
Common nodes
| The main type: Variables, Bindings, Literals and Applications.
Binding
Note [Function bindings]
Literal
Common nodes
---------------
---------------
| Compute a compact text representation of a scalar type
| Compute a compact text representation of a type
| Print an array size
In the precedence argument, 0 means that no expressions need parentesis,
Binding
Literal
| Get free variables and their annotations for an UntypedFeld expression
| Internal helper function for fv
Binding
Literal
Common nodes.
| Collect nested let binders into the binders and the body.
| Collect binders from nested lambda expressions.
| Inverse of collectLetBinders, put the term back together.
Value info of result
| Inverse of collectBinders, make a lambda abstraction.
| Make an application.
| Make a tuple; constructs the type from the types of the components
Replace.
Stop.
Stop.
Stop.
| Expressions that can and should be shared
| Expressions that can be shared without breaking fromCore
| Expressions that are expensive enough to be worth sharing | # LANGUAGE TypeFamilies #
# LANGUAGE RecordWildCards #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE StandaloneDeriving #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -Wall #
# OPTIONS_GHC -Wno - incomplete - patterns #
# OPTIONS_GHC -Wno - type - defaults #
Copyright ( c ) 2019 , ERICSSON AB
* Neither the name of the ERICSSON AB nor the names of its contributors
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY ,
module Feldspar.Core.UntypedRepresentation (
VarId (..)
, Term(..)
, UntypedFeld
, UntypedFeldF(..)
, Op(..)
, ScalarType(..)
, Type(..)
, Lit(..)
, Var(..)
, AddressSpace(..)
, Size(..)
, Signedness(..)
, Fork(..)
, HasType(..)
, getAnnotation
, dropAnnotation
, sizeWidth
, fv
, collectLetBinders
, collectBinders
, mkLets
, mkLam
, mkApp
, mkTup
, subst
, stringTree
, stringTreeExp
, indexType
, sharable
, legalToShare
, goodToShare
, legalToInline
, Rename
, rename
, newVar
)
where
import Control.Monad.State hiding (join)
import qualified Data.Map.Strict as M
import qualified Data.ByteString.Char8 as B
import Data.Function (on)
import Data.List (nubBy, intercalate)
import Data.Tree
import Language.Haskell.TH.Syntax (Lift(..))
import Feldspar.Compiler.Options (Pretty(..))
import Feldspar.Core.Representation (VarId(..))
import Feldspar.Range (Range(..), singletonRange)
import Feldspar.Core.Types (Length)
This file contains the UntypedFeld format and associated
example fv and .
The format resembles the structure of the typed Syntactic format ,
type UntypedFeld a = Term a UntypedFeldF
data Term a f = In a (f (Term a f))
deriving instance (Eq a, Eq (f (Term a f))) => Eq (Term a f)
instance (Show (f (Term a f))) => Show (Term a f) where
show (In _ f) = show f
instance Pretty a => Pretty (UntypedFeld a) where
pretty = prettyExp pretty
| Extract the annotation part of an UntypedFeld
getAnnotation :: UntypedFeld a -> a
getAnnotation (In r _) = r
| Drop the annotation part of an UntypedFeld
dropAnnotation :: UntypedFeld a -> UntypedFeldF (UntypedFeld a)
dropAnnotation (In _ e) = e
data AddressSpace = Local | Global
deriving (Eq,Show,Enum,Lift)
data Size = S8 | S16 | S32 | S40 | S64
Used by SICS .
deriving (Eq,Show,Enum,Ord,Lift)
| Returns the number of bits in a
sizeWidth :: Size -> Int
sizeWidth S8 = 8
sizeWidth S16 = 16
sizeWidth S32 = 32
sizeWidth S40 = 40
sizeWidth S64 = 64
sizeWidth S128 = 128
data Signedness = Signed | Unsigned
deriving (Eq,Show,Enum,Lift)
data Fork = None | Future | Par | Loop
deriving (Eq,Show)
data ScalarType =
BoolType
| IntType Signedness Size
| FloatType
| DoubleType
| ComplexType Type
deriving (Eq,Show)
data Type =
Length :# ScalarType
| StringType
| TupType [Type]
| MutType Type
| RefType Type
| ArrayType (Range Length) Type
| MArrType (Range Length) Type
| ParType Type
| ElementsType Type
| IVarType Type
| FunType Type Type
| FValType Type
deriving (Eq,Show)
data Var = Var { varNum :: VarId
, varType :: Type
, varName :: B.ByteString
}
instance Eq Var where
v1 == v2 = varNum v1 == varNum v2
instance Ord Var where
compare v1 v2 = compare (varNum v1) (varNum v2)
instance Show Var where
show (Var n _t name) = (if name == B.empty
then "v"
else B.unpack name) ++ show n
data Lit =
LBool Bool
| LInt Signedness Size Integer
| LFloat Float
| LDouble Double
| LComplex Lit Lit
| LTup [Lit]
deriving (Eq)
indexType :: Type
indexType = 1 :# IntType Unsigned S32
instance Show Lit where
show (LBool b) = show b
show (LInt _ _ i) = show i
show (LFloat f) = show f
show (LDouble d) = show d
show (LComplex r c) = "(" ++ show r ++ ", " ++ show c ++ "i)"
show (LString s) = s
show (LArray _ ls) = "[" ++ sls ++ "]"
where sls = intercalate "," $ map show ls
show (LTup ls) = "(" ++ intercalate ", " (map show ls) ++ ")"
data Op =
GetLength
| Parallel
| Append
| GetIx
| SetLength
| Sequential
| SetIx
| Let
| Bit
| Complement
| ReverseBits
| BitScan
| BitCount
| BAnd
| BOr
| BXor
| SetBit
| ClearBit
| ComplementBit
| TestBit
| ShiftLU
| ShiftRU
| ShiftL
| ShiftR
| RotateLU
| RotateRU
| RotateL
| RotateR
Complex
| RealPart
| ImagPart
| Conjugate
| Magnitude
| Phase
| Cis
| MkComplex
| MkPolar
| Condition
| ConditionM
| F2I
| I2N
| B2I
| Round
| Ceiling
| Floor
| ESkip
| EMaterialize
| EWrite
| EPar
| EparFor
| Equal
| NotEqual
| Undefined
| Assert String
FFI
| ForeignImport String
| Exp
| Sqrt
| Log
| Sin
| Tan
| Cos
| Asin
| Atan
| Acos
| Sinh
| Tanh
| Cosh
| Asinh
| Atanh
| Acosh
| Pow
| LogBase
| Pi
| DivFrac
| MkFuture
| Await
| Quot
| Rem
| Div
| Mod
| IExp
Logic
| Not
Logic
| And
| Or
| ForLoop
| WhileLoop
LoopM
| While
| For
| Run
| Return
| Bind
| Then
| When
MutableArray
| NewArr_
| ArrLength
| NewArr
| GetArr
| SetArr
MutableToPure
| RunMutableArray
| WithArray
MutableReference
| NewRef
| GetRef
| SetRef
| ModRef
Noinline
| NoInline
| Abs
| Sign
| Add
| Sub
| Mul
Par
| ParRun
| ParGet
| ParFork
| ParNew
| ParYield
| ParPut
| LTH
| GTH
| LTE
| GTE
| Min
| Max
RealFloat
| Atan2
| Save
SizeProp
| PropSize
SourceInfo
| SourceInfo String
Switch
| Switch
Tuples
| Tup
These are zero indexed .
| Drop Int
| Call Fork String
deriving (Eq, Show)
data UntypedFeldF e =
Variable Var
| Lambda Var e
| Literal Lit
| App Op Type [e]
deriving (Eq)
Function bindings
The LetFun constructor is different from the ordinary let - bindings ,
and therefore has its own node type . In an ordinary language the
constructor would be called LetRec , but we do not have any
recursion . Functions are created by the createTasks pass , and they can
be run sequentially or concurrently depending on the " Fork " .
Function bindings
The LetFun constructor is different from the ordinary let-bindings,
and therefore has its own node type. In an ordinary language the
constructor would be called LetRec, but we do not have any
recursion. Functions are created by the createTasks pass, and they can
be run sequentially or concurrently depending on the "Fork".
-}
instance (Show e) => Show (UntypedFeldF e) where
show (Variable v) = show v
show (Lambda v e) = "(\\" ++ show v ++ " -> " ++ show e ++ ")"
show (LetFun (s, k, e1) e2) = "letFun " ++ show k ++ " " ++ s ++" = "++ show e1 ++ " in " ++ show e2
show (Literal l) = show l
show (App p@RunMutableArray _ [e]) = show p ++ " (" ++ show e ++ ")"
show (App GetIx _ [e1,e2]) = "(" ++ show e1 ++ " ! " ++ show e2 ++ ")"
show (App Add _ [e1,e2]) = "(" ++ show e1 ++ " + " ++ show e2 ++ ")"
show (App Sub _ [e1,e2]) = "(" ++ show e1 ++ " - " ++ show e2 ++ ")"
show (App Mul _ [e1,e2]) = "(" ++ show e1 ++ " * " ++ show e2 ++ ")"
show (App Div _ [e1,e2]) = "(" ++ show e1 ++ " / " ++ show e2 ++ ")"
show (App p@Then _ [e1, e2]) = show p ++ " (" ++ show e1 ++ ") (" ++
show e2 ++ ")"
show (App p _ [e1, e2])
| p `elem` [Bind, Let, EPar] = show p ++ " (" ++ show e1 ++ ") " ++ show e2
show (App (ForeignImport s) _ es)= s ++ " " ++ unwords (map show es)
show (App Tup _ es) = "(" ++ intercalate ", " (map show es) ++ ")"
show (App p@Parallel _ [e1,e2]) = show p ++ " (" ++ show e1 ++ ") " ++ show e2
show (App p@Sequential _ [e1,e2,e3]) = show p ++ " (" ++ show e1 ++ ") (" ++ show e2 ++ ") " ++ show e3
show (App p t es)
| p `elem` [F2I, I2N, B2I, Round, Ceiling, Floor]
= show p ++ "{" ++ show t ++ "} " ++ unwords (map show es)
show (App p _ es) = show p ++ " " ++ unwords (map show es)
prTypeST :: ScalarType -> String
prTypeST BoolType = "bool"
prTypeST (IntType s sz) = prS s ++ prSz sz
where prS Signed = "i"
prS Unsigned = "u"
prSz s = drop 1 $ show s
prTypeST FloatType = "f32"
prTypeST DoubleType = "f64"
prTypeST (ComplexType t) = "c" ++ prType t
prType :: Type -> String
prType (n :# t) = show n ++ 'x':prTypeST t
prType (TupType ts) = "(" ++ intercalate "," (map prType ts) ++ ")"
prType (MutType t) = "M" ++ prType t
prType (RefType t) = "R" ++ prType t
prType (ArrayType r t) = "a" ++ prASize r ++ prType t
prType (MArrType _ t) = "A" ++ prType t
prType (ParType t) = "P" ++ prType t
prType (ElementsType t) = "e" ++ prType t
prType (IVarType t) = "V" ++ prType t
prType (FunType t1 t2) = "(" ++ prType t1 ++ "->" ++ prType t2 ++ ")"
prType (FValType t) = "F" ++ prType t
prASize :: Range Length -> String
prASize r = "[" ++ go r ++ "]"
where go (Range l h) = show l ++ ":" ++ show h
| Convert an untyped unannotated syntax tree into a @Tree@ of @String@s
stringTree :: UntypedFeld a -> Tree String
stringTree = stringTreeExp (const "")
| Convert an untyped annotated syntax tree into a @Tree@ of @String@s
stringTreeExp :: (a -> String) -> UntypedFeld a -> Tree String
stringTreeExp prA = go
where
go (In r (Variable v)) = Node (show v ++ prC (typeof v) ++ prA r) []
go (In _ (Lambda v e)) = Node ("Lambda "++show v ++ prC (typeof v)) [go e]
go (In _ (LetFun (s,k,e1) e2)) = Node (unwords ["LetFun", show k, s]) [go e1, go e2]
go (In _ (Literal l)) = Node (show l ++ prC (typeof l)) []
go (In r (App Let t es)) = Node "Let" $ goLet $ In r (App Let t es)
go (In r (App p t es)) = Node (show p ++ prP t r) (map go es)
goLet (In _ (App Let _ [eRhs, In _ (Lambda v e)]))
= Node ("Var " ++ show v ++ prC (typeof v) ++ " = ") [go eRhs]
: goLet e
goLet e = [Node "In" [go e]]
prP t r = " {" ++ prType t ++ prA r ++ "}"
prC t = " : " ++ prType t
prettyExp :: (a -> String) -> UntypedFeld a -> String
prettyExp prA e = render (pr 0 0 e)
where pr p i (In r e) = pe p i r e
pe _ i _ (Variable v) = line i $ show v
pe _ i _ (Literal l) = line i $ show l
pe p i _ (Lambda v e) = par p 0 $ join $ line i ("\\ " ++ pv Nothing v ++ " ->") ++ pr 0 (i+2) e
pe p i r (App Let t es) = par p 0 $ line i "let" ++ pLet i (In r $ App Let t es)
pe p i r (App f t es) = par p 10 $ join $ line i (show f ++ prP t r) ++ pArgs p (i+2) es
pe _ i _ (LetFun (s,k,body) e) = line i ("letfun " ++ show k ++ " " ++ s)
++ pr 0 (i+2) body
++ line i "in"
++ pr 0 (i+2) e
pArgs _ _ [] = []
pArgs p i [e@(In _ (Lambda _ _))] = pr p i e
pArgs p i (e:es) = pr 11 i e ++ pArgs p i es
pLet i (In _ (App Let _ [eRhs, In _ (Lambda v e)]))
= join (line (i+2) (pv Nothing v ++ " =") ++ pr 0 (i+4) eRhs) ++ pLet i e
pLet i e = line i "in" ++ pr 0 (i+2) e
pv mr v = show v ++ prC (typeof v) ++ maybe "" ((++) " | " . prA) mr
prP t r = " {" ++ prType t ++ " | " ++ prA r ++ "}"
prC t = " : " ++ prType t
par _ _ [] = error "UntypedRepresentation.prettyExp: parethesisizing empty text"
par p i ls = if p <= i then ls else prepend "(" $ append ")" ls
prepend s ((i,n,v) : ls) = (i, n + length s, s ++ v) : ls
append s [(i,n,v)] = [(i, n + length s, v ++ s)]
append s (l:ls) = l : append s ls
join (x:y:xs)
| indent x <= indent y &&
all ((==) (indent y) . indent) xs &&
l <= 60
= [(indent x, l, unwords $ map val $ x:y:xs)]
where l = sum (map len $ x:y:xs) + length xs + 1
join xs = xs
render = foldr (\ (i,_,cs) str -> replicate i ' ' ++ cs ++ "\n" ++ str) ""
line i cs = [(i, length cs, cs)]
indent (i,_,_) = i
len (_,l,_) = l
val (_,_,v) = v
wheras 10 accepts applications and 11 only accepts atoms ( variables and literals )
class HasType a where
type TypeOf a
typeof :: a -> TypeOf a
instance HasType Var where
type TypeOf Var = Type
typeof Var{..} = varType
instance HasType Lit where
type TypeOf Lit = Type
typeof (LInt s n _) = 1 :# IntType s n
typeof LDouble{} = 1 :# DoubleType
typeof LFloat{} = 1 :# FloatType
typeof LBool{} = 1 :# BoolType
typeof LString{} = StringType
typeof (LArray t es) = ArrayType (singletonRange $ fromIntegral $ length es) t
typeof (LComplex r _) = 1 :# ComplexType (typeof r)
typeof (LTup ls) = TupType $ map typeof ls
instance HasType (UntypedFeld a) where
type TypeOf (UntypedFeld a) = Type
typeof (In _ (Variable v)) = typeof v
typeof (In _ (Lambda v e)) = FunType (typeof v) (typeof e)
typeof (In _ (LetFun _ e)) = typeof e
typeof (In _ (Literal l)) = typeof l
typeof (In _ (App _ t _)) = t
fv :: UntypedFeld a -> [(a, Var)]
fv = nubBy ((==) `on` snd) . fvA' []
fvA' :: [Var] -> UntypedFeld a -> [(a, Var)]
fvA' vs (In r (Variable v)) | v `elem` vs = []
| otherwise = [(r, v)]
fvA' vs (In _ (Lambda v e)) = fvA' (v:vs) e
fvA' vs (In _ (LetFun (_, _, e1) e2)) = fvA' vs e1 ++ fvA' vs e2
fvA' _ (In _ Literal{}) = []
fvA' vs (In _ (App _ _ es)) = concatMap (fvA' vs) es
collectLetBinders :: UntypedFeld a -> ([(Var, UntypedFeld a)], UntypedFeld a)
collectLetBinders = go []
where go acc (In _ (App Let _ [e, In _ (Lambda v b)])) = go ((v, e):acc) b
go acc e = (reverse acc, e)
collectBinders :: UntypedFeld a -> ([(a, Var)], UntypedFeld a)
collectBinders = go []
where go acc (In a (Lambda v e)) = go ((a,v):acc) e
go acc e = (reverse acc, e)
mkLets :: ([(Var, UntypedFeld a)], UntypedFeld a) -> UntypedFeld a
mkLets ([], body) = body
mkLets ((v, e):t, body) = In r (App Let t' [e, body'])
FunType _ t' = typeof body'
r = getAnnotation body
mkLam :: [(a, Var)] -> UntypedFeld a -> UntypedFeld a
mkLam [] e = e
mkLam ((a, h):t) e = In a (Lambda h (mkLam t e))
mkApp :: a -> Type -> Op -> [UntypedFeld a] -> UntypedFeld a
mkApp a t p es = In a (App p t es)
mkTup :: a -> [UntypedFeld a] -> UntypedFeld a
mkTup a es = In a $ App Tup (TupType $ map typeof es) es
| Substitute new for dst in e. Assumes no shadowing .
subst :: UntypedFeld a -> Var -> UntypedFeld a -> UntypedFeld a
subst new dst = go
| otherwise = In r (Lambda v (go e'))
go (In r (LetFun (s, k, e1) e2))
Recurse .
Recurse .
sharable :: UntypedFeld a -> Bool
sharable e = legalToShare e && goodToShare e
legalToShare :: UntypedFeld a -> Bool
legalToShare (In _ (App op _ _)) = op `notElem` [ESkip, EWrite, EPar, EparFor,
Return, Bind, Then, When,
NewArr, NewArr_, GetArr, SetArr, ArrLength,
For, While,
NewRef, GetRef, SetRef, ModRef]
legalToShare (In _ (Lambda _ _)) = False
legalToShare _ = True
goodToShare :: UntypedFeld a -> Bool
goodToShare (In _ (Literal l))
| LArray _ (_:_) <- l = True
| LTup (_:_) <- l = True
goodToShare (In _ App{}) = True
goodToShare _ = False
legalToInline :: UntypedFeld a -> Bool
legalToInline _ = True
type Rename a = State VarId a
rename :: UntypedFeld a -> Rename (UntypedFeld a)
rename = renameA M.empty
type RRExp a = UntypedFeldF (UntypedFeld a)
renameA :: M.Map VarId (RRExp a) -> UntypedFeld a -> Rename (UntypedFeld a)
renameA env (In a r) = do r1 <- renameR env r
return $ In a r1
renameR :: M.Map VarId (RRExp a) -> RRExp a -> Rename (RRExp a)
renameR env (Variable v) = return $ env M.! varNum v
renameR env (App f t es) = do es1 <- mapM (renameA env) es
return $ App f t es1
renameR env (Lambda v e) = do v1 <- newVar v
e1 <- renameA (M.insert (varNum v) (Variable v1) env) e
return $ Lambda v1 e1
renameR _ (Literal l) = return $ Literal l
renameR _ e = error $ "FromTyped.renameR: unexpected expression " ++ show e
newVar :: MonadState VarId m => Var -> m Var
newVar v = do j <- get
put (j+1)
return $ v{varNum = j}
|
4ea6e845588c55550e5e6768add16fb5f2428774e0e41f41d28ec4c86a166c5e | mejgun/haskell-tdlib | ResendMessages.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
module TD.Query.ResendMessages where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
-- |
Resends messages which failed to send . Can be called only for messages for which messageSendingStateFailed.can_retry is true and after specified in messageSendingStateFailed.retry_after time passed .
-- If a message is re-sent, the corresponding failed to send message is deleted. Returns the sent messages in the same order as the message identifiers passed in message_ids. If a message can't be re-sent, null will be returned instead of the message
data ResendMessages = ResendMessages
{ -- | Identifiers of the messages to resend. Message identifiers must be in a strictly increasing order
message_ids :: Maybe [Int],
-- | Identifier of the chat to send messages
chat_id :: Maybe Int
}
deriving (Eq)
instance Show ResendMessages where
show
ResendMessages
{ message_ids = message_ids_,
chat_id = chat_id_
} =
"ResendMessages"
++ U.cc
[ U.p "message_ids" message_ids_,
U.p "chat_id" chat_id_
]
instance T.ToJSON ResendMessages where
toJSON
ResendMessages
{ message_ids = message_ids_,
chat_id = chat_id_
} =
A.object
[ "@type" A..= T.String "resendMessages",
"message_ids" A..= message_ids_,
"chat_id" A..= chat_id_
]
| null | https://raw.githubusercontent.com/mejgun/haskell-tdlib/dc380d18d49eaadc386a81dc98af2ce00f8797c2/src/TD/Query/ResendMessages.hs | haskell | # LANGUAGE OverloadedStrings #
|
|
If a message is re-sent, the corresponding failed to send message is deleted. Returns the sent messages in the same order as the message identifiers passed in message_ids. If a message can't be re-sent, null will be returned instead of the message
| Identifiers of the messages to resend. Message identifiers must be in a strictly increasing order
| Identifier of the chat to send messages |
module TD.Query.ResendMessages where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
Resends messages which failed to send . Can be called only for messages for which messageSendingStateFailed.can_retry is true and after specified in messageSendingStateFailed.retry_after time passed .
data ResendMessages = ResendMessages
message_ids :: Maybe [Int],
chat_id :: Maybe Int
}
deriving (Eq)
instance Show ResendMessages where
show
ResendMessages
{ message_ids = message_ids_,
chat_id = chat_id_
} =
"ResendMessages"
++ U.cc
[ U.p "message_ids" message_ids_,
U.p "chat_id" chat_id_
]
instance T.ToJSON ResendMessages where
toJSON
ResendMessages
{ message_ids = message_ids_,
chat_id = chat_id_
} =
A.object
[ "@type" A..= T.String "resendMessages",
"message_ids" A..= message_ids_,
"chat_id" A..= chat_id_
]
|
f963665668dfdd836c466b19ae6f6964ff80da049f0e2a063f469eaa8ed3f5e1 | softlab-ntua/bencherl | class_Squirrel.erl | Copyright ( C ) 2008 - 2014 EDF R&D
This file is part of Sim - Diasca .
Sim - Diasca is free software : you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
Sim - Diasca is distributed in the hope that it will be useful ,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with .
% If not, see </>.
Author : ( )
% This file is part of forest ecosystem test case, which is a Sim-Diasca
% integration test example.
% The objective of this module is to show the significant features of a
actor in multiple scheduling modes .
%
% This means that it has a periodic schedule and that it can be also triggered
% by messages.
% Class modelling a squirrel actor. It defines the common squirrel actor
% attributes and spontaneous beaviours.
%
NB : In SSI - Test , each simulation tick corresponds to a week .
%
-module(class_Squirrel).
% Determines what are the mother classes
-define( wooper_superclasses, [ class_ForestDweller ] ).
-define( wooper_construct_parameters, ActorSettings, SquirrelName, GivenAge,
ForestPid ).
Declaring all variations of WOOPER standard life - cycle operations :
( template pasted , two replacements performed to update arities )
-define( wooper_construct_export, new/4, new_link/4,
synchronous_new/4, synchronous_new_link/4,
synchronous_timed_new/4, synchronous_timed_new_link/4,
remote_new/5, remote_new_link/5, remote_synchronous_new/5,
remote_synchronous_new_link/5, remote_synchronisable_new_link/5,
remote_synchronous_timed_new/5, remote_synchronous_timed_new_link/5,
construct/5 ).
% Declarations of class-specific methods (besides inherited ones).
-define( wooper_method_export, onFirstDiasca/2, beMoved/2, beAllocated/3,
notifyTermination/1, deleteFromPeers/2, tryToRegister/3,
forestDestroyed/2 ).
% Static method declarations (to be directly called from module):
%-define( wooper_static_method_export, ).
Allows to define WOOPER base variables and methods for that class :
-include("wooper.hrl").
% Must be included before class_TraceEmitter header:
-define(TraceEmitterCategorization, "SSI-Test.Squirrel").
% Allows to use macros for trace sending:
-include("class_TraceEmitter.hrl").
Constructs a new squirrel actor :
%
% - oak_pid: records the PID of the tree where this squirrel lives
%
% - lifespan: is the nature longevity of a squirrel. In this test case, it is
defined as a static value : 208 weeks
%
% - state: can be
%
% - beNursed: if it is a newborn
% - available
% - gestation: if the female squirrel is waiting for baby
% - nursing: if the female is nursing its offsprings
%
construct( State, ?wooper_construct_parameters ) ->
% Firstly, the mother class
DwellerState = class_ForestDweller:construct( State, ActorSettings,
SquirrelName, GivenAge, ForestPid ),
% For an initial created squirrel, a default age is given to make difference
% between the initially created squirrels.
%
% For the squirrel created during the simulation, the given age is 0 and age
% will change over simulation time.
%
And the lifespan of a squirrel is defined as 4 years , i.e. 208 weeks .
%
{ InitialSquirrelState, AvailableTick } = case GivenAge of
0 ->
{ weak, 10 };
_Others ->
{ available, 0 }
end,
setAttributes( DwellerState, [
{ gender, undefined },
{ oak_pid, undefined },
{ lifespan, 208 },
All newborn squirrels must be nursed for 10 weeks :
{ be_nursed_period, 10 },
% at squirrel actor creation, the termination_tick_offset is initiated
% as its lifespan, anyway, it can be modified during the simulation
{ termination_tick_offset, 208 },
{ termination_waiting_ticks, 3 },
{ state, InitialSquirrelState },
{ available_tick, AvailableTick },
{ trace_categorization,
text_utils:string_to_binary( ?TraceEmitterCategorization ) }
] ).
Simply schedules this just created actor at the next tick ( diasca 0 ) .
%
% (actor oneway)
%
-spec onFirstDiasca( wooper:state(), pid() ) -> oneway_return().
onFirstDiasca( State, _SendingActorPid ) ->
ScheduledState = executeOneway( State, scheduleNextSpontaneousTick ),
?wooper_return_state_only( ScheduledState ).
% Called by a relative oak for notifying this squirrel that it is removed from
% the oak.
%
% When recieiving this message, the squirrel asks its forest for a relocation.
%
% (actor oneway)
%
-spec beMoved( wooper:state(), pid() ) -> class_Actor:actor_oneway_return().
beMoved( State, SenderPid ) ->
NewState = case ?getAttr(oak_pid) of
undefined ->
?info_fmt( "I receive a beMoved from ~w, but it is not my oak.",
[ SenderPid ] ),
State;
% Note the matching to this already-bound variable:
SenderPid ->
?info( "I am moved from my oak, I have no home and I am requiring "
"to be relocated." ),
UpdatedTargetPeers = lists:delete( SenderPid,
?getAttr(target_peers) ),
NState = setAttribute( State, target_peers, UpdatedTargetPeers ),
class_Actor:send_actor_message( ?getAttr(forest_pid),
requiredLocation, NState );
_OtherPid ->
?info_fmt( "I receive a beMoved from ~w, but it is not my oak.",
[ SenderPid ] ),
State
end,
?wooper_return_state_only( NewState ).
% Called by the forest for informing new oak pid
%
% (actor oneway)
%
-spec beAllocated( wooper:state(), pid(), pid() ) ->
class_Actor:actor_oneway_return().
beAllocated( State, OakPid, _SenderPid ) ->
TargetPeers = ?getAttr(target_peers),
UpdatedState = case OakPid of
undefined ->
?info( "I am moved from my tree and I am homeless." ),
NState = setAttributes( State, [
{ oak_pid, undefined },
{ target_peers, TargetPeers }
] ),
executeOneway( NState, notifyTermination );
_ ->
?info_fmt( "I am relocated to ~w.", [ OakPid ] ),
setAttributes( State, [
{ oak_pid, OakPid },
{ target_peers,[ OakPid | TargetPeers ] }
] )
end,
?wooper_return_state_only( UpdatedState ).
% Is requested to delete a specified squirrel pid from the target peers.
%
% An updated state is returned
%
% (actor oneway)
%
-spec deleteFromPeers( wooper:state(), pid() ) ->
class_Actor:actor_oneway_return().
deleteFromPeers( State, SenderPid ) ->
?info_fmt( "~w is deleted from the target peers of ~w.",
[ SenderPid, self() ] ),
TargetPeers = ?getAttr(target_peers),
UpdatedList = lists:delete( SenderPid, TargetPeers ),
?wooper_return_state_only(
setAttribute( State, target_peers, UpdatedList ) ).
% Message received from the forest.
%
% (actor oneway)
%
-spec forestDestroyed( wooper:state(), pid() ) ->
class_Actor:actor_oneway_return().
forestDestroyed( State, SenderPid )->
?info_fmt( "~w ~w will terminate because of destroyed forest.",
[ self(), ?getAttr(name) ] ),
TargetPeers = ?getAttr(target_peers),
UpdatedList = lists:delete( SenderPid, TargetPeers ),
NewState = setAttributes( State, [
{ forest_pid, undefined },
{ target_peers, UpdatedList }
] ),
executeOneway( NewState, notifyTermination ).
% The squirrel actor informs all pid in its target_peers about its termination.
%
% This message is sent by the squirrel itself.
%
% (actor oneway)
%
-spec notifyTermination( wooper:state() ) -> class_Actor:actor_oneway_return().
notifyTermination( State ) ->
% Source and target peers must be notified here, otherwise, next time they
% will send a message to this actor, they will hang forever:
%
% (this returns a new state)
CurrentOffset = ?getAttr(current_tick_offset),
?info_fmt( "I inform my relative actors for my termination at tick #~B.",
[ CurrentOffset ] ),
NewState = case ?getAttr(target_peers) of
[] ->
State;
TargetPeers ->
SendFun = fun( TargetPid, FunState ) ->
%Returns an updated state:
class_Actor:send_actor_message( TargetPid,
deleteFromPeers, FunState )
end,
% Returns an updated state:
lists:foldl( SendFun, State, TargetPeers )
end,
executeOneway( NewState, prepareTermination ).
% Called when is_registered is false.
%
The actor sends a addInPeers message when the forest PID exists and then an
% updated state is returned; otherwise, the original state is returned
%
% (actor oneway)
%
-spec tryToRegister( wooper:state(), class_name(), pid() ) ->
class_Actor:actor_oneway_return().
tryToRegister( State, ClassName, _SenderPid ) ->
UpdatedState = case ?getAttr(forest_pid) of
undefined ->
State;
ForestPid ->
NewState = class_Actor:send_actor_message( ForestPid,
{ addInPeers, ClassName }, State ),
TargetPeers = ?getAttr(target_peers),
UpdatedTargetPeers = [ ForestPid | TargetPeers ],
PeerState = setAttributes( NewState, [
{ is_registered, true },
{ target_peers, UpdatedTargetPeers }
] ),
executeOneway( PeerState, scheduleNextSpontaneousTick )
end,
?wooper_return_state_only( UpdatedState ).
| null | https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/sim-diasca/mock-simulators/ssi-test/src/class_Squirrel.erl | erlang | it under the terms of the GNU Lesser General Public License as
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
If not, see </>.
This file is part of forest ecosystem test case, which is a Sim-Diasca
integration test example.
The objective of this module is to show the significant features of a
This means that it has a periodic schedule and that it can be also triggered
by messages.
Class modelling a squirrel actor. It defines the common squirrel actor
attributes and spontaneous beaviours.
Determines what are the mother classes
Declarations of class-specific methods (besides inherited ones).
Static method declarations (to be directly called from module):
-define( wooper_static_method_export, ).
Must be included before class_TraceEmitter header:
Allows to use macros for trace sending:
- oak_pid: records the PID of the tree where this squirrel lives
- lifespan: is the nature longevity of a squirrel. In this test case, it is
- state: can be
- beNursed: if it is a newborn
- available
- gestation: if the female squirrel is waiting for baby
- nursing: if the female is nursing its offsprings
Firstly, the mother class
For an initial created squirrel, a default age is given to make difference
between the initially created squirrels.
For the squirrel created during the simulation, the given age is 0 and age
will change over simulation time.
at squirrel actor creation, the termination_tick_offset is initiated
as its lifespan, anyway, it can be modified during the simulation
(actor oneway)
Called by a relative oak for notifying this squirrel that it is removed from
the oak.
When recieiving this message, the squirrel asks its forest for a relocation.
(actor oneway)
Note the matching to this already-bound variable:
Called by the forest for informing new oak pid
(actor oneway)
Is requested to delete a specified squirrel pid from the target peers.
An updated state is returned
(actor oneway)
Message received from the forest.
(actor oneway)
The squirrel actor informs all pid in its target_peers about its termination.
This message is sent by the squirrel itself.
(actor oneway)
Source and target peers must be notified here, otherwise, next time they
will send a message to this actor, they will hang forever:
(this returns a new state)
Returns an updated state:
Returns an updated state:
Called when is_registered is false.
updated state is returned; otherwise, the original state is returned
(actor oneway)
| Copyright ( C ) 2008 - 2014 EDF R&D
This file is part of Sim - Diasca .
Sim - Diasca is free software : you can redistribute it and/or modify
published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
Sim - Diasca is distributed in the hope that it will be useful ,
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with .
Author : ( )
actor in multiple scheduling modes .
NB : In SSI - Test , each simulation tick corresponds to a week .
-module(class_Squirrel).
-define( wooper_superclasses, [ class_ForestDweller ] ).
-define( wooper_construct_parameters, ActorSettings, SquirrelName, GivenAge,
ForestPid ).
Declaring all variations of WOOPER standard life - cycle operations :
( template pasted , two replacements performed to update arities )
-define( wooper_construct_export, new/4, new_link/4,
synchronous_new/4, synchronous_new_link/4,
synchronous_timed_new/4, synchronous_timed_new_link/4,
remote_new/5, remote_new_link/5, remote_synchronous_new/5,
remote_synchronous_new_link/5, remote_synchronisable_new_link/5,
remote_synchronous_timed_new/5, remote_synchronous_timed_new_link/5,
construct/5 ).
-define( wooper_method_export, onFirstDiasca/2, beMoved/2, beAllocated/3,
notifyTermination/1, deleteFromPeers/2, tryToRegister/3,
forestDestroyed/2 ).
Allows to define WOOPER base variables and methods for that class :
-include("wooper.hrl").
-define(TraceEmitterCategorization, "SSI-Test.Squirrel").
-include("class_TraceEmitter.hrl").
Constructs a new squirrel actor :
defined as a static value : 208 weeks
construct( State, ?wooper_construct_parameters ) ->
DwellerState = class_ForestDweller:construct( State, ActorSettings,
SquirrelName, GivenAge, ForestPid ),
And the lifespan of a squirrel is defined as 4 years , i.e. 208 weeks .
{ InitialSquirrelState, AvailableTick } = case GivenAge of
0 ->
{ weak, 10 };
_Others ->
{ available, 0 }
end,
setAttributes( DwellerState, [
{ gender, undefined },
{ oak_pid, undefined },
{ lifespan, 208 },
All newborn squirrels must be nursed for 10 weeks :
{ be_nursed_period, 10 },
{ termination_tick_offset, 208 },
{ termination_waiting_ticks, 3 },
{ state, InitialSquirrelState },
{ available_tick, AvailableTick },
{ trace_categorization,
text_utils:string_to_binary( ?TraceEmitterCategorization ) }
] ).
Simply schedules this just created actor at the next tick ( diasca 0 ) .
-spec onFirstDiasca( wooper:state(), pid() ) -> oneway_return().
onFirstDiasca( State, _SendingActorPid ) ->
ScheduledState = executeOneway( State, scheduleNextSpontaneousTick ),
?wooper_return_state_only( ScheduledState ).
-spec beMoved( wooper:state(), pid() ) -> class_Actor:actor_oneway_return().
beMoved( State, SenderPid ) ->
NewState = case ?getAttr(oak_pid) of
undefined ->
?info_fmt( "I receive a beMoved from ~w, but it is not my oak.",
[ SenderPid ] ),
State;
SenderPid ->
?info( "I am moved from my oak, I have no home and I am requiring "
"to be relocated." ),
UpdatedTargetPeers = lists:delete( SenderPid,
?getAttr(target_peers) ),
NState = setAttribute( State, target_peers, UpdatedTargetPeers ),
class_Actor:send_actor_message( ?getAttr(forest_pid),
requiredLocation, NState );
_OtherPid ->
?info_fmt( "I receive a beMoved from ~w, but it is not my oak.",
[ SenderPid ] ),
State
end,
?wooper_return_state_only( NewState ).
-spec beAllocated( wooper:state(), pid(), pid() ) ->
class_Actor:actor_oneway_return().
beAllocated( State, OakPid, _SenderPid ) ->
TargetPeers = ?getAttr(target_peers),
UpdatedState = case OakPid of
undefined ->
?info( "I am moved from my tree and I am homeless." ),
NState = setAttributes( State, [
{ oak_pid, undefined },
{ target_peers, TargetPeers }
] ),
executeOneway( NState, notifyTermination );
_ ->
?info_fmt( "I am relocated to ~w.", [ OakPid ] ),
setAttributes( State, [
{ oak_pid, OakPid },
{ target_peers,[ OakPid | TargetPeers ] }
] )
end,
?wooper_return_state_only( UpdatedState ).
-spec deleteFromPeers( wooper:state(), pid() ) ->
class_Actor:actor_oneway_return().
deleteFromPeers( State, SenderPid ) ->
?info_fmt( "~w is deleted from the target peers of ~w.",
[ SenderPid, self() ] ),
TargetPeers = ?getAttr(target_peers),
UpdatedList = lists:delete( SenderPid, TargetPeers ),
?wooper_return_state_only(
setAttribute( State, target_peers, UpdatedList ) ).
-spec forestDestroyed( wooper:state(), pid() ) ->
class_Actor:actor_oneway_return().
forestDestroyed( State, SenderPid )->
?info_fmt( "~w ~w will terminate because of destroyed forest.",
[ self(), ?getAttr(name) ] ),
TargetPeers = ?getAttr(target_peers),
UpdatedList = lists:delete( SenderPid, TargetPeers ),
NewState = setAttributes( State, [
{ forest_pid, undefined },
{ target_peers, UpdatedList }
] ),
executeOneway( NewState, notifyTermination ).
-spec notifyTermination( wooper:state() ) -> class_Actor:actor_oneway_return().
notifyTermination( State ) ->
CurrentOffset = ?getAttr(current_tick_offset),
?info_fmt( "I inform my relative actors for my termination at tick #~B.",
[ CurrentOffset ] ),
NewState = case ?getAttr(target_peers) of
[] ->
State;
TargetPeers ->
SendFun = fun( TargetPid, FunState ) ->
class_Actor:send_actor_message( TargetPid,
deleteFromPeers, FunState )
end,
lists:foldl( SendFun, State, TargetPeers )
end,
executeOneway( NewState, prepareTermination ).
The actor sends a addInPeers message when the forest PID exists and then an
-spec tryToRegister( wooper:state(), class_name(), pid() ) ->
class_Actor:actor_oneway_return().
tryToRegister( State, ClassName, _SenderPid ) ->
UpdatedState = case ?getAttr(forest_pid) of
undefined ->
State;
ForestPid ->
NewState = class_Actor:send_actor_message( ForestPid,
{ addInPeers, ClassName }, State ),
TargetPeers = ?getAttr(target_peers),
UpdatedTargetPeers = [ ForestPid | TargetPeers ],
PeerState = setAttributes( NewState, [
{ is_registered, true },
{ target_peers, UpdatedTargetPeers }
] ),
executeOneway( PeerState, scheduleNextSpontaneousTick )
end,
?wooper_return_state_only( UpdatedState ).
|
e33ff4ddfecca684cbc5a9182e770f453f093f43c89bccc371ba0cb601958e75 | drathier/elm-offline | Chomp.hs | {-# LANGUAGE GADTs #-}
{-# LANGUAGE Rank2Types #-}
module Terminal.Args.Chomp
( chomp
)
where
import qualified Data.List as List
import Terminal.Args.Error
import Terminal.Args.Internal
CHOMP INTERFACE
chomp :: Maybe Int -> [String] -> Args args -> Flags flags -> ( IO [String], Either Error (args, flags) )
chomp maybeIndex strings args flags =
let
(Chomper flagChomper) =
chompFlags flags
ok suggest chunks flagValue =
fmap (flip (,) flagValue) <$> chompArgs suggest chunks args
err suggest flagError =
( addSuggest (return []) suggest, Left (BadFlag flagError) )
in
flagChomper (toSuggest maybeIndex) (toChunks strings) ok err
toChunks :: [String] -> [Chunk]
toChunks strings =
zipWith Chunk [ 1 .. length strings ] strings
toSuggest :: Maybe Int -> Suggest
toSuggest maybeIndex =
case maybeIndex of
Nothing ->
NoSuggestion
Just index ->
Suggest index
-- CHOMPER
newtype Chomper x a =
Chomper (
forall result.
Suggest
-> [Chunk]
-> (Suggest -> [Chunk] -> a -> result)
-> (Suggest -> x -> result)
-> result
)
data Chunk =
Chunk
{ _index :: Int
, _chunk :: String
}
data Suggest
= NoSuggestion
| Suggest Int
| Suggestions (IO [String])
makeSuggestion :: Suggest -> (Int -> Maybe (IO [String])) -> Suggest
makeSuggestion suggest maybeUpdate =
case suggest of
NoSuggestion ->
suggest
Suggestions _ ->
suggest
Suggest index ->
maybe suggest Suggestions (maybeUpdate index)
-- ARGS
chompArgs :: Suggest -> [Chunk] -> Args a -> (IO [String], Either Error a)
chompArgs suggest chunks (Args completeArgsList) =
chompArgsHelp suggest chunks completeArgsList [] []
chompArgsHelp :: Suggest -> [Chunk] -> [CompleteArgs a] -> [Suggest] -> [(CompleteArgs a, ArgError)] -> (IO [String], Either Error a)
chompArgsHelp suggest chunks completeArgsList revSuggest revArgErrors =
case completeArgsList of
[] ->
( foldl addSuggest (return []) revSuggest
, Left (BadArgs (reverse revArgErrors))
)
completeArgs : others ->
case chompCompleteArgs suggest chunks completeArgs of
(s1, Left argError) ->
chompArgsHelp suggest chunks others (s1:revSuggest) ((completeArgs,argError):revArgErrors)
(s1, Right value) ->
( addSuggest (return []) s1
, Right value
)
addSuggest :: IO [String] -> Suggest -> IO [String]
addSuggest everything suggest =
case suggest of
NoSuggestion ->
everything
Suggest _ ->
everything
Suggestions newStuff ->
(++) <$> newStuff <*> everything
-- COMPLETE ARGS
chompCompleteArgs :: Suggest -> [Chunk] -> CompleteArgs a -> (Suggest, Either ArgError a)
chompCompleteArgs suggest chunks completeArgs =
let
numChunks = length chunks
in
case completeArgs of
Exactly requiredArgs ->
chompExactly suggest chunks (chompRequiredArgs numChunks requiredArgs)
Optional requiredArgs parser ->
chompOptional suggest chunks (chompRequiredArgs numChunks requiredArgs) parser
Multiple requiredArgs parser ->
chompMultiple suggest chunks (chompRequiredArgs numChunks requiredArgs) parser
chompExactly :: Suggest -> [Chunk] -> Chomper ArgError a -> (Suggest, Either ArgError a)
chompExactly suggest chunks (Chomper chomper) =
let
ok s cs value =
case map _chunk cs of
[] -> (s, Right value)
es -> (s, Left (ArgExtras es))
err s argError =
(s, Left argError)
in
chomper suggest chunks ok err
chompOptional :: Suggest -> [Chunk] -> Chomper ArgError (Maybe a -> b) -> Parser a -> (Suggest, Either ArgError b)
chompOptional suggest chunks (Chomper chomper) parser =
let
ok s1 cs func =
case cs of
[] ->
(s1, Right (func Nothing))
Chunk index string : others ->
case tryToParse s1 parser index string of
(s2, Left expectation) ->
(s2, Left (ArgBad string expectation))
(s2, Right value) ->
case map _chunk others of
[] -> (s2, Right (func (Just value)))
es -> (s2, Left (ArgExtras es))
err s1 argError =
(s1, Left argError)
in
chomper suggest chunks ok err
chompMultiple :: Suggest -> [Chunk] -> Chomper ArgError ([a] -> b) -> Parser a -> (Suggest, Either ArgError b)
chompMultiple suggest chunks (Chomper chomper) parser =
let
err s1 argError =
(s1, Left argError)
in
chomper suggest chunks (chompMultipleHelp parser []) err
chompMultipleHelp :: Parser a -> [a] -> Suggest -> [Chunk] -> ([a] -> b) -> (Suggest, Either ArgError b)
chompMultipleHelp parser revArgs suggest chunks func =
case chunks of
[] ->
(suggest, Right (func (reverse revArgs)))
Chunk index string : otherChunks ->
case tryToParse suggest parser index string of
(s1, Left expectation) ->
(s1, Left (ArgBad string expectation))
(s1, Right arg) ->
chompMultipleHelp parser (arg:revArgs) s1 otherChunks func
-- REQUIRED ARGS
chompRequiredArgs :: Int -> RequiredArgs a -> Chomper ArgError a
chompRequiredArgs numChunks args =
case args of
Done value ->
return value
Required funcArgs argParser ->
do func <- chompRequiredArgs numChunks funcArgs
arg <- chompArg numChunks argParser
return (func arg)
chompArg :: Int -> Parser a -> Chomper ArgError a
chompArg numChunks parser@(Parser singular _ _ _ toExamples) =
Chomper $ \suggest chunks ok err ->
case chunks of
[] ->
let
newSuggest = makeSuggestion suggest (suggestArg parser numChunks)
theError = ArgMissing (Expectation singular (toExamples ""))
in
err newSuggest theError
Chunk index string : otherChunks ->
case tryToParse suggest parser index string of
(newSuggest, Left expectation) ->
err newSuggest (ArgBad string expectation)
(newSuggest, Right arg) ->
ok newSuggest otherChunks arg
suggestArg :: Parser a -> Int -> Int -> Maybe (IO [String])
suggestArg (Parser _ _ _ toSuggestions _) numChunks targetIndex =
if numChunks <= targetIndex then
Just (toSuggestions "")
else
Nothing
-- PARSER
tryToParse :: Suggest -> Parser a -> Int -> String -> (Suggest, Either Expectation a)
tryToParse suggest (Parser singular _ parse toSuggestions toExamples) index string =
let
newSuggest =
makeSuggestion suggest $ \targetIndex ->
if index == targetIndex then Just (toSuggestions string) else Nothing
outcome =
case parse string of
Nothing ->
Left (Expectation singular (toExamples string))
Just value ->
Right value
in
(newSuggest, outcome)
chompFlags :: Flags a -> Chomper FlagError a
chompFlags flags =
do value <- chompFlagsHelp flags
checkForUnknownFlags flags
return value
chompFlagsHelp :: Flags a -> Chomper FlagError a
chompFlagsHelp flags =
case flags of
FDone value ->
return value
FMore funcFlags argFlag ->
do func <- chompFlagsHelp funcFlags
arg <- chompFlag argFlag
return (func arg)
-- FLAG
chompFlag :: Flag a -> Chomper FlagError a
chompFlag flag =
case flag of
OnOff flagName _ ->
chompOnOffFlag flagName
Flag flagName parser _ ->
chompNormalFlag flagName parser
chompOnOffFlag :: String -> Chomper FlagError Bool
chompOnOffFlag flagName =
Chomper $ \suggest chunks ok err ->
case findFlag flagName chunks of
Nothing ->
ok suggest chunks False
Just (FoundFlag before value after) ->
case value of
DefNope ->
ok suggest (before ++ after) True
Possibly chunk ->
ok suggest (before ++ chunk : after) True
Definitely _ string ->
err suggest (FlagWithValue flagName string)
chompNormalFlag :: String -> Parser a -> Chomper FlagError (Maybe a)
chompNormalFlag flagName parser@(Parser singular _ _ _ toExamples) =
Chomper $ \suggest chunks ok err ->
case findFlag flagName chunks of
Nothing ->
ok suggest chunks Nothing
Just (FoundFlag before value after) ->
let
attempt index string =
case tryToParse suggest parser index string of
(newSuggest, Left expectation) ->
err newSuggest (FlagWithBadValue flagName string expectation)
(newSuggest, Right flagValue) ->
ok newSuggest (before ++ after) (Just flagValue)
in
case value of
Definitely index string ->
attempt index string
Possibly (Chunk index string) ->
attempt index string
DefNope ->
err suggest (FlagWithNoValue flagName (Expectation singular (toExamples "")))
-- FIND FLAG
data FoundFlag =
FoundFlag
{ _before :: [Chunk]
, _value :: Value
, _after :: [Chunk]
}
data Value
= Definitely Int String
| Possibly Chunk
| DefNope
findFlag :: String -> [Chunk] -> Maybe FoundFlag
findFlag flagName chunks =
findFlagHelp [] ("--" ++ flagName) ("--" ++ flagName ++ "=") chunks
findFlagHelp :: [Chunk] -> String -> String -> [Chunk] -> Maybe FoundFlag
findFlagHelp revPrev loneFlag flagPrefix chunks =
let
succeed value after =
Just (FoundFlag (reverse revPrev) value after)
deprefix string =
drop (length flagPrefix) string
in
case chunks of
[] ->
Nothing
chunk@(Chunk index string) : rest ->
if List.isPrefixOf flagPrefix string then
succeed (Definitely index (deprefix string)) rest
else if string /= loneFlag then
findFlagHelp (chunk:revPrev) loneFlag flagPrefix rest
else
case rest of
[] ->
succeed DefNope []
argChunk@(Chunk _ potentialArg) : restOfRest ->
if List.isPrefixOf "-" potentialArg then
succeed DefNope rest
else
succeed (Possibly argChunk) restOfRest
CHECK FOR UNKNOWN
checkForUnknownFlags :: Flags a -> Chomper FlagError ()
checkForUnknownFlags flags =
Chomper $ \suggest chunks ok err ->
case filter startsWithDash chunks of
[] ->
ok suggest chunks ()
unknownFlags@(Chunk _ unknownFlag : _) ->
err
(makeSuggestion suggest (suggestFlag unknownFlags flags))
(FlagUnknown unknownFlag flags)
suggestFlag :: [Chunk] -> Flags a -> Int -> Maybe (IO [String])
suggestFlag unknownFlags flags targetIndex =
case unknownFlags of
[] ->
Nothing
Chunk index string : otherUnknownFlags ->
if index == targetIndex then
Just (return (filter (List.isPrefixOf string) (getFlagNames flags [])))
else
suggestFlag otherUnknownFlags flags targetIndex
startsWithDash :: Chunk -> Bool
startsWithDash (Chunk _ string) =
List.isPrefixOf "-" string
getFlagNames :: Flags a -> [String] -> [String]
getFlagNames flags names =
case flags of
FDone _ ->
"--help" : names
FMore subFlags flag ->
getFlagNames subFlags (getFlagName flag : names)
getFlagName :: Flag a -> String
getFlagName flag =
case flag of
Flag name _ _ ->
"--" ++ name
OnOff name _ ->
"--" ++ name
-- CHOMPER INSTANCES
instance Functor (Chomper x) where
fmap func (Chomper chomper) =
Chomper $ \i w ok err ->
let
ok1 s1 cs1 value =
ok s1 cs1 (func value)
in
chomper i w ok1 err
instance Applicative (Chomper x) where
pure value =
Chomper $ \ss cs ok _ ->
ok ss cs value
(<*>) (Chomper funcChomper) (Chomper argChomper) =
Chomper $ \s cs ok err ->
let
ok1 s1 cs1 func =
let
ok2 s2 cs2 value =
ok s2 cs2 (func value)
in
argChomper s1 cs1 ok2 err
in
funcChomper s cs ok1 err
instance Monad (Chomper x) where
return = pure
(>>=) (Chomper aChomper) callback =
Chomper $ \s cs ok err ->
let
ok1 s1 cs1 a =
case callback a of
Chomper bChomper -> bChomper s1 cs1 ok err
in
aChomper s cs ok1 err
| null | https://raw.githubusercontent.com/drathier/elm-offline/f562198cac29f4cda15b69fde7e66edde89b34fa/ui/terminal/src/Terminal/Args/Chomp.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE Rank2Types #
CHOMPER
ARGS
COMPLETE ARGS
REQUIRED ARGS
PARSER
FLAG
FIND FLAG
CHOMPER INSTANCES | module Terminal.Args.Chomp
( chomp
)
where
import qualified Data.List as List
import Terminal.Args.Error
import Terminal.Args.Internal
CHOMP INTERFACE
chomp :: Maybe Int -> [String] -> Args args -> Flags flags -> ( IO [String], Either Error (args, flags) )
chomp maybeIndex strings args flags =
let
(Chomper flagChomper) =
chompFlags flags
ok suggest chunks flagValue =
fmap (flip (,) flagValue) <$> chompArgs suggest chunks args
err suggest flagError =
( addSuggest (return []) suggest, Left (BadFlag flagError) )
in
flagChomper (toSuggest maybeIndex) (toChunks strings) ok err
toChunks :: [String] -> [Chunk]
toChunks strings =
zipWith Chunk [ 1 .. length strings ] strings
toSuggest :: Maybe Int -> Suggest
toSuggest maybeIndex =
case maybeIndex of
Nothing ->
NoSuggestion
Just index ->
Suggest index
newtype Chomper x a =
Chomper (
forall result.
Suggest
-> [Chunk]
-> (Suggest -> [Chunk] -> a -> result)
-> (Suggest -> x -> result)
-> result
)
data Chunk =
Chunk
{ _index :: Int
, _chunk :: String
}
data Suggest
= NoSuggestion
| Suggest Int
| Suggestions (IO [String])
makeSuggestion :: Suggest -> (Int -> Maybe (IO [String])) -> Suggest
makeSuggestion suggest maybeUpdate =
case suggest of
NoSuggestion ->
suggest
Suggestions _ ->
suggest
Suggest index ->
maybe suggest Suggestions (maybeUpdate index)
chompArgs :: Suggest -> [Chunk] -> Args a -> (IO [String], Either Error a)
chompArgs suggest chunks (Args completeArgsList) =
chompArgsHelp suggest chunks completeArgsList [] []
chompArgsHelp :: Suggest -> [Chunk] -> [CompleteArgs a] -> [Suggest] -> [(CompleteArgs a, ArgError)] -> (IO [String], Either Error a)
chompArgsHelp suggest chunks completeArgsList revSuggest revArgErrors =
case completeArgsList of
[] ->
( foldl addSuggest (return []) revSuggest
, Left (BadArgs (reverse revArgErrors))
)
completeArgs : others ->
case chompCompleteArgs suggest chunks completeArgs of
(s1, Left argError) ->
chompArgsHelp suggest chunks others (s1:revSuggest) ((completeArgs,argError):revArgErrors)
(s1, Right value) ->
( addSuggest (return []) s1
, Right value
)
addSuggest :: IO [String] -> Suggest -> IO [String]
addSuggest everything suggest =
case suggest of
NoSuggestion ->
everything
Suggest _ ->
everything
Suggestions newStuff ->
(++) <$> newStuff <*> everything
chompCompleteArgs :: Suggest -> [Chunk] -> CompleteArgs a -> (Suggest, Either ArgError a)
chompCompleteArgs suggest chunks completeArgs =
let
numChunks = length chunks
in
case completeArgs of
Exactly requiredArgs ->
chompExactly suggest chunks (chompRequiredArgs numChunks requiredArgs)
Optional requiredArgs parser ->
chompOptional suggest chunks (chompRequiredArgs numChunks requiredArgs) parser
Multiple requiredArgs parser ->
chompMultiple suggest chunks (chompRequiredArgs numChunks requiredArgs) parser
chompExactly :: Suggest -> [Chunk] -> Chomper ArgError a -> (Suggest, Either ArgError a)
chompExactly suggest chunks (Chomper chomper) =
let
ok s cs value =
case map _chunk cs of
[] -> (s, Right value)
es -> (s, Left (ArgExtras es))
err s argError =
(s, Left argError)
in
chomper suggest chunks ok err
chompOptional :: Suggest -> [Chunk] -> Chomper ArgError (Maybe a -> b) -> Parser a -> (Suggest, Either ArgError b)
chompOptional suggest chunks (Chomper chomper) parser =
let
ok s1 cs func =
case cs of
[] ->
(s1, Right (func Nothing))
Chunk index string : others ->
case tryToParse s1 parser index string of
(s2, Left expectation) ->
(s2, Left (ArgBad string expectation))
(s2, Right value) ->
case map _chunk others of
[] -> (s2, Right (func (Just value)))
es -> (s2, Left (ArgExtras es))
err s1 argError =
(s1, Left argError)
in
chomper suggest chunks ok err
chompMultiple :: Suggest -> [Chunk] -> Chomper ArgError ([a] -> b) -> Parser a -> (Suggest, Either ArgError b)
chompMultiple suggest chunks (Chomper chomper) parser =
let
err s1 argError =
(s1, Left argError)
in
chomper suggest chunks (chompMultipleHelp parser []) err
chompMultipleHelp :: Parser a -> [a] -> Suggest -> [Chunk] -> ([a] -> b) -> (Suggest, Either ArgError b)
chompMultipleHelp parser revArgs suggest chunks func =
case chunks of
[] ->
(suggest, Right (func (reverse revArgs)))
Chunk index string : otherChunks ->
case tryToParse suggest parser index string of
(s1, Left expectation) ->
(s1, Left (ArgBad string expectation))
(s1, Right arg) ->
chompMultipleHelp parser (arg:revArgs) s1 otherChunks func
chompRequiredArgs :: Int -> RequiredArgs a -> Chomper ArgError a
chompRequiredArgs numChunks args =
case args of
Done value ->
return value
Required funcArgs argParser ->
do func <- chompRequiredArgs numChunks funcArgs
arg <- chompArg numChunks argParser
return (func arg)
chompArg :: Int -> Parser a -> Chomper ArgError a
chompArg numChunks parser@(Parser singular _ _ _ toExamples) =
Chomper $ \suggest chunks ok err ->
case chunks of
[] ->
let
newSuggest = makeSuggestion suggest (suggestArg parser numChunks)
theError = ArgMissing (Expectation singular (toExamples ""))
in
err newSuggest theError
Chunk index string : otherChunks ->
case tryToParse suggest parser index string of
(newSuggest, Left expectation) ->
err newSuggest (ArgBad string expectation)
(newSuggest, Right arg) ->
ok newSuggest otherChunks arg
suggestArg :: Parser a -> Int -> Int -> Maybe (IO [String])
suggestArg (Parser _ _ _ toSuggestions _) numChunks targetIndex =
if numChunks <= targetIndex then
Just (toSuggestions "")
else
Nothing
tryToParse :: Suggest -> Parser a -> Int -> String -> (Suggest, Either Expectation a)
tryToParse suggest (Parser singular _ parse toSuggestions toExamples) index string =
let
newSuggest =
makeSuggestion suggest $ \targetIndex ->
if index == targetIndex then Just (toSuggestions string) else Nothing
outcome =
case parse string of
Nothing ->
Left (Expectation singular (toExamples string))
Just value ->
Right value
in
(newSuggest, outcome)
chompFlags :: Flags a -> Chomper FlagError a
chompFlags flags =
do value <- chompFlagsHelp flags
checkForUnknownFlags flags
return value
chompFlagsHelp :: Flags a -> Chomper FlagError a
chompFlagsHelp flags =
case flags of
FDone value ->
return value
FMore funcFlags argFlag ->
do func <- chompFlagsHelp funcFlags
arg <- chompFlag argFlag
return (func arg)
chompFlag :: Flag a -> Chomper FlagError a
chompFlag flag =
case flag of
OnOff flagName _ ->
chompOnOffFlag flagName
Flag flagName parser _ ->
chompNormalFlag flagName parser
chompOnOffFlag :: String -> Chomper FlagError Bool
chompOnOffFlag flagName =
Chomper $ \suggest chunks ok err ->
case findFlag flagName chunks of
Nothing ->
ok suggest chunks False
Just (FoundFlag before value after) ->
case value of
DefNope ->
ok suggest (before ++ after) True
Possibly chunk ->
ok suggest (before ++ chunk : after) True
Definitely _ string ->
err suggest (FlagWithValue flagName string)
chompNormalFlag :: String -> Parser a -> Chomper FlagError (Maybe a)
chompNormalFlag flagName parser@(Parser singular _ _ _ toExamples) =
Chomper $ \suggest chunks ok err ->
case findFlag flagName chunks of
Nothing ->
ok suggest chunks Nothing
Just (FoundFlag before value after) ->
let
attempt index string =
case tryToParse suggest parser index string of
(newSuggest, Left expectation) ->
err newSuggest (FlagWithBadValue flagName string expectation)
(newSuggest, Right flagValue) ->
ok newSuggest (before ++ after) (Just flagValue)
in
case value of
Definitely index string ->
attempt index string
Possibly (Chunk index string) ->
attempt index string
DefNope ->
err suggest (FlagWithNoValue flagName (Expectation singular (toExamples "")))
data FoundFlag =
FoundFlag
{ _before :: [Chunk]
, _value :: Value
, _after :: [Chunk]
}
data Value
= Definitely Int String
| Possibly Chunk
| DefNope
findFlag :: String -> [Chunk] -> Maybe FoundFlag
findFlag flagName chunks =
findFlagHelp [] ("--" ++ flagName) ("--" ++ flagName ++ "=") chunks
findFlagHelp :: [Chunk] -> String -> String -> [Chunk] -> Maybe FoundFlag
findFlagHelp revPrev loneFlag flagPrefix chunks =
let
succeed value after =
Just (FoundFlag (reverse revPrev) value after)
deprefix string =
drop (length flagPrefix) string
in
case chunks of
[] ->
Nothing
chunk@(Chunk index string) : rest ->
if List.isPrefixOf flagPrefix string then
succeed (Definitely index (deprefix string)) rest
else if string /= loneFlag then
findFlagHelp (chunk:revPrev) loneFlag flagPrefix rest
else
case rest of
[] ->
succeed DefNope []
argChunk@(Chunk _ potentialArg) : restOfRest ->
if List.isPrefixOf "-" potentialArg then
succeed DefNope rest
else
succeed (Possibly argChunk) restOfRest
CHECK FOR UNKNOWN
checkForUnknownFlags :: Flags a -> Chomper FlagError ()
checkForUnknownFlags flags =
Chomper $ \suggest chunks ok err ->
case filter startsWithDash chunks of
[] ->
ok suggest chunks ()
unknownFlags@(Chunk _ unknownFlag : _) ->
err
(makeSuggestion suggest (suggestFlag unknownFlags flags))
(FlagUnknown unknownFlag flags)
suggestFlag :: [Chunk] -> Flags a -> Int -> Maybe (IO [String])
suggestFlag unknownFlags flags targetIndex =
case unknownFlags of
[] ->
Nothing
Chunk index string : otherUnknownFlags ->
if index == targetIndex then
Just (return (filter (List.isPrefixOf string) (getFlagNames flags [])))
else
suggestFlag otherUnknownFlags flags targetIndex
startsWithDash :: Chunk -> Bool
startsWithDash (Chunk _ string) =
List.isPrefixOf "-" string
getFlagNames :: Flags a -> [String] -> [String]
getFlagNames flags names =
case flags of
FDone _ ->
"--help" : names
FMore subFlags flag ->
getFlagNames subFlags (getFlagName flag : names)
getFlagName :: Flag a -> String
getFlagName flag =
case flag of
Flag name _ _ ->
"--" ++ name
OnOff name _ ->
"--" ++ name
instance Functor (Chomper x) where
fmap func (Chomper chomper) =
Chomper $ \i w ok err ->
let
ok1 s1 cs1 value =
ok s1 cs1 (func value)
in
chomper i w ok1 err
instance Applicative (Chomper x) where
pure value =
Chomper $ \ss cs ok _ ->
ok ss cs value
(<*>) (Chomper funcChomper) (Chomper argChomper) =
Chomper $ \s cs ok err ->
let
ok1 s1 cs1 func =
let
ok2 s2 cs2 value =
ok s2 cs2 (func value)
in
argChomper s1 cs1 ok2 err
in
funcChomper s cs ok1 err
instance Monad (Chomper x) where
return = pure
(>>=) (Chomper aChomper) callback =
Chomper $ \s cs ok err ->
let
ok1 s1 cs1 a =
case callback a of
Chomper bChomper -> bChomper s1 cs1 ok err
in
aChomper s cs ok1 err
|
7204f7063595de7c3ea0754850cda19dbb3fe64d13db2edc3a473de8ebeebb15 | hopbit/sonic-pi-snippets | dp_str_trk_5.sps | # key: dp str trk 5
# point_line: 0
# point_index: 0
# --
class Track5 < Track
def initialize(samples_path)
@tempo = 80
@vocal = {
'sample' => "#{samples_path}/vocals/JoshuaDavidVocals_Mini_SP/80_F_AhhHarmonyVocal_01_621.wav",
'times' => 4,
'sample_start' => 0.0,
'sample_finish' => 1.0,
'sleep_before' => 0,
'sleep_after' => 32
}
@bg = [[[:cs4, :e4, :db4], 0.5, 1.0]] * 32
@melody = [[:gs4, 0.5, 0.25], [:cs5, 0.25, 0.25], [:gs5, 0.125, 0.125], [:g4, 0.125, 0.125], [:cs5, 0.125, 0.125]] # 1 tact
@melody += [[nil, 0.125, 0.125], [:gs5, 0.25, 0.25], [:e5, 0.25, 0.25], [:ds5, 0.25, 0.25], [:cs5, 0.25, 0.25]]
@melody += [[:a4, 0.25, 0.25], [:cs5, 0.25, 0.25], [:e5, 0.125, 0.125], [:b4, 0.125, 0.125], [:ds5, 0.125, 0.125]] # 2 tact
@melody += [[nil, 0.125, 0.125], [:fs5, 0.25, 0.25], [:e5, 0.25, 0.25], [:ds5, 0.25, 0.25], [:cs5, 0.25, 0.25]]
@melody *= 4
@beat = {
'sample' => :loop_amen,
'times' => 8,
'stretch' => 4,
'sleep' => 4
}
end
end
| null | https://raw.githubusercontent.com/hopbit/sonic-pi-snippets/2232854ac9587fc2f9f684ba04d7476e2dbaa288/dp/dp_str_trk_5.sps | scheme | # key: dp str trk 5
# point_line: 0
# point_index: 0
# --
class Track5 < Track
def initialize(samples_path)
@tempo = 80
@vocal = {
'sample' => "#{samples_path}/vocals/JoshuaDavidVocals_Mini_SP/80_F_AhhHarmonyVocal_01_621.wav",
'times' => 4,
'sample_start' => 0.0,
'sample_finish' => 1.0,
'sleep_before' => 0,
'sleep_after' => 32
}
@bg = [[[:cs4, :e4, :db4], 0.5, 1.0]] * 32
@melody = [[:gs4, 0.5, 0.25], [:cs5, 0.25, 0.25], [:gs5, 0.125, 0.125], [:g4, 0.125, 0.125], [:cs5, 0.125, 0.125]] # 1 tact
@melody += [[nil, 0.125, 0.125], [:gs5, 0.25, 0.25], [:e5, 0.25, 0.25], [:ds5, 0.25, 0.25], [:cs5, 0.25, 0.25]]
@melody += [[:a4, 0.25, 0.25], [:cs5, 0.25, 0.25], [:e5, 0.125, 0.125], [:b4, 0.125, 0.125], [:ds5, 0.125, 0.125]] # 2 tact
@melody += [[nil, 0.125, 0.125], [:fs5, 0.25, 0.25], [:e5, 0.25, 0.25], [:ds5, 0.25, 0.25], [:cs5, 0.25, 0.25]]
@melody *= 4
@beat = {
'sample' => :loop_amen,
'times' => 8,
'stretch' => 4,
'sleep' => 4
}
end
end
|
|
12d150289697530fc2c10b9e1bdb6af70292b019b98b91119acd4337a31476b3 | csabahruska/jhc-components | Unique.hs | # OPTIONS_JHC -fffi #
module Data.Unique (
-- * Unique objects
instance ( Eq , Ord )
newUnique, -- :: IO Unique
hashUnique -- :: Unique -> Int
) where
import Foreign.Storable
import Foreign.Ptr
-- | An abstract unique object. Objects of type 'Unique' may be
-- compared for equality and ordering and hashed into 'Int'.
newtype Unique = Unique Int deriving (Eq,Ord)
-- | Creates a new object of type 'Unique'. The value returned will
-- not compare equal to any other value of type 'Unique' returned by
-- previous calls to 'newUnique'. There is no limit on the number of
-- times 'newUnique' may be called.
newUnique :: IO Unique
newUnique = do
n <- peek c_data_unique
poke c_data_unique (n + 1)
return $ Unique n
| Hashes a ' Unique ' into an ' Int ' . Two ' Unique 's may hash to the
-- same value, although in practice this is unlikely. The 'Int'
-- returned makes a good hash key.
hashUnique :: Unique -> Int
hashUnique (Unique u) = u
instance Show Unique where
showsPrec p (Unique n) = showsPrec p n
foreign import ccall "&jhc_data_unique" c_data_unique :: Ptr Int
| null | https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/lib/haskell-extras/Data/Unique.hs | haskell | * Unique objects
:: IO Unique
:: Unique -> Int
| An abstract unique object. Objects of type 'Unique' may be
compared for equality and ordering and hashed into 'Int'.
| Creates a new object of type 'Unique'. The value returned will
not compare equal to any other value of type 'Unique' returned by
previous calls to 'newUnique'. There is no limit on the number of
times 'newUnique' may be called.
same value, although in practice this is unlikely. The 'Int'
returned makes a good hash key. | # OPTIONS_JHC -fffi #
module Data.Unique (
instance ( Eq , Ord )
) where
import Foreign.Storable
import Foreign.Ptr
newtype Unique = Unique Int deriving (Eq,Ord)
newUnique :: IO Unique
newUnique = do
n <- peek c_data_unique
poke c_data_unique (n + 1)
return $ Unique n
| Hashes a ' Unique ' into an ' Int ' . Two ' Unique 's may hash to the
hashUnique :: Unique -> Int
hashUnique (Unique u) = u
instance Show Unique where
showsPrec p (Unique n) = showsPrec p n
foreign import ccall "&jhc_data_unique" c_data_unique :: Ptr Int
|
7622611ad028759a3ecce29bcdfbd0228578a785329dc8e1dcd8ff8ff3043077 | tuscland/lw-project-generator | package.lisp | -*- encoding : utf-8 ; mode : LISP ; syntax : COMMON - LISP ; indent - tabs - mode : nil -*-
LispWorks Project Generator .
Copyright ( c ) 2013 , . 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.
(in-package "CL-USER")
(defpackage "COM.WILDORA.PROJECT-GENERATOR"
(:nicknames "PROJECT-GENERATOR")
(:export
"FIND-PROJECT-TEMPLATES"
"RUN"
"*DRY-RUN-P*"
"*DEBUG-LOG-P*"))
| null | https://raw.githubusercontent.com/tuscland/lw-project-generator/21bafd22cd3fc6bb0762155df764dc5538369a9a/src/package.lisp | lisp | mode : LISP ; syntax : COMMON - LISP ; indent - tabs - mode : nil -*-
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,
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. |
LispWorks Project Generator .
Copyright ( c ) 2013 , . All rights reserved .
software distributed under the License is distributed on an " AS
(in-package "CL-USER")
(defpackage "COM.WILDORA.PROJECT-GENERATOR"
(:nicknames "PROJECT-GENERATOR")
(:export
"FIND-PROJECT-TEMPLATES"
"RUN"
"*DRY-RUN-P*"
"*DEBUG-LOG-P*"))
|
80e121f686ad9de61cf756549f53e698612166526c9671e78bc370a30753468a | anwarmamat/cmsc330spring19-public | public.ml | open OUnit2
open TestUtils
open Disc
let test_find_expensive ctxt =
assert_equal true (cmp_float 0.0 (find_expensive [])) ~msg:"find_expensive (1)";
assert_equal true (cmp_float 50.0 (find_expensive [{item="sofritas"; cost=50.0}; {item="chicken"; cost=50.0}; {item="guac"; cost=20.0}])) ~msg:"find_expensive (2)";
assert_equal true (cmp_float 7.15 (find_expensive [{item="sofritas"; cost=6.84}; {item="chicken"; cost=7.15}; {item="guac"; cost=2.15}])) ~msg:"find_expensive (3)"
let test_sum_list_list ctxt =
assert_equal 0 (sum_list_list []) ~msg:"sum_list_list (1)" ~printer:string_of_int;
assert_equal 6 (sum_list_list [[]; [1]; [2; 3]]) ~msg:"sum_list_list (2)" ~printer:string_of_int;
assert_equal 4 (sum_list_list [[-1; 1]; [-2; 3]; [-5; 8]]) ~msg:"sum_list_list (3)" ~printer:string_of_int
let test_full_names ctxt =
assert_equal [] (full_names []) ~msg:"full_names (1)" ~printer:string_of_string_list;
assert_equal ["Anwar Mamat"; "Michael William Hicks"] (full_names [{ first = "Anwar"; middle = None; last = "Mamat" }; { first = "Michael"; middle = Some "William"; last = "Hicks" }]) ~msg:"full_names (2)" ~printer:string_of_string_list;
assert_equal ["Tide Pods"] (full_names [{first="Tide"; middle=None; last="Pods"}]) ~msg:"full_names (3)" ~printer:string_of_string_list
let test_sum_vectors ctxt =
assert_equal { x = 0; y = 0 } (sum_vectors []) ~msg:"sum_vectors (1)";
assert_equal { x = 4; y = 6 } (sum_vectors [{ x = 1; y = 2 }; { x = 3; y = 4 }]) ~msg:"sum_vectors (2)";
assert_equal { x = 20; y = 100 } (sum_vectors [{ x = 10; y = 20 }; { x = 30; y = 40 }; { x = (-20); y = 40 }]) ~msg:"sum_vectors (3)"
let test_my_map ctxt =
assert_equal [] (my_map (fun x -> x + 1) []) ~msg:"my_map (1)" ~printer:string_of_int_list;
assert_equal [2;3;4] (my_map (fun x -> x + 1) [1;2;3]) ~msg:"my_map (2)" ~printer:string_of_int_list;
assert_equal ["Tide Pods"] (my_map (fun x -> x ^ " Pods") ["Tide"]) ~msg:"my_map (3)" ~printer:string_of_string_list
let suite =
"public" >::: [
"find_expensive" >:: test_find_expensive;
"sum_list_list" >:: test_sum_list_list;
"full_names" >:: test_full_names;
"sum_vectors" >:: test_sum_vectors;
"my_map" >:: test_my_map
]
let _ = run_test_tt_main suite
| null | https://raw.githubusercontent.com/anwarmamat/cmsc330spring19-public/98af1e8efc3d8756972731eaca19e55fe8febb69/discussions/discussion4/test/public.ml | ocaml | open OUnit2
open TestUtils
open Disc
let test_find_expensive ctxt =
assert_equal true (cmp_float 0.0 (find_expensive [])) ~msg:"find_expensive (1)";
assert_equal true (cmp_float 50.0 (find_expensive [{item="sofritas"; cost=50.0}; {item="chicken"; cost=50.0}; {item="guac"; cost=20.0}])) ~msg:"find_expensive (2)";
assert_equal true (cmp_float 7.15 (find_expensive [{item="sofritas"; cost=6.84}; {item="chicken"; cost=7.15}; {item="guac"; cost=2.15}])) ~msg:"find_expensive (3)"
let test_sum_list_list ctxt =
assert_equal 0 (sum_list_list []) ~msg:"sum_list_list (1)" ~printer:string_of_int;
assert_equal 6 (sum_list_list [[]; [1]; [2; 3]]) ~msg:"sum_list_list (2)" ~printer:string_of_int;
assert_equal 4 (sum_list_list [[-1; 1]; [-2; 3]; [-5; 8]]) ~msg:"sum_list_list (3)" ~printer:string_of_int
let test_full_names ctxt =
assert_equal [] (full_names []) ~msg:"full_names (1)" ~printer:string_of_string_list;
assert_equal ["Anwar Mamat"; "Michael William Hicks"] (full_names [{ first = "Anwar"; middle = None; last = "Mamat" }; { first = "Michael"; middle = Some "William"; last = "Hicks" }]) ~msg:"full_names (2)" ~printer:string_of_string_list;
assert_equal ["Tide Pods"] (full_names [{first="Tide"; middle=None; last="Pods"}]) ~msg:"full_names (3)" ~printer:string_of_string_list
let test_sum_vectors ctxt =
assert_equal { x = 0; y = 0 } (sum_vectors []) ~msg:"sum_vectors (1)";
assert_equal { x = 4; y = 6 } (sum_vectors [{ x = 1; y = 2 }; { x = 3; y = 4 }]) ~msg:"sum_vectors (2)";
assert_equal { x = 20; y = 100 } (sum_vectors [{ x = 10; y = 20 }; { x = 30; y = 40 }; { x = (-20); y = 40 }]) ~msg:"sum_vectors (3)"
let test_my_map ctxt =
assert_equal [] (my_map (fun x -> x + 1) []) ~msg:"my_map (1)" ~printer:string_of_int_list;
assert_equal [2;3;4] (my_map (fun x -> x + 1) [1;2;3]) ~msg:"my_map (2)" ~printer:string_of_int_list;
assert_equal ["Tide Pods"] (my_map (fun x -> x ^ " Pods") ["Tide"]) ~msg:"my_map (3)" ~printer:string_of_string_list
let suite =
"public" >::: [
"find_expensive" >:: test_find_expensive;
"sum_list_list" >:: test_sum_list_list;
"full_names" >:: test_full_names;
"sum_vectors" >:: test_sum_vectors;
"my_map" >:: test_my_map
]
let _ = run_test_tt_main suite
|
|
1606814dfdb1e071a7e1b59918b3807601849a34c653c57c8e9ea916115d39f3 | ocaml-multicore/reagents | offer.mli |
* Copyright ( c ) 2015 , < >
* Copyright ( c ) 2015 , < >
*
* Permission to use , copy , modify , and/or distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2015, Théo Laurent <>
* Copyright (c) 2015, KC Sivaramakrishnan <>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module type S = Offer_intf.S
module Make (Sched : Scheduler.S) : S
| null | https://raw.githubusercontent.com/ocaml-multicore/reagents/6721db78b21028c807fb13d0af0aaf9407c662b5/lib/offer.mli | ocaml |
* Copyright ( c ) 2015 , < >
* Copyright ( c ) 2015 , < >
*
* Permission to use , copy , modify , and/or distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2015, Théo Laurent <>
* Copyright (c) 2015, KC Sivaramakrishnan <>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module type S = Offer_intf.S
module Make (Sched : Scheduler.S) : S
|
|
1a66f4e8a7472fe4bca0c69067645e09db7f37853a2bf909d7526b66a5513b56 | penpot/penpot | slider_selector.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.colorpicker.slider-selector
(:require
[app.common.math :as mth]
[app.util.dom :as dom]
[app.util.object :as obj]
[rumext.v2 :as mf]))
(mf/defc slider-selector
[{:keys [value class min-value max-value vertical? reverse? on-change on-start-drag on-finish-drag]}]
(let [min-value (or min-value 0)
max-value (or max-value 1)
dragging? (mf/use-state false)
handle-start-drag
(mf/use-callback
(mf/deps on-start-drag)
(fn [event]
(dom/capture-pointer event)
(reset! dragging? true)
(when on-start-drag
(on-start-drag))))
handle-stop-drag
(mf/use-callback
(mf/deps on-finish-drag)
(fn [event]
(dom/release-pointer event)
(reset! dragging? false)
(when on-finish-drag
(on-finish-drag))))
calculate-pos
(fn [ev]
(when on-change
(let [{:keys [left right top bottom]} (-> ev dom/get-target dom/get-bounding-rect)
{:keys [x y]} (-> ev dom/get-client-position)
unit-value (if vertical?
(mth/clamp (/ (- bottom y) (- bottom top)) 0 1)
(mth/clamp (/ (- x left) (- right left)) 0 1))
unit-value (if reverse?
(mth/abs (- unit-value 1.0))
unit-value)
value (+ min-value (* unit-value (- max-value min-value)))]
(on-change value))))]
[:div.slider-selector
{:class (str (if vertical? "vertical " "") class)
:on-pointer-down handle-start-drag
:on-pointer-up handle-stop-drag
:on-lost-pointer-capture handle-stop-drag
:on-click calculate-pos
:on-mouse-move #(when @dragging? (calculate-pos %))}
(let [value-percent (* (/ (- value min-value)
(- max-value min-value)) 100)
value-percent (if reverse?
(mth/abs (- value-percent 100))
value-percent)
value-percent-str (str value-percent "%")
style-common #js {:pointerEvents "none"}
style-horizontal (obj/merge! #js {:left value-percent-str} style-common)
style-vertical (obj/merge! #js {:bottom value-percent-str} style-common)]
[:div.handler {:style (if vertical? style-vertical style-horizontal)}])]))
| null | https://raw.githubusercontent.com/penpot/penpot/7303d311d5f23d515fa3fcdc6cd13cf7f429d1fe/frontend/src/app/main/ui/workspace/colorpicker/slider_selector.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.colorpicker.slider-selector
(:require
[app.common.math :as mth]
[app.util.dom :as dom]
[app.util.object :as obj]
[rumext.v2 :as mf]))
(mf/defc slider-selector
[{:keys [value class min-value max-value vertical? reverse? on-change on-start-drag on-finish-drag]}]
(let [min-value (or min-value 0)
max-value (or max-value 1)
dragging? (mf/use-state false)
handle-start-drag
(mf/use-callback
(mf/deps on-start-drag)
(fn [event]
(dom/capture-pointer event)
(reset! dragging? true)
(when on-start-drag
(on-start-drag))))
handle-stop-drag
(mf/use-callback
(mf/deps on-finish-drag)
(fn [event]
(dom/release-pointer event)
(reset! dragging? false)
(when on-finish-drag
(on-finish-drag))))
calculate-pos
(fn [ev]
(when on-change
(let [{:keys [left right top bottom]} (-> ev dom/get-target dom/get-bounding-rect)
{:keys [x y]} (-> ev dom/get-client-position)
unit-value (if vertical?
(mth/clamp (/ (- bottom y) (- bottom top)) 0 1)
(mth/clamp (/ (- x left) (- right left)) 0 1))
unit-value (if reverse?
(mth/abs (- unit-value 1.0))
unit-value)
value (+ min-value (* unit-value (- max-value min-value)))]
(on-change value))))]
[:div.slider-selector
{:class (str (if vertical? "vertical " "") class)
:on-pointer-down handle-start-drag
:on-pointer-up handle-stop-drag
:on-lost-pointer-capture handle-stop-drag
:on-click calculate-pos
:on-mouse-move #(when @dragging? (calculate-pos %))}
(let [value-percent (* (/ (- value min-value)
(- max-value min-value)) 100)
value-percent (if reverse?
(mth/abs (- value-percent 100))
value-percent)
value-percent-str (str value-percent "%")
style-common #js {:pointerEvents "none"}
style-horizontal (obj/merge! #js {:left value-percent-str} style-common)
style-vertical (obj/merge! #js {:bottom value-percent-str} style-common)]
[:div.handler {:style (if vertical? style-vertical style-horizontal)}])]))
|
918962aa88d12d37168982b1f24d0dc71335635d0eda8eacd822a73347badae6 | RichiH/git-annex | Command.hs | git - annex command infrastructure
-
- Copyright 2010 - 2016 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2010-2016 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Command (
module Command,
module ReExported
) where
import Annex.Common as ReExported
import Annex.WorkTree as ReExported (whenAnnexed, ifAnnexed)
import Types.Command as ReExported
import Types.DeferredParse as ReExported
import CmdLine.Seek as ReExported
import CmdLine.Usage as ReExported
import CmdLine.Action as ReExported
import CmdLine.Option as ReExported
import CmdLine.GlobalSetter as ReExported
import CmdLine.GitAnnex.Options as ReExported
import CmdLine.Batch as ReExported
import Options.Applicative as ReExported hiding (command)
import qualified Annex
import qualified Git
import Annex.Init
import Config
import Utility.Daemon
import Types.Transfer
import Types.ActionItem
import Types.Messages
{- Generates a normal Command -}
command :: String -> CommandSection -> String -> CmdParamsDesc -> (CmdParamsDesc -> CommandParser) -> Command
command name section desc paramdesc mkparser =
Command commonChecks False False name paramdesc
section desc (mkparser paramdesc) [] Nothing
{- Simple option parser that takes all non-option params as-is. -}
withParams :: (CmdParams -> v) -> CmdParamsDesc -> Parser v
withParams mkseek paramdesc = mkseek <$> cmdParams paramdesc
{- Uses the supplied option parser, which yields a deferred parse,
- and calls finishParse on the result before passing it to the
- CommandSeek constructor. -}
< ) : : a
=> (a -> CommandSeek)
-> (CmdParamsDesc -> Parser a)
-> CmdParamsDesc
-> Parser CommandSeek
< ) =
(mkseek <=< finishParse) <$> optparser paramsdesc
{- Indicates that a command doesn't need to commit any changes to
- the git-annex branch. -}
noCommit :: Command -> Command
noCommit c = c { cmdnocommit = True }
Indicates that a command should not output the usual messages when
- starting or stopping processing a file or other item . Unless --json mode
- is enabled , this also enables quiet output mode , so only things
- explicitly output by the command are shown and not progress messages
- etc .
- starting or stopping processing a file or other item. Unless --json mode
- is enabled, this also enables quiet output mode, so only things
- explicitly output by the command are shown and not progress messages
- etc. -}
noMessages :: Command -> Command
noMessages c = c { cmdnomessages = True }
{- Undoes noMessages -}
allowMessages :: Annex ()
allowMessages = do
curr <- Annex.getState Annex.output
case outputType curr of
QuietOutput -> Annex.setOutput NormalOutput
_ -> noop
Annex.changeState $ \s -> s
{ Annex.output = (Annex.output s) { implicitMessages = True } }
{- Adds a fallback action to a command, that will be run if it's used
- outside a git repository. -}
noRepo :: (String -> Parser (IO ())) -> Command -> Command
noRepo a c = c { cmdnorepo = Just (a (cmdparamdesc c)) }
{- Adds global options to a command's. -}
withGlobalOptions :: [GlobalOption] -> Command -> Command
withGlobalOptions os c = c { cmdglobaloptions = cmdglobaloptions c ++ os }
{- For start and perform stages to indicate what step to run next. -}
next :: a -> Annex (Maybe a)
next a = return $ Just a
{- Or to indicate nothing needs to be done. -}
stop :: Annex (Maybe a)
stop = return Nothing
{- Stops unless a condition is met. -}
stopUnless :: Annex Bool -> Annex (Maybe a) -> Annex (Maybe a)
stopUnless c a = ifM c ( a , stop )
{- When acting on a failed transfer, stops unless it was in the specified
- direction. -}
checkFailedTransferDirection :: ActionItem -> Direction -> Annex (Maybe a) -> Annex (Maybe a)
checkFailedTransferDirection ai d = stopUnless (pure check)
where
check = case actionItemTransferDirection ai of
Nothing -> True
Just d' -> d' == d
commonChecks :: [CommandCheck]
commonChecks = [repoExists]
repoExists :: CommandCheck
repoExists = CommandCheck 0 ensureInitialized
notDirect :: Command -> Command
notDirect = addCheck $ whenM isDirect $
giveup "You cannot run this command in a direct mode repository."
notBareRepo :: Command -> Command
notBareRepo = addCheck $ whenM (fromRepo Git.repoIsLocalBare) $
giveup "You cannot run this command in a bare repository."
noDaemonRunning :: Command -> Command
noDaemonRunning = addCheck $ whenM (isJust <$> daemonpid) $
giveup "You cannot run this command while git-annex watch or git-annex assistant is running."
where
daemonpid = liftIO . checkDaemon =<< fromRepo gitAnnexPidFile
dontCheck :: CommandCheck -> Command -> Command
dontCheck check cmd = mutateCheck cmd $ \c -> filter (/= check) c
addCheck :: Annex () -> Command -> Command
addCheck check cmd = mutateCheck cmd $ \c ->
CommandCheck (length c + 100) check : c
mutateCheck :: Command -> ([CommandCheck] -> [CommandCheck]) -> Command
mutateCheck cmd@(Command { cmdcheck = c }) a = cmd { cmdcheck = a c }
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Command.hs | haskell | Generates a normal Command
Simple option parser that takes all non-option params as-is.
Uses the supplied option parser, which yields a deferred parse,
- and calls finishParse on the result before passing it to the
- CommandSeek constructor.
Indicates that a command doesn't need to commit any changes to
- the git-annex branch.
json mode
json mode
Undoes noMessages
Adds a fallback action to a command, that will be run if it's used
- outside a git repository.
Adds global options to a command's.
For start and perform stages to indicate what step to run next.
Or to indicate nothing needs to be done.
Stops unless a condition is met.
When acting on a failed transfer, stops unless it was in the specified
- direction. | git - annex command infrastructure
-
- Copyright 2010 - 2016 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2010-2016 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Command (
module Command,
module ReExported
) where
import Annex.Common as ReExported
import Annex.WorkTree as ReExported (whenAnnexed, ifAnnexed)
import Types.Command as ReExported
import Types.DeferredParse as ReExported
import CmdLine.Seek as ReExported
import CmdLine.Usage as ReExported
import CmdLine.Action as ReExported
import CmdLine.Option as ReExported
import CmdLine.GlobalSetter as ReExported
import CmdLine.GitAnnex.Options as ReExported
import CmdLine.Batch as ReExported
import Options.Applicative as ReExported hiding (command)
import qualified Annex
import qualified Git
import Annex.Init
import Config
import Utility.Daemon
import Types.Transfer
import Types.ActionItem
import Types.Messages
command :: String -> CommandSection -> String -> CmdParamsDesc -> (CmdParamsDesc -> CommandParser) -> Command
command name section desc paramdesc mkparser =
Command commonChecks False False name paramdesc
section desc (mkparser paramdesc) [] Nothing
withParams :: (CmdParams -> v) -> CmdParamsDesc -> Parser v
withParams mkseek paramdesc = mkseek <$> cmdParams paramdesc
< ) : : a
=> (a -> CommandSeek)
-> (CmdParamsDesc -> Parser a)
-> CmdParamsDesc
-> Parser CommandSeek
< ) =
(mkseek <=< finishParse) <$> optparser paramsdesc
noCommit :: Command -> Command
noCommit c = c { cmdnocommit = True }
Indicates that a command should not output the usual messages when
- is enabled , this also enables quiet output mode , so only things
- explicitly output by the command are shown and not progress messages
- etc .
- is enabled, this also enables quiet output mode, so only things
- explicitly output by the command are shown and not progress messages
- etc. -}
noMessages :: Command -> Command
noMessages c = c { cmdnomessages = True }
allowMessages :: Annex ()
allowMessages = do
curr <- Annex.getState Annex.output
case outputType curr of
QuietOutput -> Annex.setOutput NormalOutput
_ -> noop
Annex.changeState $ \s -> s
{ Annex.output = (Annex.output s) { implicitMessages = True } }
noRepo :: (String -> Parser (IO ())) -> Command -> Command
noRepo a c = c { cmdnorepo = Just (a (cmdparamdesc c)) }
withGlobalOptions :: [GlobalOption] -> Command -> Command
withGlobalOptions os c = c { cmdglobaloptions = cmdglobaloptions c ++ os }
next :: a -> Annex (Maybe a)
next a = return $ Just a
stop :: Annex (Maybe a)
stop = return Nothing
stopUnless :: Annex Bool -> Annex (Maybe a) -> Annex (Maybe a)
stopUnless c a = ifM c ( a , stop )
checkFailedTransferDirection :: ActionItem -> Direction -> Annex (Maybe a) -> Annex (Maybe a)
checkFailedTransferDirection ai d = stopUnless (pure check)
where
check = case actionItemTransferDirection ai of
Nothing -> True
Just d' -> d' == d
commonChecks :: [CommandCheck]
commonChecks = [repoExists]
repoExists :: CommandCheck
repoExists = CommandCheck 0 ensureInitialized
notDirect :: Command -> Command
notDirect = addCheck $ whenM isDirect $
giveup "You cannot run this command in a direct mode repository."
notBareRepo :: Command -> Command
notBareRepo = addCheck $ whenM (fromRepo Git.repoIsLocalBare) $
giveup "You cannot run this command in a bare repository."
noDaemonRunning :: Command -> Command
noDaemonRunning = addCheck $ whenM (isJust <$> daemonpid) $
giveup "You cannot run this command while git-annex watch or git-annex assistant is running."
where
daemonpid = liftIO . checkDaemon =<< fromRepo gitAnnexPidFile
dontCheck :: CommandCheck -> Command -> Command
dontCheck check cmd = mutateCheck cmd $ \c -> filter (/= check) c
addCheck :: Annex () -> Command -> Command
addCheck check cmd = mutateCheck cmd $ \c ->
CommandCheck (length c + 100) check : c
mutateCheck :: Command -> ([CommandCheck] -> [CommandCheck]) -> Command
mutateCheck cmd@(Command { cmdcheck = c }) a = cmd { cmdcheck = a c }
|
8d14428b7e61946f781cff4f45498ffd3c5ebfba122a9a54c33ee575683e71d5 | essandess/adblock2privoxy | ElementBlocker.hs | module ElementBlocker (
elemBlock
) where
import InputParser hiding (Policy(..))
import qualified InputParser
import PolicyTree
import qualified Data.Map as Map
import Data.Maybe
import Utils
import System.IO
import System.FilePath
import Data.List
import System.Directory
import qualified Templates
import Control.Monad
import Data.String.Utils (startswith)
type BlockedRulesTree = DomainTree [Pattern]
data ElemBlockData = ElemBlockData [Pattern] BlockedRulesTree deriving Show
elemBlock :: String -> [String] -> [Line] -> IO ()
elemBlock path info = writeElemBlock . elemBlockData
where
writeElemBlock :: ElemBlockData -> IO ()
writeElemBlock (ElemBlockData flatPatterns rulesTree) =
do
let debugPath = path </> "debug"
filteredInfo = filter ((||) <$> not . startswith "Url:" <*> startswith "Url: http") info
createDirectoryIfMissing True path
cont <- getDirectoryContents path
_ <- sequence $ removeOld <$> cont
createDirectoryIfMissing True debugPath
writeBlockTree path debugPath rulesTree
writeBlockTree path rulesTree
writePatterns_with_debug filteredInfo (path </> "ab2p.common.css") (debugPath </> "ab2p.common.css") flatPatterns
removeOld entry' =
let entry = path </> entry'
in do
isDir <- doesDirectoryExist entry
if isDir then when (head entry' /= '.') $ removeDirectoryRecursive entry
else when (takeExtension entry == ".css") $ removeFile entry
-- writeBlockTree :: String -> String -> BlockedRulesTree -> IO ()
writeBlockTree normalNodePath debugNodePath ( Node name patterns children ) =
writeBlockTree :: String -> BlockedRulesTree -> IO ()
writeBlockTree normalNodePath (Node name patterns children) =
do
createDirectoryIfMissing True normalPath
-- createDirectoryIfMissing True debugPath
_ < - sequence ( writeBlockTree normalPath debugPath < $ > children )
writePatterns [ " See for sources info " ] normalFilename debugFilename patterns
_ <- sequence (writeBlockTree normalPath <$> children)
writePatterns ["See ab2p.common.css for sources info"] normalFilename patterns
where
normalPath
| null name = normalNodePath
| otherwise = normalNodePath </> name
-- debugPath
-- | null name = debugNodePath
-- | otherwise = debugNodePath </> name
normalFilename = normalPath </> "ab2p.css"
-- debugFilename = debugPath </> "ab2p.css"
writePatterns_with_debug :: [String] -> String -> String -> [Pattern] -> IO ()
writePatterns_with_debug _ _ _ [] = return ()
writePatterns_with_debug info' normalFilename debugFilename patterns =
do
writeCssFile debugFilename $ intercalate "\n" $ (++ Templates.blockCss) <$> patterns
writeCssFile normalFilename $ intercalate "\n" ((++ Templates.blockCss) . intercalate "," <$>
splitEvery 4000 patterns)
where
splitEvery n = takeWhile (not . null) . unfoldr (Just . splitAt n)
writeCssFile filename content =
do outFile <- openFile filename WriteMode
hSetEncoding outFile utf8
hPutStrLn outFile "/*"
_ <- mapM (hPutStrLn outFile) info'
hPutStrLn outFile "*/"
hPutStrLn outFile content
hClose outFile
writePatterns :: [String] -> String -> [Pattern] -> IO ()
writePatterns _ _ [] = return ()
writePatterns info' normalFilename patterns =
do
-- writeCssFile debugFilename $ intercalate "\n" $ (++ Templates.blockCss) <$> patterns
writeCssFile normalFilename $ intercalate "\n" ((++ Templates.blockCss) . intercalate "," <$>
splitEvery 4000 patterns)
where
splitEvery n = takeWhile (not . null) . unfoldr (Just . splitAt n)
writeCssFile filename content =
do outFile <- openFile filename WriteMode
hSetEncoding outFile utf8
hPutStrLn outFile "/*"
_ <- mapM (hPutStrLn outFile) info'
hPutStrLn outFile "*/"
hPutStrLn outFile content
hClose outFile
elemBlockData :: [Line] -> ElemBlockData
elemBlockData input = ElemBlockData
(Map.foldrWithKey appendFlatPattern [] policyTreeMap)
(Map.foldrWithKey appendTreePattern (Node "" [] []) policyTreeMap)
where
policyTreeMap :: Map.Map String PolicyTree
policyTreeMap = Map.unionWith (trimTree Block .*. mergePolicyTrees Unblock)
blockLinesMap
(erasePolicy Block <$> unblockLinesMap)
where
blockLinesMap = Map.fromListWith (mergeAndTrim Block) (mapMaybe blockLine input)
unblockLinesMap = Map.fromListWith (mergeAndTrim Unblock) (mapMaybe unblockLine input)
unblockLine (Line _ (ElementHide domains InputParser.Unblock pattern)) = (,) pattern <$> restrictionsTree Unblock domains
unblockLine _ = Nothing
blockLine (Line _ (ElementHide domains InputParser.Block pattern)) = (,) pattern <$> restrictionsTree Block domains
blockLine _ = Nothing
appendTreePattern :: Pattern -> PolicyTree -> BlockedRulesTree -> BlockedRulesTree
appendTreePattern pattern policyTree
| null $ _children policyTree = id
| otherwise = mergeTrees appendPattern policyTree
where appendPattern policy patterns = case policy of
Block -> pattern:patterns
_ -> patterns
appendFlatPattern :: Pattern -> PolicyTree -> [Pattern] -> [Pattern]
appendFlatPattern pattern policyTree patterns
| null (_children policyTree) && _value policyTree == Block = pattern:patterns
| otherwise = patterns
| null | https://raw.githubusercontent.com/essandess/adblock2privoxy/68affb86af325b88beaa7acda8866ad9b1d030f2/adblock2privoxy/src/ElementBlocker.hs | haskell | writeBlockTree :: String -> String -> BlockedRulesTree -> IO ()
createDirectoryIfMissing True debugPath
debugPath
| null name = debugNodePath
| otherwise = debugNodePath </> name
debugFilename = debugPath </> "ab2p.css"
writeCssFile debugFilename $ intercalate "\n" $ (++ Templates.blockCss) <$> patterns | module ElementBlocker (
elemBlock
) where
import InputParser hiding (Policy(..))
import qualified InputParser
import PolicyTree
import qualified Data.Map as Map
import Data.Maybe
import Utils
import System.IO
import System.FilePath
import Data.List
import System.Directory
import qualified Templates
import Control.Monad
import Data.String.Utils (startswith)
type BlockedRulesTree = DomainTree [Pattern]
data ElemBlockData = ElemBlockData [Pattern] BlockedRulesTree deriving Show
elemBlock :: String -> [String] -> [Line] -> IO ()
elemBlock path info = writeElemBlock . elemBlockData
where
writeElemBlock :: ElemBlockData -> IO ()
writeElemBlock (ElemBlockData flatPatterns rulesTree) =
do
let debugPath = path </> "debug"
filteredInfo = filter ((||) <$> not . startswith "Url:" <*> startswith "Url: http") info
createDirectoryIfMissing True path
cont <- getDirectoryContents path
_ <- sequence $ removeOld <$> cont
createDirectoryIfMissing True debugPath
writeBlockTree path debugPath rulesTree
writeBlockTree path rulesTree
writePatterns_with_debug filteredInfo (path </> "ab2p.common.css") (debugPath </> "ab2p.common.css") flatPatterns
removeOld entry' =
let entry = path </> entry'
in do
isDir <- doesDirectoryExist entry
if isDir then when (head entry' /= '.') $ removeDirectoryRecursive entry
else when (takeExtension entry == ".css") $ removeFile entry
writeBlockTree normalNodePath debugNodePath ( Node name patterns children ) =
writeBlockTree :: String -> BlockedRulesTree -> IO ()
writeBlockTree normalNodePath (Node name patterns children) =
do
createDirectoryIfMissing True normalPath
_ < - sequence ( writeBlockTree normalPath debugPath < $ > children )
writePatterns [ " See for sources info " ] normalFilename debugFilename patterns
_ <- sequence (writeBlockTree normalPath <$> children)
writePatterns ["See ab2p.common.css for sources info"] normalFilename patterns
where
normalPath
| null name = normalNodePath
| otherwise = normalNodePath </> name
normalFilename = normalPath </> "ab2p.css"
writePatterns_with_debug :: [String] -> String -> String -> [Pattern] -> IO ()
writePatterns_with_debug _ _ _ [] = return ()
writePatterns_with_debug info' normalFilename debugFilename patterns =
do
writeCssFile debugFilename $ intercalate "\n" $ (++ Templates.blockCss) <$> patterns
writeCssFile normalFilename $ intercalate "\n" ((++ Templates.blockCss) . intercalate "," <$>
splitEvery 4000 patterns)
where
splitEvery n = takeWhile (not . null) . unfoldr (Just . splitAt n)
writeCssFile filename content =
do outFile <- openFile filename WriteMode
hSetEncoding outFile utf8
hPutStrLn outFile "/*"
_ <- mapM (hPutStrLn outFile) info'
hPutStrLn outFile "*/"
hPutStrLn outFile content
hClose outFile
writePatterns :: [String] -> String -> [Pattern] -> IO ()
writePatterns _ _ [] = return ()
writePatterns info' normalFilename patterns =
do
writeCssFile normalFilename $ intercalate "\n" ((++ Templates.blockCss) . intercalate "," <$>
splitEvery 4000 patterns)
where
splitEvery n = takeWhile (not . null) . unfoldr (Just . splitAt n)
writeCssFile filename content =
do outFile <- openFile filename WriteMode
hSetEncoding outFile utf8
hPutStrLn outFile "/*"
_ <- mapM (hPutStrLn outFile) info'
hPutStrLn outFile "*/"
hPutStrLn outFile content
hClose outFile
elemBlockData :: [Line] -> ElemBlockData
elemBlockData input = ElemBlockData
(Map.foldrWithKey appendFlatPattern [] policyTreeMap)
(Map.foldrWithKey appendTreePattern (Node "" [] []) policyTreeMap)
where
policyTreeMap :: Map.Map String PolicyTree
policyTreeMap = Map.unionWith (trimTree Block .*. mergePolicyTrees Unblock)
blockLinesMap
(erasePolicy Block <$> unblockLinesMap)
where
blockLinesMap = Map.fromListWith (mergeAndTrim Block) (mapMaybe blockLine input)
unblockLinesMap = Map.fromListWith (mergeAndTrim Unblock) (mapMaybe unblockLine input)
unblockLine (Line _ (ElementHide domains InputParser.Unblock pattern)) = (,) pattern <$> restrictionsTree Unblock domains
unblockLine _ = Nothing
blockLine (Line _ (ElementHide domains InputParser.Block pattern)) = (,) pattern <$> restrictionsTree Block domains
blockLine _ = Nothing
appendTreePattern :: Pattern -> PolicyTree -> BlockedRulesTree -> BlockedRulesTree
appendTreePattern pattern policyTree
| null $ _children policyTree = id
| otherwise = mergeTrees appendPattern policyTree
where appendPattern policy patterns = case policy of
Block -> pattern:patterns
_ -> patterns
appendFlatPattern :: Pattern -> PolicyTree -> [Pattern] -> [Pattern]
appendFlatPattern pattern policyTree patterns
| null (_children policyTree) && _value policyTree == Block = pattern:patterns
| otherwise = patterns
|
12d9cbc233b097b7aae618e3b6a07f95e0b4f68a7b2957fe44a6a34603528b69 | logicmoo/logicmoo_nlu | fchart.lsp | ;;; % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Example code from the book " Natural Language Processing in LISP " %
% published by %
% Copyright ( c ) 1989 , . %
;;; % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
;;;
fchart.lsp [ Chapter 7 ] chart parser for PATR grammars
A version that does with lexical lookup bottom - up
;;;
(uses 'lisppatr)
(uses 'subsumes)
(defvar rules)
(defvar lexical_rules)
(defvar chart)
(defvar agenda)
(defvar existing_goals)
existing_goals is used to hold a dag of the form
( ( cat c ) ( START s ) ( & .. ) ) ,
;;; where c is a category and s a starting position
in the chart . The presence of one of these in existing_goals
indicates that we have already tried ( ) looking for instances
;;; of the specified category starting at the specified position
an edge is a list of 5 elements :
;; start finish label found tofind
(defun start (edge)
(nth 0 edge))
(defun finish (edge)
(nth 1 edge))
(defun label (edge)
(nth 2 edge))
(defun found (edge)
(nth 3 edge))
(defun tofind (edge)
(nth 4 edge))
;;; add an edge to the chart, recording any new edges that may need
;;; to be added as a consequence
(defun add_edge (edge)
(setq chart (cons edge chart))
(if (null (tofind edge)) ; added edge is inactive
(progn
(dolist (chartedge chart)
(if (not (null (tofind chartedge))) ; an active edge
(check_and_combine chartedge edge)))
(inactive_edge_function edge))
(progn ; otherwise added edge is active
(dolist (chartedge chart)
(if (null (tofind chartedge)) ; an inactive edge
(check_and_combine edge chartedge)))
(active_edge_function edge))))
;;; try to combine an active and inactive edge
;;; using the fundamental rule
;;; add a new edge to agenda if these can combine
(defun check_and_combine (active_edge inactive_edge)
(if (equal (start inactive_edge) (finish active_edge))
(let ((subst (unify (label inactive_edge) (car (tofind active_edge)))))
(if subst
(let (
(subtrees
(append (found active_edge)
(list
(tree
(category (label inactive_edge) subst)
(found inactive_edge))))))
(agenda_add
(rename
(apply_subst subst
(list ;; new edge
(start active_edge)
(finish inactive_edge)
(label active_edge)
subtrees
(cdr (tofind active_edge)))))))))))
;;; initialize the chart (top-down version)
(defun initialize_chart (goal string)
;; add lexical edges
;; try each lexical rule in turn on each position in the chart
;; this is inefficient
(do (
(restwords string (cdr restwords))
(vertex 0 (+ 1 vertex)))
((null restwords))
(dolist (rule lexical_rules)
(let ((subst_others (rhs_match restwords rule)))
(if (car subst_others) ; if subst not nil
(let ((needed (ldiff restwords (cdadr subst_others))))
(agenda_add
(list
vertex
(+ vertex (length needed))
(rename (caadr subst_others))
needed
nil)))))))
;; add goal edge
(add_rules_to_expand goal 0))
;;; top level function
(defun chart_parse (goal string)
(setq agenda nil)
(setq chart nil)
(setq existing_goals nil)
(initialize_chart goal string)
(do
((edge (car agenda) (car agenda)))
((null agenda))
;; do until agenda empty
(setq agenda (cdr agenda))
(add_edge edge)
;; add and combine edge with chart
)
(let ((parses ())) ; find complete parses
(dolist (edge chart parses)
(if (and
(equal (start edge) 0)
(equal (finish edge) (length string)) ; end of string
(null (tofind edge)) ; edge complete
(unify (label edge) goal)) ; recognizes goal
(setq parses
(cons
(tree
(category (label edge) empty_subst)
(found edge))
parses))))))
;;; other top-down parsing functions
;;; (no bottom-up operations here)
(defun inactive_edge_function (x) t)
;;; The topdown rule
;;;
;;; The topdown rule is invoked when an edge requiring a next phrase of
category subgoal is added . Now subgoal may be a very general
;;; category and hence not subsumed by any category already recorded in
existing_goals . When subgoal is unified with the LHS of a rule ,
;;; however, the result will be more specific and may be subsumed by
;;; an existing goal. So subsumption by an existing goal is tested
after unification with the LHS of a rule . On the other hand , once
;;; all the rules have been through, all ways of finding an instance
of the original subgoal category category have been tried , and so
;;; it is this general category that is put into a new entry in
;;; existing_goals
(defun active_edge_function (edge)
(add_rules_to_expand (car (tofind edge)) (finish edge)))
(defun add_rules_to_expand (goal vertex)
(dolist (rule rules)
(let
((subst_rhs (lhs_match goal rule)))
(if (car subst_rhs)
(let* (
(LHS (apply_subst (car subst_rhs) goal))
(RHS (cadr subst_rhs)))
(if (not (subsumed_goal LHS vertex))
;; if goal not subsumed, add the new edge,
;; renaming so that it can combine with other
;; edges from rules using the same variable
;; symbols (e.g. edges from the same rule that just
;; produced it)
(agenda_add
(rename
(list
vertex
vertex
LHS
nil
RHS))))))))
(record_goal goal vertex))
look to see whether a particular category , or one more
;;; general than it, has been looked for at a given vertex
(defun subsumed_goal (goal vertex)
(let ((goaldag
(list
(list 'goal goal)
(list 'vertex vertex)
(list '& (newvar)))))
(dolist (g existing_goals nil)
(if (subsumes g goaldag)
(return t)))))
;;; record that a particular category has been searched for
;;; at a given vertex
(defun record_goal (goal vertex)
(setq existing_goals
(cons
(list
(list 'goal goal)
(list 'vertex vertex)
(list '& (newvar)))
existing_goals)))
Add an edge to the agenda . In parsing , the only way that
;;; duplicate edges can be introduced is via the topdown rule (as
;;; long as there are no duplicate edges, the fundamental rule cannot
;;; possibly create any). So for efficiency the checking of duplications
is done in active_edge_function .
(defun agenda_add (edge)
(setq agenda (cons edge agenda)))
| null | https://raw.githubusercontent.com/logicmoo/logicmoo_nlu/c066897f55b3ff45aa9155ebcf799fda9741bf74/ext/nlp_book/lisp/fchart.lsp | lisp | % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
where c is a category and s a starting position
of the specified category starting at the specified position
start finish label found tofind
add an edge to the chart, recording any new edges that may need
to be added as a consequence
added edge is inactive
an active edge
otherwise added edge is active
an inactive edge
try to combine an active and inactive edge
using the fundamental rule
add a new edge to agenda if these can combine
new edge
initialize the chart (top-down version)
add lexical edges
try each lexical rule in turn on each position in the chart
this is inefficient
if subst not nil
add goal edge
top level function
do until agenda empty
add and combine edge with chart
find complete parses
end of string
edge complete
recognizes goal
other top-down parsing functions
(no bottom-up operations here)
The topdown rule
The topdown rule is invoked when an edge requiring a next phrase of
category and hence not subsumed by any category already recorded in
however, the result will be more specific and may be subsumed by
an existing goal. So subsumption by an existing goal is tested
all the rules have been through, all ways of finding an instance
it is this general category that is put into a new entry in
existing_goals
if goal not subsumed, add the new edge,
renaming so that it can combine with other
edges from rules using the same variable
symbols (e.g. edges from the same rule that just
produced it)
general than it, has been looked for at a given vertex
record that a particular category has been searched for
at a given vertex
duplicate edges can be introduced is via the topdown rule (as
long as there are no duplicate edges, the fundamental rule cannot
possibly create any). So for efficiency the checking of duplications | % Example code from the book " Natural Language Processing in LISP " %
% published by %
% Copyright ( c ) 1989 , . %
fchart.lsp [ Chapter 7 ] chart parser for PATR grammars
A version that does with lexical lookup bottom - up
(uses 'lisppatr)
(uses 'subsumes)
(defvar rules)
(defvar lexical_rules)
(defvar chart)
(defvar agenda)
(defvar existing_goals)
existing_goals is used to hold a dag of the form
( ( cat c ) ( START s ) ( & .. ) ) ,
in the chart . The presence of one of these in existing_goals
indicates that we have already tried ( ) looking for instances
an edge is a list of 5 elements :
(defun start (edge)
(nth 0 edge))
(defun finish (edge)
(nth 1 edge))
(defun label (edge)
(nth 2 edge))
(defun found (edge)
(nth 3 edge))
(defun tofind (edge)
(nth 4 edge))
(defun add_edge (edge)
(setq chart (cons edge chart))
(progn
(dolist (chartedge chart)
(check_and_combine chartedge edge)))
(inactive_edge_function edge))
(dolist (chartedge chart)
(check_and_combine edge chartedge)))
(active_edge_function edge))))
(defun check_and_combine (active_edge inactive_edge)
(if (equal (start inactive_edge) (finish active_edge))
(let ((subst (unify (label inactive_edge) (car (tofind active_edge)))))
(if subst
(let (
(subtrees
(append (found active_edge)
(list
(tree
(category (label inactive_edge) subst)
(found inactive_edge))))))
(agenda_add
(rename
(apply_subst subst
(start active_edge)
(finish inactive_edge)
(label active_edge)
subtrees
(cdr (tofind active_edge)))))))))))
(defun initialize_chart (goal string)
(do (
(restwords string (cdr restwords))
(vertex 0 (+ 1 vertex)))
((null restwords))
(dolist (rule lexical_rules)
(let ((subst_others (rhs_match restwords rule)))
(let ((needed (ldiff restwords (cdadr subst_others))))
(agenda_add
(list
vertex
(+ vertex (length needed))
(rename (caadr subst_others))
needed
nil)))))))
(add_rules_to_expand goal 0))
(defun chart_parse (goal string)
(setq agenda nil)
(setq chart nil)
(setq existing_goals nil)
(initialize_chart goal string)
(do
((edge (car agenda) (car agenda)))
((null agenda))
(setq agenda (cdr agenda))
(add_edge edge)
)
(dolist (edge chart parses)
(if (and
(equal (start edge) 0)
(setq parses
(cons
(tree
(category (label edge) empty_subst)
(found edge))
parses))))))
(defun inactive_edge_function (x) t)
category subgoal is added . Now subgoal may be a very general
existing_goals . When subgoal is unified with the LHS of a rule ,
after unification with the LHS of a rule . On the other hand , once
of the original subgoal category category have been tried , and so
(defun active_edge_function (edge)
(add_rules_to_expand (car (tofind edge)) (finish edge)))
(defun add_rules_to_expand (goal vertex)
(dolist (rule rules)
(let
((subst_rhs (lhs_match goal rule)))
(if (car subst_rhs)
(let* (
(LHS (apply_subst (car subst_rhs) goal))
(RHS (cadr subst_rhs)))
(if (not (subsumed_goal LHS vertex))
(agenda_add
(rename
(list
vertex
vertex
LHS
nil
RHS))))))))
(record_goal goal vertex))
look to see whether a particular category , or one more
(defun subsumed_goal (goal vertex)
(let ((goaldag
(list
(list 'goal goal)
(list 'vertex vertex)
(list '& (newvar)))))
(dolist (g existing_goals nil)
(if (subsumes g goaldag)
(return t)))))
(defun record_goal (goal vertex)
(setq existing_goals
(cons
(list
(list 'goal goal)
(list 'vertex vertex)
(list '& (newvar)))
existing_goals)))
Add an edge to the agenda . In parsing , the only way that
is done in active_edge_function .
(defun agenda_add (edge)
(setq agenda (cons edge agenda)))
|
91601fc9465624d5c58f514a8373bc2ec5e1f669253e4c06a0d78f3333673d94 | tweag/linear-base | ReplicationStream.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE LinearTypes #-}
# LANGUAGE NoImplicitPrelude #
{-# OPTIONS_HADDOCK hide #-}
module Data.Replicator.Linear.Internal.ReplicationStream
( ReplicationStream (..),
consume,
duplicate,
map,
pure,
(<*>),
liftA2,
)
where
import Data.Unrestricted.Linear.Internal.Ur
import Prelude.Linear.Internal
-- | @ReplicationStream s g dup2 c@ is the infinite linear stream
-- @repeat (g s)@ where @dup2@ is used to make as many copies of @s@ as
necessary , and @c@ is used to consume @s@ when consuming the stream .
--
-- Although it isn't enforced at type level, @dup2@ should abide by the same
-- laws as 'Data.Unrestricted.Linear.dup2':
* @first c ( dup2 a ) ≃ a ≃ second c ( dup2 a)@ ( neutrality )
* @first dup2 ( dup2 a ) ≃ ( second dup2 ( dup2 a))@ ( associativity )
--
-- This type is solely used to implement 'Data.Replicator.Linear'
data ReplicationStream a where
ReplicationStream ::
s %1 ->
(s %1 -> a) ->
(s %1 -> (s, s)) ->
(s %1 -> ()) ->
ReplicationStream a
consume :: ReplicationStream a %1 -> ()
consume (ReplicationStream s _ _ consumes) = consumes s
# INLINEABLE consume #
duplicate :: ReplicationStream a %1 -> ReplicationStream (ReplicationStream a)
duplicate (ReplicationStream s give dups consumes) =
ReplicationStream
s
(\s' -> ReplicationStream s' give dups consumes)
dups
consumes
map :: (a %1 -> b) -> ReplicationStream a %1 -> ReplicationStream b
map f (ReplicationStream s give dups consumes) =
ReplicationStream s (f . give) dups consumes
pure :: a -> ReplicationStream a
pure x =
ReplicationStream
(Ur x)
unur
( \case
Ur x' -> (Ur x', Ur x')
)
( \case
Ur _ -> ()
)
(<*>) :: ReplicationStream (a %1 -> b) %1 -> ReplicationStream a %1 -> ReplicationStream b
(ReplicationStream sf givef dupsf consumesf) <*> (ReplicationStream sx givex dupsx consumesx) =
ReplicationStream
(sf, sx)
(\(sf', sx') -> givef sf' (givex sx'))
( \(sf', sx') ->
(dupsf sf', dupsx sx') & \case
((sf1, sf2), (sx1, sx2)) -> ((sf1, sx1), (sf2, sx2))
)
( \(sf', sx') ->
consumesf sf' & \case
() -> consumesx sx'
)
liftA2 :: (a %1 -> b %1 -> c) -> ReplicationStream a %1 -> ReplicationStream b %1 -> ReplicationStream c
liftA2 f (ReplicationStream sa givea dupsa consumesa) (ReplicationStream sb giveb dupsb consumesb) =
ReplicationStream
(sa, sb)
(\(sa', sb') -> f (givea sa') (giveb sb'))
( \(sa', sb') ->
(dupsa sa', dupsb sb') & \case
((sa1, sa2), (sb1, sb2)) -> ((sa1, sb1), (sa2, sb2))
)
( \(sa', sb') ->
consumesa sa' & \case
() -> consumesb sb'
)
-- We need to inline this to get good results with generic deriving
of Dupable .
# INLINE liftA2 #
infixl 4 <*> -- same fixity as base.<*>
| null | https://raw.githubusercontent.com/tweag/linear-base/9d82f67f1415dda385a6349954bf55f9bfa4e62e/src/Data/Replicator/Linear/Internal/ReplicationStream.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE LinearTypes #
# OPTIONS_HADDOCK hide #
| @ReplicationStream s g dup2 c@ is the infinite linear stream
@repeat (g s)@ where @dup2@ is used to make as many copies of @s@ as
Although it isn't enforced at type level, @dup2@ should abide by the same
laws as 'Data.Unrestricted.Linear.dup2':
This type is solely used to implement 'Data.Replicator.Linear'
We need to inline this to get good results with generic deriving
same fixity as base.<*> | # LANGUAGE LambdaCase #
# LANGUAGE NoImplicitPrelude #
module Data.Replicator.Linear.Internal.ReplicationStream
( ReplicationStream (..),
consume,
duplicate,
map,
pure,
(<*>),
liftA2,
)
where
import Data.Unrestricted.Linear.Internal.Ur
import Prelude.Linear.Internal
necessary , and @c@ is used to consume @s@ when consuming the stream .
* @first c ( dup2 a ) ≃ a ≃ second c ( dup2 a)@ ( neutrality )
* @first dup2 ( dup2 a ) ≃ ( second dup2 ( dup2 a))@ ( associativity )
data ReplicationStream a where
ReplicationStream ::
s %1 ->
(s %1 -> a) ->
(s %1 -> (s, s)) ->
(s %1 -> ()) ->
ReplicationStream a
consume :: ReplicationStream a %1 -> ()
consume (ReplicationStream s _ _ consumes) = consumes s
# INLINEABLE consume #
duplicate :: ReplicationStream a %1 -> ReplicationStream (ReplicationStream a)
duplicate (ReplicationStream s give dups consumes) =
ReplicationStream
s
(\s' -> ReplicationStream s' give dups consumes)
dups
consumes
map :: (a %1 -> b) -> ReplicationStream a %1 -> ReplicationStream b
map f (ReplicationStream s give dups consumes) =
ReplicationStream s (f . give) dups consumes
pure :: a -> ReplicationStream a
pure x =
ReplicationStream
(Ur x)
unur
( \case
Ur x' -> (Ur x', Ur x')
)
( \case
Ur _ -> ()
)
(<*>) :: ReplicationStream (a %1 -> b) %1 -> ReplicationStream a %1 -> ReplicationStream b
(ReplicationStream sf givef dupsf consumesf) <*> (ReplicationStream sx givex dupsx consumesx) =
ReplicationStream
(sf, sx)
(\(sf', sx') -> givef sf' (givex sx'))
( \(sf', sx') ->
(dupsf sf', dupsx sx') & \case
((sf1, sf2), (sx1, sx2)) -> ((sf1, sx1), (sf2, sx2))
)
( \(sf', sx') ->
consumesf sf' & \case
() -> consumesx sx'
)
liftA2 :: (a %1 -> b %1 -> c) -> ReplicationStream a %1 -> ReplicationStream b %1 -> ReplicationStream c
liftA2 f (ReplicationStream sa givea dupsa consumesa) (ReplicationStream sb giveb dupsb consumesb) =
ReplicationStream
(sa, sb)
(\(sa', sb') -> f (givea sa') (giveb sb'))
( \(sa', sb') ->
(dupsa sa', dupsb sb') & \case
((sa1, sa2), (sb1, sb2)) -> ((sa1, sb1), (sa2, sb2))
)
( \(sa', sb') ->
consumesa sa' & \case
() -> consumesb sb'
)
of Dupable .
# INLINE liftA2 #
|
36b0f91aaa42c0dc330b2563eae3ffe7ba4c5021ee7246d9f405accfcf31d2e1 | clojure-lsp/clojure-lsp | a.clj | (ns sample-test.definition.a
(:require [clojure.spec.alpha :as s]))
(def some-var 1)
(defn some-public-func [a]
a)
(defn ^:private some-private-func []
(+ 1 some-var))
(some-private-func)
(s/def ::my-key 1)
(cond-> [])
| null | https://raw.githubusercontent.com/clojure-lsp/clojure-lsp/3108aedbd4ccd07adc42e520d6f1bd75ea1b546d/cli/integration-test/sample-test/src/sample_test/definition/a.clj | clojure | (ns sample-test.definition.a
(:require [clojure.spec.alpha :as s]))
(def some-var 1)
(defn some-public-func [a]
a)
(defn ^:private some-private-func []
(+ 1 some-var))
(some-private-func)
(s/def ::my-key 1)
(cond-> [])
|
|
85af6ecef6c22d3510f7005a22cb3a0cae35a17cd6b430af94eb09bfa0c9a9a7 | jiangpengnju/htdp2e | ex45.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex45) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
; Let's work through the same problem statement with a time-based data definition.
; How do you think this program relates to the animate function?
; A: (animate render) acts similar to (main 0), except that no end? feature.
(require 2htdp/universe)
(require 2htdp/image)
1 . Define Constants
;; a. "Physical" constants
(define WIDTH-OF-WORLD 400)
(define HEIGHT-OF-WORLD 40)
(define WHEEL-RADIUS 5)
(define WHEEL-DISTANCE (* WHEEL-RADIUS 5))
;; b. Graphical constants
(define TREE
(underlay/xy (circle 10 "solid" "green")
9 15
(rectangle 2 20 "solid" "brown")))
(define BACKGROUND
(place-image TREE
100 (- HEIGHT-OF-WORLD (/ (image-height TREE) 2))
(empty-scene WIDTH-OF-WORLD HEIGHT-OF-WORLD)))
(define WHEEL (circle WHEEL-RADIUS "solid" "black"))
(define SPACE (rectangle WHEEL-DISTANCE WHEEL-RADIUS "solid" "white"))
(define BOTH-WHEELS (beside WHEEL SPACE WHEEL))
(define CAR-BODY (above (rectangle (* WHEEL-RADIUS 7) WHEEL-RADIUS "solid" "red")
(rectangle (* WHEEL-RADIUS 11) (* WHEEL-RADIUS 2) "solid" "red")))
(define CAR (overlay/align/offset "middle" "bottom"
BOTH-WHEELS
0 (- WHEEL-RADIUS)
CAR-BODY))
(define Y-CAR (- HEIGHT-OF-WORLD (/ (image-height CAR) 2)))
(define WIDTH-OF-CAR (image-width CAR))
(define V 3)
2 . Data Definition of the state of the world
AnimationState is a Number
; interpretation: the number of clock ticks since the animation started.
3 . Design functions for big - bang expression
AnimationState - > Image
; place the image of the car the BACKGROUND image after x ticks.
(check-expect (render 50) (place-image CAR (distance 50) Y-CAR BACKGROUND))
(check-expect (render 200) (place-image CAR (distance 200) Y-CAR BACKGROUND))
(define (render x)
(place-image CAR (distance x) Y-CAR BACKGROUND))
AnimationState - > AnimationState
adds 1 tick to x
(check-expect (tock 20) 21)
(check-expect (tock 55) 56)
(define (tock x)
(+ x 1))
AnimationState - > Boolean
; find whether the car has disappeared on the right side of the canvas
(check-expect (end? (/ (- WIDTH-OF-WORLD 1) V)) #false)
(check-expect (end? (/ (+ WIDTH-OF-WORLD WIDTH-OF-CAR) V)) #true)
(check-expect (end? (/ (+ WIDTH-OF-WORLD (/ WIDTH-OF-CAR 2)) V)) #true)
(define (end? x)
(>= (distance x) (+ WIDTH-OF-WORLD (/ WIDTH-OF-CAR 2))))
; Number -> Number
; calculate distance within x ticks
(define (distance x)
(* V x))
4 . Define main function
; WorldState -> WorldState
; launches the program from some initial state ws
(define (main ws)
(big-bang ws
[on-tick tock]
[to-draw render]
[stop-when end?]))
| null | https://raw.githubusercontent.com/jiangpengnju/htdp2e/d41555519fbb378330f75c88141f72b00a9ab1d3/fixed-size-data/how-to-design-programs/ex45.rkt | racket | about the language level of this file in a form that our tools can easily process.
Let's work through the same problem statement with a time-based data definition.
How do you think this program relates to the animate function?
A: (animate render) acts similar to (main 0), except that no end? feature.
a. "Physical" constants
b. Graphical constants
interpretation: the number of clock ticks since the animation started.
place the image of the car the BACKGROUND image after x ticks.
find whether the car has disappeared on the right side of the canvas
Number -> Number
calculate distance within x ticks
WorldState -> WorldState
launches the program from some initial state ws | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex45) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(require 2htdp/universe)
(require 2htdp/image)
1 . Define Constants
(define WIDTH-OF-WORLD 400)
(define HEIGHT-OF-WORLD 40)
(define WHEEL-RADIUS 5)
(define WHEEL-DISTANCE (* WHEEL-RADIUS 5))
(define TREE
(underlay/xy (circle 10 "solid" "green")
9 15
(rectangle 2 20 "solid" "brown")))
(define BACKGROUND
(place-image TREE
100 (- HEIGHT-OF-WORLD (/ (image-height TREE) 2))
(empty-scene WIDTH-OF-WORLD HEIGHT-OF-WORLD)))
(define WHEEL (circle WHEEL-RADIUS "solid" "black"))
(define SPACE (rectangle WHEEL-DISTANCE WHEEL-RADIUS "solid" "white"))
(define BOTH-WHEELS (beside WHEEL SPACE WHEEL))
(define CAR-BODY (above (rectangle (* WHEEL-RADIUS 7) WHEEL-RADIUS "solid" "red")
(rectangle (* WHEEL-RADIUS 11) (* WHEEL-RADIUS 2) "solid" "red")))
(define CAR (overlay/align/offset "middle" "bottom"
BOTH-WHEELS
0 (- WHEEL-RADIUS)
CAR-BODY))
(define Y-CAR (- HEIGHT-OF-WORLD (/ (image-height CAR) 2)))
(define WIDTH-OF-CAR (image-width CAR))
(define V 3)
2 . Data Definition of the state of the world
AnimationState is a Number
3 . Design functions for big - bang expression
AnimationState - > Image
(check-expect (render 50) (place-image CAR (distance 50) Y-CAR BACKGROUND))
(check-expect (render 200) (place-image CAR (distance 200) Y-CAR BACKGROUND))
(define (render x)
(place-image CAR (distance x) Y-CAR BACKGROUND))
AnimationState - > AnimationState
adds 1 tick to x
(check-expect (tock 20) 21)
(check-expect (tock 55) 56)
(define (tock x)
(+ x 1))
AnimationState - > Boolean
(check-expect (end? (/ (- WIDTH-OF-WORLD 1) V)) #false)
(check-expect (end? (/ (+ WIDTH-OF-WORLD WIDTH-OF-CAR) V)) #true)
(check-expect (end? (/ (+ WIDTH-OF-WORLD (/ WIDTH-OF-CAR 2)) V)) #true)
(define (end? x)
(>= (distance x) (+ WIDTH-OF-WORLD (/ WIDTH-OF-CAR 2))))
(define (distance x)
(* V x))
4 . Define main function
(define (main ws)
(big-bang ws
[on-tick tock]
[to-draw render]
[stop-when end?]))
|
1129c7250f6b31cb21ed88a092004e8a4577893fbd5554904dec98242aeea74b | bobzhang/fan | big.ml |
let f a c =
a.{1,2,3} <- c
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/test/printer/big.ml | ocaml |
let f a c =
a.{1,2,3} <- c
|
|
836f81e5d7059874ca24151223c9fd176aaea91a4e6df0ec557bdef99617482a | kmonad/kmonad | Keycode.hs | {-# LANGUAGE DeriveAnyClass, CPP #-}
|
Module : KMonad . Keyboard .
Description : Description of all possible keycodes .
Copyright : ( c ) , 2019
License : MIT
Maintainer :
Stability : experimental
Portability : portable
' 's are represented as a large enum lining up the keycodes defined in the Linux headers .
Module : KMonad.Keyboard.Keycode
Description : Description of all possible keycodes.
Copyright : (c) David Janssen, 2019
License : MIT
Maintainer :
Stability : experimental
Portability : portable
'Keycode's are represented as a large enum lining up the keycodes defined in the Linux headers.
-}
module KMonad.Keyboard.Keycode
* The core type
-- $typ
Keycode(..)
* Naming utilities to refer to Keycodes
-- $names
, keyNames
)
where
import KMonad.Prelude
import qualified KMonad.Util.MultiMap as Q
import qualified RIO.HashSet as S
import qualified RIO.Text as T
import qualified RIO.Text.Partial as T (head)
--------------------------------------------------------------------------------
-- $typ
--
' 's are defined as a large ADT that mimics the keycodes from the Linux
-- headers:
-- -event-codes.h.
--
-- Anywhere there are missing regions in the linux headers, we've defined
@MissingXX@ values for the ADT .
--
Calling ' RIO.Partial.toEnum ' on a Linux keycode value should produce the
corresponding ' ' value and vice - versa .
| The ' ' datatype , as an ' ' of all the values a ' ' can take .
data Keycode
= KeyReserved
| KeyEsc
| Key1
| Key2
| Key3
| Key4
| Key5
| Key6
| Key7
| Key8
| Key9
| Key0
| KeyMinus
| KeyEqual
| KeyBackspace
| KeyTab
| KeyQ
| KeyW
| KeyE
| KeyR
| KeyT
| KeyY
| KeyU
| KeyI
| KeyO
| KeyP
| KeyLeftBrace
| KeyRightBrace
| KeyEnter
| KeyLeftCtrl
| KeyA
| KeyS
| KeyD
| KeyF
| KeyG
| KeyH
| KeyJ
| KeyK
| KeyL
| KeySemicolon
| KeyApostrophe
| KeyGrave
| KeyLeftShift
| KeyBackslash
| KeyZ
| KeyX
| KeyC
| KeyV
| KeyB
| KeyN
| KeyM
| KeyComma
| KeyDot
| KeySlash
| KeyRightShift
| KeyKpAsterisk
| KeyLeftAlt
| KeySpace
| KeyCapsLock
| KeyF1
| KeyF2
| KeyF3
| KeyF4
| KeyF5
| KeyF6
| KeyF7
| KeyF8
| KeyF9
| KeyF10
| KeyNumLock
| KeyScrollLock
| KeyKp7
| KeyKp8
| KeyKp9
| KeyKpMinus
| KeyKp4
| KeyKp5
| KeyKp6
| KeyKpPlus
| KeyKp1
| KeyKp2
| KeyKp3
| KeyKp0
| KeyKpDot
| Missing84
| KeyZenkakuHankaku
| Key102nd
| KeyF11
| KeyF12
| KeyRo
| KeyKatakana
| KeyHiragana
| KeyHenkan
| KeyKatakanaHiragana
| KeyMuhenkan
| KeyKpjpcomma
| KeyKpEnter
| KeyRightCtrl
| KeyKpSlash
| KeySysRq
| KeyRightAlt
| KeyLinefeed
| KeyHome
| KeyUp
| KeyPageUp
| KeyLeft
| KeyRight
| KeyEnd
| KeyDown
| KeyPageDown
| KeyInsert
| KeyDelete
| KeyMacro
| KeyMute
| KeyVolumeDown
| KeyVolumeUp
| KeyPower
| KeyKpEqual
| KeyKpPlusMinus
| KeyPause
| KeyScale
| KeyKpComma
| KeyHangeul
| KeyHanja
| KeyYen
| KeyLeftMeta
| KeyRightMeta
| KeyCompose
| KeyStop
| KeyAgain
| KeyProps
| KeyUndo
| KeyFront
| KeyCopy
| KeyOpen
| KeyPaste
| KeyFind
| KeyCut
| KeyHelp
| KeyMenu
| KeyCalc
| KeySetup
| KeySleep
| KeyWakeUp
| KeyFile
| KeySendFile
| KeyDeleteFile
| KeyXfer
| KeyProg1
| KeyProg2
| KeyWww
| KeyMsDos
| KeyCoffee
| KeyDirection
| KeyCycleWindows
| KeyMail
| KeyBookmarks
| KeyComputer
| KeyBack
| KeyForward
| KeyCloseCd
| KeyEjectCd
| KeyEjectCloseCd
| KeyNextSong
| KeyPlayPause
| KeyPreviousSong
| KeyStopCd
| KeyRecord
| KeyRewind
| KeyPhone
| KeyIso
| KeyConfig
| KeyHomepage
| KeyRefresh
| KeyExit
| KeyMove
| KeyEdit
| KeyScrollUp
| KeyScrollDown
| KeyKpLeftParen
| KeyKpRightParen
| KeyNew
| KeyRedo
| KeyF13
| KeyF14
| KeyF15
| KeyF16
| KeyF17
| KeyF18
| KeyF19
| KeyF20
| KeyF21
| KeyF22
| KeyF23
| KeyF24
| Missing195
| Missing196
| Missing197
| Missing198
| Missing199
| KeyPlayCd
| KeyPauseCd
| KeyProg3
| KeyProg4
| KeyDashboard
| KeySuspend
| KeyClose
| KeyPlay
| KeyFastForward
| KeyBassBoost
| KeyPrint
| KeyHp
| KeyCamera
| KeySound
| KeyQuestion
| KeyEmail
| KeyChat
| KeySearch
| KeyConnect
| KeyFinance
| KeySport
| KeyShop
| KeyAlterase
| KeyCancel
| KeyBrightnessDown
| KeyBrightnessUp
| KeyMedia
| KeySwitchVideoMode
| KeyKbdIllumToggle
| KeyKbdIllumDown
| KeyKbdIllumUp
| KeySend
| KeyReply
| KeyForwardMail
| KeySave
| KeyDocuments
| KeyBattery
| KeyBluetooth
| KeyWlan
| KeyUwb
| KeyUnknown
| KeyVideoNext
| KeyVideoPrev
| KeyBrightnessCycle
| KeyBrightnessZero
| KeyDisplayOff
| KeyWimax
| Missing247
| Missing248
| Missing249
| Missing250
| Missing251
| Missing252
| Missing253
| Missing254
| Missing255
#ifdef darwin_HOST_OS
| KeyFn
| KeyLaunchpad
| KeyMissionCtrl
| KeySpotlight
| KeyDictation
#endif
deriving (Eq, Show, Bounded, Enum, Ord, Generic, Hashable)
instance Display Keycode where
textDisplay c = (\t -> "<" <> t <> ">") . fromMaybe (tshow c)
$ minimumByOf (_Just . folded) cmpName (keyNames ^. at c)
where cmpName a b =
-- Prefer the shortest, and if equal, lowercased version
case compare (T.length a) (T.length b) of
EQ -> compare (T.head b) (T.head a)
o -> o
--------------------------------------------------------------------------------
-- $sets
| The set of all existing ' '
kcAll :: S.HashSet Keycode
kcAll = S.fromList [minBound .. maxBound]
| The set of all ' ' that are not of the MissingXX pattern
kcNotMissing :: S.HashSet Keycode
kcNotMissing = S.fromList $ kcAll ^.. folded . filtered (T.isPrefixOf "Key" . tshow)
--------------------------------------------------------------------------------
-- $names
-- | Helper function to generate easy name maps
nameKC :: Foldable t
=> (Keycode -> Text)
-> t Keycode
-> Q.MultiMap Keycode Text
nameKC f = Q.mkMultiMap . map go . toList
where go k = (k, [f k, T.toLower $ f k])
| A collection of ' ' to ' Text ' mappings
keyNames :: Q.MultiMap Keycode Text
keyNames = mconcat
[ nameKC tshow kcAll
, nameKC (T.drop 3 . tshow) kcNotMissing
, aliases
]
-- | A collection of useful aliases to refer to keycode names
aliases :: Q.MultiMap Keycode Text
aliases = Q.mkMultiMap
[ (KeyEnter, ["ret", "return", "ent"])
, (KeyMinus, ["min", "-"])
, (KeyEqual, ["eql", "="])
, (KeySleep, ["zzz"])
, (KeySpace, ["spc"])
, (KeyPageUp, ["pgup"])
, (KeyPageDown, ["pgdn"])
, (KeyInsert, ["ins"])
, (KeyDelete, ["del"])
, (KeyVolumeUp, ["volu"])
, (KeyVolumeDown, ["voldwn", "vold"])
, (KeyBrightnessUp, ["brup", "bru"])
, (KeyBrightnessDown, ["brdown", "brdwn", "brdn"])
, (KeyLeftAlt, ["lalt", "alt"])
, (KeyRightAlt, ["ralt"])
, (KeyCompose, ["comp", "cmps", "cmp"])
, (KeyLeftShift, ["lshift", "lshft", "lsft", "shft", "sft"])
, (KeyRightShift, ["rshift", "rshft", "rsft"])
, (KeyLeftCtrl, ["lctrl", "lctl", "ctl"])
, (KeyRightCtrl, ["rctrl", "rctl"])
, (KeyLeftMeta, ["lmeta", "lmet", "met"])
, (KeyRightMeta, ["rmeta", "rmet"])
, (KeyBackspace, ["bks", "bspc"])
, (KeyCapsLock, ["caps"])
, (Key102nd, ["102d", "lsgt", "nubs"])
, (KeyForward, ["fwd"])
, (KeyScrollLock, ["scrlck", "slck"])
, (KeyScrollUp, ["scrup", "sup"])
, (KeyScrollDown, ["scrdn", "sdwn", "sdn"])
, (KeyPrint, ["prnt"])
, (KeyWakeUp, ["wkup"])
, (KeyLeft, ["lft"])
, (KeyRight, ["rght"])
, (KeyLeftBrace, ["lbrc", "["])
, (KeyRightBrace, ["rbrc", "]"])
, (KeySemicolon, ["scln", ";"])
, (KeyApostrophe, ["apos", "'", "apo"])
, (KeyGrave, ["grv", "`"])
NOTE : " \\ " here is a 1char string , the first \ is consumed by as an escape character
, (KeyComma, ["comm", ","])
, (KeyDot, ["."])
, (KeySlash, ["/"])
, (KeyNumLock, ["nlck"])
, (KeyKpSlash, ["kp/"])
, (KeyKpEnter, ["kprt"])
, (KeyKpPlus, ["kp+"])
, (KeyKpAsterisk, ["kp*"])
, (KeyKpMinus, ["kp-"])
, (KeyKpDot, ["kp."])
, (KeySysRq, ["ssrq", "sys"])
, (KeyKbdIllumDown, ["bldn"])
, (KeyKbdIllumUp, ["blup"])
, (KeyNextSong, ["next"])
, (KeyPlayPause, ["pp"])
, (KeyPreviousSong, ["prev"])
#ifdef darwin_HOST_OS
, (KeyLaunchpad, ["lp"])
, (KeyMissionCtrl, ["mctl"])
, (KeySpotlight, ["spot"])
, (KeyDictation, ["dict"])
#endif
]
| null | https://raw.githubusercontent.com/kmonad/kmonad/3413f1be996142c8ef4f36e246776a6df7175979/src/KMonad/Keyboard/Keycode.hs | haskell | # LANGUAGE DeriveAnyClass, CPP #
$typ
$names
------------------------------------------------------------------------------
$typ
headers:
-event-codes.h.
Anywhere there are missing regions in the linux headers, we've defined
Prefer the shortest, and if equal, lowercased version
------------------------------------------------------------------------------
$sets
------------------------------------------------------------------------------
$names
| Helper function to generate easy name maps
| A collection of useful aliases to refer to keycode names | |
Module : KMonad . Keyboard .
Description : Description of all possible keycodes .
Copyright : ( c ) , 2019
License : MIT
Maintainer :
Stability : experimental
Portability : portable
' 's are represented as a large enum lining up the keycodes defined in the Linux headers .
Module : KMonad.Keyboard.Keycode
Description : Description of all possible keycodes.
Copyright : (c) David Janssen, 2019
License : MIT
Maintainer :
Stability : experimental
Portability : portable
'Keycode's are represented as a large enum lining up the keycodes defined in the Linux headers.
-}
module KMonad.Keyboard.Keycode
* The core type
Keycode(..)
* Naming utilities to refer to Keycodes
, keyNames
)
where
import KMonad.Prelude
import qualified KMonad.Util.MultiMap as Q
import qualified RIO.HashSet as S
import qualified RIO.Text as T
import qualified RIO.Text.Partial as T (head)
' 's are defined as a large ADT that mimics the keycodes from the Linux
@MissingXX@ values for the ADT .
Calling ' RIO.Partial.toEnum ' on a Linux keycode value should produce the
corresponding ' ' value and vice - versa .
| The ' ' datatype , as an ' ' of all the values a ' ' can take .
data Keycode
= KeyReserved
| KeyEsc
| Key1
| Key2
| Key3
| Key4
| Key5
| Key6
| Key7
| Key8
| Key9
| Key0
| KeyMinus
| KeyEqual
| KeyBackspace
| KeyTab
| KeyQ
| KeyW
| KeyE
| KeyR
| KeyT
| KeyY
| KeyU
| KeyI
| KeyO
| KeyP
| KeyLeftBrace
| KeyRightBrace
| KeyEnter
| KeyLeftCtrl
| KeyA
| KeyS
| KeyD
| KeyF
| KeyG
| KeyH
| KeyJ
| KeyK
| KeyL
| KeySemicolon
| KeyApostrophe
| KeyGrave
| KeyLeftShift
| KeyBackslash
| KeyZ
| KeyX
| KeyC
| KeyV
| KeyB
| KeyN
| KeyM
| KeyComma
| KeyDot
| KeySlash
| KeyRightShift
| KeyKpAsterisk
| KeyLeftAlt
| KeySpace
| KeyCapsLock
| KeyF1
| KeyF2
| KeyF3
| KeyF4
| KeyF5
| KeyF6
| KeyF7
| KeyF8
| KeyF9
| KeyF10
| KeyNumLock
| KeyScrollLock
| KeyKp7
| KeyKp8
| KeyKp9
| KeyKpMinus
| KeyKp4
| KeyKp5
| KeyKp6
| KeyKpPlus
| KeyKp1
| KeyKp2
| KeyKp3
| KeyKp0
| KeyKpDot
| Missing84
| KeyZenkakuHankaku
| Key102nd
| KeyF11
| KeyF12
| KeyRo
| KeyKatakana
| KeyHiragana
| KeyHenkan
| KeyKatakanaHiragana
| KeyMuhenkan
| KeyKpjpcomma
| KeyKpEnter
| KeyRightCtrl
| KeyKpSlash
| KeySysRq
| KeyRightAlt
| KeyLinefeed
| KeyHome
| KeyUp
| KeyPageUp
| KeyLeft
| KeyRight
| KeyEnd
| KeyDown
| KeyPageDown
| KeyInsert
| KeyDelete
| KeyMacro
| KeyMute
| KeyVolumeDown
| KeyVolumeUp
| KeyPower
| KeyKpEqual
| KeyKpPlusMinus
| KeyPause
| KeyScale
| KeyKpComma
| KeyHangeul
| KeyHanja
| KeyYen
| KeyLeftMeta
| KeyRightMeta
| KeyCompose
| KeyStop
| KeyAgain
| KeyProps
| KeyUndo
| KeyFront
| KeyCopy
| KeyOpen
| KeyPaste
| KeyFind
| KeyCut
| KeyHelp
| KeyMenu
| KeyCalc
| KeySetup
| KeySleep
| KeyWakeUp
| KeyFile
| KeySendFile
| KeyDeleteFile
| KeyXfer
| KeyProg1
| KeyProg2
| KeyWww
| KeyMsDos
| KeyCoffee
| KeyDirection
| KeyCycleWindows
| KeyMail
| KeyBookmarks
| KeyComputer
| KeyBack
| KeyForward
| KeyCloseCd
| KeyEjectCd
| KeyEjectCloseCd
| KeyNextSong
| KeyPlayPause
| KeyPreviousSong
| KeyStopCd
| KeyRecord
| KeyRewind
| KeyPhone
| KeyIso
| KeyConfig
| KeyHomepage
| KeyRefresh
| KeyExit
| KeyMove
| KeyEdit
| KeyScrollUp
| KeyScrollDown
| KeyKpLeftParen
| KeyKpRightParen
| KeyNew
| KeyRedo
| KeyF13
| KeyF14
| KeyF15
| KeyF16
| KeyF17
| KeyF18
| KeyF19
| KeyF20
| KeyF21
| KeyF22
| KeyF23
| KeyF24
| Missing195
| Missing196
| Missing197
| Missing198
| Missing199
| KeyPlayCd
| KeyPauseCd
| KeyProg3
| KeyProg4
| KeyDashboard
| KeySuspend
| KeyClose
| KeyPlay
| KeyFastForward
| KeyBassBoost
| KeyPrint
| KeyHp
| KeyCamera
| KeySound
| KeyQuestion
| KeyEmail
| KeyChat
| KeySearch
| KeyConnect
| KeyFinance
| KeySport
| KeyShop
| KeyAlterase
| KeyCancel
| KeyBrightnessDown
| KeyBrightnessUp
| KeyMedia
| KeySwitchVideoMode
| KeyKbdIllumToggle
| KeyKbdIllumDown
| KeyKbdIllumUp
| KeySend
| KeyReply
| KeyForwardMail
| KeySave
| KeyDocuments
| KeyBattery
| KeyBluetooth
| KeyWlan
| KeyUwb
| KeyUnknown
| KeyVideoNext
| KeyVideoPrev
| KeyBrightnessCycle
| KeyBrightnessZero
| KeyDisplayOff
| KeyWimax
| Missing247
| Missing248
| Missing249
| Missing250
| Missing251
| Missing252
| Missing253
| Missing254
| Missing255
#ifdef darwin_HOST_OS
| KeyFn
| KeyLaunchpad
| KeyMissionCtrl
| KeySpotlight
| KeyDictation
#endif
deriving (Eq, Show, Bounded, Enum, Ord, Generic, Hashable)
instance Display Keycode where
textDisplay c = (\t -> "<" <> t <> ">") . fromMaybe (tshow c)
$ minimumByOf (_Just . folded) cmpName (keyNames ^. at c)
where cmpName a b =
case compare (T.length a) (T.length b) of
EQ -> compare (T.head b) (T.head a)
o -> o
| The set of all existing ' '
kcAll :: S.HashSet Keycode
kcAll = S.fromList [minBound .. maxBound]
| The set of all ' ' that are not of the MissingXX pattern
kcNotMissing :: S.HashSet Keycode
kcNotMissing = S.fromList $ kcAll ^.. folded . filtered (T.isPrefixOf "Key" . tshow)
nameKC :: Foldable t
=> (Keycode -> Text)
-> t Keycode
-> Q.MultiMap Keycode Text
nameKC f = Q.mkMultiMap . map go . toList
where go k = (k, [f k, T.toLower $ f k])
| A collection of ' ' to ' Text ' mappings
keyNames :: Q.MultiMap Keycode Text
keyNames = mconcat
[ nameKC tshow kcAll
, nameKC (T.drop 3 . tshow) kcNotMissing
, aliases
]
aliases :: Q.MultiMap Keycode Text
aliases = Q.mkMultiMap
[ (KeyEnter, ["ret", "return", "ent"])
, (KeyMinus, ["min", "-"])
, (KeyEqual, ["eql", "="])
, (KeySleep, ["zzz"])
, (KeySpace, ["spc"])
, (KeyPageUp, ["pgup"])
, (KeyPageDown, ["pgdn"])
, (KeyInsert, ["ins"])
, (KeyDelete, ["del"])
, (KeyVolumeUp, ["volu"])
, (KeyVolumeDown, ["voldwn", "vold"])
, (KeyBrightnessUp, ["brup", "bru"])
, (KeyBrightnessDown, ["brdown", "brdwn", "brdn"])
, (KeyLeftAlt, ["lalt", "alt"])
, (KeyRightAlt, ["ralt"])
, (KeyCompose, ["comp", "cmps", "cmp"])
, (KeyLeftShift, ["lshift", "lshft", "lsft", "shft", "sft"])
, (KeyRightShift, ["rshift", "rshft", "rsft"])
, (KeyLeftCtrl, ["lctrl", "lctl", "ctl"])
, (KeyRightCtrl, ["rctrl", "rctl"])
, (KeyLeftMeta, ["lmeta", "lmet", "met"])
, (KeyRightMeta, ["rmeta", "rmet"])
, (KeyBackspace, ["bks", "bspc"])
, (KeyCapsLock, ["caps"])
, (Key102nd, ["102d", "lsgt", "nubs"])
, (KeyForward, ["fwd"])
, (KeyScrollLock, ["scrlck", "slck"])
, (KeyScrollUp, ["scrup", "sup"])
, (KeyScrollDown, ["scrdn", "sdwn", "sdn"])
, (KeyPrint, ["prnt"])
, (KeyWakeUp, ["wkup"])
, (KeyLeft, ["lft"])
, (KeyRight, ["rght"])
, (KeyLeftBrace, ["lbrc", "["])
, (KeyRightBrace, ["rbrc", "]"])
, (KeySemicolon, ["scln", ";"])
, (KeyApostrophe, ["apos", "'", "apo"])
, (KeyGrave, ["grv", "`"])
NOTE : " \\ " here is a 1char string , the first \ is consumed by as an escape character
, (KeyComma, ["comm", ","])
, (KeyDot, ["."])
, (KeySlash, ["/"])
, (KeyNumLock, ["nlck"])
, (KeyKpSlash, ["kp/"])
, (KeyKpEnter, ["kprt"])
, (KeyKpPlus, ["kp+"])
, (KeyKpAsterisk, ["kp*"])
, (KeyKpMinus, ["kp-"])
, (KeyKpDot, ["kp."])
, (KeySysRq, ["ssrq", "sys"])
, (KeyKbdIllumDown, ["bldn"])
, (KeyKbdIllumUp, ["blup"])
, (KeyNextSong, ["next"])
, (KeyPlayPause, ["pp"])
, (KeyPreviousSong, ["prev"])
#ifdef darwin_HOST_OS
, (KeyLaunchpad, ["lp"])
, (KeyMissionCtrl, ["mctl"])
, (KeySpotlight, ["spot"])
, (KeyDictation, ["dict"])
#endif
]
|
eba994ab4747e5e511fe0e8f2fce9f3a66154d221ab485f786abdae633a3af59 | potatosalad/erlang-jose | jose_curve448.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 : 02 Jan 2016 by < >
%%%-------------------------------------------------------------------
-module(jose_curve448).
%% Types
-type eddsa_public_key() :: <<_:456>>.
-type eddsa_secret_key() :: <<_:912>>.
-type eddsa_seed() :: <<_:456>>.
-type message() :: binary().
-type signature() :: <<_:912>>.
-type maybe_invalid_signature() :: signature() | binary().
-type context() :: binary().
-type x448_public_key() :: <<_:448>>.
-type x448_secret_key() :: <<_:448>>.
-type x448_seed() :: <<_:448>>.
-type x448_shared_secret() :: <<_:448>>.
-export_type([
eddsa_public_key/0,
eddsa_secret_key/0,
eddsa_seed/0,
message/0,
signature/0,
maybe_invalid_signature/0,
context/0,
x448_public_key/0,
x448_secret_key/0,
x448_seed/0,
x448_shared_secret/0
]).
-callback eddsa_keypair() -> {PublicKey::eddsa_public_key(), SecretKey::eddsa_secret_key()}.
-callback eddsa_keypair(Seed::eddsa_seed()) -> {PublicKey::eddsa_public_key(), SecretKey::eddsa_secret_key()}.
-callback eddsa_secret_to_public(SecretKey::eddsa_secret_key()) -> PublicKey::eddsa_public_key().
-callback ed448_sign(Message::message(), SecretKey::eddsa_secret_key()) -> Signature::signature().
-callback ed448_sign(Message::message(), SecretKey::eddsa_secret_key(), Context::context()) -> Signature::signature().
-callback ed448_verify(Signature::maybe_invalid_signature(), Message::message(), PublicKey::eddsa_public_key()) -> boolean().
-callback ed448_verify(Signature::maybe_invalid_signature(), Message::message(), PublicKey::eddsa_public_key(), Context::context()) -> boolean().
-callback ed448ph_sign(Message::message(), SecretKey::eddsa_secret_key()) -> Signature::signature().
-callback ed448ph_sign(Message::message(), SecretKey::eddsa_secret_key(), Context::context()) -> Signature::signature().
-callback ed448ph_verify(Signature::maybe_invalid_signature(), Message::message(), PublicKey::eddsa_public_key()) -> boolean().
-callback ed448ph_verify(Signature::maybe_invalid_signature(), Message::message(), PublicKey::eddsa_public_key(), Context::context()) -> boolean().
-callback x448_keypair() -> {PublicKey::eddsa_public_key(), SecretKey::eddsa_secret_key()}.
-callback x448_keypair(Seed::x448_seed()) -> {PublicKey::x448_public_key(), SecretKey::x448_secret_key()}.
-callback x448_secret_to_public(SecretKey::x448_secret_key()) -> PublicKey::x448_public_key().
-callback x448_shared_secret(MySecretKey::x448_secret_key(), YourPublicKey::x448_public_key()) -> SharedSecret::x448_shared_secret().
jose_curve448 callbacks
-export([eddsa_keypair/0]).
-export([eddsa_keypair/1]).
-export([eddsa_secret_to_public/1]).
-export([ed448_sign/2]).
-export([ed448_sign/3]).
-export([ed448_verify/3]).
-export([ed448_verify/4]).
-export([ed448ph_sign/2]).
-export([ed448ph_sign/3]).
-export([ed448ph_verify/3]).
-export([ed448ph_verify/4]).
-export([x448_keypair/0]).
-export([x448_keypair/1]).
-export([x448_secret_to_public/1]).
-export([x448_shared_secret/2]).
Macros
-define(JOSE_CURVE448, (jose:curve448_module())).
%%====================================================================
jose_curve448 callbacks
%%====================================================================
EdDSA
-spec eddsa_keypair() -> {eddsa_public_key(), eddsa_secret_key()}.
eddsa_keypair() ->
?JOSE_CURVE448:eddsa_keypair().
-spec eddsa_keypair(eddsa_seed()) -> {eddsa_public_key(), eddsa_secret_key()}.
eddsa_keypair(Seed) ->
?JOSE_CURVE448:eddsa_keypair(Seed).
-spec eddsa_secret_to_public(eddsa_secret_key()) -> eddsa_public_key().
eddsa_secret_to_public(SecretKey) ->
?JOSE_CURVE448:eddsa_secret_to_public(SecretKey).
% Ed448
-spec ed448_sign(message(), eddsa_secret_key()) -> signature().
ed448_sign(Message, SecretKey) ->
?JOSE_CURVE448:ed448_sign(Message, SecretKey).
-spec ed448_sign(message(), eddsa_secret_key(), context()) -> signature().
ed448_sign(Message, SecretKey, Context) ->
?JOSE_CURVE448:ed448_sign(Message, SecretKey, Context).
-spec ed448_verify(maybe_invalid_signature(), message(), eddsa_public_key()) -> boolean().
ed448_verify(Signature, Message, PublicKey) ->
?JOSE_CURVE448:ed448_verify(Signature, Message, PublicKey).
-spec ed448_verify(maybe_invalid_signature(), message(), eddsa_public_key(), context()) -> boolean().
ed448_verify(Signature, Message, PublicKey, Context) ->
?JOSE_CURVE448:ed448_verify(Signature, Message, PublicKey, Context).
% Ed448ph
-spec ed448ph_sign(message(), eddsa_secret_key()) -> signature().
ed448ph_sign(Message, SecretKey) ->
?JOSE_CURVE448:ed448ph_sign(Message, SecretKey).
-spec ed448ph_sign(message(), eddsa_secret_key(), context()) -> signature().
ed448ph_sign(Message, SecretKey, Context) ->
?JOSE_CURVE448:ed448ph_sign(Message, SecretKey, Context).
-spec ed448ph_verify(maybe_invalid_signature(), message(), eddsa_public_key()) -> boolean().
ed448ph_verify(Signature, Message, PublicKey) ->
?JOSE_CURVE448:ed448ph_verify(Signature, Message, PublicKey).
-spec ed448ph_verify(maybe_invalid_signature(), message(), eddsa_public_key(), context()) -> boolean().
ed448ph_verify(Signature, Message, PublicKey, Context) ->
?JOSE_CURVE448:ed448ph_verify(Signature, Message, PublicKey, Context).
X448
-spec x448_keypair() -> {x448_public_key(), x448_secret_key()}.
x448_keypair() ->
?JOSE_CURVE448:x448_keypair().
-spec x448_keypair(x448_seed()) -> {x448_public_key(), x448_secret_key()}.
x448_keypair(Seed) ->
?JOSE_CURVE448:x448_keypair(Seed).
-spec x448_secret_to_public(x448_secret_key()) -> x448_public_key().
x448_secret_to_public(SecretKey) ->
?JOSE_CURVE448:x448_secret_to_public(SecretKey).
-spec x448_shared_secret(MySecretKey :: x448_secret_key(), YourPublicKey :: x448_public_key()) -> x448_shared_secret().
x448_shared_secret(MySecretKey, YourPublicKey) ->
?JOSE_CURVE448:x448_shared_secret(MySecretKey, YourPublicKey).
| null | https://raw.githubusercontent.com/potatosalad/erlang-jose/dbc4074066080692246afe613345ef6becc2a3fe/src/jwa/curve448/jose_curve448.erl | erlang | vim: ts=4 sw=4 ft=erlang noet
-------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
Types
====================================================================
====================================================================
Ed448
Ed448ph | -*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*-
@author < >
2014 - 2022 ,
Created : 02 Jan 2016 by < >
-module(jose_curve448).
-type eddsa_public_key() :: <<_:456>>.
-type eddsa_secret_key() :: <<_:912>>.
-type eddsa_seed() :: <<_:456>>.
-type message() :: binary().
-type signature() :: <<_:912>>.
-type maybe_invalid_signature() :: signature() | binary().
-type context() :: binary().
-type x448_public_key() :: <<_:448>>.
-type x448_secret_key() :: <<_:448>>.
-type x448_seed() :: <<_:448>>.
-type x448_shared_secret() :: <<_:448>>.
-export_type([
eddsa_public_key/0,
eddsa_secret_key/0,
eddsa_seed/0,
message/0,
signature/0,
maybe_invalid_signature/0,
context/0,
x448_public_key/0,
x448_secret_key/0,
x448_seed/0,
x448_shared_secret/0
]).
-callback eddsa_keypair() -> {PublicKey::eddsa_public_key(), SecretKey::eddsa_secret_key()}.
-callback eddsa_keypair(Seed::eddsa_seed()) -> {PublicKey::eddsa_public_key(), SecretKey::eddsa_secret_key()}.
-callback eddsa_secret_to_public(SecretKey::eddsa_secret_key()) -> PublicKey::eddsa_public_key().
-callback ed448_sign(Message::message(), SecretKey::eddsa_secret_key()) -> Signature::signature().
-callback ed448_sign(Message::message(), SecretKey::eddsa_secret_key(), Context::context()) -> Signature::signature().
-callback ed448_verify(Signature::maybe_invalid_signature(), Message::message(), PublicKey::eddsa_public_key()) -> boolean().
-callback ed448_verify(Signature::maybe_invalid_signature(), Message::message(), PublicKey::eddsa_public_key(), Context::context()) -> boolean().
-callback ed448ph_sign(Message::message(), SecretKey::eddsa_secret_key()) -> Signature::signature().
-callback ed448ph_sign(Message::message(), SecretKey::eddsa_secret_key(), Context::context()) -> Signature::signature().
-callback ed448ph_verify(Signature::maybe_invalid_signature(), Message::message(), PublicKey::eddsa_public_key()) -> boolean().
-callback ed448ph_verify(Signature::maybe_invalid_signature(), Message::message(), PublicKey::eddsa_public_key(), Context::context()) -> boolean().
-callback x448_keypair() -> {PublicKey::eddsa_public_key(), SecretKey::eddsa_secret_key()}.
-callback x448_keypair(Seed::x448_seed()) -> {PublicKey::x448_public_key(), SecretKey::x448_secret_key()}.
-callback x448_secret_to_public(SecretKey::x448_secret_key()) -> PublicKey::x448_public_key().
-callback x448_shared_secret(MySecretKey::x448_secret_key(), YourPublicKey::x448_public_key()) -> SharedSecret::x448_shared_secret().
jose_curve448 callbacks
-export([eddsa_keypair/0]).
-export([eddsa_keypair/1]).
-export([eddsa_secret_to_public/1]).
-export([ed448_sign/2]).
-export([ed448_sign/3]).
-export([ed448_verify/3]).
-export([ed448_verify/4]).
-export([ed448ph_sign/2]).
-export([ed448ph_sign/3]).
-export([ed448ph_verify/3]).
-export([ed448ph_verify/4]).
-export([x448_keypair/0]).
-export([x448_keypair/1]).
-export([x448_secret_to_public/1]).
-export([x448_shared_secret/2]).
Macros
-define(JOSE_CURVE448, (jose:curve448_module())).
jose_curve448 callbacks
EdDSA
-spec eddsa_keypair() -> {eddsa_public_key(), eddsa_secret_key()}.
eddsa_keypair() ->
?JOSE_CURVE448:eddsa_keypair().
-spec eddsa_keypair(eddsa_seed()) -> {eddsa_public_key(), eddsa_secret_key()}.
eddsa_keypair(Seed) ->
?JOSE_CURVE448:eddsa_keypair(Seed).
-spec eddsa_secret_to_public(eddsa_secret_key()) -> eddsa_public_key().
eddsa_secret_to_public(SecretKey) ->
?JOSE_CURVE448:eddsa_secret_to_public(SecretKey).
-spec ed448_sign(message(), eddsa_secret_key()) -> signature().
ed448_sign(Message, SecretKey) ->
?JOSE_CURVE448:ed448_sign(Message, SecretKey).
-spec ed448_sign(message(), eddsa_secret_key(), context()) -> signature().
ed448_sign(Message, SecretKey, Context) ->
?JOSE_CURVE448:ed448_sign(Message, SecretKey, Context).
-spec ed448_verify(maybe_invalid_signature(), message(), eddsa_public_key()) -> boolean().
ed448_verify(Signature, Message, PublicKey) ->
?JOSE_CURVE448:ed448_verify(Signature, Message, PublicKey).
-spec ed448_verify(maybe_invalid_signature(), message(), eddsa_public_key(), context()) -> boolean().
ed448_verify(Signature, Message, PublicKey, Context) ->
?JOSE_CURVE448:ed448_verify(Signature, Message, PublicKey, Context).
-spec ed448ph_sign(message(), eddsa_secret_key()) -> signature().
ed448ph_sign(Message, SecretKey) ->
?JOSE_CURVE448:ed448ph_sign(Message, SecretKey).
-spec ed448ph_sign(message(), eddsa_secret_key(), context()) -> signature().
ed448ph_sign(Message, SecretKey, Context) ->
?JOSE_CURVE448:ed448ph_sign(Message, SecretKey, Context).
-spec ed448ph_verify(maybe_invalid_signature(), message(), eddsa_public_key()) -> boolean().
ed448ph_verify(Signature, Message, PublicKey) ->
?JOSE_CURVE448:ed448ph_verify(Signature, Message, PublicKey).
-spec ed448ph_verify(maybe_invalid_signature(), message(), eddsa_public_key(), context()) -> boolean().
ed448ph_verify(Signature, Message, PublicKey, Context) ->
?JOSE_CURVE448:ed448ph_verify(Signature, Message, PublicKey, Context).
X448
-spec x448_keypair() -> {x448_public_key(), x448_secret_key()}.
x448_keypair() ->
?JOSE_CURVE448:x448_keypair().
-spec x448_keypair(x448_seed()) -> {x448_public_key(), x448_secret_key()}.
x448_keypair(Seed) ->
?JOSE_CURVE448:x448_keypair(Seed).
-spec x448_secret_to_public(x448_secret_key()) -> x448_public_key().
x448_secret_to_public(SecretKey) ->
?JOSE_CURVE448:x448_secret_to_public(SecretKey).
-spec x448_shared_secret(MySecretKey :: x448_secret_key(), YourPublicKey :: x448_public_key()) -> x448_shared_secret().
x448_shared_secret(MySecretKey, YourPublicKey) ->
?JOSE_CURVE448:x448_shared_secret(MySecretKey, YourPublicKey).
|
9b2304a368aba1eb8850c1d29e97af5dcdec919a247dd46876e72283f1a8702a | threatgrid/asami | memory_index_test.cljc | (ns asami.memory-index-test
#?(:clj
(:require [asami.graph :refer [graph-add resolve-pattern count-pattern]]
[asami.index :refer [empty-graph]]
[schema.test :as st :refer [deftest]]
[clojure.test :as t :refer [testing is run-tests]])
:cljs
(:require [asami.graph :refer [graph-add resolve-pattern count-pattern]]
[asami.index :refer [empty-graph]]
[schema.test :as st :refer-macros [deftest]]
[clojure.test :as t :refer-macros [testing is run-tests]])))
(t/use-fixtures :once st/validate-schemas)
(def data
[[:a :p1 :x]
[:a :p1 :y]
[:a :p2 :z]
[:a :p3 :x]
[:b :p1 :x]
[:b :p2 :x]
[:b :p3 :z]
[:c :p4 :t]])
(defn assert-data
([g d]
(assert-data g d 1))
([g d tx]
(reduce (fn [g [s p o]] (graph-add g s p o tx)) g d)))
(defn unordered-resolve
[g pattern]
(into #{} (resolve-pattern g pattern)))
(deftest test-load
(let [g (assert-data empty-graph data)
r1 (unordered-resolve g '[:a ?a ?b])
r2 (unordered-resolve g '[?a :p2 ?b])
r3 (unordered-resolve g '[:a :p1 ?a])
r4 (unordered-resolve g '[?a :p2 :z])
r5 (unordered-resolve g '[:a ?a :x])
r6 (unordered-resolve g '[:a :p4 ?a])
r6' (unordered-resolve g '[:a :p3 ?a])
r7 (unordered-resolve g '[:a :p1 :x])
r8 (unordered-resolve g '[:a :p1 :b])
r9 (unordered-resolve g '[?a ?b ?c])]
(is (= #{[:p1 :x]
[:p1 :y]
[:p2 :z]
[:p3 :x]} r1))
(is (= #{[:a :z]
[:b :x]} r2))
(is (= #{[:x]
[:y]} r3))
(is (= #{[:a]} r4))
(is (= #{[:p1]
[:p3]} r5))
(is (empty? r6))
(is (= #{[:x]} r6'))
(is (= #{[]} r7))
(is (empty? r8))
(is (= (into #{} data) r9))))
(deftest test-count
(let [g (assert-data empty-graph data)
r1 (count-pattern g '[:a ?a ?b])
r2 (count-pattern g '[?a :p2 ?b])
r3 (count-pattern g '[:a :p1 ?a])
r4 (count-pattern g '[?a :p2 :z])
r5 (count-pattern g '[:a ?a :x])
r6 (count-pattern g '[:a :p4 ?a])
r7 (count-pattern g '[:a :p1 :x])
r8 (count-pattern g '[:a :p1 :b])
r9 (count-pattern g '[?a ?b ?c])]
(is (= 4 r1))
(is (= 2 r2))
(is (= 2 r3))
(is (= 1 r4))
(is (= 2 r5))
(is (zero? r6))
(is (= 1 r7))
(is (zero? r8))
(is (= 8 r9))))
#?(:cljs (run-tests))
(deftest test-txn-values
(let [g (-> empty-graph
(assert-data (take 2 data) 1)
(assert-data (drop 2 data) 2))
last-stmt-id (count data)]
(is (= (inc last-stmt-id) (:next-stmt-id g)))
TODO use actual queries instead once they 're supported
(is (= 1 (get-in g [:spo :a :p1 :y :t])))
(is (= 1 (get-in g [:osp :y :a :p1 :t])))
(is (= 1 (get-in g [:pos :p1 :y :a :t])))
(is (= 2 (get-in g [:spo :c :p4 :t :t])))
(is (= 2 (get-in g [:osp :t :c :p4 :t])))
(is (= 2 (get-in g [:pos :p4 :t :c :t])))
(is (= 1 (get-in g [:spo :a :p1 :x :id])))
(is (= 1 (get-in g [:osp :x :a :p1 :id])))
(is (= 1 (get-in g [:pos :p1 :x :a :id])))
(is (= last-stmt-id (get-in g [:spo :c :p4 :t :id])))
(is (= last-stmt-id (get-in g [:osp :t :c :p4 :id])))
(is (= last-stmt-id (get-in g [:pos :p4 :t :c :id])))))
| null | https://raw.githubusercontent.com/threatgrid/asami/69ddbe3c263202f5bbbaf31a8c4abd7e69aa4005/test/asami/memory_index_test.cljc | clojure | (ns asami.memory-index-test
#?(:clj
(:require [asami.graph :refer [graph-add resolve-pattern count-pattern]]
[asami.index :refer [empty-graph]]
[schema.test :as st :refer [deftest]]
[clojure.test :as t :refer [testing is run-tests]])
:cljs
(:require [asami.graph :refer [graph-add resolve-pattern count-pattern]]
[asami.index :refer [empty-graph]]
[schema.test :as st :refer-macros [deftest]]
[clojure.test :as t :refer-macros [testing is run-tests]])))
(t/use-fixtures :once st/validate-schemas)
(def data
[[:a :p1 :x]
[:a :p1 :y]
[:a :p2 :z]
[:a :p3 :x]
[:b :p1 :x]
[:b :p2 :x]
[:b :p3 :z]
[:c :p4 :t]])
(defn assert-data
([g d]
(assert-data g d 1))
([g d tx]
(reduce (fn [g [s p o]] (graph-add g s p o tx)) g d)))
(defn unordered-resolve
[g pattern]
(into #{} (resolve-pattern g pattern)))
(deftest test-load
(let [g (assert-data empty-graph data)
r1 (unordered-resolve g '[:a ?a ?b])
r2 (unordered-resolve g '[?a :p2 ?b])
r3 (unordered-resolve g '[:a :p1 ?a])
r4 (unordered-resolve g '[?a :p2 :z])
r5 (unordered-resolve g '[:a ?a :x])
r6 (unordered-resolve g '[:a :p4 ?a])
r6' (unordered-resolve g '[:a :p3 ?a])
r7 (unordered-resolve g '[:a :p1 :x])
r8 (unordered-resolve g '[:a :p1 :b])
r9 (unordered-resolve g '[?a ?b ?c])]
(is (= #{[:p1 :x]
[:p1 :y]
[:p2 :z]
[:p3 :x]} r1))
(is (= #{[:a :z]
[:b :x]} r2))
(is (= #{[:x]
[:y]} r3))
(is (= #{[:a]} r4))
(is (= #{[:p1]
[:p3]} r5))
(is (empty? r6))
(is (= #{[:x]} r6'))
(is (= #{[]} r7))
(is (empty? r8))
(is (= (into #{} data) r9))))
(deftest test-count
(let [g (assert-data empty-graph data)
r1 (count-pattern g '[:a ?a ?b])
r2 (count-pattern g '[?a :p2 ?b])
r3 (count-pattern g '[:a :p1 ?a])
r4 (count-pattern g '[?a :p2 :z])
r5 (count-pattern g '[:a ?a :x])
r6 (count-pattern g '[:a :p4 ?a])
r7 (count-pattern g '[:a :p1 :x])
r8 (count-pattern g '[:a :p1 :b])
r9 (count-pattern g '[?a ?b ?c])]
(is (= 4 r1))
(is (= 2 r2))
(is (= 2 r3))
(is (= 1 r4))
(is (= 2 r5))
(is (zero? r6))
(is (= 1 r7))
(is (zero? r8))
(is (= 8 r9))))
#?(:cljs (run-tests))
(deftest test-txn-values
(let [g (-> empty-graph
(assert-data (take 2 data) 1)
(assert-data (drop 2 data) 2))
last-stmt-id (count data)]
(is (= (inc last-stmt-id) (:next-stmt-id g)))
TODO use actual queries instead once they 're supported
(is (= 1 (get-in g [:spo :a :p1 :y :t])))
(is (= 1 (get-in g [:osp :y :a :p1 :t])))
(is (= 1 (get-in g [:pos :p1 :y :a :t])))
(is (= 2 (get-in g [:spo :c :p4 :t :t])))
(is (= 2 (get-in g [:osp :t :c :p4 :t])))
(is (= 2 (get-in g [:pos :p4 :t :c :t])))
(is (= 1 (get-in g [:spo :a :p1 :x :id])))
(is (= 1 (get-in g [:osp :x :a :p1 :id])))
(is (= 1 (get-in g [:pos :p1 :x :a :id])))
(is (= last-stmt-id (get-in g [:spo :c :p4 :t :id])))
(is (= last-stmt-id (get-in g [:osp :t :c :p4 :id])))
(is (= last-stmt-id (get-in g [:pos :p4 :t :c :id])))))
|
|
484cb2d5fec154b789a90c1432c68425d2db54079cd0c3b31c3e9937dbc9c7d7 | pveber/bistro | sra_toolkit.ml | open Core
open Bistro
open Bistro.Shell_dsl
let img = [ docker_image ~account:"pegi3s" ~name:"sratoolkit" ~tag:"2.10.0" () ]
type 'a output =
| Fasta
| Fastq
| Fastq_gz
type library_type = SE | PE
let fasta = Fasta
let fastq = Fastq
let fastq_gz = Fastq_gz
let sra_of_input = function
| `id id -> string id
| `idw w -> string_dep w
| `file w -> dep w
let q s = quote ~using:'\'' (string s)
let call ?minReadLen ?defline_seq ?defline_qual ?_N_ ?_X_ se_or_pe output input =
let stdout = match se_or_pe with
| SE -> Some dest
| PE -> None
in
let _O_ = match se_or_pe with
| SE -> None
| PE -> Some dest
in
cmd "fastq-dump" ?stdout [
option (opt "-M" int) minReadLen ;
option (opt "--defline-seq" q) defline_seq ;
option (opt "--defline-qual" q) defline_qual ;
option (opt "-N" int) _N_ ;
option (opt "-X" int) _X_ ;
option (opt "-O" Fn.id) _O_ ;
string "-Z" ;
option string (
match output with
| Fasta -> Some "--fasta"
| Fastq | Fastq_gz -> None
) ;
option string (
match se_or_pe with
| SE -> None
| PE -> Some "--split-files"
) ;
option string (
match output with
| Fastq_gz -> Some "--gzip"
| Fasta | Fastq -> None
) ;
sra_of_input input ;
]
let fastq_dump ?minReadLen ?_N_ ?_X_ ?defline_qual ?defline_seq output input =
let fastq_dump_call = call ?minReadLen ?_N_ ?_X_ ?defline_seq ?defline_qual in
let descr = "sratoolkit.fastq_dump" in
Workflow.shell ~descr ~img [ fastq_dump_call SE output input ]
let fastq_dump_pe ?minReadLen ?_N_ ?_X_ ?defline_qual ?defline_seq output input =
let fastq_dump_call = call ?minReadLen ?_N_ ?_X_ ?defline_seq ?defline_qual in
let descr = "sratoolkit.fastq_dump" in
let dir =
Workflow.shell ~descr ~img [
mkdir_p dest ;
fastq_dump_call PE output input ;
mv (dest // "*_1.fastq") (dest // "reads_1.fastq") ;
mv (dest // "*_2.fastq") (dest // "reads_2.fastq") ;
]
in
Workflow.select dir ["reads_1.fastq"],
Workflow.select dir ["reads_2.fastq"]
| null | https://raw.githubusercontent.com/pveber/bistro/49c7a0ea09baa44ad567fc558b8bf9f5cbe02c08/lib/bio/sra_toolkit.ml | ocaml | open Core
open Bistro
open Bistro.Shell_dsl
let img = [ docker_image ~account:"pegi3s" ~name:"sratoolkit" ~tag:"2.10.0" () ]
type 'a output =
| Fasta
| Fastq
| Fastq_gz
type library_type = SE | PE
let fasta = Fasta
let fastq = Fastq
let fastq_gz = Fastq_gz
let sra_of_input = function
| `id id -> string id
| `idw w -> string_dep w
| `file w -> dep w
let q s = quote ~using:'\'' (string s)
let call ?minReadLen ?defline_seq ?defline_qual ?_N_ ?_X_ se_or_pe output input =
let stdout = match se_or_pe with
| SE -> Some dest
| PE -> None
in
let _O_ = match se_or_pe with
| SE -> None
| PE -> Some dest
in
cmd "fastq-dump" ?stdout [
option (opt "-M" int) minReadLen ;
option (opt "--defline-seq" q) defline_seq ;
option (opt "--defline-qual" q) defline_qual ;
option (opt "-N" int) _N_ ;
option (opt "-X" int) _X_ ;
option (opt "-O" Fn.id) _O_ ;
string "-Z" ;
option string (
match output with
| Fasta -> Some "--fasta"
| Fastq | Fastq_gz -> None
) ;
option string (
match se_or_pe with
| SE -> None
| PE -> Some "--split-files"
) ;
option string (
match output with
| Fastq_gz -> Some "--gzip"
| Fasta | Fastq -> None
) ;
sra_of_input input ;
]
let fastq_dump ?minReadLen ?_N_ ?_X_ ?defline_qual ?defline_seq output input =
let fastq_dump_call = call ?minReadLen ?_N_ ?_X_ ?defline_seq ?defline_qual in
let descr = "sratoolkit.fastq_dump" in
Workflow.shell ~descr ~img [ fastq_dump_call SE output input ]
let fastq_dump_pe ?minReadLen ?_N_ ?_X_ ?defline_qual ?defline_seq output input =
let fastq_dump_call = call ?minReadLen ?_N_ ?_X_ ?defline_seq ?defline_qual in
let descr = "sratoolkit.fastq_dump" in
let dir =
Workflow.shell ~descr ~img [
mkdir_p dest ;
fastq_dump_call PE output input ;
mv (dest // "*_1.fastq") (dest // "reads_1.fastq") ;
mv (dest // "*_2.fastq") (dest // "reads_2.fastq") ;
]
in
Workflow.select dir ["reads_1.fastq"],
Workflow.select dir ["reads_2.fastq"]
|
|
11054b17669d711fa2fb539fa327c7e3308e2b6f81136cb761132709bb8e0524 | gerritjvv/tcp-driver | util.clj | (ns tcp-driver.test.util
(:require [tcp-driver.io.conn :as tcp-conn]
[tcp-driver.io.stream :as tcp-stream])
(:import (java.net ServerSocket SocketException)))
(defn ^ServerSocket server-socket []
(ServerSocket. (int 0)))
(defn ^Long get-port [^ServerSocket socket]
(Long. (.getLocalPort socket)))
(defn get-connection! [^ServerSocket socket]
(.accept socket))
;;;;;;;;;;;;;;;;;;;;
;;;;;;;;; Public API
(defn create-server
"Connects a server socket to an abritrary free port
Params:
handler-f called (handler-f ^ITCPConn conn)
Returns:
{:server-socket ...
:port the binded port
:future an instance of (future that accepts and calls handler-f}"
[handler-f]
(let [socket (server-socket)]
{
:server-socket socket
:port (get-port socket)
:future-loop (future
(while (not (Thread/interrupted))
(try
(handler-f (tcp-conn/wrap-tcp-conn (get-connection! socket)))
(catch InterruptedException _ nil)
(catch SocketException _ nil)
(catch Exception e (do (prn e) (.printStackTrace e))))))}))
(defn stop-server [{:keys [server-socket future-loop]}]
(.close ^ServerSocket server-socket)
(future-cancel future-loop))
(defn echo-handler [conn]
(prn "echo-handler: " conn)
(let [bts (tcp-stream/read-bytes conn 10000)]
;;we need to ensure we have some bytes
(if (pos? (count bts))
(do
(tcp-stream/write-bytes conn bts)
(tcp-stream/flush-out conn)
(tcp-conn/close! conn))
(do
(Thread/sleep 1000)
(recur conn)))))
(defn echo-server
"Return {:port :server-socket and :future-loop}"
[]
(create-server echo-handler))
(defn with-echo-server [f]
(let [server (echo-server)]
(try
(f server)
(finally
(stop-server server))))) | null | https://raw.githubusercontent.com/gerritjvv/tcp-driver/2a9373cda20d176bfb5b00e63f4816fa83c88591/test/tcp_driver/test/util.clj | clojure |
Public API
we need to ensure we have some bytes | (ns tcp-driver.test.util
(:require [tcp-driver.io.conn :as tcp-conn]
[tcp-driver.io.stream :as tcp-stream])
(:import (java.net ServerSocket SocketException)))
(defn ^ServerSocket server-socket []
(ServerSocket. (int 0)))
(defn ^Long get-port [^ServerSocket socket]
(Long. (.getLocalPort socket)))
(defn get-connection! [^ServerSocket socket]
(.accept socket))
(defn create-server
"Connects a server socket to an abritrary free port
Params:
handler-f called (handler-f ^ITCPConn conn)
Returns:
{:server-socket ...
:port the binded port
:future an instance of (future that accepts and calls handler-f}"
[handler-f]
(let [socket (server-socket)]
{
:server-socket socket
:port (get-port socket)
:future-loop (future
(while (not (Thread/interrupted))
(try
(handler-f (tcp-conn/wrap-tcp-conn (get-connection! socket)))
(catch InterruptedException _ nil)
(catch SocketException _ nil)
(catch Exception e (do (prn e) (.printStackTrace e))))))}))
(defn stop-server [{:keys [server-socket future-loop]}]
(.close ^ServerSocket server-socket)
(future-cancel future-loop))
(defn echo-handler [conn]
(prn "echo-handler: " conn)
(let [bts (tcp-stream/read-bytes conn 10000)]
(if (pos? (count bts))
(do
(tcp-stream/write-bytes conn bts)
(tcp-stream/flush-out conn)
(tcp-conn/close! conn))
(do
(Thread/sleep 1000)
(recur conn)))))
(defn echo-server
"Return {:port :server-socket and :future-loop}"
[]
(create-server echo-handler))
(defn with-echo-server [f]
(let [server (echo-server)]
(try
(f server)
(finally
(stop-server server))))) |
c589e32b65b8b7d55f8eb515632c2469dcbcf3b81d8e511df6e4d4c480adcbf8 | didier-wenzek/ocaml-kafka | kafka.mli | * OCaml bindings for
(** Version of the librdkafka library used by this binding. *)
val librdkafka_version : string
(** Handler to a cluster of kafka brokers. Either a producer or a consumer. *)
type handler
(** A handler to a kafka topic. *)
type topic
* A message queue allows the application to re - route consumed messages
from multiple topics and partitions into one single queue point .
from multiple topics and partitions into one single queue point. *)
type queue
(** Partition id, from 0 to topic partition count -1 *)
type partition = int
(** Offset in a partition *)
type offset = int64
(** A message consumed from a consumer or a queue. *)
type message =
| Message of topic * partition * offset * string * string option (* topic, partition, offset, payload, optional key *)
| PartitionEnd of topic * partition * offset (* topic, partition, offset *)
(** Message identifier used by producers for delivery callbacks.*)
type msg_id = int
(** Error *)
type error =
Internal errors to rdkafka
| BAD_MSG (** Received message is incorrect *)
| BAD_COMPRESSION (** Bad/unknown compression *)
| DESTROY (** Broker is going away *)
| FAIL (** Generic failure *)
| TRANSPORT (** Broker transport error *)
| CRIT_SYS_RESOURCE (** Critical system resource failure *)
| RESOLVE (** Failed to resolve broker. *)
| MSG_TIMED_OUT (** Produced message timed out. *)
| UNKNOWN_PARTITION (** Permanent: Partition does not exist in cluster. *)
| FS (** File or filesystem error *)
| UNKNOWN_TOPIC (** Permanent: Topic does not exist in cluster. *)
| ALL_BROKERS_DOWN (** All broker connections are down. *)
| INVALID_ARG (** Invalid argument, or invalid configuration *)
| TIMED_OUT (** Operation timed out *)
| QUEUE_FULL (** Queue is full *)
| ISR_INSUFF (** ISR count < required.acks *)
Standard Kafka errors
| UNKNOWN
| OFFSET_OUT_OF_RANGE
| INVALID_MSG
| UNKNOWN_TOPIC_OR_PART
| INVALID_MSG_SIZE
| LEADER_NOT_AVAILABLE
| NOT_LEADER_FOR_PARTITION
| REQUEST_TIMED_OUT
| BROKER_NOT_AVAILABLE
| REPLICA_NOT_AVAILABLE
| MSG_SIZE_TOO_LARGE
| STALE_CTRL_EPOCH
| OFFSET_METADATA_TOO_LARGE
(* Configuration errors *)
| CONF_UNKNOWN (** Unknown configuration name. *)
| CONF_INVALID (** Invalid configuration value. *)
(** Exception *)
exception Error of error * string
(** Create a kafka handler aimed to consume messages.
- A single option is required : "metadata.broker.list", which is a comma sepated list of "host:port".
- For a list of options,
see {{:} librdkafka configuration}
and {{:#configuration} Kafka configuration}.
*)
val new_consumer : (string*string) list -> handler
(** Create a kafka handler aimed to produce messages.
- A single option is required : "metadata.broker.list", which is a comma sepated list of "host:port".
- For a list of options,
see {{:} librdkafka configuration}
and {{:#configuration} Kafka configuration}.
- A delivery callback may be attached to the producer.
This callback will be call after each message delivery
as in [delivery_callback msg_id error_if_any].
Note that on contrary librdkafka, such a callback do not return the message but only its id.
Callbacks must be triggered by the [poll] function.
The producer option 'delivery.report.only.error' may be set to true to report only errors.
*)
val new_producer :
?delivery_callback:(msg_id -> error option -> unit)
-> (string*string) list
-> handler
* Destroy handle ( either a consumer or a producer )
val destroy_handler : handler -> unit
* handle name
val handler_name : handler -> string
(** Creates a new topic handler for the kafka topic with the given name.
- For a list of options,
see {{:} librdkafka configuration}
- For a producer, a partition_callback may be provided
to assign a partition after the key provided by [produce ~key msg].
*)
val new_topic :
[ partitioner partition_count key ] assigns a partition for a key in [ 0 .. partition_count-1 ]
-> handler (* consumer or producer *)
-> string (* topic name *)
-> (string*string) list (* topic option *)
-> topic
(** Destroy topic handle *)
val destroy_topic : topic -> unit
* topic handle name
val topic_name : topic -> string
* [ produce topic message ]
produces and sends a single message to the broker .
An optional [ partition ] argument may be passed to specify the partition to
emit to ( 0 .. N-1 ) , otherwise a partition will be automatically determined .
An optional key may be attached to the message .
This key will be used by the partitioner of the topic handler .
as well as be sent with the message to the broker and passed on to the consumer .
An optional i d may be attached to the message .
This i d will be passed to the delivery callback of the producer ,
once the message delivered .
Since producing is asynchronous , you should call [ ] before you destroy the producer .
Otherwise , any outstanding messages will be silently discarded .
produces and sends a single message to the broker.
An optional [partition] argument may be passed to specify the partition to
emit to (0..N-1), otherwise a partition will be automatically determined.
An optional key may be attached to the message.
This key will be used by the partitioner of the topic handler.
as well as be sent with the message to the broker and passed on to the consumer.
An optional id may be attached to the message.
This id will be passed to the delivery callback of the producer,
once the message delivered.
Since producing is asynchronous, you should call [Kafka.flush] before you destroy the producer.
Otherwise, any outstanding messages will be silently discarded.
*)
val produce: topic -> ?partition:partition -> ?key:string -> ?msg_id:msg_id -> string -> unit
(** Wait until all outstanding produce requests are completed. *)
val flush: ?timeout_ms:int -> handler -> unit
(** Returns the current out queue length: messages waiting to be sent to, or acknowledged by, the broker. *)
val outq_len : handler -> int
* Polls the provided kafka handle for events .
Events will cause application provided callbacks to be called .
The ' timeout_ms ' argument specifies the minimum amount of time
( in milliseconds ) that the call will block waiting for events .
For non - blocking calls , provide 0 as ' timeout_ms ' .
To wait indefinately for an event , provide -1 .
Events :
- delivery report callbacks ( if delivery_callback is configured ) [ producer ]
- error callbacks ( if is configured ) [ producer & consumer ]
- stats callbacks ( if is configured ) [ producer & consumer ]
Returns the number of events served .
Events will cause application provided callbacks to be called.
The 'timeout_ms' argument specifies the minimum amount of time
(in milliseconds) that the call will block waiting for events.
For non-blocking calls, provide 0 as 'timeout_ms'.
To wait indefinately for an event, provide -1.
Events:
- delivery report callbacks (if delivery_callback is configured) [producer]
- error callbacks (if error_cb is configured) [producer & consumer]
- stats callbacks (if stats_cb is configured) [producer & consumer]
Returns the number of events served.
*)
val poll_events: ?timeout_ms:int -> handler -> int
(** Wait that messages are delivered (waiting that less than max_outq_len messages are pending). *)
val wait_delivery: ?timeout_ms:int -> ?max_outq_len:int -> handler -> unit
* [ consume_start topic partition offset ]
starts consuming messages for topic [ topic ] and [ partition ] at [ offset ] .
Offset may either be a proper offset ( 0 .. N )
or one of the the special offsets :
[ Kafka.offset_beginning ] , [ Kafka.offset_end ] , [ Kafka.offset_stored ]
of [ Kafka.offset_tail n ] ( i.e. [ n ] messages before [ Kafka.offset_end ] ) .
The system ( librdkafka ) will attempt to keep ' queued.min.messages ' ( consumer config property )
messages in the local queue by repeatedly fetching batches of messages
from the broker until the threshold is reached .
Raise an Error of error * string on error .
starts consuming messages for topic [topic] and [partition] at [offset].
Offset may either be a proper offset (0..N)
or one of the the special offsets:
[Kafka.offset_beginning], [Kafka.offset_end], [Kafka.offset_stored]
of [Kafka.offset_tail n] (i.e. [n] messages before [Kafka.offset_end]).
The system (librdkafka) will attempt to keep 'queued.min.messages' (consumer config property)
messages in the local queue by repeatedly fetching batches of messages
from the broker until the threshold is reached.
Raise an Error of error * string on error.
*)
val consume_start : topic -> partition -> offset -> unit
val offset_beginning: offset
val offset_end: offset
val offset_stored: offset
val offset_tail: int -> offset
(** [consume_stop topic partition]
stop consuming messages for topic [topic] and [partition],
purging all messages currently in the local queue.
*)
val consume_stop : topic -> partition -> unit
* [ consume ~timeout_ms topic partition ]
consumes a single message from topic [ topic ] and [ partition ] .
Waits at most [ timeout_ms ] milli - seconds for a message to be received .
The default timout is 1 second .
Consumer must have been previously started with [ Kafka.consume_start ] .
consumes a single message from topic [topic] and [partition].
Waits at most [timeout_ms] milli-seconds for a message to be received.
The default timout is 1 second.
Consumer must have been previously started with [Kafka.consume_start].
*)
val consume : ?timeout_ms:int -> topic -> partition -> message
* [ consume_batch ~timeout_ms ~msg_count topic partition ]
consumes up to [ msg_count ] messages from [ topic ] and [ partition ] ,
taking at most [ timeout_ms ] to collect the messages
( hence , it may return less messages than requested ) .
The default timout is 1 second .
The default count of messages is 1k .
consumes up to [msg_count] messages from [topic] and [partition],
taking at most [timeout_ms] to collect the messages
(hence, it may return less messages than requested).
The default timout is 1 second.
The default count of messages is 1k.
*)
val consume_batch : ?timeout_ms:int -> ?msg_count:int -> topic -> partition -> message list
(** Create a new message queue. *)
val new_queue : handler -> queue
(** Destroy a message queue. *)
val destroy_queue : queue -> unit
(** [consume_start_queue queue topic partition offset]
starts consuming messages for topic [topic] and [partition] at [offset]
and routes consumed messages to the given queue.
For a topic, either [consume_start] or [consume_start_queue] must be called.
[consume_stop] has to be called to stop consuming messages from the topic.
*)
val consume_start_queue : queue -> topic -> partition -> offset -> unit
* [ consume_queue ~timeout_ms queue ]
consumes a single message from topics and partitions
attached to the queue using [ Kafka.consume_start_queue ] .
at most [ timeout_ms ] milli - seconds for a message to be received .
The default timout is 1 second .
consumes a single message from topics and partitions
attached to the queue using [Kafka.consume_start_queue].
Waits at most [timeout_ms] milli-seconds for a message to be received.
The default timout is 1 second.
*)
val consume_queue : ?timeout_ms:int -> queue -> message
* [ consume_batch_queue ~timeout_ms ~msg_count queue ]
consumes up to [ msg_count ] messages from the [ queue ] ,
taking at most [ timeout_ms ] to collect the messages
( hence , it may return less messages than requested ) .
The default timout is 1 second .
The default count of messages is 1k .
consumes up to [msg_count] messages from the [queue],
taking at most [timeout_ms] to collect the messages
(hence, it may return less messages than requested).
The default timout is 1 second.
The default count of messages is 1k.
*)
val consume_batch_queue : ?timeout_ms:int -> ?msg_count:int -> queue -> message list
(** [store_offset topic partition offset]
stores [offset] for given [topic] and [partition].
The offset will be commited (written) to the offset store according to the topic properties:
- "offset.store.method" : "file" or "broker"
- "offset.store.path"
- "auto.commit.enable" : must be set to "false"
*)
val store_offset : topic -> partition -> offset -> unit
module Metadata : sig
(** Topic information *)
type topic_metadata = {
topic_name: string;
topic_partitions: partition list;
}
end
(** Topic information of a given topic. *)
val topic_metadata: ?timeout_ms:int -> handler -> topic -> Metadata.topic_metadata
(** Information of all local topics. *)
val local_topics_metadata: ?timeout_ms:int -> handler -> Metadata.topic_metadata list
(** Information of all topics known by the brokers. *)
val all_topics_metadata: ?timeout_ms:int -> handler -> Metadata.topic_metadata list
(* Store the consumer offset of a particular partition to a specific offset *)
val offset_store: topic -> partition -> offset -> unit
| null | https://raw.githubusercontent.com/didier-wenzek/ocaml-kafka/d4e831d400c98b9a67ce984e09665d144cc15717/lib/kafka.mli | ocaml | * Version of the librdkafka library used by this binding.
* Handler to a cluster of kafka brokers. Either a producer or a consumer.
* A handler to a kafka topic.
* Partition id, from 0 to topic partition count -1
* Offset in a partition
* A message consumed from a consumer or a queue.
topic, partition, offset, payload, optional key
topic, partition, offset
* Message identifier used by producers for delivery callbacks.
* Error
* Received message is incorrect
* Bad/unknown compression
* Broker is going away
* Generic failure
* Broker transport error
* Critical system resource failure
* Failed to resolve broker.
* Produced message timed out.
* Permanent: Partition does not exist in cluster.
* File or filesystem error
* Permanent: Topic does not exist in cluster.
* All broker connections are down.
* Invalid argument, or invalid configuration
* Operation timed out
* Queue is full
* ISR count < required.acks
Configuration errors
* Unknown configuration name.
* Invalid configuration value.
* Exception
* Create a kafka handler aimed to consume messages.
- A single option is required : "metadata.broker.list", which is a comma sepated list of "host:port".
- For a list of options,
see {{:} librdkafka configuration}
and {{:#configuration} Kafka configuration}.
* Create a kafka handler aimed to produce messages.
- A single option is required : "metadata.broker.list", which is a comma sepated list of "host:port".
- For a list of options,
see {{:} librdkafka configuration}
and {{:#configuration} Kafka configuration}.
- A delivery callback may be attached to the producer.
This callback will be call after each message delivery
as in [delivery_callback msg_id error_if_any].
Note that on contrary librdkafka, such a callback do not return the message but only its id.
Callbacks must be triggered by the [poll] function.
The producer option 'delivery.report.only.error' may be set to true to report only errors.
* Creates a new topic handler for the kafka topic with the given name.
- For a list of options,
see {{:} librdkafka configuration}
- For a producer, a partition_callback may be provided
to assign a partition after the key provided by [produce ~key msg].
consumer or producer
topic name
topic option
* Destroy topic handle
* Wait until all outstanding produce requests are completed.
* Returns the current out queue length: messages waiting to be sent to, or acknowledged by, the broker.
* Wait that messages are delivered (waiting that less than max_outq_len messages are pending).
* [consume_stop topic partition]
stop consuming messages for topic [topic] and [partition],
purging all messages currently in the local queue.
* Create a new message queue.
* Destroy a message queue.
* [consume_start_queue queue topic partition offset]
starts consuming messages for topic [topic] and [partition] at [offset]
and routes consumed messages to the given queue.
For a topic, either [consume_start] or [consume_start_queue] must be called.
[consume_stop] has to be called to stop consuming messages from the topic.
* [store_offset topic partition offset]
stores [offset] for given [topic] and [partition].
The offset will be commited (written) to the offset store according to the topic properties:
- "offset.store.method" : "file" or "broker"
- "offset.store.path"
- "auto.commit.enable" : must be set to "false"
* Topic information
* Topic information of a given topic.
* Information of all local topics.
* Information of all topics known by the brokers.
Store the consumer offset of a particular partition to a specific offset | * OCaml bindings for
val librdkafka_version : string
type handler
type topic
* A message queue allows the application to re - route consumed messages
from multiple topics and partitions into one single queue point .
from multiple topics and partitions into one single queue point. *)
type queue
type partition = int
type offset = int64
type message =
type msg_id = int
type error =
Internal errors to rdkafka
Standard Kafka errors
| UNKNOWN
| OFFSET_OUT_OF_RANGE
| INVALID_MSG
| UNKNOWN_TOPIC_OR_PART
| INVALID_MSG_SIZE
| LEADER_NOT_AVAILABLE
| NOT_LEADER_FOR_PARTITION
| REQUEST_TIMED_OUT
| BROKER_NOT_AVAILABLE
| REPLICA_NOT_AVAILABLE
| MSG_SIZE_TOO_LARGE
| STALE_CTRL_EPOCH
| OFFSET_METADATA_TOO_LARGE
exception Error of error * string
val new_consumer : (string*string) list -> handler
val new_producer :
?delivery_callback:(msg_id -> error option -> unit)
-> (string*string) list
-> handler
* Destroy handle ( either a consumer or a producer )
val destroy_handler : handler -> unit
* handle name
val handler_name : handler -> string
val new_topic :
[ partitioner partition_count key ] assigns a partition for a key in [ 0 .. partition_count-1 ]
-> topic
val destroy_topic : topic -> unit
* topic handle name
val topic_name : topic -> string
* [ produce topic message ]
produces and sends a single message to the broker .
An optional [ partition ] argument may be passed to specify the partition to
emit to ( 0 .. N-1 ) , otherwise a partition will be automatically determined .
An optional key may be attached to the message .
This key will be used by the partitioner of the topic handler .
as well as be sent with the message to the broker and passed on to the consumer .
An optional i d may be attached to the message .
This i d will be passed to the delivery callback of the producer ,
once the message delivered .
Since producing is asynchronous , you should call [ ] before you destroy the producer .
Otherwise , any outstanding messages will be silently discarded .
produces and sends a single message to the broker.
An optional [partition] argument may be passed to specify the partition to
emit to (0..N-1), otherwise a partition will be automatically determined.
An optional key may be attached to the message.
This key will be used by the partitioner of the topic handler.
as well as be sent with the message to the broker and passed on to the consumer.
An optional id may be attached to the message.
This id will be passed to the delivery callback of the producer,
once the message delivered.
Since producing is asynchronous, you should call [Kafka.flush] before you destroy the producer.
Otherwise, any outstanding messages will be silently discarded.
*)
val produce: topic -> ?partition:partition -> ?key:string -> ?msg_id:msg_id -> string -> unit
val flush: ?timeout_ms:int -> handler -> unit
val outq_len : handler -> int
* Polls the provided kafka handle for events .
Events will cause application provided callbacks to be called .
The ' timeout_ms ' argument specifies the minimum amount of time
( in milliseconds ) that the call will block waiting for events .
For non - blocking calls , provide 0 as ' timeout_ms ' .
To wait indefinately for an event , provide -1 .
Events :
- delivery report callbacks ( if delivery_callback is configured ) [ producer ]
- error callbacks ( if is configured ) [ producer & consumer ]
- stats callbacks ( if is configured ) [ producer & consumer ]
Returns the number of events served .
Events will cause application provided callbacks to be called.
The 'timeout_ms' argument specifies the minimum amount of time
(in milliseconds) that the call will block waiting for events.
For non-blocking calls, provide 0 as 'timeout_ms'.
To wait indefinately for an event, provide -1.
Events:
- delivery report callbacks (if delivery_callback is configured) [producer]
- error callbacks (if error_cb is configured) [producer & consumer]
- stats callbacks (if stats_cb is configured) [producer & consumer]
Returns the number of events served.
*)
val poll_events: ?timeout_ms:int -> handler -> int
val wait_delivery: ?timeout_ms:int -> ?max_outq_len:int -> handler -> unit
* [ consume_start topic partition offset ]
starts consuming messages for topic [ topic ] and [ partition ] at [ offset ] .
Offset may either be a proper offset ( 0 .. N )
or one of the the special offsets :
[ Kafka.offset_beginning ] , [ Kafka.offset_end ] , [ Kafka.offset_stored ]
of [ Kafka.offset_tail n ] ( i.e. [ n ] messages before [ Kafka.offset_end ] ) .
The system ( librdkafka ) will attempt to keep ' queued.min.messages ' ( consumer config property )
messages in the local queue by repeatedly fetching batches of messages
from the broker until the threshold is reached .
Raise an Error of error * string on error .
starts consuming messages for topic [topic] and [partition] at [offset].
Offset may either be a proper offset (0..N)
or one of the the special offsets:
[Kafka.offset_beginning], [Kafka.offset_end], [Kafka.offset_stored]
of [Kafka.offset_tail n] (i.e. [n] messages before [Kafka.offset_end]).
The system (librdkafka) will attempt to keep 'queued.min.messages' (consumer config property)
messages in the local queue by repeatedly fetching batches of messages
from the broker until the threshold is reached.
Raise an Error of error * string on error.
*)
val consume_start : topic -> partition -> offset -> unit
val offset_beginning: offset
val offset_end: offset
val offset_stored: offset
val offset_tail: int -> offset
val consume_stop : topic -> partition -> unit
* [ consume ~timeout_ms topic partition ]
consumes a single message from topic [ topic ] and [ partition ] .
Waits at most [ timeout_ms ] milli - seconds for a message to be received .
The default timout is 1 second .
Consumer must have been previously started with [ Kafka.consume_start ] .
consumes a single message from topic [topic] and [partition].
Waits at most [timeout_ms] milli-seconds for a message to be received.
The default timout is 1 second.
Consumer must have been previously started with [Kafka.consume_start].
*)
val consume : ?timeout_ms:int -> topic -> partition -> message
* [ consume_batch ~timeout_ms ~msg_count topic partition ]
consumes up to [ msg_count ] messages from [ topic ] and [ partition ] ,
taking at most [ timeout_ms ] to collect the messages
( hence , it may return less messages than requested ) .
The default timout is 1 second .
The default count of messages is 1k .
consumes up to [msg_count] messages from [topic] and [partition],
taking at most [timeout_ms] to collect the messages
(hence, it may return less messages than requested).
The default timout is 1 second.
The default count of messages is 1k.
*)
val consume_batch : ?timeout_ms:int -> ?msg_count:int -> topic -> partition -> message list
val new_queue : handler -> queue
val destroy_queue : queue -> unit
val consume_start_queue : queue -> topic -> partition -> offset -> unit
* [ consume_queue ~timeout_ms queue ]
consumes a single message from topics and partitions
attached to the queue using [ Kafka.consume_start_queue ] .
at most [ timeout_ms ] milli - seconds for a message to be received .
The default timout is 1 second .
consumes a single message from topics and partitions
attached to the queue using [Kafka.consume_start_queue].
Waits at most [timeout_ms] milli-seconds for a message to be received.
The default timout is 1 second.
*)
val consume_queue : ?timeout_ms:int -> queue -> message
* [ consume_batch_queue ~timeout_ms ~msg_count queue ]
consumes up to [ msg_count ] messages from the [ queue ] ,
taking at most [ timeout_ms ] to collect the messages
( hence , it may return less messages than requested ) .
The default timout is 1 second .
The default count of messages is 1k .
consumes up to [msg_count] messages from the [queue],
taking at most [timeout_ms] to collect the messages
(hence, it may return less messages than requested).
The default timout is 1 second.
The default count of messages is 1k.
*)
val consume_batch_queue : ?timeout_ms:int -> ?msg_count:int -> queue -> message list
val store_offset : topic -> partition -> offset -> unit
module Metadata : sig
type topic_metadata = {
topic_name: string;
topic_partitions: partition list;
}
end
val topic_metadata: ?timeout_ms:int -> handler -> topic -> Metadata.topic_metadata
val local_topics_metadata: ?timeout_ms:int -> handler -> Metadata.topic_metadata list
val all_topics_metadata: ?timeout_ms:int -> handler -> Metadata.topic_metadata list
val offset_store: topic -> partition -> offset -> unit
|
5ee9effb0aeaea81989240a2bc0b10d9eda331e7aea4b8886b06aee35f567dde | mirage/ocaml-qcow | gen.ml | let output_file = ref "lib/qcow_word_size.ml"
let _ =
Arg.parse [
"-o", Arg.Set_string output_file, "output filename"
] (fun x ->
Printf.fprintf stderr "Unexpected argument: %s\n%!" x;
exit 1;
) "Auto-detect the host word size";
let oc = open_out !output_file in
begin match Sys.word_size with
| 64 ->
Printf.fprintf stderr "On a 64-bit machine so using 'int' for clusters\n";
output_string oc "module Cluster = Qcow_int\n"
| _ ->
Printf.fprintf stderr "Not on a 64-bit machine to using 'int64' for clusters\n";
output_string oc "module Cluster = Qcow_int64\n"
end;
close_out oc
| null | https://raw.githubusercontent.com/mirage/ocaml-qcow/2418c66627dcce8420bcb06d7547db171528060a/generator/gen.ml | ocaml | let output_file = ref "lib/qcow_word_size.ml"
let _ =
Arg.parse [
"-o", Arg.Set_string output_file, "output filename"
] (fun x ->
Printf.fprintf stderr "Unexpected argument: %s\n%!" x;
exit 1;
) "Auto-detect the host word size";
let oc = open_out !output_file in
begin match Sys.word_size with
| 64 ->
Printf.fprintf stderr "On a 64-bit machine so using 'int' for clusters\n";
output_string oc "module Cluster = Qcow_int\n"
| _ ->
Printf.fprintf stderr "Not on a 64-bit machine to using 'int64' for clusters\n";
output_string oc "module Cluster = Qcow_int64\n"
end;
close_out oc
|
|
fdc650650595965bf7345009080a12cbe79016fc27d36a8bba571639a797f3f0 | zwizwa/staapl | pattern-utils.rkt | (module pattern-utils mzscheme
(provide (all-defined))
(define (process/merge-patterns meta-pattern stx)
(apply append
(map (lambda (p-stx)
(syntax->list
(meta-pattern p-stx)))
(syntax->list stx))))
)
| null | https://raw.githubusercontent.com/zwizwa/staapl/e30e6ae6ac45de7141b97ad3cebf9b5a51bcda52/coma/pattern-utils.rkt | racket | (module pattern-utils mzscheme
(provide (all-defined))
(define (process/merge-patterns meta-pattern stx)
(apply append
(map (lambda (p-stx)
(syntax->list
(meta-pattern p-stx)))
(syntax->list stx))))
)
|
|
8634b6f6a0d930cff353b89fb78d96745a3b9c1fb1bcb77eedae99a6a92ec01e | dhleong/wish | util.cljs | (ns ^{:author "Daniel Leong"
:doc "View/widget utils"}
wish.views.util)
(defn dispatch-change-from-keyup
"Event handler that be used for :on-key-up
that dispatches on-change immediately."
[e]
(let [el (.-target e)]
(js/console.log e)
(js/console.log el)
(js/console.log (.-onchange el))
(js/console.log (.-oninput el))
(js/console.log (.-onblur el))
(.dispatchEvent
el
(doto (js/document.createEvent "HTMLEvents")
(.initEvent "input" true false)))))
| null | https://raw.githubusercontent.com/dhleong/wish/9036f9da3706bfcc1e4b4736558b6f7309f53b7b/src/cljs/wish/views/util.cljs | clojure | (ns ^{:author "Daniel Leong"
:doc "View/widget utils"}
wish.views.util)
(defn dispatch-change-from-keyup
"Event handler that be used for :on-key-up
that dispatches on-change immediately."
[e]
(let [el (.-target e)]
(js/console.log e)
(js/console.log el)
(js/console.log (.-onchange el))
(js/console.log (.-oninput el))
(js/console.log (.-onblur el))
(.dispatchEvent
el
(doto (js/document.createEvent "HTMLEvents")
(.initEvent "input" true false)))))
|
|
7cf97e6e6565fe31f2f4204eb3f5cf7e00a4e06db647f9b24747046fd56c351c | metabase/metabase | prevent_infinite_recursive_preprocesses.clj | (ns metabase.query-processor.middleware.prevent-infinite-recursive-preprocesses
(:require
[metabase.query-processor.error-type :as qp.error-type]
[metabase.util.i18n :refer [tru]]
[metabase.util.log :as log]))
(def ^:private ^:dynamic *preprocessing-level* 1)
(def ^:private ^:const max-preprocessing-level 20)
(defn prevent-infinite-recursive-preprocesses
"QP around-middleware only used for preprocessing queries with [[metabase.query-processor/preprocess]]. Prevent
infinite recursive calls to `preprocess`."
[qp]
(fn [query rff context]
(binding [*preprocessing-level* (inc *preprocessing-level*)]
;; record the number of recursive preprocesses taking place to prevent infinite preprocessing loops.
(log/tracef "*preprocessing-level*: %d" *preprocessing-level*)
(when (>= *preprocessing-level* max-preprocessing-level)
(throw (ex-info (str (tru "Infinite loop detected: recursively preprocessed query {0} times."
max-preprocessing-level))
{:type qp.error-type/qp})))
(qp query rff context))))
| null | https://raw.githubusercontent.com/metabase/metabase/dad3d414e5bec482c15d826dcc97772412c98652/src/metabase/query_processor/middleware/prevent_infinite_recursive_preprocesses.clj | clojure | record the number of recursive preprocesses taking place to prevent infinite preprocessing loops. | (ns metabase.query-processor.middleware.prevent-infinite-recursive-preprocesses
(:require
[metabase.query-processor.error-type :as qp.error-type]
[metabase.util.i18n :refer [tru]]
[metabase.util.log :as log]))
(def ^:private ^:dynamic *preprocessing-level* 1)
(def ^:private ^:const max-preprocessing-level 20)
(defn prevent-infinite-recursive-preprocesses
"QP around-middleware only used for preprocessing queries with [[metabase.query-processor/preprocess]]. Prevent
infinite recursive calls to `preprocess`."
[qp]
(fn [query rff context]
(binding [*preprocessing-level* (inc *preprocessing-level*)]
(log/tracef "*preprocessing-level*: %d" *preprocessing-level*)
(when (>= *preprocessing-level* max-preprocessing-level)
(throw (ex-info (str (tru "Infinite loop detected: recursively preprocessed query {0} times."
max-preprocessing-level))
{:type qp.error-type/qp})))
(qp query rff context))))
|
8c9390e755e9ea5f51fe0ee90972f929f620e121ec4ae71a1307aff1895085dc | ocaml-flambda/flambda-backend | recmodules.ml | (* TEST
flags = "-dshape"
* expect
*)
(**********)
(* Simple *)
(**********)
module rec A : sig
type t = Leaf of B.t
end = struct
type t = Leaf of B.t
end
and B
: sig type t = int end
= struct type t = int end
[%%expect{|
{
"A"[module] -> {
"t"[type] -> <.8>;
};
"B"[module] -> {
"t"[type] -> <.10>;
};
}
module rec A : sig type t = Leaf of B.t end
and B : sig type t = int end
|}]
(*****************)
only ...
(*****************)
(* reduce is going to die on this. *)
module rec A : sig
type t = Leaf of B.t
end = A
and B : sig
type t = int
end = B
[%%expect{|
{
"A"[module] -> A/302<.11>;
"B"[module] -> B/303<.12>;
}
module rec A : sig type t = Leaf of B.t end
and B : sig type t = int end
|}]
(***************************)
(* Example from the manual *)
(***************************)
module rec A : sig
type t = Leaf of string | Node of ASet.t
val compare: t -> t -> int
end = struct
type t = Leaf of string | Node of ASet.t
let compare t1 t2 =
match (t1, t2) with
| (Leaf s1, Leaf s2) -> Stdlib.compare s1 s2
| (Leaf _, Node _) -> 1
| (Node _, Leaf _) -> -1
| (Node n1, Node n2) -> ASet.compare n1 n2
end
(* we restrict the sig to limit the bloat in the expected output. *)
and ASet : sig
type t
type elt = A.t
val compare : t -> t -> int
end = Set.Make(A)
[%%expect{|
{
"A"[module] -> {
"compare"[value] -> <.38>;
"t"[type] -> <.35>;
};
"ASet"[module] ->
{
"compare"[value] ->
CU Stdlib . "Set"[module] . "Make"[module](A/324<.19>) .
"compare"[value];
"elt"[type] ->
CU Stdlib . "Set"[module] . "Make"[module](A/324<.19>) .
"elt"[type];
"t"[type] ->
CU Stdlib . "Set"[module] . "Make"[module](A/324<.19>) . "t"[type];
};
}
module rec A :
sig
type t = Leaf of string | Node of ASet.t
val compare : t -> t -> int
end
and ASet : sig type t type elt = A.t val compare : t -> t -> int end
|}]
| null | https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/1d905beda2707698d36835ef3acd77a5992fc389/ocaml/testsuite/tests/shapes/recmodules.ml | ocaml | TEST
flags = "-dshape"
* expect
********
Simple
********
***************
***************
reduce is going to die on this.
*************************
Example from the manual
*************************
we restrict the sig to limit the bloat in the expected output. |
module rec A : sig
type t = Leaf of B.t
end = struct
type t = Leaf of B.t
end
and B
: sig type t = int end
= struct type t = int end
[%%expect{|
{
"A"[module] -> {
"t"[type] -> <.8>;
};
"B"[module] -> {
"t"[type] -> <.10>;
};
}
module rec A : sig type t = Leaf of B.t end
and B : sig type t = int end
|}]
only ...
module rec A : sig
type t = Leaf of B.t
end = A
and B : sig
type t = int
end = B
[%%expect{|
{
"A"[module] -> A/302<.11>;
"B"[module] -> B/303<.12>;
}
module rec A : sig type t = Leaf of B.t end
and B : sig type t = int end
|}]
module rec A : sig
type t = Leaf of string | Node of ASet.t
val compare: t -> t -> int
end = struct
type t = Leaf of string | Node of ASet.t
let compare t1 t2 =
match (t1, t2) with
| (Leaf s1, Leaf s2) -> Stdlib.compare s1 s2
| (Leaf _, Node _) -> 1
| (Node _, Leaf _) -> -1
| (Node n1, Node n2) -> ASet.compare n1 n2
end
and ASet : sig
type t
type elt = A.t
val compare : t -> t -> int
end = Set.Make(A)
[%%expect{|
{
"A"[module] -> {
"compare"[value] -> <.38>;
"t"[type] -> <.35>;
};
"ASet"[module] ->
{
"compare"[value] ->
CU Stdlib . "Set"[module] . "Make"[module](A/324<.19>) .
"compare"[value];
"elt"[type] ->
CU Stdlib . "Set"[module] . "Make"[module](A/324<.19>) .
"elt"[type];
"t"[type] ->
CU Stdlib . "Set"[module] . "Make"[module](A/324<.19>) . "t"[type];
};
}
module rec A :
sig
type t = Leaf of string | Node of ASet.t
val compare : t -> t -> int
end
and ASet : sig type t type elt = A.t val compare : t -> t -> int end
|}]
|
2d62bd422eaac4fb8ef072b070489e691706294ad667f10e943392a3686ede91 | Ptival/language-ocaml | Variance.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Language.OCaml.PrettyPrinter.Variance
( variancePP,
)
where
import Language.OCaml.Definitions.Parsing.ASTTypes (Variance (..))
import Language.OCaml.PrettyPrinter.ConstructorDeclaration ()
import Language.OCaml.PrettyPrinter.LabelDeclaration ()
import Prettyprinter (Doc, Pretty (pretty))
variancePP :: Variance -> Doc a
variancePP = \case
Contravariant -> "-"
Covariant -> "+"
Invariant -> ""
instance Pretty Variance where
pretty = variancePP
| null | https://raw.githubusercontent.com/Ptival/language-ocaml/7b07fd3cc466bb2ad2cac4bfe3099505cb63a4f4/lib/Language/OCaml/PrettyPrinter/Variance.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Language.OCaml.PrettyPrinter.Variance
( variancePP,
)
where
import Language.OCaml.Definitions.Parsing.ASTTypes (Variance (..))
import Language.OCaml.PrettyPrinter.ConstructorDeclaration ()
import Language.OCaml.PrettyPrinter.LabelDeclaration ()
import Prettyprinter (Doc, Pretty (pretty))
variancePP :: Variance -> Doc a
variancePP = \case
Contravariant -> "-"
Covariant -> "+"
Invariant -> ""
instance Pretty Variance where
pretty = variancePP
|
c2660fd1b4ec96903740b73d52fb192863952e39bf520147fd0c7fbe7c6659bc | ygmpkk/house | Handle.hs | -- #hide
-----------------------------------------------------------------------------
-- |
-- Module : Window.Handle
Copyright : ( c ) 2002
-- License : BSD-style
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- Window.Handle contains the internal data structures that represent the
-- state of windows.
--
-----------------------------------------------------------------------------
module Graphics.UI.ObjectIO.Window.Handle
( ControlState, WindowHandles(..)
, Graphics.UI.ObjectIO.CommonDef.Bound(..), WindowStateHandle(..), WIDS(..)
, WindowLSHandle(..)
, ScrollInfo(..), ClipState(..)
, WindowHandle(..), WindowKind(..), WindowMode(..)
, WElementHandle(..)
, LayoutInfo(..), WItemInfo(..)
, RadioInfo(..), RadioItemInfo(..), CheckInfo(..)
, CheckItemInfo(..), PopUpInfo(..), PopUpEditInfo(..), ListBoxInfo(..)
, SliderInfo(..), ButtonInfo(..), EditInfo(..), TextInfo(..)
, ControlKind(..), FinalModalLS(..)
, wElementHandleToControlState, controlStateToWElementHandle
, Graphics.UI.ObjectIO.OS.Picture.OSPictContext
, Graphics.UI.ObjectIO.OS.Picture.Origin
, Graphics.UI.ObjectIO.OS.Picture.Pen(..)
, Graphics.UI.ObjectIO.OS.Picture.Font(..)
, Graphics.UI.ObjectIO.OS.Picture.Colour(..)
, module Graphics.UI.ObjectIO.StdControlDef
, module Graphics.UI.ObjectIO.StdWindowDef
, module Graphics.UI.ObjectIO.OS.Types
, isCustomisedControl, isRecursiveControl
, LookInfo(..), WindowInfo(..)
, CustomButtonInfo(..), CustomInfo(..)
, CompoundInfo(..), CompoundLookInfo(..)
) where
import Graphics.UI.ObjectIO.CommonDef
import Graphics.UI.ObjectIO.StdControlDef
import Graphics.UI.ObjectIO.StdWindowDef
import Graphics.UI.ObjectIO.KeyFocus
import Graphics.UI.ObjectIO.Receiver.Handle(ReceiverHandle(..))
import Graphics.UI.ObjectIO.OS.Picture
import Graphics.UI.ObjectIO.OS.Types
import Graphics.UI.ObjectIO.OS.Rgn(OSRgnHandle)
type ControlState ls ps
= WElementHandle ls ps -- is a WElementHandle
data WindowHandles ps
= WindowHandles
{ whsWindows :: [WindowStateHandle ps] -- The windows and their controls of a process
, whsNrWindowBound:: !Bound -- The maximum number of windows that are allowed to be opened
, whsModal :: Bool -- Flag: the window system is modal (used in combination with modal dialogues)
, whsFinalModalLS :: [FinalModalLS] -- The final local states of terminated modal dialogs
}
data FinalModalLS = forall ls . FinalModalLS WIDS ls
data WindowStateHandle ps
= forall ls .
WindowStateHandle
WIDS -- A window is identified by an Id and an OSWindowPtr
(Maybe (WindowLSHandle ls ps)) -- If used as placeholder, Nothing; otherwise window with local state
data WindowLSHandle ls ps
= WindowLSHandle
{ wlsState :: ls -- The local state of this window
, wlsHandle :: WindowHandle ls ps -- The window implementation
}
data WIDS
= WIDS
{ wId :: Id -- Id of window
, wPtr :: !OSWindowPtr -- Ptr of window
, wActive :: !Bool -- The window is the active window (True) or not (False)
}
data WindowHandle ls ps
= WindowHandle
The window mode ( Modal or Modeless )
, whKind :: !WindowKind -- The window kind (Window or Dialog)
, whTitle :: !Title -- The window title
, whItemNrs :: [Int] -- The list of free system item numbers for all controls
, whKeyFocus :: KeyFocus -- The item that has the keyboard input focus
, whWindowInfo:: WindowInfo -- Additional information about the window
, whItems :: [WElementHandle ls ps] -- The window controls
, whShow :: Bool -- The visibility of the window (True iff visible)
, whSelect :: Bool -- The WindowSelectState==Able (by default True)
, whAtts :: ![WindowAttribute ls ps] -- The window attributes
, whDefaultId :: Maybe Id -- The Id of the optional default button
, whCancelId :: Maybe Id -- The Id of the optional cancel button
, whSize :: !Size -- The exact size of the window
, whClosing :: !Bool -- Flag: the window is being closed (True)
}
data LookInfo
= LookInfo
{ lookFun :: Look -- The Look function
, lookPen :: Pen -- The settings of the Pen
, lookSysUpdate :: Bool -- The system handles updates as much as possible
}
data WindowInfo
= WindowInfo
{ windowDomain :: Rect -- The optional view domain of the window
, windowOrigin :: Point2 -- The Origin of the view domain
, windowHScroll :: Maybe ScrollInfo -- The scroll data of the WindowHScroll attribute
, windowVScroll :: Maybe ScrollInfo -- The scroll data of the WindowVScroll attribute
, windowLook :: LookInfo -- The look and pen of the window
, windowClip :: ClipState -- The clipped elements of the window
}
| NoWindowInfo
data WindowMode -- Modality of the window
= Modal -- Modal window (only for dialogs)
| Modeless -- Modeless window
deriving (Eq)
data WindowKind
= IsWindow -- Window kind
| IsDialog -- Dialog kind
deriving (Eq)
data ScrollInfo
= ScrollInfo
{ scrollFunction :: ScrollFunction -- The ScrollFunction of the (horizontal/vertical) scroll attribute
, scrollItemPos :: Point2 -- The exact position of the scrollbar
, scrollItemSize :: Size -- The exact size of the scrollbar
, scrollItemPtr :: OSWindowPtr -- The OSWindowPtr of the scrollbar
}
data ClipState
= ClipState
{ clipRgn :: OSRgnHandle -- The clipping region
, clipOk :: Bool -- Flag: the clipping region is valid
}
data WElementHandle ls ps
= WListLSHandle [WElementHandle ls ps]
| forall ls1 .
WExtendLSHandle ls1 [WElementHandle (ls1,ls) ps]
| forall ls1 .
WChangeLSHandle ls1 [WElementHandle ls1 ps]
| WItemHandle
If the control has a ( ControlId i d ) attribute , then Just i d ; Nothing
, wItemNr :: Int -- The internal nr of this control (generated from whItemNrs)
, wItemKind :: ControlKind -- The sort of control
, wItemShow :: Bool -- The visibility of the control (True iff visible)
, wItemSelect :: Bool -- The ControlSelectState==Able (by default True)
, wItemInfo :: WItemInfo ls ps -- Additional information of the control
, wItemAtts :: [ControlAttribute ls ps] -- The control attributes
In case of CompoundControl : its control elements
-- Otherwise : []
The control is virtual ( True ) and should not be layn out
, wItemPos :: Point2 -- The exact position of the item
, wItemSize :: Size -- The exact size of the item
The ptr to the item ( osNoWindowPtr if no handle )
, wItemLayoutInfo :: LayoutInfo -- Additional information on layout
}
data LayoutInfo -- The layout attribute of the layout root control is:
ItemPos = Fix
| LayoutFrame -- any other attribute
deriving (Eq)
data WItemInfo ls ps
In case of ButtonControl : the button information
| WCheckInfo (CheckInfo ls ps) -- In case of CheckControl : the check items information
In case of CompoundControl : the compound control information
| WCustomButtonInfo CustomButtonInfo -- In case of CustomButtonControl : the custom button information
| WCustomInfo CustomInfo -- In case of CustomControl : the custom information
In case of EditControl : the edit text information
| WPopUpInfo (PopUpInfo ls ps) -- In case of PopUpControl : the pop up information
| WListBoxInfo (ListBoxInfo ls ps) -- In case of ListBoxControl : the list box information
| WRadioInfo (RadioInfo ls ps) -- In case of RadioControl : the radio items information
In case of ReceiverControl : the receiver information
In case of SliderControl : the slider information
In case of TextControl : the text information
| NoWItemInfo -- No additional information
data RadioInfo ls ps
= RadioInfo
The radio items and their exact position ( initially zero )
, radioLayout :: RowsOrColumns -- The layout of the radio items
The currently selected radio item ( 1<=radioIndex<=length radioItems )
}
data RadioItemInfo ls ps
= RadioItemInfo
The RadioItem of the definition ( Int field redundant )
, radioItemPos :: !Point2 -- The exact position of the item
, radioItemSize :: Size -- The exact size of the item
, radioItemPtr :: OSWindowPtr -- The OSWindowPtr of the item
}
data CheckInfo ls ps
= CheckInfo
The check items and their exact position ( initially zero )
, checkLayout :: RowsOrColumns -- The layout of the check items
}
data CheckItemInfo ls ps
= CheckItemInfo
The CheckItem of the definition ( Int field redundant )
, checkItemPos :: !Point2 -- The exact position of the item
, checkItemSize :: Size -- The exact size of the item
, checkItemPtr :: OSWindowPtr -- The OSWindowPtr of the item
}
data PopUpInfo ls ps
= PopUpInfo
{ popUpInfoItems :: [PopUpControlItem ps (ls,ps)] -- The pop up items
The currently selected pop up item ( 1<=popUpInfoIndex<=length popUpInfoItems )
, popUpInfoEdit :: Maybe PopUpEditInfo -- If the pop up is editable: the PopUpEditInfo, otherwise Nothing
}
data PopUpEditInfo
= PopUpEditInfo
{ popUpEditText :: String -- The current content of the editable pop up
, popUpEditPtr :: OSWindowPtr -- The OSWindowPtr of the editable pop up
}
data ListBoxInfo ls ps
= ListBoxInfo
{ listBoxInfoItems :: [ListBoxControlItem ps (ls,ps)] -- The list box items
, listBoxNrLines :: NrLines
, listBoxInfoMultiSel :: Bool
}
data SliderInfo ls ps
= SliderInfo
{ sliderInfoDir :: Direction -- The direction of the slider
, sliderInfoLength :: Int -- The length (in pixels) of the slider
, sliderInfoState :: SliderState -- The current slider state
, sliderInfoAction :: SliderAction ls ps -- The action of the slider
}
data ButtonInfo
= ButtonInfo
{ buttonInfoText :: String -- The title of the button control
}
data CustomButtonInfo
= CustomButtonInfo
{ cButtonInfoLook :: LookInfo -- The look of the custom button control
}
data CustomInfo
= CustomInfo
{ customInfoLook :: LookInfo -- The look of the custom control
}
data CompoundInfo
= CompoundInfo
{ compoundDomain :: Rect -- The optional view domain of the compound control
, compoundOrigin :: Point2 -- The Origin of the view domain
, compoundHScroll :: Maybe ScrollInfo -- The scroll data of the ControlHScroll attribute
, compoundVScroll :: Maybe ScrollInfo -- The scroll data of the ControlVScroll attribute
, compoundLookInfo:: CompoundLookInfo -- The look information of the compound control
}
data CompoundLookInfo
= CompoundLookInfo
{ compoundLook :: LookInfo -- The look of the compound control
, compoundClip :: ClipState -- The clipped elements of the compound control
}
data EditInfo
= EditInfo
{ editInfoText :: !String -- The content of the edit control
, editInfoWidth :: Int -- The width (in pixels) of the edit item
, editInfoNrLines :: Int -- The nr of complete visible lines of the edit item
}
data TextInfo
= TextInfo
{ textInfoText :: String -- The content of the text control
}
data ControlKind
= IsButtonControl
| IsCheckControl
| IsCompoundControl
| IsCustomButtonControl
| IsCustomControl
| IsEditControl
| IsLayoutControl
| IsPopUpControl
| IsListBoxControl
| IsRadioControl
| IsSliderControl
| IsTextControl
Of other controls the ControlType
deriving (Eq,Show)
instance Eq WIDS where
(==) wids wids' = wPtr wids==wPtr wids' && wId wids==wId wids'
The given ControlKind corresponds with a custom - drawn control .
isCustomisedControl :: ControlKind -> Bool
isCustomisedControl IsCustomButtonControl = True
isCustomisedControl IsCustomControl = True
isCustomisedControl _ = False
The given ControlKind corresponds with a control that contains other controls ( CompoundControl ) .
isRecursiveControl :: ControlKind -> Bool
isRecursiveControl IsCompoundControl = True
isRecursiveControl IsLayoutControl = True
isRecursiveControl _ = False
Conversion functions from ControlState to WElementHandle , and vice versa :
wElementHandleToControlState :: WElementHandle ls ps -> ControlState ls ps
wElementHandleToControlState wH = wH
controlStateToWElementHandle :: ControlState ls ps -> WElementHandle ls ps
controlStateToWElementHandle wH = wH
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/ObjectIO/Graphics/UI/ObjectIO/Window/Handle.hs | haskell | #hide
---------------------------------------------------------------------------
|
Module : Window.Handle
License : BSD-style
Maintainer :
Stability : provisional
Portability : portable
Window.Handle contains the internal data structures that represent the
state of windows.
---------------------------------------------------------------------------
is a WElementHandle
The windows and their controls of a process
The maximum number of windows that are allowed to be opened
Flag: the window system is modal (used in combination with modal dialogues)
The final local states of terminated modal dialogs
A window is identified by an Id and an OSWindowPtr
If used as placeholder, Nothing; otherwise window with local state
The local state of this window
The window implementation
Id of window
Ptr of window
The window is the active window (True) or not (False)
The window kind (Window or Dialog)
The window title
The list of free system item numbers for all controls
The item that has the keyboard input focus
Additional information about the window
The window controls
The visibility of the window (True iff visible)
The WindowSelectState==Able (by default True)
The window attributes
The Id of the optional default button
The Id of the optional cancel button
The exact size of the window
Flag: the window is being closed (True)
The Look function
The settings of the Pen
The system handles updates as much as possible
The optional view domain of the window
The Origin of the view domain
The scroll data of the WindowHScroll attribute
The scroll data of the WindowVScroll attribute
The look and pen of the window
The clipped elements of the window
Modality of the window
Modal window (only for dialogs)
Modeless window
Window kind
Dialog kind
The ScrollFunction of the (horizontal/vertical) scroll attribute
The exact position of the scrollbar
The exact size of the scrollbar
The OSWindowPtr of the scrollbar
The clipping region
Flag: the clipping region is valid
The internal nr of this control (generated from whItemNrs)
The sort of control
The visibility of the control (True iff visible)
The ControlSelectState==Able (by default True)
Additional information of the control
The control attributes
Otherwise : []
The exact position of the item
The exact size of the item
Additional information on layout
The layout attribute of the layout root control is:
any other attribute
In case of CheckControl : the check items information
In case of CustomButtonControl : the custom button information
In case of CustomControl : the custom information
In case of PopUpControl : the pop up information
In case of ListBoxControl : the list box information
In case of RadioControl : the radio items information
No additional information
The layout of the radio items
The exact position of the item
The exact size of the item
The OSWindowPtr of the item
The layout of the check items
The exact position of the item
The exact size of the item
The OSWindowPtr of the item
The pop up items
If the pop up is editable: the PopUpEditInfo, otherwise Nothing
The current content of the editable pop up
The OSWindowPtr of the editable pop up
The list box items
The direction of the slider
The length (in pixels) of the slider
The current slider state
The action of the slider
The title of the button control
The look of the custom button control
The look of the custom control
The optional view domain of the compound control
The Origin of the view domain
The scroll data of the ControlHScroll attribute
The scroll data of the ControlVScroll attribute
The look information of the compound control
The look of the compound control
The clipped elements of the compound control
The content of the edit control
The width (in pixels) of the edit item
The nr of complete visible lines of the edit item
The content of the text control | Copyright : ( c ) 2002
module Graphics.UI.ObjectIO.Window.Handle
( ControlState, WindowHandles(..)
, Graphics.UI.ObjectIO.CommonDef.Bound(..), WindowStateHandle(..), WIDS(..)
, WindowLSHandle(..)
, ScrollInfo(..), ClipState(..)
, WindowHandle(..), WindowKind(..), WindowMode(..)
, WElementHandle(..)
, LayoutInfo(..), WItemInfo(..)
, RadioInfo(..), RadioItemInfo(..), CheckInfo(..)
, CheckItemInfo(..), PopUpInfo(..), PopUpEditInfo(..), ListBoxInfo(..)
, SliderInfo(..), ButtonInfo(..), EditInfo(..), TextInfo(..)
, ControlKind(..), FinalModalLS(..)
, wElementHandleToControlState, controlStateToWElementHandle
, Graphics.UI.ObjectIO.OS.Picture.OSPictContext
, Graphics.UI.ObjectIO.OS.Picture.Origin
, Graphics.UI.ObjectIO.OS.Picture.Pen(..)
, Graphics.UI.ObjectIO.OS.Picture.Font(..)
, Graphics.UI.ObjectIO.OS.Picture.Colour(..)
, module Graphics.UI.ObjectIO.StdControlDef
, module Graphics.UI.ObjectIO.StdWindowDef
, module Graphics.UI.ObjectIO.OS.Types
, isCustomisedControl, isRecursiveControl
, LookInfo(..), WindowInfo(..)
, CustomButtonInfo(..), CustomInfo(..)
, CompoundInfo(..), CompoundLookInfo(..)
) where
import Graphics.UI.ObjectIO.CommonDef
import Graphics.UI.ObjectIO.StdControlDef
import Graphics.UI.ObjectIO.StdWindowDef
import Graphics.UI.ObjectIO.KeyFocus
import Graphics.UI.ObjectIO.Receiver.Handle(ReceiverHandle(..))
import Graphics.UI.ObjectIO.OS.Picture
import Graphics.UI.ObjectIO.OS.Types
import Graphics.UI.ObjectIO.OS.Rgn(OSRgnHandle)
type ControlState ls ps
data WindowHandles ps
= WindowHandles
}
data FinalModalLS = forall ls . FinalModalLS WIDS ls
data WindowStateHandle ps
= forall ls .
WindowStateHandle
data WindowLSHandle ls ps
= WindowLSHandle
}
data WIDS
= WIDS
}
data WindowHandle ls ps
= WindowHandle
The window mode ( Modal or Modeless )
}
data LookInfo
= LookInfo
}
data WindowInfo
= WindowInfo
}
| NoWindowInfo
deriving (Eq)
data WindowKind
deriving (Eq)
data ScrollInfo
= ScrollInfo
}
data ClipState
= ClipState
}
data WElementHandle ls ps
= WListLSHandle [WElementHandle ls ps]
| forall ls1 .
WExtendLSHandle ls1 [WElementHandle (ls1,ls) ps]
| forall ls1 .
WChangeLSHandle ls1 [WElementHandle ls1 ps]
| WItemHandle
If the control has a ( ControlId i d ) attribute , then Just i d ; Nothing
In case of CompoundControl : its control elements
The control is virtual ( True ) and should not be layn out
The ptr to the item ( osNoWindowPtr if no handle )
}
ItemPos = Fix
deriving (Eq)
data WItemInfo ls ps
In case of ButtonControl : the button information
In case of CompoundControl : the compound control information
In case of EditControl : the edit text information
In case of ReceiverControl : the receiver information
In case of SliderControl : the slider information
In case of TextControl : the text information
data RadioInfo ls ps
= RadioInfo
The radio items and their exact position ( initially zero )
The currently selected radio item ( 1<=radioIndex<=length radioItems )
}
data RadioItemInfo ls ps
= RadioItemInfo
The RadioItem of the definition ( Int field redundant )
}
data CheckInfo ls ps
= CheckInfo
The check items and their exact position ( initially zero )
}
data CheckItemInfo ls ps
= CheckItemInfo
The CheckItem of the definition ( Int field redundant )
}
data PopUpInfo ls ps
= PopUpInfo
The currently selected pop up item ( 1<=popUpInfoIndex<=length popUpInfoItems )
}
data PopUpEditInfo
= PopUpEditInfo
}
data ListBoxInfo ls ps
= ListBoxInfo
, listBoxNrLines :: NrLines
, listBoxInfoMultiSel :: Bool
}
data SliderInfo ls ps
= SliderInfo
}
data ButtonInfo
= ButtonInfo
}
data CustomButtonInfo
= CustomButtonInfo
}
data CustomInfo
= CustomInfo
}
data CompoundInfo
= CompoundInfo
}
data CompoundLookInfo
= CompoundLookInfo
}
data EditInfo
= EditInfo
}
data TextInfo
= TextInfo
}
data ControlKind
= IsButtonControl
| IsCheckControl
| IsCompoundControl
| IsCustomButtonControl
| IsCustomControl
| IsEditControl
| IsLayoutControl
| IsPopUpControl
| IsListBoxControl
| IsRadioControl
| IsSliderControl
| IsTextControl
Of other controls the ControlType
deriving (Eq,Show)
instance Eq WIDS where
(==) wids wids' = wPtr wids==wPtr wids' && wId wids==wId wids'
The given ControlKind corresponds with a custom - drawn control .
isCustomisedControl :: ControlKind -> Bool
isCustomisedControl IsCustomButtonControl = True
isCustomisedControl IsCustomControl = True
isCustomisedControl _ = False
The given ControlKind corresponds with a control that contains other controls ( CompoundControl ) .
isRecursiveControl :: ControlKind -> Bool
isRecursiveControl IsCompoundControl = True
isRecursiveControl IsLayoutControl = True
isRecursiveControl _ = False
Conversion functions from ControlState to WElementHandle , and vice versa :
wElementHandleToControlState :: WElementHandle ls ps -> ControlState ls ps
wElementHandleToControlState wH = wH
controlStateToWElementHandle :: ControlState ls ps -> WElementHandle ls ps
controlStateToWElementHandle wH = wH
|
1e25190cec4c272f87b07da9e05f2a62d5a7def40d9c07aed952c23c955653d8 | bennn/iPoe | bad-syllables.rkt | #lang ipoe/villanelle
I shut mine eyes and all the world drops dead;
I lift mine lid and all is born again.
(I think I made you up inside mine head.)
The star go dancing out in blue and red,
And arbitrary blackness run again
I shut mine eyes and all the world drops dead.
I did dream that you put mine into bed
And sung mine moon-struck, kiss mine quite again
(I think I made you up inside mine head.)
God top less from the sky, hell's fire did fed:
enter seraphim and Satan a men:
I shut mine eyes and all the world drops dead.
I fancied you'd return the way you said,
But I grow old and I forget again
(I think I made you up inside mine head.)
I should have love a thunderbird instead;
At least when spring comes they roar back again.
I shut mine eyes and all the world drops dead.
(I think I made you up inside mine head.)
| null | https://raw.githubusercontent.com/bennn/iPoe/4a988f6537fb738b4fe842c404f9d78f658ab76f/examples/villanelle/bad-syllables.rkt | racket | #lang ipoe/villanelle
I lift mine lid and all is born again.
(I think I made you up inside mine head.)
The star go dancing out in blue and red,
And arbitrary blackness run again
I shut mine eyes and all the world drops dead.
I did dream that you put mine into bed
And sung mine moon-struck, kiss mine quite again
(I think I made you up inside mine head.)
God top less from the sky, hell's fire did fed:
enter seraphim and Satan a men:
I shut mine eyes and all the world drops dead.
I fancied you'd return the way you said,
But I grow old and I forget again
(I think I made you up inside mine head.)
At least when spring comes they roar back again.
I shut mine eyes and all the world drops dead.
(I think I made you up inside mine head.)
|
|
42573da818a77cc9fbc58600846994c3b39578129405fba15e029624aa27b6eb | yuriy-chumak/ol | case-sensitivity_of_identifiers.scm | ; www.rosettacode.org/wiki/Case-sensitivity_of_identifiers#Ol
(define dog "Benjamin")
(define Dog "Samba")
(define DOG "Bernie")
(print "The three dogs are named " dog ", " Dog " and " DOG ".")
| null | https://raw.githubusercontent.com/yuriy-chumak/ol/83dd03d311339763682eab02cbe0c1321daa25bc/tests/rosettacode/case-sensitivity_of_identifiers.scm | scheme | www.rosettacode.org/wiki/Case-sensitivity_of_identifiers#Ol |
(define dog "Benjamin")
(define Dog "Samba")
(define DOG "Bernie")
(print "The three dogs are named " dog ", " Dog " and " DOG ".")
|
59c5166952ec5864673655258e5967071e3d10496468870e3c65f6682e180906 | jeromesimeon/Galax | evaluation_expr.ml | (***********************************************************************)
(* *)
(* GALAX *)
(* XQuery Engine *)
(* *)
Copyright 2001 - 2007 .
(* Distributed only by permission. *)
(* *)
(***********************************************************************)
$ I d : evaluation_expr.ml , v 1.18 2007/03/18 21:38:01 mff Exp $
Module : Evaluation_expr
Description :
Execute the code associated to each algebraic operation
Description:
Execute the code associated to each algebraic operation
*)
open Algebra_type
open Xquery_algebra_ast
open Error
NOTE :
The reason we have this first step that instantiate the dependant
expressions is because those may have changed in the course of
algebraic rewriting .
A better strategy would be to change the evaluation to instantiate
all of the code in the AST * before * starting actual evaluation .
- J & C
The reason we have this first step that instantiate the dependant
expressions is because those may have changed in the course of
algebraic rewriting.
A better strategy would be to change the evaluation to instantiate
all of the code in the AST *before* starting actual evaluation.
- J & C *)
let has_delta_update op =
let {has_delta_update=hdu} = op.annotation in
hdu
let has_two_deltas_sexprs sexpr =
match sexpr with
| NoSub
| OneSub _ -> false
| TwoSub (op1,op2) ->
(has_delta_update op1) &&
(has_delta_update op2)
| ManySub ops ->
let count_fold cur op =
if has_delta_update op
then (cur+1)
else cur
in
let counts = Array.fold_left count_fold 0 ops in
counts >= 2
let update_allocate_holder_if_needed alg_ctxt subexpr =
match Execution_context.get_current_snap_semantic alg_ctxt with
| Xquery_common_ast.Snap_Ordered_Deterministic ->
if has_two_deltas_sexprs subexpr
then Execution_context.allocate_update_holder alg_ctxt
else alg_ctxt
| Xquery_common_ast.Snap_Unordered_Deterministic
| Xquery_common_ast.Snap_Nondeterministic ->
(* Here we do not need to allocate holders because it is done else where *)
alg_ctxt
(****************************************)
Physical typing debug code -
(****************************************)
open Xquery_physical_type_ast
open Print_xquery_physical_type
open Physical_value
let counter_check_physical_type algop pv =
let string_of_physical_value pv =
match pv with
| PXMLValue (SaxValue _) -> "PXMLValue (SaxValue _)"
| PXMLValue (DomValue (CSeq _)) -> "PXMLValue (DomValue (CSeq _))"
| PXMLValue (DomValue (LSeq _)) -> "PXMLValue (DomValue (LSeq _))"
| PTable _ -> "PTable _"
in
let raise_type_mismatch pt =
let physop = Cs_util.get_physical_opname algop in
raise (Query (Prototype ("Physical type mismatch - " ^ (string_of_physical_type pt) ^ " vs. " ^ (string_of_physical_value pv)
^ " at " ^ (string_of_physop_expr_name physop) ^ "! This should have been compiled out (evaluation_expr)!")))
in
let counter_check_physical_sax_type pt =
match pv with
| PXMLValue (SaxValue _) -> ()
| _ -> raise_type_mismatch pt
in
let counter_check_physical_dom_cursor_type pt =
match pv with
| PXMLValue (DomValue (CSeq _)) -> ()
| _ -> raise_type_mismatch pt
in
let counter_check_physical_dom_list_type pt =
match pv with
| PXMLValue (DomValue (LSeq _)) -> ()
| _ -> raise_type_mismatch pt
in
let counter_check_physical_table_type pt =
match pv with
| PTable _ -> ()
| _ -> raise_type_mismatch pt
in
match algop.palgop_expr_eval_sig with
| Some (_, _, pt) ->
begin
match pt with
| PT_Table _ -> counter_check_physical_table_type pt
| PT_XML (PT_Sax PT_Stream)-> counter_check_physical_sax_type pt
| PT_XML (PT_Sax PT_Discarded)-> raise_type_mismatch pt
| PT_XML (PT_Dom PT_CursorSeq) -> counter_check_physical_dom_cursor_type pt
| PT_XML (PT_Dom PT_ListSeq) -> counter_check_physical_dom_list_type pt
end
| None -> ()
let memtotal = ref None
let memlive = ref None
(* This function must be tail recursive as well!!!! *)
let recmem msg =
let st = (Gc.full_major(); Gc.stat ()) in
Printf.eprintf "%s %d\n%!" msg st.Gc.live_words
Should be compiled out ! -
let bcounter_check_physical_type = false
let empty_sequence = Physical_value_util.empty_xml_value ()
* Algebra_iterative_evaluate evaluates a top - level algebraic plan or
* a user - defined function call , contained in " alg_term " . In both cases ,
* an XQuery " stack frame " ( heap - allocated code context ) is allocated
* upon entry . Any tail - recursive function call in " alg_term " is
* evaluated in the _ same _ stack frame .
*
* Evaluation continues in the current stack frame as long as
* tail - recursive calls occur in alg_term .
*
* See algebra_execute_aux below to see how tail - recursive calls are
* detected .
* Algebra_iterative_evaluate evaluates a top-level algebraic plan or
* a user-defined function call, contained in "alg_term". In both cases,
* an XQuery "stack frame" (heap-allocated code context) is allocated
* upon entry. Any tail-recursive function call in "alg_term" is
* evaluated in the _same_ stack frame.
*
* Evaluation continues in the current stack frame as long as
* tail-recursive calls occur in alg_term.
*
* See algebra_execute_aux below to see how tail-recursive calls are
* detected.
*)
(************************************************************)
(* DO NOT TOUCH THIS CODE WITHOUT CONSULTING MARY OR JEROME *)
(************************************************************)
let count = ref 0
let rec algebra_iterative_evaluate alg_ctxt (alg_term: algop_expr) =
let tail_recursive_call = ref true in
let tail_alg_term = ref alg_term in
let result_ref = ref (Physical_value_util.empty_xml_value ()) in
while (!tail_recursive_call) do
tail_recursive_call := false;
result_ref := algebra_execute_aux (tail_recursive_call, tail_alg_term) alg_ctxt (!tail_alg_term);
done;
!result_ref
Algebra_execute_aux recursively evaluates an algebraic plan in " alg_term " .
Recursion terminates in two ways :
1 . A leaf operator in the algebraic plan is evaluated or
2 . A tail recursive function call is encountered .
In case 2 , all calls to algebra_execute_aux are exited / unrolled upto
the last call to algebra_iterative_evaluate , which evaluated the
containing function . Evaluation of the tail call continues from
this point , re - using the same XQuery stack frame as that allocated
for the containing function .
Algebra_execute_aux recursively evaluates an algebraic plan in "alg_term".
Recursion terminates in two ways:
1. A leaf operator in the algebraic plan is evaluated or
2. A tail recursive function call is encountered.
In case 2, all calls to algebra_execute_aux are exited/unrolled upto
the last call to algebra_iterative_evaluate, which evaluated the
containing function. Evaluation of the tail call continues from
this point, re-using the same XQuery stack frame as that allocated
for the containing function.
*)
(************************************************************)
(* DO NOT TOUCH THIS CODE WITHOUT CONSULTING MARY OR JEROME *)
(************************************************************)
and algebra_execute_aux (tail_recursive_call, tail_alg_term) alg_ctxt (alg_term: algop_expr) =
(* The algebraic operator contains the file location that should be
correlated with errors, so we catch any dynamic exceptions here
and rewrap the exceptions with the file location.
*)
Printf.printf ( " = > % s@%d\n% ! " ) ( Xquery_algebra_ast_util.string_of_algop_expr_name alg_term.palgop_expr_name ) ! count ;
count : = ! count + 1 ;
Printf.printf ("=> %s@%d\n%!") (Xquery_algebra_ast_util.string_of_algop_expr_name alg_term.palgop_expr_name) !count;
count := !count + 1;
*)
begin
let fi = (alg_term).palgop_expr_loc in
let v =
(try
begin
1 . Instantiate function " actual_code " , which implements the
algebraic operator and " tailcode " , which implements a
tail - recursive function call .
If operator is a non - tail - recursive function call , the
function is evaluated in a new stack frame , and the
function 's body is evaluated by algebra_iterative_evaluate ,
which keeps track of the current frame .
algebraic operator and "tailcode", which implements a
tail-recursive function call.
If operator is a non-tail-recursive function call, the
function is evaluated in a new stack frame, and the
function's body is evaluated by algebra_iterative_evaluate,
which keeps track of the current frame.
*)
let (actual_code, tailcode) =
match !(alg_term.palgop_expr_eval) with
| NoDep (f, tailcode) ->
begin
match alg_term.palgop_expr_name with
| AOECallUserDefined ((cfname, arity), _, _, _, false) ->
(f algebra_iterative_evaluate, tailcode)
| _ -> (f (algebra_execute_aux (tail_recursive_call, tail_alg_term)), tailcode)
end
| SomeDep (f, tailcode) ->
begin
match alg_term.palgop_expr_name with
| AOECallUserDefined ((cfname, arity), _, _, _, false) ->
(f algebra_iterative_evaluate, tailcode)
| _ -> (f (algebra_execute_aux (tail_recursive_call, tail_alg_term)), tailcode)
end
in
2 . Evaluate independent sub - expressions , then call the code
that implements the operator itself .
that implements the operator itself.
*)
let sub_alg_terms = (alg_term).psub_expression in
begin
match (sub_alg_terms, actual_code) with
| (NoSub,AOECUnit f) ->
f alg_ctxt ()
| (OneSub alg1,AOECUnary f) ->
let ac1 = update_allocate_holder_if_needed alg_ctxt sub_alg_terms in
let input1 = algebra_execute_aux (tail_recursive_call, tail_alg_term) ac1 alg1 in
f alg_ctxt input1
| (TwoSub (alg1,alg2),AOECBinary f) ->
let ac1 = update_allocate_holder_if_needed alg_ctxt sub_alg_terms in
let ac2 = update_allocate_holder_if_needed alg_ctxt sub_alg_terms in
let input1 = algebra_execute_aux (tail_recursive_call, tail_alg_term) ac1 alg1 in
let input2 = algebra_execute_aux (tail_recursive_call, tail_alg_term) ac2 alg2 in
f alg_ctxt input1 input2
| (ManySub algs, AOECMany f) ->
begin
let acs = Array.map
(fun _ -> update_allocate_holder_if_needed alg_ctxt sub_alg_terms) algs in
let inputs = Array.mapi
(fun i alg -> algebra_execute_aux (tail_recursive_call, tail_alg_term) acs.(i) alg) algs in
3 . If the operator is tail - recursive - function call ,
recursion terminates . The tail call 's " entry code " , which
updates the current stack frame with the
function 's actual arguments , is evaluated ; the
current plan is replaced by the body of the
tail - call ; and the empty sequence is returned .
recursion terminates. The tail call's "entry code", which
updates the current stack frame with the
function's actual arguments, is evaluated; the
current plan is replaced by the body of the
tail-call; and the empty sequence is returned.
*)
match alg_term.palgop_expr_name with
| AOECallUserDefined ((cfname, arity), _, _, _, true) ->
begin
match tailcode with
| None ->
raise (Query(Code_Selection("No tail-recursive code for "^
Namespace_names.prefixed_string_of_rqname cfname)))
| Some (entry_code, exit_code) ->
begin
tail_recursive_call := true;
let body = entry_code inputs in
tail_alg_term := body;
empty_sequence
end;
end
| _ ->
f alg_ctxt inputs
end
| _ ->
raise (Query (Malformed_Algebra_Expr
"Number of input sub-algebraic operations does not match code arity"))
end
end
with
| exn -> raise (error_with_file_location fi exn)) in
(*****************************************************************)
(* IF YOU PUT ANY CODE HERE, YOU RISK MAKING algebra_execute_aux *)
(* non-tail-recursive and possibly cause a memory leak. *)
(*****************************************************************)
count : = ! count - 1 ;
Printf.printf ( " < = % s@%d\n% ! " )
( Xquery_algebra_ast_util.string_of_algop_expr_name alg_term.palgop_expr_name ) ! count ;
count := !count - 1;
Printf.printf ("<= %s@%d\n%!")
(Xquery_algebra_ast_util.string_of_algop_expr_name alg_term.palgop_expr_name) !count;
*)
v
end
(************************************************************)
(* DO NOT TOUCH THIS CODE WITHOUT CONSULTING MARY OR JEROME *)
(************************************************************)
let algebra_execute alg_ctxt (alg_term: algop_expr) =
let v = algebra_iterative_evaluate alg_ctxt alg_term in
v
(*****************************************)
Physical typing debug code -
(****************************************)
if ( )
then ( counter_check_physical_type alg_term result ) ;
if (bcounter_check_physical_type)
then (counter_check_physical_type alg_term result);
*)
| null | https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/evaluation/evaluation_expr.ml | ocaml | *********************************************************************
GALAX
XQuery Engine
Distributed only by permission.
*********************************************************************
Here we do not need to allocate holders because it is done else where
**************************************
**************************************
This function must be tail recursive as well!!!!
**********************************************************
DO NOT TOUCH THIS CODE WITHOUT CONSULTING MARY OR JEROME
**********************************************************
**********************************************************
DO NOT TOUCH THIS CODE WITHOUT CONSULTING MARY OR JEROME
**********************************************************
The algebraic operator contains the file location that should be
correlated with errors, so we catch any dynamic exceptions here
and rewrap the exceptions with the file location.
***************************************************************
IF YOU PUT ANY CODE HERE, YOU RISK MAKING algebra_execute_aux
non-tail-recursive and possibly cause a memory leak.
***************************************************************
**********************************************************
DO NOT TOUCH THIS CODE WITHOUT CONSULTING MARY OR JEROME
**********************************************************
***************************************
************************************** | Copyright 2001 - 2007 .
$ I d : evaluation_expr.ml , v 1.18 2007/03/18 21:38:01 mff Exp $
Module : Evaluation_expr
Description :
Execute the code associated to each algebraic operation
Description:
Execute the code associated to each algebraic operation
*)
open Algebra_type
open Xquery_algebra_ast
open Error
NOTE :
The reason we have this first step that instantiate the dependant
expressions is because those may have changed in the course of
algebraic rewriting .
A better strategy would be to change the evaluation to instantiate
all of the code in the AST * before * starting actual evaluation .
- J & C
The reason we have this first step that instantiate the dependant
expressions is because those may have changed in the course of
algebraic rewriting.
A better strategy would be to change the evaluation to instantiate
all of the code in the AST *before* starting actual evaluation.
- J & C *)
let has_delta_update op =
let {has_delta_update=hdu} = op.annotation in
hdu
let has_two_deltas_sexprs sexpr =
match sexpr with
| NoSub
| OneSub _ -> false
| TwoSub (op1,op2) ->
(has_delta_update op1) &&
(has_delta_update op2)
| ManySub ops ->
let count_fold cur op =
if has_delta_update op
then (cur+1)
else cur
in
let counts = Array.fold_left count_fold 0 ops in
counts >= 2
let update_allocate_holder_if_needed alg_ctxt subexpr =
match Execution_context.get_current_snap_semantic alg_ctxt with
| Xquery_common_ast.Snap_Ordered_Deterministic ->
if has_two_deltas_sexprs subexpr
then Execution_context.allocate_update_holder alg_ctxt
else alg_ctxt
| Xquery_common_ast.Snap_Unordered_Deterministic
| Xquery_common_ast.Snap_Nondeterministic ->
alg_ctxt
Physical typing debug code -
open Xquery_physical_type_ast
open Print_xquery_physical_type
open Physical_value
let counter_check_physical_type algop pv =
let string_of_physical_value pv =
match pv with
| PXMLValue (SaxValue _) -> "PXMLValue (SaxValue _)"
| PXMLValue (DomValue (CSeq _)) -> "PXMLValue (DomValue (CSeq _))"
| PXMLValue (DomValue (LSeq _)) -> "PXMLValue (DomValue (LSeq _))"
| PTable _ -> "PTable _"
in
let raise_type_mismatch pt =
let physop = Cs_util.get_physical_opname algop in
raise (Query (Prototype ("Physical type mismatch - " ^ (string_of_physical_type pt) ^ " vs. " ^ (string_of_physical_value pv)
^ " at " ^ (string_of_physop_expr_name physop) ^ "! This should have been compiled out (evaluation_expr)!")))
in
let counter_check_physical_sax_type pt =
match pv with
| PXMLValue (SaxValue _) -> ()
| _ -> raise_type_mismatch pt
in
let counter_check_physical_dom_cursor_type pt =
match pv with
| PXMLValue (DomValue (CSeq _)) -> ()
| _ -> raise_type_mismatch pt
in
let counter_check_physical_dom_list_type pt =
match pv with
| PXMLValue (DomValue (LSeq _)) -> ()
| _ -> raise_type_mismatch pt
in
let counter_check_physical_table_type pt =
match pv with
| PTable _ -> ()
| _ -> raise_type_mismatch pt
in
match algop.palgop_expr_eval_sig with
| Some (_, _, pt) ->
begin
match pt with
| PT_Table _ -> counter_check_physical_table_type pt
| PT_XML (PT_Sax PT_Stream)-> counter_check_physical_sax_type pt
| PT_XML (PT_Sax PT_Discarded)-> raise_type_mismatch pt
| PT_XML (PT_Dom PT_CursorSeq) -> counter_check_physical_dom_cursor_type pt
| PT_XML (PT_Dom PT_ListSeq) -> counter_check_physical_dom_list_type pt
end
| None -> ()
let memtotal = ref None
let memlive = ref None
let recmem msg =
let st = (Gc.full_major(); Gc.stat ()) in
Printf.eprintf "%s %d\n%!" msg st.Gc.live_words
Should be compiled out ! -
let bcounter_check_physical_type = false
let empty_sequence = Physical_value_util.empty_xml_value ()
* Algebra_iterative_evaluate evaluates a top - level algebraic plan or
* a user - defined function call , contained in " alg_term " . In both cases ,
* an XQuery " stack frame " ( heap - allocated code context ) is allocated
* upon entry . Any tail - recursive function call in " alg_term " is
* evaluated in the _ same _ stack frame .
*
* Evaluation continues in the current stack frame as long as
* tail - recursive calls occur in alg_term .
*
* See algebra_execute_aux below to see how tail - recursive calls are
* detected .
* Algebra_iterative_evaluate evaluates a top-level algebraic plan or
* a user-defined function call, contained in "alg_term". In both cases,
* an XQuery "stack frame" (heap-allocated code context) is allocated
* upon entry. Any tail-recursive function call in "alg_term" is
* evaluated in the _same_ stack frame.
*
* Evaluation continues in the current stack frame as long as
* tail-recursive calls occur in alg_term.
*
* See algebra_execute_aux below to see how tail-recursive calls are
* detected.
*)
let count = ref 0
let rec algebra_iterative_evaluate alg_ctxt (alg_term: algop_expr) =
let tail_recursive_call = ref true in
let tail_alg_term = ref alg_term in
let result_ref = ref (Physical_value_util.empty_xml_value ()) in
while (!tail_recursive_call) do
tail_recursive_call := false;
result_ref := algebra_execute_aux (tail_recursive_call, tail_alg_term) alg_ctxt (!tail_alg_term);
done;
!result_ref
Algebra_execute_aux recursively evaluates an algebraic plan in " alg_term " .
Recursion terminates in two ways :
1 . A leaf operator in the algebraic plan is evaluated or
2 . A tail recursive function call is encountered .
In case 2 , all calls to algebra_execute_aux are exited / unrolled upto
the last call to algebra_iterative_evaluate , which evaluated the
containing function . Evaluation of the tail call continues from
this point , re - using the same XQuery stack frame as that allocated
for the containing function .
Algebra_execute_aux recursively evaluates an algebraic plan in "alg_term".
Recursion terminates in two ways:
1. A leaf operator in the algebraic plan is evaluated or
2. A tail recursive function call is encountered.
In case 2, all calls to algebra_execute_aux are exited/unrolled upto
the last call to algebra_iterative_evaluate, which evaluated the
containing function. Evaluation of the tail call continues from
this point, re-using the same XQuery stack frame as that allocated
for the containing function.
*)
and algebra_execute_aux (tail_recursive_call, tail_alg_term) alg_ctxt (alg_term: algop_expr) =
Printf.printf ( " = > % s@%d\n% ! " ) ( Xquery_algebra_ast_util.string_of_algop_expr_name alg_term.palgop_expr_name ) ! count ;
count : = ! count + 1 ;
Printf.printf ("=> %s@%d\n%!") (Xquery_algebra_ast_util.string_of_algop_expr_name alg_term.palgop_expr_name) !count;
count := !count + 1;
*)
begin
let fi = (alg_term).palgop_expr_loc in
let v =
(try
begin
1 . Instantiate function " actual_code " , which implements the
algebraic operator and " tailcode " , which implements a
tail - recursive function call .
If operator is a non - tail - recursive function call , the
function is evaluated in a new stack frame , and the
function 's body is evaluated by algebra_iterative_evaluate ,
which keeps track of the current frame .
algebraic operator and "tailcode", which implements a
tail-recursive function call.
If operator is a non-tail-recursive function call, the
function is evaluated in a new stack frame, and the
function's body is evaluated by algebra_iterative_evaluate,
which keeps track of the current frame.
*)
let (actual_code, tailcode) =
match !(alg_term.palgop_expr_eval) with
| NoDep (f, tailcode) ->
begin
match alg_term.palgop_expr_name with
| AOECallUserDefined ((cfname, arity), _, _, _, false) ->
(f algebra_iterative_evaluate, tailcode)
| _ -> (f (algebra_execute_aux (tail_recursive_call, tail_alg_term)), tailcode)
end
| SomeDep (f, tailcode) ->
begin
match alg_term.palgop_expr_name with
| AOECallUserDefined ((cfname, arity), _, _, _, false) ->
(f algebra_iterative_evaluate, tailcode)
| _ -> (f (algebra_execute_aux (tail_recursive_call, tail_alg_term)), tailcode)
end
in
2 . Evaluate independent sub - expressions , then call the code
that implements the operator itself .
that implements the operator itself.
*)
let sub_alg_terms = (alg_term).psub_expression in
begin
match (sub_alg_terms, actual_code) with
| (NoSub,AOECUnit f) ->
f alg_ctxt ()
| (OneSub alg1,AOECUnary f) ->
let ac1 = update_allocate_holder_if_needed alg_ctxt sub_alg_terms in
let input1 = algebra_execute_aux (tail_recursive_call, tail_alg_term) ac1 alg1 in
f alg_ctxt input1
| (TwoSub (alg1,alg2),AOECBinary f) ->
let ac1 = update_allocate_holder_if_needed alg_ctxt sub_alg_terms in
let ac2 = update_allocate_holder_if_needed alg_ctxt sub_alg_terms in
let input1 = algebra_execute_aux (tail_recursive_call, tail_alg_term) ac1 alg1 in
let input2 = algebra_execute_aux (tail_recursive_call, tail_alg_term) ac2 alg2 in
f alg_ctxt input1 input2
| (ManySub algs, AOECMany f) ->
begin
let acs = Array.map
(fun _ -> update_allocate_holder_if_needed alg_ctxt sub_alg_terms) algs in
let inputs = Array.mapi
(fun i alg -> algebra_execute_aux (tail_recursive_call, tail_alg_term) acs.(i) alg) algs in
3 . If the operator is tail - recursive - function call ,
recursion terminates . The tail call 's " entry code " , which
updates the current stack frame with the
function 's actual arguments , is evaluated ; the
current plan is replaced by the body of the
tail - call ; and the empty sequence is returned .
recursion terminates. The tail call's "entry code", which
updates the current stack frame with the
function's actual arguments, is evaluated; the
current plan is replaced by the body of the
tail-call; and the empty sequence is returned.
*)
match alg_term.palgop_expr_name with
| AOECallUserDefined ((cfname, arity), _, _, _, true) ->
begin
match tailcode with
| None ->
raise (Query(Code_Selection("No tail-recursive code for "^
Namespace_names.prefixed_string_of_rqname cfname)))
| Some (entry_code, exit_code) ->
begin
tail_recursive_call := true;
let body = entry_code inputs in
tail_alg_term := body;
empty_sequence
end;
end
| _ ->
f alg_ctxt inputs
end
| _ ->
raise (Query (Malformed_Algebra_Expr
"Number of input sub-algebraic operations does not match code arity"))
end
end
with
| exn -> raise (error_with_file_location fi exn)) in
count : = ! count - 1 ;
Printf.printf ( " < = % s@%d\n% ! " )
( Xquery_algebra_ast_util.string_of_algop_expr_name alg_term.palgop_expr_name ) ! count ;
count := !count - 1;
Printf.printf ("<= %s@%d\n%!")
(Xquery_algebra_ast_util.string_of_algop_expr_name alg_term.palgop_expr_name) !count;
*)
v
end
let algebra_execute alg_ctxt (alg_term: algop_expr) =
let v = algebra_iterative_evaluate alg_ctxt alg_term in
v
Physical typing debug code -
if ( )
then ( counter_check_physical_type alg_term result ) ;
if (bcounter_check_physical_type)
then (counter_check_physical_type alg_term result);
*)
|
572ef3da3efa79e3c5f7547e69fccaeddb7a4588f3b5053c9b55de38af3fa32f | mbenelli/klio | binary-io#.scm | ; binary-io.scm - Binary parsing and writing.
;
Copyright ( c ) 2011 by . All rights reserved .
(##namespace
("binary-io#"
default-endian
default-float-endian
binary-port?
open-binary-input-file
open-binary-output-file
call-with-binary-input-file
call-with-binary-output-file
with-input-from-binary-file
with-output-to-binary-file
read-binary-uint8
read-binary-uint16
read-binary-uint32
read-binary-uint64
read-binary-sint8
read-binary-sint16
read-binary-sint32
read-binary-sint64
write-binary-uint8
write-binary-uint16
write-binary-uint32
write-binary-uint64
write-binary-sint8
write-binary-sint16
write-binary-sint32
write-binary-sint64
read-network-uint16
read-network-uint32
read-network-uint64
read-network-sint16
read-network-sint32
read-network-sint64
write-network-uint16
write-network-uint32
write-network-uint64
write-network-sint16
write-network-sint32
write-network-sint64
read-ber-integer
write-ber-integer
read-ieee-float32
read-ieee-float64
TODO
;
write-ieee-float32
write-ieee-float64
))
| null | https://raw.githubusercontent.com/mbenelli/klio/33c11700d6080de44a22a27a5147f97899583f6e/klio/binary-io%23.scm | scheme | binary-io.scm - Binary parsing and writing.
| Copyright ( c ) 2011 by . All rights reserved .
(##namespace
("binary-io#"
default-endian
default-float-endian
binary-port?
open-binary-input-file
open-binary-output-file
call-with-binary-input-file
call-with-binary-output-file
with-input-from-binary-file
with-output-to-binary-file
read-binary-uint8
read-binary-uint16
read-binary-uint32
read-binary-uint64
read-binary-sint8
read-binary-sint16
read-binary-sint32
read-binary-sint64
write-binary-uint8
write-binary-uint16
write-binary-uint32
write-binary-uint64
write-binary-sint8
write-binary-sint16
write-binary-sint32
write-binary-sint64
read-network-uint16
read-network-uint32
read-network-uint64
read-network-sint16
read-network-sint32
read-network-sint64
write-network-uint16
write-network-uint32
write-network-uint64
write-network-sint16
write-network-sint32
write-network-sint64
read-ber-integer
write-ber-integer
read-ieee-float32
read-ieee-float64
TODO
write-ieee-float32
write-ieee-float64
))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.